noracu 0.3.0 → 0.3.2

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.
@@ -48,6 +48,8 @@ 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
+ # a hold longer than this looks at the frontmost app again every so often (a long press may last 10 s)
52
+ LONG_PRESS_CHECK_S = 1.0
51
53
  # Device run 2026-11-07/08 (macOS 27.2): iPhone Mirroring pastes
52
54
  # through Universal Clipboard, which tells the phone about new Mac clipboard content
53
55
  # asynchronously. Once in about 30 pastes (23:33, Cmd+V ~0.5 s after the write) the phone pasted
@@ -67,7 +69,7 @@ class InputError(RuntimeError):
67
69
 
68
70
 
69
71
  class FocusLost(InputError):
70
- """Raised when iPhone Mirroring stopped being the frontmost app (F26).
72
+ """Raised when iPhone Mirroring stopped being the frontmost app.
71
73
 
72
74
  The frontmost check runs right before every synthesized event; a
73
75
  keystroke landing in whatever app took the foreground in the meantime
@@ -83,14 +85,14 @@ class PasteFocusLost(FocusLost):
83
85
  rule. Raised instead of bringing iPhone Mirroring forward again."""
84
86
 
85
87
 
86
- # F26: consulted right before every synthesized event. Module-level so
88
+ # Consulted right before every synthesized event. Module-level so
87
89
  # tests can swap it; window.is_frontmost asks System Events afresh on
88
- # every call (F30: an in-process NSWorkspace answer is a stale snapshot).
90
+ # every call (an in-process NSWorkspace answer is a stale snapshot).
89
91
  _focus_check = window.is_frontmost
90
92
 
91
93
 
92
94
  def _require_focus() -> None:
93
- """Refuse to send any event unless iPhone Mirroring is still frontmost (F26)."""
95
+ """Refuse to send any event unless iPhone Mirroring is still frontmost."""
94
96
  if not _focus_check():
95
97
  raise FocusLost("iPhone Mirroring is not the frontmost app")
96
98
 
@@ -114,7 +116,7 @@ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
114
116
  """Scroll like a two-finger trackpad swipe: continuous wheel events with phases.
115
117
 
116
118
  iPhone Mirroring turns these into a touch scroll of the list under the cursor
