noracu 0.2.6 → 0.3.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.
@@ -339,12 +339,13 @@ def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=
339
339
  # a Top Hit card header near the top of the window (Spotlight's sits at ny ≈ 0.14; a
340
340
  # "Top Hit" line far down is no evidence), "none", or "unreadable"
341
341
  try:
342
- header = _tophit_header(read_screen())
342
+ hits = read_screen()
343
343
  except Exception as exc:
344
344
  if not verify.is_capture_error(exc):
345
345
  raise
346
346
  return "unreadable"
347
- return "card" if header is not None and header.ny < SPOTLIGHT_HEADER_MAX_NY else "none"
347
+ # 2026-11-08: or the top-field layout's field (a completion, or "Search or Ask")
348
+ return "card" if _spotlight_up(hits) else "none"
348
349
 
349
350
  before_home = card()
350
351
  if not home():
@@ -469,19 +470,36 @@ def choose_app_hit(hits: list, name: str, ambiguous: list | None = None) -> visi
469
470
  label inside the card → None: "not found" beats opening the
470
471
  wrong thing. Suggestion, website and Settings deep-link rows of
471
472
  the same name are never candidates.
473
+
474
+ 2026-11-08 (iOS 27 "Search or Ask"): Spotlight may put the search
475
+ field at the TOP and show no "Top Hit" header. Then the label band
476
+ under the field counts (more than TOP_FIELD_LABEL_MIN and at most
477
+ TOP_FIELD_CARD_SPAN below it: not the field line, not the Home Screen
478
+ showing through above the label, not the first section header) — but only when the field shows exactly ``name``
479
+ completed with "— Open" (OPEN_COMPLETION_ACTIONS): Spotlight's own
480
+ statement that its top result is something of that name that opens.
481
+ Any other completion, or none, → None.
472
482
  """
473
483
  want = _norm_label(name)
474
484
  header = _tophit_header(hits)
475
- if header is None:
476
- return None
485
+ if header is not None:
486
+ lo, hi = header.ny, header.ny + TOP_HIT_CARD_SPAN
487
+ else:
488
+ # 2026-11-08, top-field layout: no "Top Hit" header. Only when the field itself
489
+ # completes the exact name with "— Open" is the block right under it the top result;
490
+ # the field line (and any part of it OCR split off) is never a candidate.
491
+ field = _top_field_for(hits, name)
492
+ if field is None or field[1] not in OPEN_COMPLETION_ACTIONS:
493
+ return None
494
+ lo, hi = field[0] + TOP_FIELD_LABEL_MIN, field[0] + TOP_FIELD_CARD_SPAN
477
495
  found = []
478
496
  for hit in hits:
479
497
  if _norm_label(hit.text) != want:
480
498
  continue
481
499
  if hit.ny >= SEARCH_FIELD_NY:
482
500
  continue # the search field echoing the query
483
- if not header.ny < hit.ny <= header.ny + TOP_HIT_CARD_SPAN:
484
- continue # outside the Top Hit card (F35)
501
+ if not lo < hit.ny <= hi:
502
+ continue # outside the Top Hit card (F35) / the block under the top field
485
503
  found.append(hit)
486
504
  if not found:
487
505
  return None
@@ -592,6 +610,27 @@ def _tophit_labels(raw):
592
610
  TOP_HIT_LABELS = _tophit_labels(os.environ.get("NORACU_TOPHIT_LABELS"))
593
611
 
594
612
 
613
+ # NORACU_OCR_MIN_CONFIDENCE (opt-in, off by default): phone_open does not tap a label the
614
+ # recognizer read with a lower confidence than this. Unset or empty: no label is refused on its
615
+ # confidence. Set to anything but a number above 0 and at most 1 (text, 0, 90, nan): the person
616
+ # meant a check to be on and it cannot be, so phone_open refuses (cli._cmd_open) rather than run
617
+ # without it. → (minimum or None, the unusable text or None)
618
+ def _min_confidence(raw):
619
+ text = (raw or "").strip()
620
+ if not text:
621
+ return None, None
622
+ try:
623
+ value = float(text)
624
+ except ValueError:
625
+ return None, text
626
+ if math.isfinite(value) and 0.0 < value <= 1.0:
627
+ return value, None
628
+ return None, text
629
+
630
+
631
+ OCR_MIN_CONFIDENCE, OCR_MIN_CONFIDENCE_PROBLEM = _min_confidence(os.environ.get("NORACU_OCR_MIN_CONFIDENCE"))
632
+
633
+
595
634
  def _field_echo(hits, name) -> bool:
596
635
  """True when the search field shows ``name`` (F42).
