Repository navigation
Expand file tree
/
Copy pathnavigator.py
More file actions
1243 lines (1054 loc) · 47.1 KB
/
Copy pathnavigator.py
File metadata and controls
1243 lines (1054 loc) · 47.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
navigator.py — Accessible hierarchical navigation overlay for macOS.
The LLM pipeline sends a JSON menu structure describing what is on screen.
This script shows a full-width overlay at the bottom of the screen so the
user can navigate with three single-key presses:
Tab → cycle to the next option
Return → select (drill into a sub-menu, or fire a click and exit)
Escape → go back one level / dismiss
Every item change is announced via VoiceOver so the user does not need to
look at the screen. When the user selects a leaf item, a synthetic mouse
click is posted at the coordinates supplied in the JSON.
Input JSON format
-----------------
{
"context": "LLM description of what is visible on screen",
"menus": [
{
"label": "Navigation Bar",
"items": [
{"label": "Home", "x": 100, "y": 50},
{"label": "About", "x": 200, "y": 50, "coords": "physical"}
]
},
{
"label": "Images",
"items": [
{"label": "Hero image", "x": 400, "y": 300}
]
}
]
}
Fields:
context — displayed + spoken when the overlay opens
menus[].label — top-level category name
menus[].items[].label — item name, announced on each cycle step
menus[].items[].x/y — click target in logical points (omit/null = no click)
menus[].items[].coords — "logical" (default) or "physical"
CLI
---
python navigator.py '<json>'
python navigator.py --input menu.json
Import
------
from navigator import Navigator
nav = Navigator()
nav.load(json_str_or_dict)
result = nav.show() # blocks; returns NavigationItem or None
if result:
print(result.label, result.x, result.y)
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import threading
import time
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
try:
import AppKit
import Foundation
except ImportError:
print("Missing PyObjC. Run: pip install pyobjc-framework-Cocoa")
sys.exit(1)
from pynput import keyboard
# Quartz is imported lazily inside _NavigatorKeyTap so importing this module
# doesn't fail on non-macOS machines (dev environments, tests, etc.).
warnings.filterwarnings("ignore", message=".*PyObjCPointer created.*")
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
OVERLAY_HEIGHT = 320 # px — tall enough for context + items + hints
ACCENT_BAR_H = 8 # px — cyan stripe at top
SCREEN_BOTTOM_MARGIN = 40 # px — gap from dock / taskbar
ACCENT_R, ACCENT_G, ACCENT_B = 0.0, 0.85, 0.95 # vivid cyan
# Lower-half layout (fixed, in AppKit bottom-up coords)
_CURRENT_Y = 108 # bottom edge of the big current-item label
_CURRENT_H = 88 # height of the big current-item label
_NBR_Y = 84 # bottom edge of the dimmed neighbours label
_NBR_H = 20 # height of the neighbours label
_SEP3_Y = 56 # y of the separator above hints
_HINTS_Y = 22 # bottom edge of the hints label
_HINTS_H = 22 # height of the hints label
# Key name → pynput Key mapping (also accepts pynput Key objects directly)
_KEY_MAP: dict[str, keyboard.Key] = {
"tab": keyboard.Key.tab,
"enter": keyboard.Key.enter,
"return": keyboard.Key.enter,
"esc": keyboard.Key.esc,
"escape": keyboard.Key.esc,
"space": keyboard.Key.space,
"up": keyboard.Key.up,
"down": keyboard.Key.down,
"right": keyboard.Key.right,
"left": keyboard.Key.left,
}
# ---------------------------------------------------------------------------
# Data types
# ---------------------------------------------------------------------------
@dataclass
class NavigationItem:
"""A selectable leaf item with an optional click target."""
label: str
x: Optional[float] = None
y: Optional[float] = None
coords: str = "logical" # "logical" or "physical"
@dataclass
class NavigationMenu:
"""A top-level category containing selectable items."""
label: str
items: list[NavigationItem] = field(default_factory=list)
@dataclass
class NavigationResult:
"""
Outcome of a navigation session.
Protocol for the caller::
result = nav.show()
if result is None:
pass # user dismissed with Esc — do nothing
elif result.clicked:
pass # click already fired — done
else:
llm.send(result.label) # no coordinates — send label back to LLM
``clicked`` is True only when the selected item had (x, y) coordinates and
auto_click was True. ``clicked`` is False when the item had no coordinates,
meaning the selection was conceptual and the LLM should decide what to do next.
"""
label: str # selected item label — always present
clicked: bool # True → Quartz click was fired at (x, y)
item: NavigationItem # full item for reference
def _parse_data(data: "dict | str") -> tuple[str, list[NavigationMenu]]:
"""Parse a JSON string or dict into (context_text, menus)."""
if isinstance(data, str):
data = json.loads(data)
context = str(data.get("context", ""))
menus: list[NavigationMenu] = []
for m in data.get("menus", []):
items = [
NavigationItem(
label = str(it["label"]),
x = float(it["x"]) if it.get("x") is not None else None,
y = float(it["y"]) if it.get("y") is not None else None,
coords = str(it.get("coords", "logical")),
)
for it in m.get("items", [])
]
menus.append(NavigationMenu(label=str(m["label"]), items=items))
return context, menus
# ---------------------------------------------------------------------------
# Internal AppKit helpers
# ---------------------------------------------------------------------------
def _make_label(
text: str,
size: float,
weight,
color,
monospaced: bool = False,
) -> "AppKit.NSTextField":
lbl = AppKit.NSTextField.labelWithString_(text)
if monospaced:
lbl.setFont_(AppKit.NSFont.monospacedSystemFontOfSize_weight_(size, weight))
else:
lbl.setFont_(AppKit.NSFont.systemFontOfSize_weight_(size, weight))
lbl.setTextColor_(color)
lbl.setBackgroundColor_(AppKit.NSColor.clearColor())
lbl.setBezeled_(False)
lbl.setEditable_(False)
return lbl
def _add_colored_view(parent, rect, r: float, g: float, b: float, a: float = 1.0) -> None:
v = AppKit.NSView.alloc().initWithFrame_(rect)
v.setWantsLayer_(True)
v.layer().setBackgroundColor_(
AppKit.NSColor.colorWithRed_green_blue_alpha_(r, g, b, a).CGColor()
)
parent.addSubview_(v)
def _add_separator(parent, cw: float, y: float) -> None:
_add_colored_view(
parent,
Foundation.NSMakeRect(24, y, cw - 48, 1),
1.0, 1.0, 1.0, 0.12,
)
# ---------------------------------------------------------------------------
# Direct Quartz key-event tap
# ---------------------------------------------------------------------------
#
# pynput's `suppress=True` listener is unreliable on macOS — keys routinely
# leak through to the frontmost app. We install a real CGEventTap at the
# session-event layer so we can either swallow or forward each key.
#
# Only Tab, Return and Escape are intercepted. Everything else passes through
# untouched so the user can still use modifier keys, app shortcuts, etc.
# macOS virtual key codes (HIToolbox / Events.h)
_KC_TAB = 48 # 0x30
_KC_RETURN = 36 # 0x24
_KC_ESCAPE = 53 # 0x35
class _NavigatorKeyTap:
"""Install a CGEventTap that swallows Tab/Return/Escape and calls handlers.
Install with `start()`, remove with `stop()`. `start()` must be called
from the same thread whose CFRunLoop will pump events (the main thread
in our case, since `Navigator.show()` pumps the main NSRunLoop).
"""
def __init__(self, on_tab, on_return, on_escape) -> None:
self._on_tab = on_tab
self._on_return = on_return
self._on_escape = on_escape
self._tap = None
self._source = None
# Keep the callback reference alive for as long as the tap is
# installed — pyobjc's bridge holds a weak reference otherwise.
self._callback_ref = None
def start(self) -> bool:
"""Install the event tap. Returns True on success, False if the
tap could not be created (usually a missing Accessibility grant)."""
try:
import Quartz
except ImportError:
print("[navigator] Quartz (pyobjc) not available — key tap disabled")
return False
mask = Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown)
# Keep a bound reference to the callback so pyobjc doesn't GC it
# out from under the C tap while it's still installed.
self._callback_ref = self._handle
try:
self._tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap, # tap location
Quartz.kCGHeadInsertEventTap, # placement
Quartz.kCGEventTapOptionDefault, # active: can suppress/modify
mask,
self._callback_ref,
None,
)
except Exception as exc:
print(f"[navigator] CGEventTapCreate raised: {exc}")
self._tap = None
if not self._tap:
print(
"[navigator] CGEventTapCreate returned NULL — "
"is Accessibility granted to this terminal?"
)
return False
try:
self._source = Quartz.CFMachPortCreateRunLoopSource(None, self._tap, 0)
Quartz.CFRunLoopAddSource(
Quartz.CFRunLoopGetCurrent(),
self._source,
Quartz.kCFRunLoopCommonModes,
)
Quartz.CGEventTapEnable(self._tap, True)
except Exception as exc:
print(f"[navigator] key tap install failed: {exc}")
self._tap = None
self._source = None
return False
return True
def stop(self) -> None:
"""Remove the tap from the run loop and disable it."""
try:
import Quartz
except ImportError:
return
if self._tap is not None:
try:
Quartz.CGEventTapEnable(self._tap, False)
except Exception:
pass
if self._source is not None:
try:
Quartz.CFRunLoopRemoveSource(
Quartz.CFRunLoopGetCurrent(),
self._source,
Quartz.kCFRunLoopCommonModes,
)
except Exception:
pass
self._tap = None
self._source = None
self._callback_ref = None
def _handle(self, proxy, type_, event, refcon):
"""CGEventTap callback.
Return `None` to swallow the event, or the event itself to let it
pass through to the frontmost app.
"""
try:
import Quartz
# macOS sometimes disables the tap on timeout — re-enable and
# pass the event through unchanged.
if type_ in (
Quartz.kCGEventTapDisabledByTimeout,
Quartz.kCGEventTapDisabledByUserInput,
):
if self._tap is not None:
Quartz.CGEventTapEnable(self._tap, True)
return event
if type_ != Quartz.kCGEventKeyDown:
return event
keycode = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGKeyboardEventKeycode
)
if keycode == _KC_TAB:
try:
self._on_tab()
except Exception as exc:
print(f"[navigator] on_tab handler error: {exc}")
return None # suppress
if keycode == _KC_RETURN:
try:
self._on_return()
except Exception as exc:
print(f"[navigator] on_return handler error: {exc}")
return None
if keycode == _KC_ESCAPE:
try:
self._on_escape()
except Exception as exc:
print(f"[navigator] on_escape handler error: {exc}")
return None
return event # pass through
except Exception as exc:
# Never let the C tap crash on a Python exception.
print(f"[navigator] tap callback error: {exc}")
return event
# ---------------------------------------------------------------------------
# Navigator
# ---------------------------------------------------------------------------
class Navigator:
"""
Accessible hierarchical navigation overlay.
Must be instantiated and ``show()`` called on the main thread (AppKit
requires all window operations on the main thread).
Example::
from navigator import Navigator
nav = Navigator()
nav.load('{"context": "...", "menus": [...]}')
result = nav.show() # blocks; returns NavigationItem or None
if result:
print(result.label, result.x, result.y)
Keys (configurable via constructor)::
Tab → cycle to next item
Return → select / drill into sub-menu
Escape → back one level / dismiss
"""
def __init__(
self,
cycle_key: str = "tab",
select_key: str = "enter",
back_key: str = "esc",
) -> None:
self._cycle_key = _KEY_MAP.get(cycle_key.lower(), keyboard.Key.tab)
self._select_key = _KEY_MAP.get(select_key.lower(), keyboard.Key.enter)
self._back_key = _KEY_MAP.get(back_key.lower(), keyboard.Key.esc)
# Menu data
self._context: str = ""
self._menus: list[NavigationMenu] = []
# Navigation state (all writes protected by _lock)
self._lock = threading.Lock()
self._level = 0 # 0 = top-level menus, 1 = items in selected menu
self._menu_idx = 0
self._item_idx = 0
# Display mode: "idle" | "message" | "menu". "message" mode shows
# arbitrary text (announcements, thinking state, errors); "menu"
# mode shows the hierarchical menu UI.
self._display_mode: str = "idle"
self._message_text: str = ""
# Session result
self._selected_item: Optional[NavigationItem] = None
self._done_event = threading.Event()
# AppKit objects (created lazily on first show() / show_message())
self._app: Optional[object] = None
self._panel: Optional[object] = None
self._label_breadcrumb: Optional[object] = None
self._label_context: Optional[object] = None
self._label_current: Optional[object] = None
self._label_neighbours: Optional[object] = None
self._announce_timer: Optional[object] = None
# Handle to the current `say` process for interruption
self._say_proc: Optional[subprocess.Popen] = None
self._listener: Optional[keyboard.Listener] = None
self._key_tap: Optional[_NavigatorKeyTap] = None
# Name of the app to re-focus before firing a click. The overlay is
# nonactivating so clicks normally land fine, but some apps (like
# Chrome's dropdown menus) need to be frontmost to accept clicks.
self.target_app: str = "Google Chrome"
from click_at import Clicker
self._clicker = Clicker()
# ---- Data ---------------------------------------------------------------
def load(self, data: "dict | str") -> None:
"""Parse a JSON string or dict and store the menu structure."""
self._context, self._menus = _parse_data(data)
# ---- Panel lifecycle (main-thread only) ---------------------------------
def _ensure_panel_built(self) -> None:
"""Build the NSApplication + panel if it doesn't exist yet.
Must be called on the main thread. Safe to call repeatedly — no-op
if the panel already exists.
"""
if self._app is None:
self._app = AppKit.NSApplication.sharedApplication()
self._app.setActivationPolicy_(AppKit.NSApplicationActivationPolicyAccessory)
if self._panel is None:
self._build_panel()
def ensure_visible(self) -> None:
"""Make sure the panel is built and shown at the top layer.
Safe to call on every session start — idempotent. Used so the
overlay is up immediately when ScreenUI boots, not only on the
first Gemma-triggered announcement.
"""
self._ensure_panel_built()
with self._lock:
if self._display_mode == "idle":
mode_is_idle = True
else:
mode_is_idle = False
if mode_is_idle:
self._apply_idle_display()
self._raise_to_top()
self._pump_briefly(0.03)
def show_message(self, text: str, speak: bool = True) -> None:
"""Show arbitrary text in the overlay and optionally speak it.
Must be called on the main thread. Unlike show(), this does NOT
block — it updates the panel and returns immediately. Used for
announcements, "Thinking..." status, and error messages.
"""
self._ensure_panel_built()
with self._lock:
self._display_mode = "message"
self._message_text = text or ""
self._apply_message_display(self._message_text)
self._raise_to_top()
# Pump the NSRunLoop briefly so the window server actually
# composites and presents the update BEFORE the caller's next
# blocking operation (e.g., Gemma inference on the main thread).
# Without this, the 'Thinking...' or announcement text wouldn't
# appear on screen until the inference finished.
self._pump_briefly(0.03)
if speak and text:
self._speak(text)
def _pump_briefly(self, seconds: float) -> None:
"""Tick the main NSRunLoop for `seconds` so deferred UI work renders."""
if threading.current_thread() is not threading.main_thread():
return
try:
loop = Foundation.NSRunLoop.currentRunLoop()
dl = Foundation.NSDate.dateWithTimeIntervalSinceNow_(seconds)
loop.runMode_beforeDate_(Foundation.NSDefaultRunLoopMode, dl)
except Exception:
pass
# ---- Speech -------------------------------------------------------------
def _speak(self, text: str) -> None:
"""Speak `text` via macOS `say`, interrupting any in-flight utterance.
Safe to call from any thread. Uses a detached subprocess so it
never blocks the caller.
"""
text = (text or "").strip()
if not text:
return
prev = self._say_proc
if prev is not None and prev.poll() is None:
try:
prev.terminate()
except Exception:
pass
try:
self._say_proc = subprocess.Popen(
["say", "-r", "210", text],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
except Exception as exc:
print(f"[navigator] say failed: {exc}")
# ---- App focus (for reliable clicks) ------------------------------------
def _activate_target_app(self) -> None:
"""Bring the click target app to the foreground via osascript.
Some click targets (dropdown menus, modals, form controls) only
register the click when the target app is frontmost, so we force
activation before firing the Quartz event.
"""
if not self.target_app:
return
try:
subprocess.run(
["osascript", "-e", f'tell application "{self.target_app}" to activate'],
capture_output=True,
timeout=2,
)
except Exception as exc:
print(f"[navigator] target-app activate failed: {exc}")
def _raise_to_top(self) -> None:
"""Re-assert panel level and bring it to the front without focus steal."""
if self._panel is None:
return
self._panel.setLevel_(AppKit.NSScreenSaverWindowLevel + 1)
self._panel.orderFrontRegardless()
self._panel.setAlphaValue_(0.96)
def _hide_for_click(self) -> None:
"""Make the panel invisible without destroying it (pre-click)."""
if self._panel is None:
return
self._panel.setAlphaValue_(0.0)
# ---- Public API ---------------------------------------------------------
def show(self, auto_click: bool = True) -> Optional[NavigationResult]:
"""
Display the overlay and block until the user selects an item or
dismisses with Escape.
Must be called on the main thread.
Args:
auto_click: If True (default), fires a Quartz mouse click at the
selected item's (x, y) coordinates when they are present.
Returns:
NavigationResult if the user selected something, None if dismissed.
Check ``result.clicked`` to branch:
- True → click was fired; nothing more to do.
- False → item had no coordinates; send ``result.label`` to the LLM.
"""
if not self._menus:
raise RuntimeError("No menus loaded. Call load() first.")
# Reset state for this session
with self._lock:
self._level = 0
self._menu_idx = 0
self._item_idx = 0
self._selected_item = None
self._display_mode = "menu"
self._done_event.clear()
# Build / raise the panel.
self._ensure_panel_built()
self._refresh_display()
self._raise_to_top()
# Install the Quartz event tap BEFORE we announce / draw so it's
# ready the instant the user starts pressing keys. pynput's
# suppress=True listener is unreliable on macOS — keys leak
# through to the frontmost app. A direct CGEventTap swallows
# Tab/Return/Escape cleanly.
self._key_tap = _NavigatorKeyTap(
on_tab=self._handle_cycle,
on_return=self._handle_select,
on_escape=self._handle_back,
)
tap_ok = self._key_tap.start()
if not tap_ok:
# Fallback: pynput. Better than nothing, but keys may leak.
self._key_tap = None
self._listener = keyboard.Listener(
on_press=self._on_key_press,
suppress=True,
)
self._listener.start()
# Announce context text immediately so the user hears what's on
# offer as soon as the panel appears. _announce handles both the
# `say` subprocess AND the NSAccessibility notification.
open_text = self._context or self._menus[0].label
self._announce(open_text, delay=0.02)
# Pump NSRunLoop until the user selects or dismisses. The event
# tap callback fires on this same main thread during the pump,
# so _handle_cycle / _handle_select / _handle_back run inline.
loop = Foundation.NSRunLoop.currentRunLoop()
while not self._done_event.is_set():
dl = Foundation.NSDate.dateWithTimeIntervalSinceNow_(0.05)
loop.runMode_beforeDate_(Foundation.NSDefaultRunLoopMode, dl)
time.sleep(0.01)
# Tear down the key tap BEFORE the click so the user's Return
# press doesn't bleed through to the browser.
if self._key_tap is not None:
self._key_tap.stop()
self._key_tap = None
if self._listener is not None:
self._listener.stop()
self._listener = None
# Fire the click if the item has coordinates.
item = self._selected_item
if auto_click and item is not None and item.x is not None and item.y is not None:
# ── Click path: hide panel → focus target app → click → restore ──
self._hide_for_click()
# Let the window server paint the alpha 0 before we activate
# the target app, so the panel is actually gone when the click
# lands (important when the click target is behind the panel).
end_t = time.time() + 0.12
while time.time() < end_t:
dl = Foundation.NSDate.dateWithTimeIntervalSinceNow_(0.02)
loop.runMode_beforeDate_(Foundation.NSDefaultRunLoopMode, dl)
# Bring Chrome (or whatever target_app is) to the foreground.
self._activate_target_app()
# Brief settle so activation completes before the click.
time.sleep(0.15)
try:
self._clicker.click(item.x, item.y, coords=item.coords)
except Exception as exc:
print(f"[navigator] click failed: {exc}")
# Give the click a moment to register before we put the panel back.
time.sleep(0.25)
# Flash "Clicked: X" on the overlay as visual confirmation, then
# let the caller's run_session take over with "Thinking…" as it
# grabs the new screenshot.
with self._lock:
self._display_mode = "message"
self._message_text = f"Clicked: {item.label}"
self._apply_message_display(self._message_text)
self._raise_to_top()
return NavigationResult(label=item.label, clicked=True, item=item)
# ── No click path: dismissal or conceptual pick ────────────────────
# Return to idle so the panel isn't left showing the last menu state.
with self._lock:
self._display_mode = "idle"
self._apply_idle_display()
self._raise_to_top()
if item is None:
return None
# Conceptual pick — item had no coords; caller feeds label to Gemma.
return NavigationResult(label=item.label, clicked=False, item=item)
# ---- Panel construction -------------------------------------------------
def _build_panel(self) -> None:
screen = AppKit.NSScreen.mainScreen()
sw = screen.frame().size.width
# NSWindowStyleMaskNonactivatingPanel is CRITICAL: it tells macOS
# that this panel should never become the key window and never
# activate our app, so clicking elsewhere in any other app does
# NOT deactivate us and the panel stays visible forever.
style_mask = (
AppKit.NSWindowStyleMaskBorderless
| AppKit.NSWindowStyleMaskNonactivatingPanel
)
self._panel = AppKit.NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(
Foundation.NSMakeRect(0, SCREEN_BOTTOM_MARGIN, sw, OVERLAY_HEIGHT),
style_mask,
AppKit.NSBackingStoreBuffered,
False,
)
# Explicit: this panel should never become key or main. Belt and
# suspenders on top of the NonactivatingPanel style mask.
self._panel.setBecomesKeyOnlyIfNeeded_(True)
# NSScreenSaverWindowLevel (1000) sits above every normal, floating,
# menu, popup, and even fullscreen-app window. +1 guarantees we're
# above anything else that claims the same level. This makes the
# overlay stuck on the top-most layer; it cannot be occluded.
self._panel.setLevel_(AppKit.NSScreenSaverWindowLevel + 1)
self._panel.setOpaque_(True)
# Start fully visible — no fade in. The panel will appear the moment
# orderFrontRegardless() is called.
self._panel.setAlphaValue_(0.96)
self._panel.setIgnoresMouseEvents_(True)
# Hide-on-deactivate off: keep the panel visible even when another app
# is in the foreground.
self._panel.setHidesOnDeactivate_(False)
self._panel.setCollectionBehavior_(
AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces
| AppKit.NSWindowCollectionBehaviorStationary
| AppKit.NSWindowCollectionBehaviorFullScreenAuxiliary
# Treat the panel as transient so Mission Control / Expose don't
# force it into a space and then hide it on switch.
| AppKit.NSWindowCollectionBehaviorTransient
# Ignore the app's cycle so Cmd+~ and Mission Control can't move
# focus to our panel.
| AppKit.NSWindowCollectionBehaviorIgnoresCycle,
)
cv = self._panel.contentView()
cw = cv.bounds().size.width
ch = cv.bounds().size.height # == OVERLAY_HEIGHT
# ── Background fill ──────────────────────────────────────────────────
bg = AppKit.NSView.alloc().initWithFrame_(cv.bounds())
bg.setWantsLayer_(True)
bg.layer().setBackgroundColor_(
AppKit.NSColor.colorWithRed_green_blue_alpha_(0.06, 0.06, 0.09, 1.0).CGColor()
)
cv.addSubview_(bg)
# ── Cyan accent bar (top edge) ───────────────────────────────────────
_add_colored_view(cv,
Foundation.NSMakeRect(0, ch - ACCENT_BAR_H, cw, ACCENT_BAR_H),
ACCENT_R, ACCENT_G, ACCENT_B)
# ── "NAVIGATOR" badge ────────────────────────────────────────────────
badge = _make_label(
" NAVIGATOR ", 12, AppKit.NSFontWeightBold,
AppKit.NSColor.colorWithRed_green_blue_alpha_(ACCENT_R, ACCENT_G, ACCENT_B, 1.0),
monospaced=True,
)
badge.sizeToFit()
bsz = badge.frame().size
by = ch - ACCENT_BAR_H - bsz.height - 8 # bottom of badge
badge.setFrame_(Foundation.NSMakeRect(24, by, bsz.width, bsz.height))
cv.addSubview_(badge)
# ── Breadcrumb label (right-aligned, same row as badge) ──────────────
self._label_breadcrumb = _make_label(
"", 12, AppKit.NSFontWeightRegular,
AppKit.NSColor.colorWithRed_green_blue_alpha_(1.0, 1.0, 1.0, 0.55),
monospaced=True,
)
self._label_breadcrumb.setAlignment_(AppKit.NSTextAlignmentRight)
self._label_breadcrumb.setFrame_(Foundation.NSMakeRect(
24 + bsz.width + 12,
by,
cw - 24 - bsz.width - 12 - 24,
bsz.height,
))
cv.addSubview_(self._label_breadcrumb)
# ── Separator 1 (below badge row) ────────────────────────────────────
sep1_y = by - 9
_add_separator(cv, cw, sep1_y)
# ── Context label (2 lines, 15 pt) ───────────────────────────────────
ctx_h = 44
ctx_y = sep1_y - 1 - ctx_h
self._label_context = _make_label(
"", 15, AppKit.NSFontWeightRegular,
AppKit.NSColor.colorWithRed_green_blue_alpha_(1.0, 1.0, 1.0, 0.70),
)
self._label_context.setLineBreakMode_(AppKit.NSLineBreakByWordWrapping)
self._label_context.setMaximumNumberOfLines_(2)
self._label_context.setFrame_(Foundation.NSMakeRect(24, ctx_y, cw - 48, ctx_h))
cv.addSubview_(self._label_context)
# ── Separator 2 (below context) ──────────────────────────────────────
_add_separator(cv, cw, ctx_y - 9)
# ── Current item label (BIG, centered) ───────────────────────────────
self._label_current = _make_label(
"", 38, AppKit.NSFontWeightSemibold,
AppKit.NSColor.whiteColor(),
)
self._label_current.setAlignment_(AppKit.NSTextAlignmentCenter)
self._label_current.setLineBreakMode_(AppKit.NSLineBreakByTruncatingTail)
self._label_current.setMaximumNumberOfLines_(2)
self._label_current.setFrame_(
Foundation.NSMakeRect(24, _CURRENT_Y, cw - 48, _CURRENT_H)
)
self._label_current.setAccessibilityRole_(AppKit.NSAccessibilityStaticTextRole)
cv.addSubview_(self._label_current)
# ── Neighbours label (dimmed, just below current item) ───────────────
self._label_neighbours = _make_label(
"", 13, AppKit.NSFontWeightRegular,
AppKit.NSColor.colorWithRed_green_blue_alpha_(1.0, 1.0, 1.0, 0.35),
)
self._label_neighbours.setAlignment_(AppKit.NSTextAlignmentCenter)
self._label_neighbours.setFrame_(
Foundation.NSMakeRect(24, _NBR_Y, cw - 48, _NBR_H)
)
cv.addSubview_(self._label_neighbours)
# ── Separator 3 (above hints) ────────────────────────────────────────
_add_separator(cv, cw, _SEP3_Y)
# ── Hints (static) ───────────────────────────────────────────────────
hints = _make_label(
"[Tab] Cycle [↩] Select [Esc] Back / Dismiss",
11, AppKit.NSFontWeightLight,
AppKit.NSColor.colorWithRed_green_blue_alpha_(1.0, 1.0, 1.0, 0.38),
monospaced=True,
)
hints.setAlignment_(AppKit.NSTextAlignmentCenter)
hints.setFrame_(Foundation.NSMakeRect(24, _HINTS_Y, cw - 48, _HINTS_H))
cv.addSubview_(hints)
# ---- Display update -----------------------------------------------------
def _refresh_display(self) -> None:
"""Push the current state to the panel labels (main thread safe)."""
with self._lock:
mode = self._display_mode
if mode == "message":
self._apply_message_display(self._message_text)
return
if mode == "idle":
self._apply_idle_display()
return
# else fall through → menu mode
self._apply_menu_display()
def _apply_menu_display(self) -> None:
"""Update labels for menu mode."""
with self._lock:
level = self._level
menu_idx = self._menu_idx
item_idx = self._item_idx
menus = self._menus
context = self._context
if not menus:
return
if level == 0:
n = len(menus)
current = menus[menu_idx].label
crumb = f"Choose a category {menu_idx + 1} / {n}"
prev_l = menus[(menu_idx - 1) % n].label if n > 1 else ""
next_l = menus[(menu_idx + 1) % n].label if n > 1 else ""
else:
menu = menus[menu_idx]
n = len(menu.items)
current = menu.items[item_idx].label if n > 0 else "(empty)"
crumb = f"{menu.label} {item_idx + 1} / {n}"
prev_l = menu.items[(item_idx - 1) % n].label if n > 1 else ""
next_l = menu.items[(item_idx + 1) % n].label if n > 1 else ""
if prev_l and next_l:
nbr = f"← {prev_l} · {next_l} →"
else:
nbr = prev_l or next_l or ""
ctx_short = (context[:117] + "…") if len(context) > 120 else context
def _apply() -> None:
if self._label_breadcrumb is not None:
self._label_breadcrumb.setStringValue_(crumb)
if self._label_context is not None:
self._label_context.setStringValue_(ctx_short)
if self._label_current is not None:
self._label_current.setFont_(
AppKit.NSFont.systemFontOfSize_weight_(38, AppKit.NSFontWeightSemibold)
)
self._label_current.setMaximumNumberOfLines_(2)
self._label_current.setLineBreakMode_(AppKit.NSLineBreakByTruncatingTail)
self._label_current.setStringValue_(f"▶ {current}")
if self._label_neighbours is not None:
self._label_neighbours.setStringValue_(nbr)
try:
self._panel.display()
except Exception:
pass
Foundation.NSOperationQueue.mainQueue().addOperationWithBlock_(_apply)
def _apply_message_display(self, text: str) -> None:
"""Update labels to show `text` as a large announcement."""
if self._panel is None:
return
# Pick font size based on message length so long sentences still fit.
n = len(text)
if n > 80:
font_size = 20
max_lines = 5
elif n > 35:
font_size = 26
max_lines = 3
else:
font_size = 36
max_lines = 2
def _apply() -> None:
if self._label_breadcrumb is not None:
self._label_breadcrumb.setStringValue_("announcement")
if self._label_context is not None:
self._label_context.setStringValue_("")
if self._label_current is not None:
self._label_current.setFont_(
AppKit.NSFont.systemFontOfSize_weight_(
font_size, AppKit.NSFontWeightSemibold
)
)
self._label_current.setMaximumNumberOfLines_(max_lines)
self._label_current.setLineBreakMode_(AppKit.NSLineBreakByWordWrapping)
self._label_current.setAlignment_(AppKit.NSTextAlignmentCenter)
self._label_current.setStringValue_(text)
if self._label_neighbours is not None:
self._label_neighbours.setStringValue_("")
try:
self._panel.display()
except Exception:
pass
# Dispatch to main queue if we're off the main thread; otherwise run
# inline so the redraw happens before we return.