117
- (F16: a mouse drag scrolls nothing in a list, and a bare wheel event without a
119
+ (a mouse drag scrolls nothing in a list, and a bare wheel event without a
118
120
  phase is ignored). Negative total_px moves the content up, revealing what is
119
121
  below. The cursor is moved over the mirror first, because scroll events go to
120
122
  the window under the cursor.
@@ -123,9 +125,12 @@ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
123
125
  b = bounds or get_bounds()
124
126
  x, y = b.denormalize(nx, ny)
125
127
  src = _source()
126
- _require_focus() # F26: before the first event
128
+ _require_focus() # before the first event
127
129
  _mouse_event(kCGEventMouseMoved, x, y, src)
128
130
  time.sleep(0.12)
131
+ # that pause is long enough for another app to come to the front, with its window under the
132
+ # pointer: look again before the first wheel event, not only after the fifth
133
+ _require_focus()
129
134
  deltas = scroll_steps(total_px)
130
135
  last = len(deltas) - 1
131
136
  sent = 1 # events posted so far (the mouse-moved above)
@@ -134,7 +139,7 @@ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
134
139
  try:
135
140
  for i, d in enumerate(deltas):
136
141
  if sent % 6 == 0:
137
- _require_focus() # F26: every 6 events; drop the rest on focus loss
142
+ _require_focus() # every 6 events; drop the rest on focus loss
138
143
  phase = 1 if i == 0 else (4 if i == last else 2)
139
144
  _scroll_event(src, d, x, y, phase)
140
145
  if phase == 1:
@@ -162,6 +167,10 @@ def _key_event(keycode: int, down: bool, source) -> None:
162
167
  event = CGEventCreateKeyboardEvent(source, keycode, down)
163
168
  if event is None:
164
169
  raise InputError(f"CGEventCreateKeyboardEvent returned None for {keycode}")
170
+ # A key pressed by itself (Return, Delete, an arrow) carries no modifier. The event source is the
171
+ # HID state, so without this a modifier held on the Mac's keyboard at that moment rides along:
172
+ # with ⌘ down, Delete goes out as ⌘Delete.
173
+ CGEventSetFlags(event, 0)
165
174
  CGEventPost(kCGHIDEventTap, event)
166
175
 
167
176
 
@@ -197,7 +206,7 @@ def tap(nx: float = 0.5, ny: float = 0.5, bounds: WindowBounds | None = None) ->
197
206
  b = bounds or get_bounds()
198
207
  x, y = b.denormalize(nx, ny)
199
208
  src = _source()
200
- _require_focus() # F26: before the first event
209
+ _require_focus() # before the first event
201
210
  _mouse_event(kCGEventLeftMouseDown, x, y, src)
202
211
  try:
203
212
  time.sleep(TAP_INTERVAL_S)
@@ -224,10 +233,18 @@ def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_
224
233
  b = bounds or get_bounds()
225
234
  x, y = b.denormalize(nx, ny)
226
235
  src = _source()
227
- _require_focus() # F26: before the press-down
236
+ _require_focus() # before the press-down
228
237
  _mouse_event(kCGEventLeftMouseDown, x, y, src)
229
238
  try:
230
- time.sleep(duration_s)
239
+ # the button is not kept down under another app: when one comes to the front during a long hold,
240
+ # the hold ends there (FocusLost) and the finally below lets the button go
241
+ left = duration_s
242
+ while left > 0:
243
+ step = min(LONG_PRESS_CHECK_S, left)
244
+ time.sleep(step)
245
+ left -= step
246
+ if left > 0:
247
+ _require_focus()
231
248
  finally:
232
249
  _mouse_event(kCGEventLeftMouseUp, x, y, src)
233
250
 
@@ -270,7 +287,7 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
270
287
  src = _source()
271
288
  step_delay = (duration_ms / 1000.0) / SWIPE_STEPS
272
289
 
273
- _require_focus() # F26: before the first event
290
+ _require_focus() # before the first event
274
291
  cx, cy = x0, y0
275
292
  _mouse_event(kCGEventLeftMouseDown, cx, cy, src)
276
293
  try:
@@ -286,7 +303,7 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
286
303
 
287
304
  for i in range(1, SWIPE_STEPS + 1):
288
305
  if i % 5 == 0:
289
- _require_focus() # R18: a long swipe stops (and releases) when the mirror loses focus
306
+ _require_focus() # a long swipe stops (and releases) when the mirror loses focus
290
307
  t = i / SWIPE_STEPS
291
308
  e = _ease_in_out(t)
292
309
  nx = x0 + (x1 - x0) * e
@@ -305,7 +322,7 @@ def scroll(dy_pixels: int, nx: float = 0.5, ny: float = 0.5,
305
322
  b = bounds or get_bounds()
306
323
  x, y = b.denormalize(nx, ny)
307
324
  src = _source()
308
- _require_focus() # F26: before the only event
325
+ _require_focus() # before the only event
309
326
  # Axis 1 = vertical; pixel units; negative = scroll down (content up).
310
327
  _scroll_event(src, dy_pixels)
311
328
 
@@ -349,7 +366,7 @@ class KeyboardLayoutMismatch(InputError):
349
366
  Command chords are sent from ANSI key codes; iPhone Mirroring (a Mac
350
367
  app) reads its own key equivalents through the Mac's layout first. On
351
368
  French AZERTY key code 0 is "q": a ⌘A select-all would arrive as ⌘Q.
352
- Raised before anything is posted (review 0.2.6 #5).
369
+ Raised before anything is posted.
353
370
  """
354
371
 
355
372
 
@@ -398,14 +415,15 @@ def _cmd_chord(keycode: int, before_key=None, activate: bool = True) -> None:
398
415
  iPhone Mirroring forwards the *state* of the physical modifier
399
416
  keys, not the per-event flag bits: a target-key event that merely
400
417
  carries kCGEventFlagMaskCommand arrives on the phone as an
401
- unmodified keystroke (F14 — a "Cmd+V" paste typed a literal "v").
418
+ unmodified keystroke (a "Cmd+V" paste typed a literal "v").
402
419
  The chord therefore presses the Command key itself, keeps the
403
420
  flag set on every event, and releases Command last. ~30ms between
404
421
  steps, all events from one shared source.
405
422
 
406
423
  ``before_key`` runs after the focus checks, right before the first
407
424
  event: the caller's last chance to call the chord off by raising —
408
- nothing is posted then (F35).
425
+ nothing is posted then. The focus is looked at once more between ⌘ down
426
+ and the key: lost there, ⌘ is released and no key is sent.
409
427
 
410
428
  ``activate=False``: never bring iPhone Mirroring forward — when another
411
429
  app is frontmost, raise FocusLost before anything is posted. type_text's
@@ -413,10 +431,10 @@ def _cmd_chord(keycode: int, before_key=None, activate: bool = True) -> None:
413
431
  wait after the clipboard write, and pulling the mirror back would send
414
432
  the paste (and their next keystrokes) to the phone.
415
433
  """
416
- check_chord_layout(keycode) # review 0.2.6 #5: before anything is sent
434
+ check_chord_layout(keycode) # before anything is sent
417
435
  if activate:
418
436
  ensure_frontmost()
419
- _require_focus() # F26: before the chord's first event
437
+ _require_focus() # before the chord's first event
420
438
  if before_key is not None:
421
439
  before_key()
422
440
  src = _source()
@@ -431,6 +449,9 @@ def _cmd_chord(keycode: int, before_key=None, activate: bool = True) -> None:
431
449
  post(_VK_COMMAND, True, kCGEventFlagMaskCommand)
432
450
  try:
433
451
  time.sleep(0.03)
452
+ # the mirror can lose the front in these 30 ms: then no key goes out with ⌘ held — ⌘ is let go (finally)
453
+ # and FocusLost is raised, as before the chord's first event
454
+ _require_focus()
434
455
  post(keycode, True, kCGEventFlagMaskCommand)
435
456
  try:
436
457
  time.sleep(0.03)
@@ -448,7 +469,7 @@ def press_key(key: str) -> None:
448
469
  if key not in keymap:
449
470
  raise InputError(f"unsupported key: {key!r} (supported: {sorted(keymap)})")
450
471
  src = _source()
451
- _require_focus() # F26: before the key-down
472
+ _require_focus() # before the key-down
452
473
  _key_event(keymap[key], True, src)
453
474
  try:
454
475
  time.sleep(0.02)
@@ -458,7 +479,7 @@ def press_key(key: str) -> None:
458
479
 
459
480
  class ClipboardChanged(InputError):
460
481
  """Raised when something else wrote the pasteboard between type_text()'s
461
- own write and Cmd+V (F35): another app, or Universal Clipboard bringing
482
+ own write and Cmd+V: another app, or Universal Clipboard bringing
462
483
  a copy over from another device. Cmd+V would paste THEIR content into
463
484
  the phone, so nothing is sent and their newer content is left alone.
464
485
  """
@@ -532,6 +553,7 @@ def restore_pasteboard(pasteboard, saved) -> bool:
532
553
  """Put a save_pasteboard() snapshot back (the caller checked the
533
554
  changeCount). Returns False when it cannot be put back ("remote",
534
555
  "too_large"): then the clipboard is left holding the typed text.
556
+ False as well when the pasteboard refuses the write.
535
557
  Raw text data (bytes or None, the older snapshot) is accepted too."""
536
558
  if not isinstance(saved, tuple):
537
559
  saved = ("text", saved)
@@ -539,9 +561,10 @@ def restore_pasteboard(pasteboard, saved) -> bool:
539
561
  if kind in ("remote", "too_large"):
540
562
  return False
541
563
  pasteboard.clearContents()
564
+ # A write the pasteboard refuses (it answers NO) has not put anything back: that is "not restored".
542
565
  if kind == "text":
543
- if data is not None:
544
- pasteboard.setData_forType_(data, "public.utf8-plain-text")
566
+ if data is not None and pasteboard.setData_forType_(data, "public.utf8-plain-text") is False:
567
+ return False
545
568
  elif kind == "items" and data:
546
569
  objs = []
547
570
  for rec in data:
@@ -549,12 +572,21 @@ def restore_pasteboard(pasteboard, saved) -> bool:
549
572
  for t, d in rec:
550
573
  it.setData_forType_(d, t)
551
574
  objs.append(it)
552
- pasteboard.writeObjects_(objs)
575
+ if pasteboard.writeObjects_(objs) is False:
576
+ return False
553
577
  return True
554
578
 
555
579
 
580
+ def restore_failure(saved) -> str:
581
+ """Why restore_pasteboard(saved) answered False. "kept_text": the snapshot could not be taken (another
582
+ device's clipboard, or more than the size limit), so the clipboard was never cleared and still holds what
583
+ was written last — the typed text. "may_be_empty": it was cleared, then refused the write."""
584
+ kind = saved[0] if isinstance(saved, tuple) else "text"
585
+ return "kept_text" if kind in ("remote", "too_large") else "may_be_empty"
586
+
587
+
556
588
  class PendingRestore:
557
- """A clipboard restore type_text() could not license itself (F33).
589
+ """A clipboard restore type_text() could not license itself.
558
590
 
559
591
  Holds the user's saved clipboard after a one-character paste whose
560
592
  checks did not see the character arrive in time — on the device the
@@ -565,7 +597,7 @@ class PendingRestore:
565
597
  clipboard goes back, under the same changeCount rule as type_text().
566
598
  Nothing else restores it.
567
599
 
568
- Since review R38 (Andy's call, 2026-11-07) type_text() creates none: a
600
+ Since 2026-11-07 type_text() creates none: a
569
601
  one-character paste never puts the clipboard back. The class stays for
570
602
  its own tests and for open_app's offer loop, which still takes any
571
603
  PendingRestore an injected type_text hands over.
@@ -614,13 +646,13 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
614
646
  4. wait until the paste is visible on screen,
615
647
  5. only then restore the pasteboard.
616
648
 
617
- Step 4 yields two SEPARATE judgments (F18, tightened in G26b):
649
+ Step 4 yields two SEPARATE judgments:
618
650
 
619
651
  ``landed`` — did the paste show up? This decides the return
620
652
  value. The whole-window luma frame diff is the fast path; when
621
653
  it never fires within ``timeout_s``, a single OCR probe is the
622
654
  fallback. Either one confirms the paste (the frame diff not
623
- while the phone shows its paste-progress box — F44 below).
655
+ while the phone shows its paste-progress box — see below).
624
656
 
625
657
  ``restore_ok`` — may the user's clipboard be restored? ONLY an
626
658
  OCR hit grants this. The frame diff merely proves "the picture
@@ -650,7 +682,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
650
682
  the pasteboard at any moment, so the clipboard is NEVER restored
651
683
  after an error there and the original exception is re-raised.
652
684
 
653
- Capture failures are not errors (F25): when changed() or
685
+ Capture failures are not errors: when changed() or
654
686
  ocr_check() cannot get the mirroring window's pixels (window
655
687
  offscreen, blank transition frame, capture by id failed), that
656
688
  poll counts as "no change" and the OCR probe as "not seen" —
@@ -663,13 +695,13 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
663
695
  restored.
664
696
 
665
697
  ``replace=True`` sends Cmd+A before the paste, replacing the
666
- focused field's content. Like clear_text() (F17), Cmd+A targets
698
+ focused field's content. Like clear_text(), Cmd+A targets
667
699
  whatever field currently has focus on the phone: if the focus is
668
700
  not the intended input, this overwrites content elsewhere. Use it
669
701
  only when the caller has established the focus (e.g. guarded by
670
702
  a preceding expect/verify step).
671
703
 
672
- F41: for text of two or more characters the default OCR check used to
704
+ For text of two or more characters the default OCR check used to
673
705
  ask only "is the text on screen?" — so text that was already there (a
674
706
  search-history chip with the same query, an older message) licensed a
675
707
  restore at once, and a paste that the phone read late could then paste
@@ -699,11 +731,11 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
699
731
  ``restore=False``: once Cmd+V may be on its way the user's clipboard is
700
732
  never put back — no restore here and no PendingRestore — and it keeps
701
733
  ``text``; only an error before Cmd+V still restores it. open_app uses
702
- this (F42): a paste can reach the phone more than 10 s late, and
734
+ this: a paste can reach the phone more than 10 s late, and
703
735
  Spotlight can show the name in its own suggestions before that, so a
704
736
  licensed restore could still paste the user's clipboard into the search.
705
737
 
706
- F44: a paste the phone is slow to fetch puts up its "Pasting from <Mac>…"
738
+ A paste the phone is slow to fetch puts up its "Pasting from <Mac>…"
707
739
  progress box, and that box alone moves the frame diff. So when the frame
708
740
  diff fired but OCR did not see the text, ``hud_check`` (one more screen
709
741
  read) looks for the box: while it shows, the paste is still on its way —
@@ -715,10 +747,10 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
715
747
  this one or an earlier one, is still on its way and could fetch the
716
748
  restored clipboard — and the box's own words never count as the text.
717
749
 
718
- ``pending`` (F33): kept for callers that pass one, but nothing is
750
+ ``pending``: kept for callers that pass one, but nothing is
719
751
  appended to it any more. A one-character paste used to hand over a
720
- PendingRestore for a later restore on evidence; since Andy's call
721
- (2026-11-07, review R38) a one-character paste never puts the user's
752
+ PendingRestore for a later restore on evidence; since 2026-11-07
753
+ a one-character paste never puts the user's
722
754
  clipboard back, here or later — like a text of two or three
723
755
  characters, it leaves the clipboard holding ``text``.
724
756
 
@@ -729,7 +761,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
729
761
 
730
762
  from . import verify, vision
731
763
 
732
- # review 0.2.6 #5: both chords are checked against the Mac's keyboard layout before anything is
764
+ # both chords are checked against the Mac's keyboard layout before anything is
733
765
  # sent, the mirror is brought forward or the clipboard is touched (the chord checks again itself)
734
766
  if replace:
735
767
  check_chord_layout(_VK_A)
@@ -752,7 +784,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
752
784
  paste_chord = chord # injected (tests): one chord for both keys
753
785
  if pasteboard is None:
754
786
  pasteboard = NSPasteboard.generalPasteboard()
755
- # F27: a single character is invisible to the default OCR probe
787
+ # A single character is invisible to the default OCR probe
756
788
  # (screen_shows_text never matches it) and may already be on screen, so
757
789
  # the default checks wait for a still screen, read it with the
758
790
  # minimumTextHeight sweep before Cmd+V, and confirm the paste only when
@@ -760,17 +792,17 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
760
792
  # reads, looking for up to 4 s (the paste can land while Spotlight
761
793
  # redraws its results; the field echo blinks with the cursor). A screen
762
794
  # that never holds still gets no baseline and so no such sighting. Since
763
- # review R38 the sighting never licenses a restore: the clipboard keeps
795
+ # 2026-11-07 the sighting never licenses a restore: the clipboard keeps
764
796
  # holding ``text``.
765
797
  single = verify.is_short_text(text, limit=1)
766
798
  sweep_before = [None]
767
- # F41: the probe count of a 2+ character text before the paste (None = unknown)
799
+ # The probe count of a 2+ character text before the paste (None = unknown)
768
800
  multi = not single and verify.text_probe(text) is not None
769
801
  count_before = [None]
770
802
  # 0.2.5: where the probe showed before the paste (None = unknown → no confirmation)
771
803
  spots_before = [None]
772
- strip_before = [[]] # and inside the banner strip (review 0.2.6 #7: explains, never confirms)
773
- # review 0.2.6 #7: why OCR could not confirm a paste the frame diff saw — "too_short" (fewer
804
+ strip_before = [[]] # and inside the banner strip (explains, never confirms)
805
+ # why OCR could not confirm a paste the frame diff saw — "too_short" (fewer
774
806
  # than VERIFY_MIN_PROBE characters, never confirmed) or "strip_only" (the text appeared only in
775
807
  # the banner strip at the top, where a field cannot be told from a banner)
776
808
  unverifiable = [None]
@@ -785,7 +817,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
785
817
  if hud_check is None:
786
818
  if before_check is None:
787
819
  def hud_check() -> bool:
788
- # F44: one more look for the phone's paste-progress box (a
820
+ # One more look for the phone's paste-progress box (a
789
821
  # sweep for a single character, like every read of it)
790
822
  return verify.shows_paste_hud(sweep_read() if single else vision.read_screen())
791
823
  else:
@@ -814,7 +846,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
814
846
  deadline = clock() + 4.0
815
847
  while True:
816
848
  hits = sweep_read()
817
- # F44: a read showing the paste-progress box is no evidence —
849
+ # A read showing the paste-progress box is no evidence —
818
850
  # a paste is still on its way, and a restore now could hand it
819
851
  # the user's clipboard
820
852
  if not verify.shows_paste_hud(hits) and evidence.add(hits):
@@ -823,7 +855,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
823
855
  return False
824
856
  sleep(0.3)
825
857
  if multi:
826
- # F41: only a rise over the pre-paste count is the paste, and it
858
+ # Only a rise over the pre-paste count is the paste, and it
827
859
  # must show in two reads (one misread is no license to restore)
828
860
  if count_before[0] is None:
829
861
  return False
@@ -831,7 +863,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
831
863
  if i:
832
864
  sleep(0.3)
833
865
  hits = vision.read_screen()
834
- # F44: no license while the paste-progress box shows — a paste
866
+ # No license while the paste-progress box shows — a paste
835
867
  # (this one or an earlier one) is still on its way
836
868
  if (verify.shows_paste_hud(hits)
837
869
  or verify.probe_count(text, hits) <= count_before[0]
@@ -848,6 +880,9 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
848
880
  sent = [False] # True from the moment a Cmd+V may be on its way
849
881
  saved = None
850
882
  saved_change = None
883
+ # with replace, ⌘A has gone out before any of the checks below: a refusal says so ("nothing was typed" alone
884
+ # reads as nothing done — the field's text is selected)
885
+ nothing = "nothing was typed (⌘A had already selected the field's text)" if replace else "nothing was typed"
851
886
  try:
852
887
  if replace:
853
888
  chord(_VK_A) # select the focused field's content first (see docstring)
@@ -861,7 +896,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
861
896
  saved_change = None # nothing of ours to undo
862
897
  raise ClipboardChanged(
863
898
  "another app or device changed the clipboard while it was being saved; "
864
- "nothing was typed and the clipboard was left as it is")
899
+ f"{nothing} and the clipboard was left as it is")
865
900
 
866
901
  pasteboard.clearContents()
867
902
  pasteboard.setString_forType_(text, "public.utf8-plain-text")
@@ -879,10 +914,10 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
879
914
  if pasteboard.changeCount() != saved_change + 1:
880
915
  raise ClipboardChanged(
881
916
  "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")
917
+ f"{nothing} and the clipboard was left as it is")
883
918
 
884
919
  if pre_read:
885
- # F27: the pre-paste sweep for a single character, taken on a
920
+ # The pre-paste sweep for a single character, taken on a
886
921
  # still screen only (a mid-transition read could miss a label
887
922
  # that is already there and later pass it off as the paste).
888
923
  # Taken after the clipboard write and the wait (0.2.7), so
@@ -896,7 +931,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
896
931
  sweep_before[0] = None
897
932
 
898
933
  if pre_count:
899
- # F41: count the text before the paste — the higher of two reads
934
+ # Count the text before the paste — the higher of two reads
900
935
  # 0.3 s apart (a redraw or the select-all highlight can hide an
901
936
  # occurrence from one read). A capture failure in either leaves it
902
937
  # unknown: then OCR can never license a restore for this paste.
@@ -930,18 +965,18 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
930
965
  raise
931
966
 
932
967
  def last_check():
933
- # F35: the last look at the pasteboard, after the chord's focus
968
+ # The last look at the pasteboard, after the chord's focus
934
969
  # round-trips and right before its first event: anything else
935
970
  # that wrote it since our own write would be pasted instead.
936
971
  if pasteboard.changeCount() != saved_change + 1:
937
972
  raise ClipboardChanged(
938
973
  "another app or device changed the clipboard before the "
939
- "paste; nothing was typed and the clipboard was left as it is")
974
+ f"paste; {nothing} and the clipboard was left as it is")
940
975
  # From here on a paste may be on its way: an error from now on