597
636
 
@@ -609,6 +648,89 @@ def _field_echo(hits, name) -> bool:
609
648
  # the magnifier glyph may come back as "Q", "Q." or "Q:" in front of the text
610
649
  if _echo_matches(got, want) or _echo_matches(re.sub(r"^q[\s.,:;·•]*", "", got, count=1), want):
611
650
  return True
651
+ # 2026-11-08: the top-field layout echoes the query at the top, often with a completion
652
+ # ("Calculator — Open"); the query part alone is compared, with the same OCR-slip tolerance
653
+ return any(_echo_matches(query, want) for _, query, _a in _top_field_lines(hits))
654
+
655
+
656
+ # 2026-11-08 device run (iOS 27, the "Search or Ask" Spotlight): the search field can sit at the
657
+ # TOP of the window (ny ≈ 0.12). Typing an app's exact name then shows the query with an inline
658
+ # completion in the field — read as "Calculator -Open" — and the results start right under it with
659
+ # that app's icon and label (label at ny ≈ 0.28) under NO "Top Hit" header; the first section
660
+ # header ("Chrome", "Settings", …) follows at ny ≈ 0.32, and a Settings row of the same name lower
661
+ # down (ny ≈ 0.49). phone_open's every read failed there: no header, and the bottom-field echo
662
+ # never matched (0.2.6 failed the same way). The field's own completion is the evidence this layout
663
+ # offers: "<name> — Open" says Spotlight's top result is something named <name> that opens.
664
+ TOP_FIELD_MAX_NY = 0.16 # the top search field line (measured 0.12)
665
+ TOP_FIELD_LINE_EPS = 0.02 # hits this close to the field line are parts of it (OCR may split it)
666
+ # the top result's label band under the field: label measured at +0.16, the first section header at
667
+ # +0.20, and the dimmed Home Screen behind the panel shows through above the label (a widget's
668
+ # "SUNDAY" at +0.06). Only (field + TOP_FIELD_LABEL_MIN, field + TOP_FIELD_CARD_SPAN] counts, so
669
+ # neither that background text nor a section header that carries the app's name ("Chrome" over
670
+ # Chrome's own results) is ever a candidate.
671
+ TOP_FIELD_LABEL_MIN = 0.10
672
+ TOP_FIELD_CARD_SPAN = 0.18
673
+ OPEN_COMPLETION_ACTIONS = ("open",) # the completion word that marks something that opens (English)
674
+ # completion words that also show Spotlight is up (a previous query that was no app: "— Ask Siri")
675
+ SPOTLIGHT_UP_ACTIONS = OPEN_COMPLETION_ACTIONS + ("ask siri",)
676
+ # the dash needs whitespace on at least one side: OCR reads the completion as "Calculator -Open" or
677
+ # "zq7pdcan- Ask Siri" (both seen on the device); a hyphen inside a name ("Wi-Fi") has none
678
+ _COMPLETION = re.compile(r"^(?P<q>.*\S)(?:\s+[—–-]\s*|[—–-]\s+)(?P<a>\S.*)$")
679
+
680
+
681
+ def _top_field_lines(hits):
682
+ """(ny, query, action) for each line in the top search-field zone: the hits within
683
+ TOP_FIELD_LINE_EPS of each other joined left to right, split at a " — <action>" completion
684
+ (action None without one). Query and action are _norm_label'ed."""
685
+ top = sorted((h for h in hits if h.ny < TOP_FIELD_MAX_NY), key=lambda h: (h.ny, h.nx))
686
+ lines, used = [], set()
687
+ for i, h in enumerate(top):
688
+ if i in used:
689
+ continue
690
+ group = [j for j in range(i, len(top)) if j not in used and abs(top[j].ny - h.ny) <= TOP_FIELD_LINE_EPS]
691
+ used.update(group)
692
+ text = " ".join(top[j].text for j in sorted(group, key=lambda j: top[j].nx))
693
+ m = _COMPLETION.match(unicodedata.normalize("NFKC", text).strip())
694
+ if m:
695
+ lines.append((h.ny, _norm_label(m.group("q")), _norm_label(m.group("a"))))
696
+ else:
697
+ lines.append((h.ny, _norm_label(text), None))
698
+ return lines
699
+
700
+
701
+ def _top_field_for(hits, name):
702
+ """(ny, action) of the top search field when it shows ``name`` (exactly, after _norm_label),
703
+ with or without a completion; None otherwise."""
704
+ want = _norm_label(name)
705
+ for ny, query, action in _top_field_lines(hits):
706
+ if query == want:
707
+ return ny, action
708
+ return None
709
+
710
+
711
+ def _spotlight_up(hits, name=None) -> bool:
712
+ """Spotlight is on screen: a "Top Hit" header near the top, or (top-field layout) the empty
713
+ field's "Search or Ask", or a field line completed with a SPOTLIGHT_UP_ACTIONS word whose
714
+ query is exactly ``name`` — or, without a name (the F43 check), completed with "Open" AND
715
+ with that query's label in the label band under it. Any other line in that zone (the
716
+ notification strip: a banner can read "X - Y" or even "X - Open") is no evidence."""
717
+ header = _tophit_header(hits)
718
+ if header is not None and header.ny < SPOTLIGHT_HEADER_MAX_NY:
719
+ return True
720
+ want = None if name is None else _norm_label(name)
721
+ for ny, query, action in _top_field_lines(hits):
722
+ if query == "search or ask":
723
+ return True
724
+ if want is not None:
725
+ if action in SPOTLIGHT_UP_ACTIONS and query == want:
726
+ return True
727
+ elif action in OPEN_COMPLETION_ACTIONS and any(
728
+ _norm_label(h.text) == query and ny + TOP_FIELD_LABEL_MIN < h.ny <= ny + TOP_FIELD_CARD_SPAN
729
+ for h in hits):
730
+ # without a name to match (the F43 check after Home), an "Open" completion counts
731
+ # only with Spotlight's own structure under it — that query's label in the label band;
732
+ # a banner that happens to read "Calendar - Open" has none
733
+ return True
612
734
  return False
