noracu 0.1.3 → 0.2.0
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 +483 -0
- package/README.md +40 -21
- package/README.zh-CN.md +42 -23
- package/SECURITY.md +15 -8
- package/docs/architecture.md +58 -27
- package/docs/tools.md +46 -35
- package/docs/usage.md +195 -66
- package/imctl/README.md +19 -16
- package/imctl/pyproject.toml +1 -1
- package/imctl/src/imctl/__init__.py +1 -1
- package/imctl/src/imctl/cli.py +315 -35
- package/imctl/src/imctl/gestures.py +313 -96
- package/imctl/src/imctl/input.py +300 -60
- package/imctl/src/imctl/verify.py +39 -0
- package/imctl/src/imctl/vision.py +55 -4
- package/imctl/src/imctl/window.py +61 -9
- package/package.json +5 -4
- package/src/mac-ax.js +2397 -0
- package/src/server.mjs +1887 -510
package/imctl/src/imctl/input.py
CHANGED
|
@@ -23,6 +23,7 @@ methodology):
|
|
|
23
23
|
|
|
24
24
|
from __future__ import annotations
|
|
25
25
|
|
|
26
|
+
import math
|
|
26
27
|
import time
|
|
27
28
|
|
|
28
29
|
from Quartz import (
|
|
@@ -112,12 +113,23 @@ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
|
|
|
112
113
|
deltas = scroll_steps(total_px)
|
|
113
114
|
last = len(deltas) - 1
|
|
114
115
|
sent = 1 # events posted so far (the mouse-moved above)
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
116
|
+
began = False
|
|
117
|
+
ended = False
|
|
118
|
+
try:
|
|
119
|
+
for i, d in enumerate(deltas):
|
|
120
|
+
if sent % 6 == 0:
|
|
121
|
+
_require_focus() # F26: every 6 events; drop the rest on focus loss
|
|
122
|
+
phase = 1 if i == 0 else (4 if i == last else 2)
|
|
123
|
+
_scroll_event(src, d, x, y, phase)
|
|
124
|
+
if phase == 1:
|
|
125
|
+
began = True
|
|
126
|
+
elif phase == 4:
|
|
127
|
+
ended = True
|
|
128
|
+
sent += 1
|
|
129
|
+
time.sleep(0.016)
|
|
130
|
+
finally:
|
|
131
|
+
if began and not ended:
|
|
132
|
+
_scroll_event(src, 0, x, y, 4)
|
|
121
133
|
|
|
122
134
|
|
|
123
135
|
def _mouse_event(kind: int, x: float, y: float, source) -> None:
|
|
@@ -170,21 +182,37 @@ def tap(nx: float = 0.5, ny: float = 0.5, bounds: WindowBounds | None = None) ->
|
|
|
170
182
|
src = _source()
|
|
171
183
|
_require_focus() # F26: before the first event
|
|
172
184
|
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
173
|
-
|
|
174
|
-
|
|
185
|
+
try:
|
|
186
|
+
time.sleep(TAP_INTERVAL_S)
|
|
187
|
+
finally:
|
|
188
|
+
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
SWIPE_MS_RANGE = (50, 5000)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _check_duration(value: float, lo: float, hi: float, what: str) -> None:
|
|
195
|
+
# before any event: an invalid duration must not turn into a real press (math.isfinite: no nan/inf;
|
|
196
|
+
# bool is an int subclass in Python, so it is refused by name)
|
|
197
|
+
if not (isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
198
|
+
and math.isfinite(value) and lo <= value <= hi):
|
|
199
|
+
raise ValueError(f"{what} must be between {lo} and {hi}")
|
|
175
200
|
|
|
176
201
|
|
|
177
202
|
def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_S,
|
|
178
203
|
bounds: WindowBounds | None = None) -> None:
|
|
179
204
|
"""Press and hold at normalized coordinates."""
|
|
205
|
+
_check_duration(duration_s, 0.01, 10, "long-press duration (s)")
|
|
180
206
|
ensure_frontmost()
|
|
181
207
|
b = bounds or get_bounds()
|
|
182
208
|
x, y = b.denormalize(nx, ny)
|
|
183
209
|
src = _source()
|
|
184
210
|
_require_focus() # F26: before the press-down
|
|
185
211
|
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
186
|
-
|
|
187
|
-
|
|
212
|
+
try:
|
|
213
|
+
time.sleep(duration_s)
|
|
214
|
+
finally:
|
|
215
|
+
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
188
216
|
|
|
189
217
|
|
|
190
218
|
def _ease_in_out(t: float) -> float:
|
|
@@ -202,6 +230,7 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
|
202
230
|
The gesture is: mouse-down, 3px nudge, 20 eased drag steps,
|
|
203
231
|
mouse-up. This is the shape iPhone Mirroring's recognizer accepts.
|
|
204
232
|
"""
|
|
233
|
+
_check_duration(duration_ms, *SWIPE_MS_RANGE, "swipe duration (ms)")
|
|
205
234
|
ensure_frontmost()
|
|
206
235
|
b = bounds or get_bounds()
|
|
207
236
|
x0, y0 = b.denormalize(from_x, from_y)
|
|
@@ -211,25 +240,31 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
|
211
240
|
step_delay = (duration_ms / 1000.0) / SWIPE_STEPS
|
|
212
241
|
|
|
213
242
|
_require_focus() # F26: before the first event
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
243
|
+
cx, cy = x0, y0
|
|
244
|
+
_mouse_event(kCGEventLeftMouseDown, cx, cy, src)
|
|
245
|
+
try:
|
|
246
|
+
time.sleep(0.02)
|
|
247
|
+
|
|
248
|
+
# Initial nudge: disambiguates swipe from long-press-drag.
|
|
249
|
+
dx = 1 if x1 >= x0 else -1
|
|
250
|
+
dy = 1 if y1 >= y0 else -1
|
|
251
|
+
nx, ny = x0 + dx * SWIPE_NUDGE_PX, y0 + dy * SWIPE_NUDGE_PX
|
|
252
|
+
_mouse_event(kCGEventLeftMouseDragged, nx, ny, src)
|
|
253
|
+
cx, cy = nx, ny
|
|
254
|
+
time.sleep(0.01)
|
|
255
|
+
|
|
256
|
+
for i in range(1, SWIPE_STEPS + 1):
|
|
257
|
+
if i % 5 == 0:
|
|
258
|
+
_require_focus() # R18: a long swipe stops (and releases) when the mirror loses focus
|
|
259
|
+
t = i / SWIPE_STEPS
|
|
260
|
+
e = _ease_in_out(t)
|
|
261
|
+
nx = x0 + (x1 - x0) * e
|
|
262
|
+
ny = y0 + (y1 - y0) * e
|
|
263
|
+
_mouse_event(kCGEventLeftMouseDragged, nx, ny, src)
|
|
264
|
+
cx, cy = nx, ny
|
|
265
|
+
time.sleep(step_delay)
|
|
266
|
+
finally:
|
|
267
|
+
_mouse_event(kCGEventLeftMouseUp, cx, cy, src)
|
|
233
268
|
|
|
234
269
|
|
|
235
270
|
def scroll(dy_pixels: int, nx: float = 0.5, ny: float = 0.5,
|
|
@@ -303,12 +338,16 @@ def _cmd_chord(keycode: int, before_key=None) -> None:
|
|
|
303
338
|
CGEventPost(kCGHIDEventTap, event)
|
|
304
339
|
|
|
305
340
|
post(_VK_COMMAND, True, kCGEventFlagMaskCommand)
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
341
|
+
try:
|
|
342
|
+
time.sleep(0.03)
|
|
343
|
+
post(keycode, True, kCGEventFlagMaskCommand)
|
|
344
|
+
try:
|
|
345
|
+
time.sleep(0.03)
|
|
346
|
+
finally:
|
|
347
|
+
post(keycode, False, kCGEventFlagMaskCommand)
|
|
348
|
+
time.sleep(0.03)
|
|
349
|
+
finally:
|
|
350
|
+
post(_VK_COMMAND, False, 0)
|
|
312
351
|
|
|
313
352
|
|
|
314
353
|
def press_key(key: str) -> None:
|
|
@@ -320,8 +359,10 @@ def press_key(key: str) -> None:
|
|
|
320
359
|
src = _source()
|
|
321
360
|
_require_focus() # F26: before the key-down
|
|
322
361
|
_key_event(keymap[key], True, src)
|
|
323
|
-
|
|
324
|
-
|
|
362
|
+
try:
|
|
363
|
+
time.sleep(0.02)
|
|
364
|
+
finally:
|
|
365
|
+
_key_event(keymap[key], False, src)
|
|
325
366
|
|
|
326
367
|
|
|
327
368
|
class ClipboardChanged(InputError):
|
|
@@ -332,6 +373,95 @@ class ClipboardChanged(InputError):
|
|
|
332
373
|
"""
|
|
333
374
|
|
|
334
375
|
|
|
376
|
+
# The user's clipboard is copied aside whole (every item, every type) and put back the same way. Items a
|
|
377
|
+
# password manager marks concealed (nspasteboard.org) or an app marks transient are never copied: putting
|
|
378
|
+
# the clipboard "back" means clearing it. Universal Clipboard content (reading it would fetch it from
|
|
379
|
+
# the other device), promised files and clipboards over the size limit are not copied either: the
|
|
380
|
+
# clipboard keeps the typed text. Our own write is not marked transient — iPhone Mirroring reads the
|
|
381
|
+
# Mac pasteboard, and the marker's effect on that path is unproven.
|
|
382
|
+
_CONCEALED = "org.nspasteboard.ConcealedType"
|
|
383
|
+
_TRANSIENT = "org.nspasteboard.TransientType"
|
|
384
|
+
_REMOTE = "com.apple.is-remote-clipboard"
|
|
385
|
+
_SAVE_LIMIT = 64 * 1024 * 1024
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _new_item():
|
|
389
|
+
from AppKit import NSPasteboardItem
|
|
390
|
+
return NSPasteboardItem.alloc().init()
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def save_pasteboard(pasteboard, limit: int = _SAVE_LIMIT):
|
|
394
|
+
"""Snapshot ``pasteboard`` for restore_pasteboard(): ``(kind, items)``.
|
|
395
|
+
|
|
396
|
+
kind "items": items is [[(type, data), ...], ...]; "concealed" /
|
|
397
|
+
"transient": not copied (restore clears); "empty"; "remote" /
|
|
398
|
+
"too_large": not copied (restore leaves the clipboard as it is).
|
|
399
|
+
A pasteboard object without ``types()`` (a text-only stand-in) is
|
|
400
|
+
saved as ("text", data of public.utf8-plain-text).
|
|
401
|
+
"""
|
|
402
|
+
if getattr(pasteboard, "types", None) is None:
|
|
403
|
+
return ("text", pasteboard.dataForType_("public.utf8-plain-text"))
|
|
404
|
+
# types() lists only the first item's types: it tells a remote clipboard before any item is
|
|
405
|
+
# touched; every item's own types are then read (without data) for concealed / transient marks
|
|
406
|
+
types = [str(t) for t in (pasteboard.types() or [])]
|
|
407
|
+
if _REMOTE in types:
|
|
408
|
+
return ("remote", None)
|
|
409
|
+
items_ = list(pasteboard.pasteboardItems() or [])
|
|
410
|
+
for it in items_:
|
|
411
|
+
types += [str(t) for t in (it.types() or [])]
|
|
412
|
+
if _CONCEALED in types:
|
|
413
|
+
return ("concealed", None)
|
|
414
|
+
if _TRANSIENT in types:
|
|
415
|
+
return ("transient", None)
|
|
416
|
+
promised = any(t.startswith("com.apple.pasteboard.promised-file") for t in types)
|
|
417
|
+
if _REMOTE in types or (promised and "public.file-url" not in types):
|
|
418
|
+
return ("remote", None)
|
|
419
|
+
if not types:
|
|
420
|
+
return ("empty", None)
|
|
421
|
+
items, total = [], 0
|
|
422
|
+
for it in items_:
|
|
423
|
+
rec = []
|
|
424
|
+
for t in (it.types() or []):
|
|
425
|
+
d = it.dataForType_(t)
|
|
426
|
+
if d is None:
|
|
427
|
+
continue
|
|
428
|
+
total += int(d.length()) if hasattr(d, "length") else len(d)
|
|
429
|
+
if total > limit:
|
|
430
|
+
return ("too_large", None)
|
|
431
|
+
rec.append((str(t), d))
|
|
432
|
+
if rec:
|
|
433
|
+
items.append(rec)
|
|
434
|
+
if not items:
|
|
435
|
+
# a provider that answers only at the pasteboard level
|
|
436
|
+
return ("text", pasteboard.dataForType_("public.utf8-plain-text"))
|
|
437
|
+
return ("items", items)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def restore_pasteboard(pasteboard, saved) -> bool:
|
|
441
|
+
"""Put a save_pasteboard() snapshot back (the caller checked the
|
|
442
|
+
changeCount). Returns False when it cannot be put back ("remote",
|
|
443
|
+
"too_large"): then the clipboard is left holding the typed text.
|
|
444
|
+
Raw text data (bytes or None, the older snapshot) is accepted too."""
|
|
445
|
+
if not isinstance(saved, tuple):
|
|
446
|
+
saved = ("text", saved)
|
|
447
|
+
kind, data = saved
|
|
448
|
+
if kind in ("remote", "too_large"):
|
|
449
|
+
return False
|
|
450
|
+
pasteboard.clearContents()
|
|
451
|
+
if kind == "text":
|
|
452
|
+
if data is not None:
|
|
453
|
+
pasteboard.setData_forType_(data, "public.utf8-plain-text")
|
|
454
|
+
elif kind == "items" and data:
|
|
455
|
+
objs = []
|
|
456
|
+
for rec in data:
|
|
457
|
+
it = _new_item()
|
|
458
|
+
for t, d in rec:
|
|
459
|
+
it.setData_forType_(d, t)
|
|
460
|
+
objs.append(it)
|
|
461
|
+
pasteboard.writeObjects_(objs)
|
|
462
|
+
return True
|
|
463
|
+
|
|
464
|
+
|
|
335
465
|
class PendingRestore:
|
|
336
466
|
"""A clipboard restore type_text() could not license itself (F33).
|
|
337
467
|
|
|
@@ -368,17 +498,15 @@ class PendingRestore:
|
|
|
368
498
|
self.done = True
|
|
369
499
|
if self._pasteboard.changeCount() != self._saved_change + 1:
|
|
370
500
|
return False # something else wrote the pasteboard: never restore
|
|
371
|
-
self._pasteboard.
|
|
372
|
-
if self._saved is not None:
|
|
373
|
-
self._pasteboard.setData_forType_(self._saved, "public.utf8-plain-text")
|
|
374
|
-
return True
|
|
501
|
+
return restore_pasteboard(self._pasteboard, self._saved)
|
|
375
502
|
|
|
376
503
|
|
|
377
504
|
def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
378
|
-
chord=None, before_check=None, ocr_check=None,
|
|
505
|
+
chord=None, before_check=None, ocr_check=None, hud_check=None,
|
|
379
506
|
sleep=time.sleep, clock=time.monotonic,
|
|
380
507
|
timeout_s: float = 2.5, poll_s: float = 0.15,
|
|
381
|
-
min_hold_s: float = 0.3, pending: list | None = None
|
|
508
|
+
min_hold_s: float = 0.3, pending: list | None = None,
|
|
509
|
+
report: dict | None = None, restore: bool = True) -> bool:
|
|
382
510
|
"""Type text via clipboard paste (IME-safe), confirmed on screen.
|
|
383
511
|
|
|
384
512
|
Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
|
|
@@ -394,7 +522,8 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
394
522
|
``landed`` — did the paste show up? This decides the return
|
|
395
523
|
value. The whole-window luma frame diff is the fast path; when
|
|
396
524
|
it never fires within ``timeout_s``, a single OCR probe is the
|
|
397
|
-
fallback. Either one confirms the paste
|
|
525
|
+
fallback. Either one confirms the paste (the frame diff not
|
|
526
|
+
while the phone shows its paste-progress box — F44 below).
|
|
398
527
|
|
|
399
528
|
``restore_ok`` — may the user's clipboard be restored? ONLY an
|
|
400
529
|
OCR hit grants this. The frame diff merely proves "the picture
|
|
@@ -442,6 +571,39 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
442
571
|
only when the caller has established the focus (e.g. guarded by
|
|
443
572
|
a preceding expect/verify step).
|
|
444
573
|
|
|
574
|
+
F41: for text of two or more characters the default OCR check used to
|
|
575
|
+
ask only "is the text on screen?" — so text that was already there (a
|
|
576
|
+
search-history chip with the same query, an older message) licensed a
|
|
577
|
+
restore at once, and a paste that the phone read late could then paste
|
|
578
|
+
the user's ORIGINAL clipboard. The default checks now count the text's
|
|
579
|
+
probe before the pasteboard write — the higher of two reads 0.3 s
|
|
580
|
+
apart, so a read that misses an occurrence cannot fake a rise — and
|
|
581
|
+
license a restore only when the count RISES over it, in two reads 0.3 s
|
|
582
|
+
apart. Without a pre-paste count (a read failed) OCR never licenses a
|
|
583
|
+
restore for such text, and the paste can only be confirmed by the
|
|
584
|
+
frame diff. ``report`` (a dict), when given, receives that pre-paste
|
|
585
|
+
count as ``count_before`` (None: unknown), for a caller that keeps
|
|
586
|
+
watching after a False result.
|
|
587
|
+
|
|
588
|
+
``restore=False``: once Cmd+V may be on its way the user's clipboard is
|
|
589
|
+
never put back — no restore here and no PendingRestore — and it keeps
|
|
590
|
+
``text``; only an error before Cmd+V still restores it. open_app uses
|
|
591
|
+
this (F42): a paste can reach the phone more than 10 s late, and
|
|
592
|
+
Spotlight can show the name in its own suggestions before that, so a
|
|
593
|
+
licensed restore could still paste the user's clipboard into the search.
|
|
594
|
+
|
|
595
|
+
F44: a paste the phone is slow to fetch puts up its "Pasting from <Mac>…"
|
|
596
|
+
progress box, and that box alone moves the frame diff. So when the frame
|
|
597
|
+
diff fired but OCR did not see the text, ``hud_check`` (one more screen
|
|
598
|
+
read) looks for the box: while it shows, the paste is still on its way —
|
|
599
|
+
not landed, the result is False and the caller's late watch takes over. A
|
|
600
|
+
capture failure there keeps the frame diff's verdict. ``hud_check`` is
|
|
601
|
+
injectable; by default it reads the screen only with the real frame diff
|
|
602
|
+
(an injected ``before_check`` gets no real read here). The default OCR
|
|
603
|
+
checks never license a restore from a read that shows the box — a paste,
|
|
604
|
+
this one or an earlier one, is still on its way and could fetch the
|
|
605
|
+
restored clipboard — and the box's own words never count as the text.
|
|
606
|
+
|
|
445
607
|
``pending`` (F33): when a one-character paste was not licensed for a
|
|
446
608
|
restore here — not seen within the checks, or landed while OCR stayed
|
|
447
609
|
blind — and the caller passes a list, a PendingRestore is appended to
|
|
@@ -474,6 +636,9 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
474
636
|
# too the clipboard keeps holding ``text``, as before.
|
|
475
637
|
single = verify.is_short_text(text, limit=1)
|
|
476
638
|
sweep_before = [None]
|
|
639
|
+
# F41: the probe count of a 2+ character text before the paste (None = unknown)
|
|
640
|
+
multi = not single and verify.text_probe(text) is not None
|
|
641
|
+
count_before = [None]
|
|
477
642
|
|
|
478
643
|
def sweep_read():
|
|
479
644
|
return vision.read_screen(language_correction=False, sweep=True)
|
|
@@ -481,15 +646,32 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
481
646
|
def defer_restore():
|
|
482
647
|
# F33: hand the caller what it needs to restore later, on evidence.
|
|
483
648
|
before = sweep_before[0]
|
|
484
|
-
if pending is None or not single or before is None:
|
|
649
|
+
if pending is None or not single or before is None or not restore:
|
|
485
650
|
return
|
|
486
651
|
|
|
487
|
-
|
|
488
|
-
|
|
652
|
+
sighting = verify.RepeatedSighting(text, before)
|
|
653
|
+
|
|
654
|
+
def confirm(hits):
|
|
655
|
+
# F44: as in ocr_check — a read showing the paste-progress box is
|
|
656
|
+
# no evidence (a paste is still on its way)
|
|
657
|
+
return not verify.shows_paste_hud(hits) and sighting.add(hits)
|
|
658
|
+
|
|
659
|
+
pending.append(PendingRestore(pasteboard, saved, saved_change, confirm,
|
|
489
660
|
sent_at=t0, clock=clock,
|
|
490
661
|
min_hold_s=min_hold_s))
|
|
491
662
|
|
|
492
663
|
pre_read = single and before_check is None
|
|
664
|
+
pre_count = multi and ocr_check is None
|
|
665
|
+
if hud_check is None:
|
|
666
|
+
if before_check is None:
|
|
667
|
+
def hud_check() -> bool:
|
|
668
|
+
# F44: one more look for the phone's paste-progress box (a
|
|
669
|
+
# sweep for a single character, like every read of it)
|
|
670
|
+
return verify.shows_paste_hud(sweep_read() if single else vision.read_screen())
|
|
671
|
+
else:
|
|
672
|
+
def hud_check() -> bool:
|
|
673
|
+
# an injected frame diff (tests) gets no real screen read here
|
|
674
|
+
return False
|
|
493
675
|
if before_check is None:
|
|
494
676
|
def before_check():
|
|
495
677
|
# Baseline luma is captured here, right before Cmd+V, so the
|
|
@@ -511,11 +693,30 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
511
693
|
evidence = verify.RepeatedSighting(text, sweep_before[0])
|
|
512
694
|
deadline = clock() + 4.0
|
|
513
695
|
while True:
|
|
514
|
-
|
|
696
|
+
hits = sweep_read()
|
|
697
|
+
# F44: a read showing the paste-progress box is no evidence —
|
|
698
|
+
# a paste is still on its way, and a restore now could hand it
|
|
699
|
+
# the user's clipboard
|
|
700
|
+
if not verify.shows_paste_hud(hits) and evidence.add(hits):
|
|
515
701
|
return True
|
|
516
702
|
if clock() >= deadline:
|
|
517
703
|
return False
|
|
518
704
|
sleep(0.3)
|
|
705
|
+
if multi:
|
|
706
|
+
# F41: only a rise over the pre-paste count is the paste, and it
|
|
707
|
+
# must show in two reads (one misread is no license to restore)
|
|
708
|
+
if count_before[0] is None:
|
|
709
|
+
return False
|
|
710
|
+
for i in range(2):
|
|
711
|
+
if i:
|
|
712
|
+
sleep(0.3)
|
|
713
|
+
hits = vision.read_screen()
|
|
714
|
+
# F44: no license while the paste-progress box shows — a paste
|
|
715
|
+
# (this one or an earlier one) is still on its way
|
|
716
|
+
if (verify.shows_paste_hud(hits)
|
|
717
|
+
or verify.probe_count(text, hits) <= count_before[0]):
|
|
718
|
+
return False
|
|
719
|
+
return True
|
|
519
720
|
return verify.screen_shows_text(text, vision.read_screen)
|
|
520
721
|
|
|
521
722
|
sent = [False] # True from the moment a Cmd+V may be on its way
|
|
@@ -540,8 +741,31 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
540
741
|
raise
|
|
541
742
|
sweep_before[0] = None
|
|
542
743
|
|
|
543
|
-
|
|
744
|
+
if pre_count:
|
|
745
|
+
# F41: count the text before the paste — the higher of two reads
|
|
746
|
+
# 0.3 s apart (a redraw or the select-all highlight can hide an
|
|
747
|
+
# occurrence from one read). A capture failure in either leaves it
|
|
748
|
+
# unknown: then OCR can never license a restore for this paste.
|
|
749
|
+
try:
|
|
750
|
+
first = verify.probe_count(text, vision.read_screen())
|
|
751
|
+
sleep(0.3)
|
|
752
|
+
count_before[0] = max(first, verify.probe_count(text, vision.read_screen()))
|
|
753
|
+
except Exception as exc:
|
|
754
|
+
if not verify.is_capture_error(exc):
|
|
755
|
+
raise
|
|
756
|
+
count_before[0] = None
|
|
757
|
+
if report is not None:
|
|
758
|
+
report["count_before"] = count_before[0]
|
|
759
|
+
|
|
760
|
+
# the change count first: a copy that lands while the clipboard is being saved must not be
|
|
761
|
+
# overwritten by our write
|
|
544
762
|
saved_change = pasteboard.changeCount()
|
|
763
|
+
saved = save_pasteboard(pasteboard)
|
|
764
|
+
if pasteboard.changeCount() != saved_change:
|
|
765
|
+
saved_change = None # nothing of ours to undo
|
|
766
|
+
raise ClipboardChanged(
|
|
767
|
+
"another app or device changed the clipboard while it was being saved; "
|
|
768
|
+
"nothing was typed and the clipboard was left as it is")
|
|
545
769
|
|
|
546
770
|
pasteboard.clearContents()
|
|
547
771
|
pasteboard.setString_forType_(text, "public.utf8-plain-text")
|
|
@@ -594,8 +818,25 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
594
818
|
if not verify.is_capture_error(exc):
|
|
595
819
|
raise
|
|
596
820
|
restore_ok = False
|
|
821
|
+
if landed and not restore_ok:
|
|
822
|
+
# F44: the frame diff fired but OCR did not see the text. If the
|
|
823
|
+
# phone shows its "Pasting from …" progress box, the box was the
|
|
824
|
+
# change and the paste is still on its way: not landed. A capture
|
|
825
|
+
# failure tells nothing either way and keeps the frame diff's
|
|
826
|
+
# verdict; any other error propagates (after Cmd+V: no restore).
|
|
827
|
+
try:
|
|
828
|
+
if hud_check():
|
|
829
|
+
landed = False
|
|
830
|
+
except Exception as exc:
|
|
831
|
+
if not verify.is_capture_error(exc):
|
|
832
|
+
raise
|
|
597
833
|
if not landed:
|
|
598
834
|
landed = restore_ok
|
|
835
|
+
if report is not None:
|
|
836
|
+
# device run 2026-11-06: the frame diff alone (no OCR sighting) once
|
|
837
|
+
# confirmed a paste that never reached the field — the caller must
|
|
838
|
+
# not report such a paste as verified
|
|
839
|
+
report["seen"] = bool(restore_ok)
|
|
599
840
|
|
|
600
841
|
if not landed:
|
|
601
842
|
# F18 invariant: never restore unconfirmed — a late paste
|
|
@@ -603,7 +844,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
603
844
|
defer_restore()
|
|
604
845
|
return False
|
|
605
846
|
|
|
606
|
-
if restore_ok:
|
|
847
|
+
if restore_ok and restore:
|
|
607
848
|
# Hold the paste long enough for the asynchronous
|
|
608
849
|
# pasteboard read before putting the user's data back.
|
|
609
850
|
elapsed = clock() - t0
|
|
@@ -611,12 +852,11 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
611
852
|
sleep(min_hold_s - elapsed)
|
|
612
853
|
# Restore the user's clipboard only if nothing else changed it.
|
|
613
854
|
if pasteboard.changeCount() == saved_change + 1:
|
|
614
|
-
pasteboard
|
|
615
|
-
if saved is not None:
|
|
616
|
-
pasteboard.setData_forType_(saved, "public.utf8-plain-text")
|
|
855
|
+
restore_pasteboard(pasteboard, saved)
|
|
617
856
|
else:
|
|
618
|
-
# landed but OCR is blind to it (short/cropped text)
|
|
619
|
-
#
|
|
857
|
+
# landed but OCR is blind to it (short/cropped text), or the
|
|
858
|
+
# caller keeps the clipboard (restore=False): success, but the
|
|
859
|
+
# clipboard keeps `text` — see the docstring's tradeoff.
|
|
620
860
|
defer_restore()
|
|
621
861
|
return True
|
|
622
862
|
except BaseException:
|
|
@@ -626,9 +866,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
|
626
866
|
# restore then. Either way the original exception propagates.
|
|
627
867
|
if not sent[0] and saved_change is not None:
|
|
628
868
|
if pasteboard.changeCount() == saved_change + 1:
|
|
629
|
-
pasteboard
|
|
630
|
-
if saved is not None:
|
|
631
|
-
pasteboard.setData_forType_(saved, "public.utf8-plain-text")
|
|
869
|
+
restore_pasteboard(pasteboard, saved)
|
|
632
870
|
raise
|
|
633
871
|
|
|
634
872
|
|
|
@@ -640,5 +878,7 @@ def clear_text() -> None:
|
|
|
640
878
|
src = _source()
|
|
641
879
|
_require_focus() # F26: re-check between Cmd+A and Delete
|
|
642
880
|
_key_event(_VK_DELETE, True, src)
|
|
643
|
-
|
|
644
|
-
|
|
881
|
+
try:
|
|
882
|
+
time.sleep(0.02)
|
|
883
|
+
finally:
|
|
884
|
+
_key_event(_VK_DELETE, False, src)
|
|
@@ -179,6 +179,45 @@ def mean_abs_diff(a: bytes, b: bytes) -> float:
|
|
|
179
179
|
TYPE_MIN_DIFF = 0.5
|
|
180
180
|
|
|
181
181
|
|
|
182
|
+
def text_probe(text: str) -> str | None:
|
|
183
|
+
"""The OCR probe for ``text`` (screen_shows_text's rule: the first ≤12
|
|
184
|
+
characters after NFKC, lowercasing and whitespace removal), or None when
|
|
185
|
+
it is shorter than 2 characters — too short for OCR to confirm."""
|
|
186
|
+
probe = _compact(text)[:12]
|
|
187
|
+
return probe if len(probe) >= 2 else None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def probe_count(text: str, hits) -> int | None:
|
|
191
|
+
"""How many times ``text``'s probe occurs in the joined OCR ``hits``;
|
|
192
|
+
None when the text is too short for a probe. The phone's "Pasting from …"
|
|
193
|
+
box is left out (F44): its words are never the typed text, even when the
|
|
194
|
+
probe is a piece of them ("from", "pro" in a Mac named "M5pro")."""
|
|
195
|
+
probe = text_probe(text)
|
|
196
|
+
if probe is None:
|
|
197
|
+
return None
|
|
198
|
+
return _compact("".join(getattr(hit, "text", hit) for hit in hits
|
|
199
|
+
if not _is_paste_hud(hit))).count(probe)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# F44 (2026-11-05 real device, load ~25): when the phone is slow to fetch a paste
|
|
203
|
+
# it shows a "Pasting from <Mac name>…" progress box mid-screen. That box alone
|
|
204
|
+
# moves the whole-window frame diff past TYPE_MIN_DIFF while the text has not
|
|
205
|
+
# arrived, and type_text() reported such pastes as typed. English UI only: an
|
|
206
|
+
# iPhone in another language shows the box in that language, unrecognized here.
|
|
207
|
+
PASTE_HUD_PROBE = "pastingfrom"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _is_paste_hud(hit) -> bool:
|
|
211
|
+
return PASTE_HUD_PROBE in _compact(getattr(hit, "text", hit))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def shows_paste_hud(hits) -> bool:
|
|
215
|
+
"""True when one OCR hit reads like the phone's "Pasting from …" progress
|
|
216
|
+
box (compared like probes: NFKC, lowercase, whitespace removed). While it
|
|
217
|
+
shows, a paste is still on its way to the phone."""
|
|
218
|
+
return any(_is_paste_hud(hit) for hit in hits)
|
|
219
|
+
|
|
220
|
+
|
|
182
221
|
def screen_shows_text(text: str, read_screen) -> bool:
|
|
183
222
|
"""Report whether the OCR'd screen shows ``text`` (probe match).
|
|
184
223
|
|
|
@@ -13,8 +13,10 @@ from __future__ import annotations
|
|
|
13
13
|
|
|
14
14
|
import atexit
|
|
15
15
|
import os
|
|
16
|
+
import re
|
|
16
17
|
import shutil
|
|
17
18
|
import subprocess
|
|
19
|
+
import sys
|
|
18
20
|
import tempfile
|
|
19
21
|
import time
|
|
20
22
|
from dataclasses import dataclass
|
|
@@ -129,7 +131,56 @@ def capture_window(path: str | None = None) -> str:
|
|
|
129
131
|
raise CaptureError("could not capture the iPhone Mirroring window by id")
|
|
130
132
|
|
|
131
133
|
|
|
132
|
-
|
|
134
|
+
# F36 (2026-11-05, macOS 27.2): Vision weights the languages in the order given. With
|
|
135
|
+
# English first it returned no Chinese at all on a Spotlight frame (0 CJK hits; the
|
|
136
|
+
# Top Hit label 拼多多 was missing, so phone_open could not find the app and every
|
|
137
|
+
# Chinese `expect` failed). Chinese first read the same frame's Chinese AND its English
|
|
138
|
+
# labels (it even read "Suggestions" correctly where English-first read
|
|
139
|
+
# "Sugestions"), slightly faster. One shared default for ocr() and ocr_sweep().
|
|
140
|
+
# NORACU_OCR_LANGUAGES (comma-separated, e.g. "zh-Hant,en-US" or "en-US") overrides it.
|
|
141
|
+
DEFAULT_OCR_LANGUAGES: tuple[str, ...] = ("zh-Hans", "en-US")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _ocr_languages(raw: str | None) -> tuple[str, ...]:
|
|
145
|
+
# ASCII and full-width commas, and the ideographic enumeration comma
|
|
146
|
+
langs = tuple(x.strip() for x in re.split(r"[,,、]", raw or "") if x.strip())
|
|
147
|
+
return langs or DEFAULT_OCR_LANGUAGES
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
OCR_LANGUAGES: tuple[str, ...] = _ocr_languages(os.environ.get("NORACU_OCR_LANGUAGES"))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_SUPPORTED_LANGUAGES: set | None = None # read once per process
|
|
154
|
+
_WARNED_LANGUAGES: set = set()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _supported_languages(request, languages):
|
|
158
|
+
"""``languages`` minus any Vision does not support (a typo in
|
|
159
|
+
NORACU_OCR_LANGUAGES must not break every OCR call); none left → the
|
|
160
|
+
defaults. Exact codes from Vision's list only (e.g. "en-US", not "en");
|
|
161
|
+
a dropped code is reported once on stderr. When the supported list cannot
|
|
162
|
+
be read, ``languages`` as given."""
|
|
163
|
+
global _SUPPORTED_LANGUAGES
|
|
164
|
+
if _SUPPORTED_LANGUAGES is None:
|
|
165
|
+
try:
|
|
166
|
+
res = request.supportedRecognitionLanguagesAndReturnError_(None)
|
|
167
|
+
found = res[0] if isinstance(res, tuple) else res
|
|
168
|
+
_SUPPORTED_LANGUAGES = {str(x) for x in (found or [])}
|
|
169
|
+
except Exception:
|
|
170
|
+
_SUPPORTED_LANGUAGES = set()
|
|
171
|
+
supported = _SUPPORTED_LANGUAGES
|
|
172
|
+
if not supported:
|
|
173
|
+
return tuple(languages)
|
|
174
|
+
kept = tuple(x for x in languages if x in supported)
|
|
175
|
+
for x in languages:
|
|
176
|
+
if x not in supported and x not in _WARNED_LANGUAGES:
|
|
177
|
+
_WARNED_LANGUAGES.add(x)
|
|
178
|
+
print(f"imctl: OCR language {x!r} is not supported by Vision here; skipped",
|
|
179
|
+
file=sys.stderr)
|
|
180
|
+
return kept or tuple(x for x in DEFAULT_OCR_LANGUAGES if x in supported) or tuple(languages)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def ocr(image_path: str, languages: tuple[str, ...] = OCR_LANGUAGES,
|
|
133
184
|
language_correction: bool = True) -> list[OCRHit]:
|
|
134
185
|
"""Run Vision OCR on an image; return hits sorted reading-order.
|
|
135
186
|
|
|
@@ -162,7 +213,7 @@ def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans"),
|
|
|
162
213
|
request = Vision.VNRecognizeTextRequest.alloc().init()
|
|
163
214
|
request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
|
|
164
215
|
if hasattr(request, "setRecognitionLanguages_"):
|
|
165
|
-
request.setRecognitionLanguages_(list(languages))
|
|
216
|
+
request.setRecognitionLanguages_(list(_supported_languages(request, languages)))
|
|
166
217
|
request.setUsesLanguageCorrection_(language_correction)
|
|
167
218
|
|
|
168
219
|
handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
|
|
@@ -222,7 +273,7 @@ def dedupe_hits(hits: list[OCRHit], eps: float = 0.02) -> list[OCRHit]:
|
|
|
222
273
|
SWEEP_MIN_TEXT_HEIGHTS = (0.018, 0.02, 0.022, 0.025, 0.03)
|
|
223
274
|
|
|
224
275
|
|
|
225
|
-
def ocr_sweep(image_path: str, languages: tuple[str, ...] =
|
|
276
|
+
def ocr_sweep(image_path: str, languages: tuple[str, ...] = OCR_LANGUAGES,
|
|
226
277
|
language_correction: bool = False,
|
|
227
278
|
heights: tuple[float, ...] = SWEEP_MIN_TEXT_HEIGHTS) -> list[OCRHit]:
|
|
228
279
|
"""Full-frame OCR once per minimumTextHeight in ``heights``; merged hits (F27).
|
|
@@ -250,7 +301,7 @@ def ocr_sweep(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")
|
|
|
250
301
|
request = Vision.VNRecognizeTextRequest.alloc().init()
|
|
251
302
|
request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
|
|
252
303
|
if hasattr(request, "setRecognitionLanguages_"):
|
|
253
|
-
request.setRecognitionLanguages_(list(languages))
|
|
304
|
+
request.setRecognitionLanguages_(list(_supported_languages(request, languages)))
|
|
254
305
|
request.setUsesLanguageCorrection_(language_correction)
|
|
255
306
|
request.setMinimumTextHeight_(min_height)
|
|
256
307
|
handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
|