941
976
  # must never put the user's clipboard back.
942
977
  sent[0] = True
943
978
 
944
- # real ⌘ chord — flags alone reach the phone as "v" (F14)
979
+ # real ⌘ chord — flags alone reach the phone as "v"
945
980
  paste_chord(_VK_V, before_key=last_check) # never re-activates the mirror after the wait
946
981
  t0 = clock()
947
982
 
@@ -956,7 +991,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
956
991
  landed = True
957
992
  break
958
993
  except Exception as exc:
959
- # F25: a capture failure is "no change observed this
994
+ # A capture failure is "no change observed this
960
995
  # round", never proof of change — keep polling. Other
961
996
  # errors still propagate (after Cmd+V: no restore).
962
997
  if not verify.is_capture_error(exc):
@@ -966,7 +1001,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
966
1001
  # restore. When the frame-diff window timed out, this same
967
1002
  # probe is also the confirmation — one call covers both, and
968
1003
  # its result is reused rather than re-checked. A capture
969
- # failure counts as "not seen" (F25): the paste stays
1004
+ # failure counts as "not seen": the paste stays
970
1005
  # unconfirmed rather than trusting another window's pixels.
971
1006
  try:
972
1007
  restore_ok = ocr_check()
@@ -975,7 +1010,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
975
1010
  raise