613
735
 
614
736
 
@@ -636,7 +758,7 @@ def home_via_menu(timeout: float = TIDY_OSASCRIPT_TIMEOUT_S) -> bool:
636
758
  return _run_view_menu_command("Home Screen", timeout=timeout)
637
759
 
638
760
 
639
- def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
761
+ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen, name=None):
640
762
  """Tap (nx, ny) and confirm the app actually opened (F24 ②).
641
763
 
642
764
  One luma frame before the tap, one after a 1.0s settle, then one
@@ -654,8 +776,10 @@ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
654
776
  sleep(1.0)
655
777
  after = luma()
656
778
  hits = read_screen()
779
+ # 2026-11-08: Spotlight still up in either layout (a Top Hit header near the top, or the top
780
+ # field with its completion / "Search or Ask") means the tap did not open anything
657
781
  opened = (verify.mean_abs_diff(before, after) >= OPEN_MIN_DIFF
658
- and _tophit_header(hits) is None)
782
+ and _tophit_header(hits) is None and not _spotlight_up(hits, name))
659
783
  return opened, hits
660
784
 
661
785
 
@@ -731,8 +855,14 @@ def open_app(name: str, *, spotlight_open: bool = False,
731
855
  "deadline" (the OPEN_DEADLINE_S budget ran out before a tap; back on
732
856
  the Home Screen); "ambiguous" (Y6: the Top Hit card showed the name at
733
857
  two or more spots and no read showed it at one — nothing was tapped;
734
- back on the Home Screen); or "spotlight_unavailable" (Spotlight could
735
- not be opened; nothing was typed or tapped).
858
+ back on the Home Screen); "low_confidence" (NORACU_OCR_MIN_CONFIDENCE is set and the label was read below it: nothing tapped; back on the Home Screen); "focus_lost" (another app came to the front
859
+ during type_text's wait after the clipboard write: the paste was called
860
+ off and nothing was tapped; Spotlight is left as it is — going Home
861
+ would pull the mirror forward again); "clipboard_changed" (another app or
862
+ device wrote the clipboard before ⌘V: nothing was pasted or tapped, the
863
+ new clipboard is left alone; back on the Home Screen); or
864
+ "spotlight_unavailable" (Spotlight could not be opened; nothing was
865
+ typed or tapped).
736
866
 
737
867
  ``read_screen`` (default vision.read_screen), ``luma`` (default
738
868
  verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
@@ -809,7 +939,21 @@ def open_app(name: str, *, spotlight_open: bool = False,
809
939
  return "deadline"
810
940
  clear_text() # iOS kept the last query; new input would append (F17)
811
941
  sleep(0.3)
812
- typed = type_text(name)
942
+ try:
943
+ typed = type_text(name)
944
+ except inp.PasteFocusLost:
945
+ # 0.2.7: another app came to the front during the wait after the clipboard write;
946
+ # the paste was called off. No trip Home: that would pull the mirror forward again, the
947
+ # very thing the paste refused to do (Spotlight closes by itself when left idle).
948
+ return "focus_lost"
949
+ except inp.ClipboardChanged:
950
+ # another app or device wrote the clipboard before ⌘V: nothing was pasted and their
951
+ # clipboard is left alone. Tidy up only while the mirror is still in front — if the
952
+ # user also moved away, going Home would pull it forward: report focus_lost instead
953
+ if not inp._focus_check():
954
+ return "focus_lost"
955
+ tidy()
956
+ return "clipboard_changed"
813
957
  sleep(1.5) # wait for Spotlight results
814
958
  hit = None
815
959
  if typed is not False:
@@ -889,12 +1033,19 @@ def open_app(name: str, *, spotlight_open: bool = False,
889
1033
  if out_of_time():
890
1034
  tidy()
891
1035
  return "deadline"
1036
+ if report is not None:
1037
+ # how sure the recognizer was of the label about to be tapped, and the opt-in minimum
1038
+ report["confidence"] = hit.confidence
1039
+ report["min_confidence"] = OCR_MIN_CONFIDENCE
1040
+ if OCR_MIN_CONFIDENCE is not None and not (hit.confidence >= OCR_MIN_CONFIDENCE):
1041
+ tidy()
1042
+ return "low_confidence" # opt-in: a label read below the minimum is not tapped
892
1043
  # ② tap the row (the label inside the Top Hit card) and confirm.
893
1044
  # The post-tap read uses reread(): for a short name it also sweeps,
894
1045
  # so ③ can find the label again (F32/F35).
895
1046
  opened, hits = _tap_and_confirm_open(
896
1047
  hit.nx, hit.ny, luma=luma, sleep=sleep, tap=tap,
897
- read_screen=reread)
1048
+ read_screen=reread, name=name)
898
1049
  if opened:
899
1050
  return "opened"
900
1051
 
@@ -903,10 +1054,15 @@ def open_app(name: str, *, spotlight_open: bool = False,
903
1054
  # card NOW (choose_app_hit, F35) — never the first read's position:
904
1055
  # the results may have changed. No such label → no second tap.
905
1056
  again = choose_app_hit(hits, name)
1057
+ if (again is not None and OCR_MIN_CONFIDENCE is not None
1058
+ and not (again.confidence >= OCR_MIN_CONFIDENCE)):
1059
+ again = None # opt-in: no second tap aimed at a label read below the minimum
906
1060
  if again is not None and not out_of_time():
1061
+ if report is not None:
1062
+ report["confidence"] = again.confidence
907
1063
  opened, _ = _tap_and_confirm_open(
908
1064
  again.nx, again.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
909
- luma=luma, sleep=sleep, tap=tap, read_screen=reread)
1065
+ luma=luma, sleep=sleep, tap=tap, read_screen=reread, name=name)
910
1066
  if opened:
911
1067
  return "opened"
912
1068
  except Exception as exc:
@@ -43,11 +43,20 @@ from Quartz import (
43
43
  CGEventSetFlags,
44
44
  )
45
45
 
46
- from . import window
46
+ from . import pointer, window
47
47
  from .window import WindowBounds, ensure_frontmost, get_bounds
48
48
 
49
49
  TAP_INTERVAL_S = 0.05
50
50
  LONG_PRESS_S = 0.8
51
+ # Device run 2026-11-07/08 (macOS 27.2): iPhone Mirroring pastes
52
+ # through Universal Clipboard, which tells the phone about new Mac clipboard content
53
+ # asynchronously. Once in about 30 pastes (23:33, Cmd+V ~0.5 s after the write) the phone pasted
54
+ # the text the Mac clipboard held BEFORE the write; shell pastes 0.4-3.4 s after the write landed
55
+ # 23/23 the same night, so the race is rare. type_text waits this long between its write and
56
+ # Cmd+V to narrow it. The value is a judgement, not a measured threshold, and it does not close
57
+ # the race. It does not address the other failure seen (the phone shows "Pasting from ..." and
58
+ # then pastes nothing), whose cause is not established.
59
+ PASTE_SETTLE_S = 1.5
51
60
  SWIPE_STEPS = 20
52
61
  SWIPE_NUDGE_PX = 3
53
62
  SWIPE_DEFAULT_MS = 300
@@ -67,6 +76,13 @@ class FocusLost(InputError):
67
76
  """
