noracu 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,10 +11,13 @@ synthesized touch gestures — see the menu-command section below.
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import math
14
15
  import subprocess
15
16
  import time
17
+ import unicodedata
16
18
 
17
19
  from . import input as inp
20
+ from . import verify
18
21
  from . import vision
19
22
  from .window import WindowError, ensure_frontmost, ensure_running, get_bounds
20
23
 
@@ -86,6 +89,56 @@ def scroll_up(distance: float = 0.5) -> None:
86
89
  inp.scroll_trackpad(distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
87
90
 
88
91
 
92
+ # 待真机标定:一次 0.5 窗口高度滚动的整窗 luma 帧差下限。
93
+ SCROLL_MIN_DIFF = 2.0
94
+
95
+
96
+ def scroll_checked(direction, distance=0.5, *, luma=None, scroller=None,
97
+ sleep=time.sleep, settle_s=0.6) -> bool:
98
+ """Scroll by `distance` window heights and confirm the screen moved (F20).
99
+
100
+ `direction` is "up" or "down"; `distance` is in window heights and
101
+ must satisfy 0 < distance <= 3. Both are validated before anything
102
+ is captured or sent: the 0.1.1 tool description named no unit, so
103
+ callers passed pixels (150-600) and a 600-window-height scroll was
104
+ silently accepted as success.
105
+
106
+ The scroll itself is the existing scroll_down/scroll_up trackpad
107
+ events. A list already at its end, or a view that does not scroll,
108
+ leaves the screen unchanged — this gate compares the mirroring
109
+ window's luma before/after and reports that as False instead of
110
+ success.
111
+
112
+ `luma` (default verify.window_luma), `scroller` (default:
113
+ scroll_down/scroll_up by direction) and `sleep` are injectable so
114
+ tests can drive this without a phone.
115
+
116
+ Returns True when the screen changed by at least SCROLL_MIN_DIFF.
117
+
118
+ Capture failures are never swallowed (F25): a WindowError or
119
+ CaptureError from the luma captures propagates to the caller (the
120
+ CLI reports capture_failed) — an unreadable screen is not evidence
121
+ that the scroll had no effect.
122
+ """
123
+ if direction not in ("up", "down"):
124
+ raise ValueError(f"direction must be 'up' or 'down', got {direction!r}")
125
+ if (not isinstance(distance, (int, float)) or isinstance(distance, bool)
126
+ or not 0 < distance <= 3 or not math.isfinite(distance)):
127
+ raise ValueError(
128
+ "distance is in window heights, 0 < distance <= 3 (default 0.5); "
129
+ f"got {distance!r}"
130
+ )
131
+ if luma is None:
132
+ luma = verify.window_luma
133
+ if scroller is None:
134
+ scroller = lambda d, dist: (scroll_down if d == "down" else scroll_up)(dist)
135
+ before = luma()
136
+ scroller(direction, distance)
137
+ sleep(settle_s)
138
+ after = luma()
139
+ return verify.mean_abs_diff(before, after) >= SCROLL_MIN_DIFF
140
+
141
+
89
142
  def page_left() -> None:
90
143
  """Swipe right-to-left: go to the next home-screen page."""
91
144
  inp.swipe(0.8, 0.5, 0.2, 0.5, duration_ms=280)
@@ -214,21 +267,103 @@ def open_spotlight() -> bool:
214
267
  return _run_view_menu_command("Spotlight")
215
268
 
216
269
 
270
+ # Minimum mean-abs-luma diff (0-255 scale, verify.mean_abs_diff) for
271
+ # "Spotlight actually opened". Pending on-device calibration of the
272
+ # single "Home Screen → Spotlight" frame diff — the gate below always
273
+ # starts from the home screen, so that is the only scenario to
274
+ # calibrate.
275
+ SPOTLIGHT_MIN_DIFF = 6.0
276
+
277
+
278
+ def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=None, home=None, home_settle_s=0.8) -> bool:
279
+ """Go to the Home Screen, open Spotlight, and confirm it (F17 guard).
280
+
281
+ Two layers of protection, in order:
282
+
283
+ ① Home Screen first (View ▸ Home Screen). The home screen has no
284
+ app input field, so even if every later step fails, the caller's
285
+ clear_text() (Cmd+A + Delete) cannot delete user content. It also
286
+ avoids re-sending the Spotlight command when Spotlight is already
287
+ open: if that command is a toggle, it would close Spotlight, and
288
+ the large screen change would fool layer ② into reporting success
289
+ while the keystrokes land in the app underneath.
290
+
291
+ ② A visible-change gate. open_spotlight() returning True only
292
+ means the View ▸ Spotlight menu command was dispatched — not that
293
+ Spotlight appeared on the phone. This gate compares the mirroring
294
+ window's luma before and after the menu command and reports
295
+ success only when the screen changed by at least
296
+ SPOTLIGHT_MIN_DIFF (calibrated for the single home-screen →
297
+ Spotlight transition).
298
+
299
+ ``luma`` (default verify.window_luma), ``sleep``, ``opener``
300
+ (default open_spotlight) and ``home`` (default: View ▸ Home
301
+ Screen) are injectable so tests can drive this without a phone.
302
+ """
303
+ if luma is None:
304
+ luma = verify.window_luma
305
+ if opener is None:
306
+ opener = open_spotlight
307
+ if home is None:
308
+ home = lambda: _run_view_menu_command("Home Screen")
309
+ if not home():
310
+ return False
311
+ sleep(home_settle_s)
312
+ before = luma()
313
+ if not opener():
314
+ return False
315
+ sleep(settle_s)
316
+ after = luma()
317
+ return verify.mean_abs_diff(before, after) >= SPOTLIGHT_MIN_DIFF
318
+
319
+
320
+ # OCR look-alikes: characters Vision misreads a Latin letter as (the
321
+ # one-letter app "X" comes back as a multiplication sign, a Cyrillic
322
+ # ha, …). Only characters that get misread AS a Latin letter belong
323
+ # here — this is deliberately NOT a general transliteration table.
324
+ _LABEL_LOOKALIKES = {
325
+ "×": "x", # multiplication sign
326
+ "х": "x", # Cyrillic small letter ha (U+0445)
327
+ "Х": "x", # Cyrillic capital letter ha (U+0425)
328
+ }
329
+
330
+
331
+ def _norm_label(s: str) -> str:
332
+ """Normalize an app label (or query) for exact comparison.
333
+
334
+ NFKC (folds full-width "X" to "X") → strip → drop trailing
335
+ punctuation OCR appends to labels ("X.") → lowercase → map the
336
+ look-alike characters above to the Latin letter they get
337
+ misread as. Lets very short names like "X" match what Vision
338
+ actually returns without ever falling back to substring
339
+ matching.
340
+ """
341
+ s = unicodedata.normalize("NFKC", s).strip()
342
+ s = s.rstrip(".:·•,")
343
+ s = s.lower()
344
+ return "".join(_LABEL_LOOKALIKES.get(ch, ch) for ch in s)
345
+
346
+
217
347
  def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