976
1011
  restore_ok = False
977
1012
  if landed and not restore_ok:
978
- # F44: the frame diff fired but OCR did not see the text. If the
1013
+ # The frame diff fired but OCR did not see the text. If the
979
1014
  # phone shows its "Pasting from …" progress box, the box was the
980
1015
  # change and the paste is still on its way: not landed. A capture
981
1016
  # failure tells nothing either way and keeps the frame diff's
@@ -997,11 +1032,11 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
997
1032
  report["unverifiable"] = unverifiable[0]
998
1033
 
999
1034
  if not landed:
1000
- # F18 invariant: never restore unconfirmed — a late paste
1035
+ # Invariant: never restore unconfirmed — a late paste
1001
1036
  # must at worst repeat `text`, never the user's own clipboard.
1002
1037
  return False
1003
1038
 
1004
- # Andy's call (2026-11-07, review R38): one character seen on screen
1039
+ # one character seen on screen
1005
1040
  # confirms the paste but never licenses a restore — like a text of two or
1006
1041
  # three characters (VERIFY_MIN_PROBE), it keeps the clipboard holding `text`.
1007
1042
  if restore_ok and restore and not single:
@@ -1012,30 +1047,37 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
1012
1047
  sleep(min_hold_s - elapsed)
1013
1048
  # Restore the user's clipboard only if nothing else changed it.