68
77
 
69
78
 
79
+ class PasteFocusLost(FocusLost):
80
+ """type_text's Cmd+V was called off: another app came to the front during
81
+ the wait after the clipboard write. Nothing was pasted (a replace's Cmd+A
82
+ had already been sent), and the clipboard went back under the changeCount
83
+ rule. Raised instead of bringing iPhone Mirroring forward again."""
84
+
85
+
70
86
  # F26: consulted right before every synthesized event. Module-level so
71
87
  # tests can swap it; window.is_frontmost asks System Events afresh on
72
88
  # every call (F30: an in-process NSWorkspace answer is a stale snapshot).
@@ -139,6 +155,7 @@ def _mouse_event(kind: int, x: float, y: float, source) -> None:
139
155
  if event is None:
140
156
  raise InputError(f"CGEventCreateMouseEvent returned None for {kind}")
141
157
  CGEventPost(kCGHIDEventTap, event)
158
+ pointer.moved_to(x, y) # 0.2.7: the CLI puts the pointer back after the command
142
159
 
143
160
 
144
161
  def _key_event(keycode: int, down: bool, source) -> None:
@@ -215,6 +232,20 @@ def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_
215
232
  _mouse_event(kCGEventLeftMouseUp, x, y, src)
216
233
 
217
234
 