218
348
  """Pick the Spotlight result row for ``name`` from OCR hits.
219
349
 
220
350
  iOS 26 draws the Spotlight search field at the BOTTOM of the screen
221
351
  (ny ≈ 0.95) and echoes the typed query inside it, so a plain text
222
352
  match finds the field itself. A result row must:
223
- - equal ``name`` case-insensitively after stripping whitespace, and
353
+ - equal ``name`` after _norm_label() on BOTH sides (NFKC, strip,
354
+ trailing-punctuation drop, lowercase, OCR look-alike folding —
355
+ so the one-letter app "X" still matches labels Vision reads as
356
+ "x", "×", "X." or full-width "X"), and
224
357
  - lie above the bottom search-field zone (ny < 0.88).
225
- When several rows match, the topmost (smallest ny) wins. Returns
226
- None when nothing qualifies.
358
+ The comparison stays EXACT — substring/prefix matching is
359
+ forbidden: "X" must never hit "Xcode" or "X Corp". When several
360
+ rows match, the topmost (smallest ny) wins. Returns None when
361
+ nothing qualifies.
227
362
  """
228
- want = name.strip().lower()
363
+ want = _norm_label(name)
229
364
  best = None
230
365
  for hit in hits:
231
- if hit.text.strip().lower() != want:
366
+ if _norm_label(hit.text) != want:
232
367
  continue
233
368
  if hit.ny >= 0.88:
234
369
  continue # the search field echoing the query
@@ -237,32 +372,251 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
237
372
  return best
238
373
 
239
374
 