1014
1049
  if pasteboard.changeCount() == saved_change + 1:
1015
- restore_pasteboard(pasteboard, saved)
1050
+ # what the clipboard held before could not be written back: the caller is told
1051
+ if restore_pasteboard(pasteboard, saved) is False and report is not None:
1052
+ report["restore_failed"] = restore_failure(saved)
1016
1053
  # else: landed but OCR is blind to it (short/cropped text), a single
1017
1054
  # character, or the caller keeps the clipboard (restore=False): success,
1018
1055
  # but the clipboard keeps `text` — see the docstring's tradeoff.
1019
1056
  return True
1020
- except BaseException:
1057
+ except BaseException as exc:
1021
1058
  # Before Cmd+V the phone never got a paste command, so the
1022
1059
  # user's clipboard can safely go back (changeCount rule).
1023
1060
  # After Cmd+V a late asynchronous read may still happen — never
1024
1061
  # restore then. Either way the original exception propagates.
1025
1062
  if not sent[0] and saved_change is not None:
1026
1063
  if pasteboard.changeCount() == saved_change + 1:
1027
- restore_pasteboard(pasteboard, saved)
1064
+ if restore_pasteboard(pasteboard, saved) is False:
1065
+ # the error goes on as it is; it carries that the clipboard was not put back
1066
+ try:
1067
+ exc.restore_failed = restore_failure(saved)
1068
+ except Exception:
1069
+ pass
1028
1070
  raise