235
+ # 2026-11-10: every point of a phone_swipe stays this far inside the phone screen (verify.screen_rect),
236
+ # in window units (0.01 is about 6 pt of a 620 pt window), because iOS cancels a drag that starts or
237
+ # ends on the transparent window margin around the screen.
238
+ SCREEN_INSET = 0.01
239
+
240
+
241
+ def clamp_to_rect(nx: float, ny: float, rect, inset: float = SCREEN_INSET) -> tuple[float, float]:
242
+ """Move (nx, ny) to the nearest point at least `inset` inside rect = (x0, y0, x1, y1)."""
243
+ x0, y0, x1, y1 = rect
244
+ if x1 - x0 <= 2 * inset or y1 - y0 <= 2 * inset:
245
+ raise ValueError(f"phone screen rect too small to swipe in: {rect!r}")
246
+ return (min(max(nx, x0 + inset), x1 - inset), min(max(ny, y0 + inset), y1 - inset))
247
+
248
+
218
249
  def _ease_in_out(t: float) -> float:
219
250
  """Quadratic ease-in-out: slow start, fast middle, slow end."""
220
251
  if t < 0.5:
@@ -361,7 +392,7 @@ def check_chord_layout(keycode: int) -> None:
361
392
  "switch the Mac to a QWERTY-style input source (U.S., ABC, Pinyin) and retry")
362
393
 
363
394
 