240
- def open_app(name: str, *, spotlight_open: bool = False) -> bool:
241
- """Open an app by name: Spotlight → type → OCR → tap the result row.
242
-
243
- ``spotlight_open`` lets a caller that already ran open_spotlight()
244
- itself (to tell "spotlight unavailable" apart from "app not found")
245
- skip the internal call. Returns True when a row matching ``name``
246
- was tapped; False when Spotlight could not be opened or no row
247
- matched (after returning to the home screen).
375
+ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep):
376
+ """Read the screen up to ``attempts`` times for a Spotlight result row.
377
+
378
+ Each pass calls ``read_screen()`` for OCR hits and hands them to
379
+ choose_app_hit(); a match returns immediately. Between passes we
380
+ wait ``delay_s`` — Spotlight results can lag the keystrokes, so a
381
+ single read races them (F17). No sleep after the last pass. Returns
382
+ None when no pass matches. ``read_screen`` and ``sleep`` are
383
+ injectable so tests can drive this without a phone.
384
+
385
+ Very short names (``_norm_label(name)`` ≤ 2 chars, e.g. "X") get one
386
+ extra read per pass, with ``read_screen(language_correction=False)``:
387
+ Vision's language correction tends to drop or rewrite
388
+ single-character labels, and they are recognized more reliably
389
+ without it. F27: Vision's full-frame pass can also skip such a label
390
+ entirely (the app "X" on 2026-11-04), so a short name that both
391
+ reads miss gets a third read with the minimumTextHeight sweep —
392
+ ``read_screen(language_correction=False, sweep=True)``. The match
393
+ stays exact either way. Long names keep the exact original
394
+ read/sleep sequence.
395
+ """
396
+ short = len(_norm_label(name)) <= 2
397
+ for i in range(attempts):
398
+ hit = choose_app_hit(read_screen(), name)
399
+ if hit is not None:
400
+ return hit
401
+ if short:
402
+ hit = choose_app_hit(read_screen(language_correction=False), name)
403
+ if hit is not None:
404
+ return hit
405
+ hit = choose_app_hit(
406
+ read_screen(language_correction=False, sweep=True), name)
407
+ if hit is not None:
408
+ return hit
409
+ if i + 1 < attempts:
410
+ sleep(delay_s)
411
+ return None
412
+
413
+
414
+ # 2026-11-03 在 iPhone 17 Pro Max 镜像上实测:Spotlight「Top Hit」卡片里
415
+ # App 图标中心在文字标签中心上方 0.052(标签中心 0.27 → 图标中心
416
+ # 0.218,单位为窗口高度比例)。
417
+ SPOTLIGHT_ICON_ABOVE_LABEL = 0.052
418
+
419
+ # 待真机标定:打开 App 前后整窗 luma 帧差下限。
420
+ OPEN_MIN_DIFF = 12.0
421
+
422
+
423
+ def _tophit_header(hits):
424
+ """The OCR hit for the Spotlight "Top Hit" card header, or None.
425
+
426
+ Matched exactly after _norm_label (case-folding, trailing
427
+ punctuation), so a list row that merely contains the words can
428
+ never pose as the card header.
429
+ """
430
+ want = _norm_label("Top Hit")
431
+ for hit in hits:
432
+ if _norm_label(hit.text) == want:
433
+ return hit
434
+ return None
435
+
436
+
437
+ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
438
+ """Tap (nx, ny) and confirm the app actually opened (F24 ②).
439
+
440
+ One luma frame before the tap, one after a 1.0s settle, then one
441
+ OCR read. The tap counts as opened only when BOTH hold: the
442
+ whole-window frame diff reached OPEN_MIN_DIFF (the screen
443
+ visibly left Spotlight — a dead tap leaves it nearly identical)
444
+ and the "Top Hit" header is gone from the OCR read (a large
445
+ diff alone can be the results list reflowing under a dead tap).
446
+ Returns (opened, hits); ``hits`` is the post-tap OCR read, handed
447
+ back so the caller can search it for the Top Hit header without
448
+ reading the screen a second time.
449
+ """
450
+ before = luma()
451
+ tap(nx, ny)
452
+ sleep(1.0)
453
+ after = luma()
454
+ hits = read_screen()
455
+ opened = (verify.mean_abs_diff(before, after) >= OPEN_MIN_DIFF
456
+ and _tophit_header(hits) is None)
457
+ return opened, hits
458
+
459
+
460
+ def open_app(name: str, *, spotlight_open: bool = False,
461
+ read_screen=None, luma=None, sleep=time.sleep, tap=None,
462
+ home=None, clear_text=None, type_text=None) -> str:
463
+ """Open an app by name: Spotlight → clear → type → OCR → tap → CONFIRM.
464
+
465
+ ``spotlight_open`` lets a caller that already ran
466
+ open_spotlight_checked() itself (to tell "spotlight unavailable"
467
+ apart from "app not found") skip the internal call and go
468
+ straight to clear → type.
469
+
470
+ Spotlight is opened through open_spotlight_checked(), which
471
+ first returns to the Home Screen and only then opens Spotlight,
472
+ and reports success only when the screen visibly changed: if the
473
+ menu command silently failed, clear_text() (Cmd+A + Delete) would
474
+ land in whatever focused text field the frontmost app shows (a
475
+ note body, a message draft…) and wipe it — so on a failed gate
476
+ this does nothing at all: no clearing, no typing, no taps (F17
477
+ safety gate).
478
+
479
+ The search field is cleared (Cmd+A + Delete) before typing: iOS
480
+ keeps the previous Spotlight query, so the new name would be
481
+ appended to it and no result row would match (F17). Results are
482
+ then read up to twice (find_app_hit) because they can lag the
483
+ keystrokes.
248
484
 