1029
1071
 
1030
1072
 
1031
1073
  def clear_text() -> None:
1032
1074
  """Select-all and delete in the focused field."""
1033
- check_chord_layout(_VK_A) # review 0.2.6 #5: before the mirror is brought forward
1075
+ check_chord_layout(_VK_A) # before the mirror is brought forward
1034
1076
  ensure_frontmost()
1035
1077
  _cmd_chord(_VK_A) # Cmd+A — real chord, same reason as type_text
1036
1078
  time.sleep(0.05)
1037
1079
  src = _source()
1038
- _require_focus() # F26: re-check between Cmd+A and Delete
1080
+ _require_focus() # re-check between Cmd+A and Delete
1039
1081
  _key_event(_VK_DELETE, True, src)
1040
1082
  try:
1041
1083
  time.sleep(0.02)
@@ -122,7 +122,9 @@ def _save(path, sizes: dict) -> None:
122
122
  p = Path(path)
123
123
  p.parent.mkdir(parents=True, exist_ok=True)
124
124
  if len(sizes) > MAX_SIZES: # keep the most recently written entries
125
- newest = sorted(sizes, key=lambda k: max(sizes[k].get("measured_at", 0), sizes[k].get("untrusted_at", 0)))
125
+ # a time that is not a number (null in a file written by hand or cut short) counts as the oldest
126
+ num = lambda v: v if isinstance(v, (int, float)) and not isinstance(v, bool) else 0
127
+ newest = sorted(sizes, key=lambda k: max(num(sizes[k].get("measured_at")), num(sizes[k].get("untrusted_at"))))
126
128
  sizes = {k: sizes[k] for k in newest[-MAX_SIZES:]}
127
129
  tmp = p.with_name(f"{p.name}.{os.getpid()}.tmp")
128
130
  tmp.write_text(json.dumps({"version": VERSION, "sizes": sizes}, indent=1) + "\n", encoding="utf-8")