364
- def _cmd_chord(keycode: int, before_key=None) -> None:
395
+ def _cmd_chord(keycode: int, before_key=None, activate: bool = True) -> None:
365
396
  """Send a real Command chord: ⌘ down → key down → key up → ⌘ up.
366
397
 
367
398
  iPhone Mirroring forwards the *state* of the physical modifier
@@ -375,9 +406,16 @@ def _cmd_chord(keycode: int, before_key=None) -> None:
375
406
  ``before_key`` runs after the focus checks, right before the first
376
407
  event: the caller's last chance to call the chord off by raising —
377
408
  nothing is posted then (F35).
409
+
410
+ ``activate=False``: never bring iPhone Mirroring forward — when another
411
+ app is frontmost, raise FocusLost before anything is posted. type_text's
412
+ ⌘V uses it: by then the user may have moved to another app during the
413
+ wait after the clipboard write, and pulling the mirror back would send
414
+ the paste (and their next keystrokes) to the phone.
378
415
  """
379
416
  check_chord_layout(keycode) # review 0.2.6 #5: before anything is sent
380
- ensure_frontmost()
417
+ if activate:
418
+ ensure_frontmost()
381
419
  _require_focus() # F26: before the chord's first event
382
420
  if before_key is not None:
383
421
  before_key()
@@ -564,7 +602,8 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
564
602
  sleep=time.sleep, clock=time.monotonic,
565
603
  timeout_s: float = 2.5, poll_s: float = 0.15,
566
604
  min_hold_s: float = 0.3, pending: list | None = None,