249
485
  The top hit is never opened with Return — it may belong to a
250
486
  different app than the requested one.
251
- """
252
- if not spotlight_open and not open_spotlight():
253
- return False
254
- time.sleep(1.0)
255
- inp.type_text(name)
256
- time.sleep(1.5) # wait for Spotlight results
257
487
 
258
- hit = choose_app_hit(vision.read_screen(), name)
488
+ F24 (2026-11-03 real-device retest): a tapped row is not an
489
+ opened app. On iOS 27 Spotlight the OCR hit can be the Top Hit
490
+ card's label UNDER the app icon, and tapping that label text
491
+ does nothing — the screen stays on Spotlight while the caller
492
+ was told "opened". So after find_app_hit matches a row:
493
+
494
+ ① stability — wait 0.5s, re-read, re-pick with choose_app_hit.
495
+ When the row moved by more than 0.02 the results were still
496
+ reflowing: the second read wins, with at most one more read
497
+ (still moving → the last read is authoritative).
498
+ ② tap the row, then confirm via _tap_and_confirm_open (frame
499
+ diff ≥ OPEN_MIN_DIFF and the "Top Hit" header gone).
500
+ ③ when that tap did nothing and the hit sits inside the Top Hit
501
+ card — the "Top Hit" header above the hit, less than 0.15 away —
502
+ tap the icon SPOTLIGHT_ICON_ABOVE_LABEL above the label and
503
+ confirm the same way. Any other hit gets NO second tap: an
504
+ upward offset there could land on a different app's row.
505
+ ④ still nothing confirmed → back to the Home Screen (View ▸
506
+ Home Screen), reported as not_confirmed.
507
+
508
+ A capture failure after the hit is found (WindowError /
509
+ CaptureError, F25) counts as unconfirmed — no further taps.
510
+
511
+ Returns "opened"; "not_found" (no row matched; back on the Home
512
+ Screen); "not_confirmed" (row — and possibly the Top Hit icon —
513
+ tapped but the app never verifiably opened; back on the Home
514
+ Screen); or "spotlight_unavailable" (Spotlight could not be
515
+ opened; nothing was typed or tapped).
516
+
517
+ ``read_screen`` (default vision.read_screen), ``luma`` (default
518
+ verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
519
+ ``home`` (default View ▸ Home Screen), ``clear_text`` and
520
+ ``type_text`` are injectable so tests can drive this without a
521
+ phone.
522
+ """
523
+ if read_screen is None:
524
+ read_screen = vision.read_screen
525
+ if luma is None:
526
+ luma = verify.window_luma
527
+ if tap is None:
528
+ tap = inp.tap
529
+ if home is None:
530
+ home = lambda: _run_view_menu_command("Home Screen")
531
+ if clear_text is None:
532
+ clear_text = inp.clear_text
533
+ pending: list = []
534
+ if type_text is None:
535
+ def type_text(text):
536
+ return inp.type_text(text, pending=pending)
537
+ raw_read = read_screen
538
+
539
+ def read_screen(**kwargs):
540
+ # F33: every later read is also evidence for a clipboard restore
541
+ # type_text could not license in time (a paste that landed late).
542
+ hits = raw_read(**kwargs)
543
+ for restore in pending:
544
+ restore.offer(hits)
545
+ return hits
546
+
547
+ short = len(_norm_label(name)) <= 2
548
+
549
+ def reread():
550
+ # F32: the default pass alone keeps missing a one-letter label, and
551
+ # a missed row looked like a moved row — the tap then went to a
552
+ # different row ("X" opened a Chrome search). Short names read the
553
+ # same frame with the sweep too.
554
+ return read_screen(also_sweep=True) if short else read_screen()
555
+
556
+ # F34: one retry — on the device the Spotlight command was once ignored
557
+ # right after an app closed. Each try starts from the Home Screen, so a
558
+ # second try cannot toggle an open Spotlight shut.
559
+ if not spotlight_open and not (open_spotlight_checked()
560
+ or open_spotlight_checked()):
561
+ return "spotlight_unavailable"
562
+ clear_text() # iOS kept the last query; new input would append (F17)
563
+ sleep(0.3)
564
+ typed = type_text(name)
565
+ sleep(1.5) # wait for Spotlight results
566
+
567
+ # F33: a paste type_text did not see arrive may still be on its way (on
568
+ # the device it once showed up 8-10 s after Cmd+V): one more read pass.
569
+ hit = find_app_hit(read_screen, name, attempts=3 if typed is False else 2,
570
+ sleep=sleep)
259
571
  if hit is None:
260
572
  # Leave the phone tidy: back to the home screen (View ▸ Home Screen).
261
- _run_view_menu_command("Home Screen")
262
- return False
263
- inp.tap(hit.nx, hit.ny)
264
- time.sleep(1.0)
265
- return True
573
+ home()
574
+ return "not_found"
575
+
576
+ try:
577
+ # ① the Spotlight results can still be reflowing when
578
+ # find_app_hit returns; re-read after 0.5s and re-pick.
579
+ sleep(0.5)
580
+ again = choose_app_hit(reread(), name)
581
+ if again is not None:
582
+ if math.hypot(again.nx - hit.nx, again.ny - hit.ny) > 0.02:
583
+ # the row moved: the second read wins, with at most
584
+ # one more read — still moving → the last one wins
585
+ hit = again
586
+ once_more = choose_app_hit(reread(), name)
587
+ if (once_more is not None
588
+ and math.hypot(once_more.nx - hit.nx,
589
+ once_more.ny - hit.ny) > 0.02):
590
+ hit = once_more
591
+ # else: the two reads agree — the first hit stands
592
+
593
+ # ② tap the row (the label inside the Top Hit card) and confirm
594
+ opened, hits = _tap_and_confirm_open(
595
+ hit.nx, hit.ny, luma=luma, sleep=sleep, tap=tap,
596
+ read_screen=read_screen)
597
+ if opened:
598
+ return "opened"
599
+
600
+ # ③ the label tap did nothing and the hit sits inside the Top
601
+ # Hit card → tap the icon above the label. Anywhere else, no
602
+ # second tap: an upward offset could hit another app's row.
603
+ header = _tophit_header(hits)
604
+ if (header is not None and header.ny < hit.ny
605
+ and hit.ny - header.ny < 0.15):
606
+ opened, _ = _tap_and_confirm_open(
607
+ hit.nx, hit.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
608
+ luma=luma, sleep=sleep, tap=tap, read_screen=read_screen)
609
+ if opened:
610
+ return "opened"
611
+ except Exception as exc:
612
+ if not verify.is_capture_error(exc):
613
+ raise
614
+ # F25: an unreadable screen is not evidence the app opened —
615
+ # no further taps; wrap up unconfirmed below.
616
+
617
+ # ④ leave the phone tidy and say the taps were not confirmed
618
+ home()
619
+ return "not_confirmed"
266
620
 
267
621
 
268
622
  def read_text() -> list:
@@ -308,10 +662,17 @@ def resume() -> bool:
308
662
  return _resume()
309
663
 
310
664
 
311
- def launch() -> None:
312
- """Ensure iPhone Mirroring is running, frontmost, and not paused."""
665
+ def launch() -> bool | None:
666
+ """Ensure iPhone Mirroring is running, frontmost, and not paused.
667
+
668
+ Returns the stream state afterwards: True live, False still paused or connecting,
669
+ None unknown. F29: resume()'s result used to be dropped, so phone_launch reported
670
+ "ready" while the overlay was still up.
671
+ """
313
672
  ensure_running()
314
- from .window import ensure_frontmost, resume as _resume
673
+ from .window import ensure_frontmost, get_overlay, resume as _resume
315
674
 
316
675
  ensure_frontmost()
317
- _resume()
676
+ if _resume():
677
+ return True
678
+ return get_overlay()["live"]