567
- report: dict | None = None, restore: bool = True) -> bool:
605
+ report: dict | None = None, restore: bool = True,
606
+ settle_s: float = PASTE_SETTLE_S) -> bool:
568
607
  """Type text via clipboard paste (IME-safe), confirmed on screen.
569
608
 
570
609
  Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
@@ -635,7 +674,8 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
635
674
  search-history chip with the same query, an older message) licensed a
636
675
  restore at once, and a paste that the phone read late could then paste
637
676
  the user's ORIGINAL clipboard. The default checks now count the text's
638
- probe before the pasteboard write — the higher of two reads 0.3 s
677
+ probe right before Cmd+V (after the pasteboard write and the
678
+ ``settle_s`` wait) — the higher of two reads 0.3 s
639
679
  apart, so a read that misses an occurrence cannot fake a rise — and
640
680
  license a restore only when the count RISES over it, in two reads 0.3 s
641
681
  apart. Without a pre-paste count (a read failed) OCR never licenses a
@@ -644,6 +684,18 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
644
684
  count as ``count_before`` (None: unknown), for a caller that keeps
645
685
  watching after a False result.
646
686
 
687
+ ``settle_s`` (device run 2026-11-07/08): the wait between writing the
688
+ pasteboard and Cmd+V. The phone reads the Mac clipboard through Universal
689
+ Clipboard, which announces new content asynchronously; a Cmd+V that
690
+ arrives first pastes the phone's OWN clipboard (an older paste, or
691
+ something copied on the phone) instead of ``text``. The wait lowers that
692
+ chance; it cannot rule it out, so an unconfirmed paste is still reported
693
+ as unconfirmed and the caller reads the field. The pre-paste reads come
694
+ after the wait, so the write-to-Cmd+V time is ``settle_s`` plus those
695
+ reads. Cmd+V never brings iPhone Mirroring back to the front: when
696
+ another app took it during the wait, FocusLost (nothing pasted; the
697
+ clipboard goes back under the changeCount rule).
698
+
647
699
  ``restore=False``: once Cmd+V may be on its way the user's clipboard is
648
700
  never put back — no restore here and no PendingRestore — and it keeps
649
701
  ``text``; only an error before Cmd+V still restores it. open_app uses
@@ -683,8 +735,21 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
683
735
  check_chord_layout(_VK_A)
684
736
  check_chord_layout(_VK_V)
685
737
  ensure_frontmost()
738
+ default_chord = chord is None
686
739
  if chord is None:
687
740
  chord = _cmd_chord
741
+
742
+ def paste_chord(keycode, before_key=None):
743
+ # the ⌘V after the wait never re-activates the mirror: PasteFocusLost instead
744
+ # (_cmd_chord raises FocusLost only before its first event)
745
+ try:
746
+ return _cmd_chord(keycode, before_key=before_key, activate=False)
747
+ except PasteFocusLost:
748
+ raise
749
+ except FocusLost as exc:
750
+ raise PasteFocusLost(str(exc)) from exc
751
+ else:
752
+ paste_chord = chord # injected (tests): one chord for both keys
688
753
  if pasteboard is None:
689
754
  pasteboard = NSPasteboard.generalPasteboard()
690
755
  # F27: a single character is invisible to the default OCR probe
@@ -788,12 +853,40 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
788
853
  chord(_VK_A) # select the focused field's content first (see docstring)
789
854
  sleep(0.05)
790
855
 
856
+ # the change count first: a copy that lands while the clipboard is being saved must not be
857
+ # overwritten by our write
858
+ saved_change = pasteboard.changeCount()
859
+ saved = save_pasteboard(pasteboard)
860
+ if pasteboard.changeCount() != saved_change:
861
+ saved_change = None # nothing of ours to undo
862
+ raise ClipboardChanged(
863
+ "another app or device changed the clipboard while it was being saved; "
864
+ "nothing was typed and the clipboard was left as it is")
865
+
866
+ pasteboard.clearContents()
867
+ pasteboard.setString_forType_(text, "public.utf8-plain-text")
868
+ # Device run 2026-11-07/08: let Universal Clipboard tell the phone about the new content
869
+ # before Cmd+V (PASTE_SETTLE_S). The pre-paste reads, the "before" frame, the chord's
870
+ # focus check and last_check (the changeCount guard) all come after the wait, so each
871
+ # describes the moment right before Cmd+V.
872
+ sleep(max(0.05, settle_s))
873
+ # 0.2.7: the wait is when someone copies something or moves to another app (or Space):
874
+ # say so now, before any screen read — the same checks run again right before Cmd+V
875
+ # focus first: when both happened, the user moved away — a caller must not take the
876
+ # clipboard change for a reason to bring the mirror forward again (open_app tidies on it)
877
+ if default_chord and not _focus_check():
878
+ raise PasteFocusLost("iPhone Mirroring is not the frontmost app")
879
+ if pasteboard.changeCount() != saved_change + 1:
880
+ raise ClipboardChanged(
881
+ "another app or device changed the clipboard during the wait before the paste; "
882
+ "nothing was typed and the clipboard was left as it is")
883
+
791
884
  if pre_read:
792
885
  # F27: the pre-paste sweep for a single character, taken on a
793
886
  # still screen only (a mid-transition read could miss a label
794
887
  # that is already there and later pass it off as the paste).
795
- # It runs before the pasteboard write so the stretch between our
796
- # write and Cmd+V (F35) stays short.
888
+ # Taken after the clipboard write and the wait (0.2.7), so
889
+ # the baseline is the screen right before Cmd+V.
797
890
  try:
798
891
  if verify.wait_still(sleep=sleep, clock=clock):
799
892
  sweep_before[0] = sweep_read()
@@ -807,6 +900,9 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
807
900
  # 0.3 s apart (a redraw or the select-all highlight can hide an
808
901
  # occurrence from one read). A capture failure in either leaves it
809
902
  # unknown: then OCR can never license a restore for this paste.
903
+ # 0.2.7: read after the clipboard write and the wait, so
904
+ # text that appears during the wait is part of the baseline and
905
+ # can never pass for the paste (a restore license).
810
906
  try:
811
907
  r1 = vision.read_screen()
812
908
  first = verify.probe_count(text, r1)
@@ -824,21 +920,14 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
824
920
  if report is not None:
825
921
  report["count_before"] = count_before[0]
826
922
 
827
- # the change count first: a copy that lands while the clipboard is being saved must not be
828
- # overwritten by our write
829
- saved_change = pasteboard.changeCount()
830
- saved = save_pasteboard(pasteboard)
831
- if pasteboard.changeCount() != saved_change:
832
- saved_change = None # nothing of ours to undo
833
- raise ClipboardChanged(
834
- "another app or device changed the clipboard while it was being saved; "
835
- "nothing was typed and the clipboard was left as it is")
836
-
837
- pasteboard.clearContents()
838
- pasteboard.setString_forType_(text, "public.utf8-plain-text")
839
- sleep(0.05)
840
-
841
- changed = before_check()
923
+ try:
924
+ changed = before_check()
925
+ except Exception as exc:
926
+ # the mirror window left the screen during the reads (another Space came to the
927
+ # front): that is the user moving away, not a broken capture — call the paste off
928
+ if default_chord and verify.is_capture_error(exc) and not _focus_check():
929
+ raise PasteFocusLost("iPhone Mirroring is not the frontmost app") from exc
930
+ raise
842
931
 
843
932
  def last_check():
844
933
  # F35: the last look at the pasteboard, after the chord's focus
@@ -853,7 +942,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
853
942
  sent[0] = True
854
943
 
855
944
  # real ⌘ chord — flags alone reach the phone as "v" (F14)
856
- chord(_VK_V, before_key=last_check)
945
+ paste_chord(_VK_V, before_key=last_check) # never re-activates the mirror after the wait
857
946
  t0 = clock()
858
947
 
859
948
  # landed: did the paste show up on screen? (decides the return
@@ -0,0 +1,81 @@
1
+ """Put the Mac pointer back after a phone gesture (0.2.7, a Mac shared with a person).
2
+
3
+ A tap, swipe, long press or scroll moves the real pointer onto the mirror
4
+ window (a mouse event with a location moves it). When the Mac is shared
5
+ (NORACU_USER_IDLE_S is not 0 — the same variable and rule as the noracu
6
+ server), the CLI remembers where the pointer was before a command and, after
7
+ it, warps it back — only when the pointer is still where noracu's own last
8
+ event left it: if someone moved it meanwhile, it stays where they put it.
9
+ A warp posts no event (the person's idle time is not reset by it).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import re
16
+ import time
17
+
18
+ _home = None # where the pointer was before the command (None: not tracking)
19
+ _last = None # where noracu's last mouse event put it (None: no mouse event yet)
20
+
21
+
22
+ def enabled() -> bool:
23
+ """Off only for a plain zero ("0", "0.0"), like the server; unset or unreadable means on."""
24
+ raw = os.environ.get("NORACU_USER_IDLE_S", "").strip()
25
+ return not re.fullmatch(r"0+(\.0+)?", raw)
26
+
27
+
28
+ def _where():
29
+ try:
30
+ import Quartz # type: ignore
31
+
32
+ ev = Quartz.CGEventCreate(None)
33
+ if ev is None:
34
+ return None
35
+ p = Quartz.CGEventGetLocation(ev)
36
+ return (float(p.x), float(p.y))
37
+ except Exception:
38
+ return None
39
+
40
+
41
+ def _warp(p) -> None:
42
+ import Quartz # type: ignore
43
+
44
+ Quartz.CGWarpMouseCursorPosition(p)
45
+ Quartz.CGAssociateMouseAndMouseCursorPosition(True)
46
+
47
+
48
+ def remember() -> None:
49
+ """Called once before a command runs."""
50
+ global _home, _last
51
+ _last = None
52
+ _home = _where() if enabled() else None
53
+
54
+
55
+ def moved_to(x: float, y: float) -> None:
56
+ """Called after every mouse event noracu posts."""
57
+ global _last
58
+ _last = (float(x), float(y))
59
+
60
+
61
+ def restore() -> bool:
62
+ """Called once after a command (also after an error). True when the pointer was put back."""
63
+ global _home, _last
64
+ home, last = _home, _last
65
+ _home = _last = None
66
+ if home is None or last is None:
67
+ return False
68
+ def still_ours() -> bool:
69
+ now = _where()
70
+ return now is not None and abs(now[0] - last[0]) <= 2 and abs(now[1] - last[1]) <= 2
71
+
72
+ if not still_ours():
73
+ return False # someone moved it: leave it where they put it
74
+ try:
75
+ time.sleep(0.1) # let the last posted events reach the mirror before the pointer leaves it
76
+ if not still_ours():
77
+ return False # moved during that wait
78
+ _warp(home)
79
+ return True
80
+ except Exception:
81
+ return False