curses_ui.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. """Curses checklist / radiolist / single-select menus with keyboard navigation and fuzzy ``/``
  2. search, plus a numbered text fallback for terminals without curses."""
  3. import re
  4. import sys
  5. from contextvars import ContextVar, Token
  6. from dataclasses import dataclass
  7. from enum import Enum
  8. from typing import Callable, List, Optional, Sequence, Set, Tuple, Union
  9. from hermes_cli.colors import Colors, color
  10. # Rich radiolist rows: (text, style). style is None | "yellow" | "dim" | "green" | "red". Plain ``str`` works too.
  11. RadioItem = str | Sequence[tuple[str, str | None]]
  12. _NO_REPLAY = object()
  13. @dataclass(frozen=True)
  14. class MenuNavigationStart:
  15. """Navigation instructions returned when a scoped menu begins."""
  16. allow_back: bool = False
  17. replay_value: object = _NO_REPLAY
  18. @property
  19. def should_replay(self) -> bool:
  20. return self.replay_value is not _NO_REPLAY
  21. class MenuNavigationEvent(str, Enum):
  22. BEGIN = "begin"
  23. RESOLVE = "resolve"
  24. CANCEL = "cancel"
  25. BACK = "back"
  26. # Scoped flow controller: ``handler(event, value=None) -> MenuNavigationStart | None``.
  27. MenuNavigationHandler = Callable[..., "MenuNavigationStart | None"]
  28. _MENU_NAVIGATION_HANDLER: ContextVar[MenuNavigationHandler | None] = ContextVar(
  29. "hermes_menu_navigation_handler", default=None)
  30. _NUMBERED_BACK_ENABLED: ContextVar[bool] = ContextVar("hermes_numbered_back_enabled", default=False)
  31. def set_menu_navigation_handler(handler: MenuNavigationHandler) -> Token:
  32. """Scope setup-style cancel/back behavior to the current CLI invocation."""
  33. return _MENU_NAVIGATION_HANDLER.set(handler)
  34. def reset_menu_navigation_handler(token: Token) -> None:
  35. """Restore the menu navigation handler active before ``token``."""
  36. _MENU_NAVIGATION_HANDLER.reset(token)
  37. def _notify_scoped_navigation(event: MenuNavigationEvent) -> None:
  38. handler = _MENU_NAVIGATION_HANDLER.get()
  39. if handler is not None:
  40. handler(event)
  41. class _NumberedNavigation(Enum):
  42. CANCEL = "cancel"
  43. BACK = "back"
  44. _NAV_ABORT = object()
  45. def _read_numbered_choice(prompt_text: str) -> int | None | object:
  46. """Numbered-fallback choice as a 0-based index; ``None`` for empty input, ``_NAV_ABORT`` when
  47. cancelled / backed out / interrupted / non-integer (scoped navigation is notified)."""
  48. try:
  49. val = _read_numbered_input(prompt_text)
  50. except (KeyboardInterrupt, EOFError):
  51. _notify_scoped_navigation(MenuNavigationEvent.CANCEL)
  52. return _NAV_ABORT
  53. if isinstance(val, _NumberedNavigation):
  54. _notify_scoped_navigation(MenuNavigationEvent(val.value))
  55. return _NAV_ABORT
  56. if not val.strip():
  57. return None
  58. idx = _parse_int(val.strip(), default=None)
  59. return _NAV_ABORT if idx is None else idx - 1
  60. def _read_numbered_input(prompt_text: str) -> str | _NumberedNavigation:
  61. """Plain ``input()`` outside setup flows; inside a scoped flow prompt_toolkit supplies portable
  62. Escape / Ctrl+C / Left bindings on POSIX and native Windows."""
  63. if _MENU_NAVIGATION_HANDLER.get() is None:
  64. return input(prompt_text)
  65. from prompt_toolkit import PromptSession
  66. from prompt_toolkit.formatted_text import ANSI
  67. from prompt_toolkit.key_binding import KeyBindings
  68. from prompt_toolkit.keys import Keys
  69. # Setup may run without the classic CLI, which normally installs CSI-u aliases at startup.
  70. from hermes_cli.pt_input_extras import install_modify_other_keys_aliases
  71. install_modify_other_keys_aliases()
  72. bindings = KeyBindings()
  73. @bindings.add(Keys.Escape)
  74. @bindings.add(Keys.ControlC)
  75. def _cancel(event) -> None:
  76. event.app.exit(result=_NumberedNavigation.CANCEL)
  77. if _NUMBERED_BACK_ENABLED.get():
  78. @bindings.add(Keys.Left)
  79. def _back(event) -> None:
  80. event.app.exit(result=_NumberedNavigation.BACK)
  81. return PromptSession().prompt(ANSI(prompt_text), key_bindings=bindings)
  82. def radio_item_plain(item: RadioItem) -> str:
  83. """Flatten a radiolist item to searchable/plain display text."""
  84. return item if isinstance(item, str) else "".join(text for text, _style in item)
  85. def _curses_style_attr(curses, style: Optional[str], *, is_cursor: bool):
  86. """Map a segment style to a curses attribute."""
  87. has_colors = curses.has_colors()
  88. if is_cursor:
  89. return curses.A_BOLD | (curses.color_pair(1) if has_colors else 0)
  90. if style == "yellow" and has_colors:
  91. return curses.color_pair(2)
  92. if style == "green" and has_colors:
  93. return curses.color_pair(1)
  94. if style == "red" and has_colors:
  95. try:
  96. return curses.color_pair(4)
  97. except curses.error:
  98. return curses.A_BOLD
  99. if style != "dim":
  100. return curses.A_NORMAL
  101. attr = curses.A_DIM
  102. if has_colors:
  103. try:
  104. attr |= curses.color_pair(3) # dim-gray status pair (extra_color_pairs)
  105. except curses.error:
  106. pass
  107. return attr
  108. def _addnstr(stdscr, y: int, x: int, text: str, n: int, attr) -> None:
  109. """``stdscr.addnstr`` that swallows ``curses.error`` (drawing past the screen edge)."""
  110. import curses
  111. try:
  112. stdscr.addnstr(y, x, text, n, attr)
  113. except curses.error:
  114. pass
  115. def _draw_title_and_hint(stdscr, title: str, hint: str, max_x: int, *, hint_row: int = 1) -> None:
  116. """Bold/yellow menu title on row 0, dim key hint on ``hint_row``."""
  117. import curses
  118. hattr = curses.A_BOLD | (curses.color_pair(2) if curses.has_colors() else 0)
  119. _addnstr(stdscr, 0, 0, title, max_x - 1, hattr)
  120. _addnstr(stdscr, hint_row, 0, hint, max_x - 1, curses.A_DIM)
  121. def _draw_segments(stdscr, y: int, x: int, segments, max_x: int) -> None:
  122. """Draw ``(text, attr)`` segments left to right from column ``x``, clipped at the edge."""
  123. col = x
  124. for text, attr in segments:
  125. remaining = max_x - 1 - col
  126. if remaining <= 0:
  127. break
  128. chunk = text[:remaining]
  129. _addnstr(stdscr, y, col, chunk, remaining, attr)
  130. col += len(chunk)
  131. def _draw_description_line(stdscr, y: int, text: str, max_x: int) -> None:
  132. """Draw a description line, highlighting ★ in yellow and ``[|||| ]`` gauges by how much is used."""
  133. import curses
  134. star_attr = curses.color_pair(2) if curses.has_colors() else curses.A_NORMAL
  135. segments = []
  136. for i, part in enumerate(text.split("★")):
  137. if i:
  138. segments.append(("★", star_attr))
  139. if part:
  140. segments.extend(
  141. (chunk, _curses_style_attr(curses, style, is_cursor=False))
  142. for chunk, style in _gauge_bar_segments(part)
  143. )
  144. _draw_segments(stdscr, y, 0, segments, max_x)
  145. def _draw_radio_item(
  146. stdscr, y: int, x: int, item: RadioItem, max_x: int, *, is_cursor: bool) -> None:
  147. """Draw a plain or segmented radiolist item starting at column ``x``."""
  148. import curses
  149. if isinstance(item, str):
  150. attr = _curses_style_attr(curses, None, is_cursor=is_cursor)
  151. _addnstr(stdscr, y, x, item, max(0, max_x - 1 - x), attr)
  152. return
  153. _draw_segments(
  154. stdscr, y, x,
  155. ((text, _curses_style_attr(curses, style, is_cursor=is_cursor)) for text, style in item),
  156. max_x)
  157. def _draw_plain_row(stdscr, y: int, line: str, max_x: int, *, is_cursor: bool) -> None:
  158. """Draw a plain menu row, bold green when it is the cursor row."""
  159. import curses
  160. _addnstr(stdscr, y, 0, line, max_x - 1, _curses_style_attr(curses, None, is_cursor=is_cursor))
  161. _WORD_BOUNDARY = frozenset("-_/. ")
  162. def _is_boundary(target: str, index: int) -> bool:
  163. """Mirrors ``isBoundary`` in the TS scorer: start, after a separator, or lower->Upper."""
  164. if index == 0:
  165. return True
  166. prev, cur = target[index - 1], target[index]
  167. return prev in _WORD_BOUNDARY or (
  168. prev == prev.lower() and cur != cur.lower() and cur == cur.upper())
  169. def _token_score(orig: str, lower: str, token: str) -> float | None:
  170. """Score one token against a target; None if not a subsequence. Faithful port of ``fuzzyScore``
  171. in ui-tui / web ``fuzzy.ts`` so all surfaces rank identically; matches run against ``lower``,
  172. boundary detection uses ``orig`` for camelCase."""
  173. score, prev = 0.0, -1
  174. positions: list[int] = []
  175. for ch in token:
  176. idx = lower.find(ch, prev + 1)
  177. if idx < 0:
  178. return None
  179. positions.append(idx)
  180. score += 1
  181. if prev >= 0 and idx == prev + 1:
  182. score += 5
  183. elif prev >= 0:
  184. score -= min(idx - prev - 1, 3)
  185. if _is_boundary(orig, idx):
  186. score += 3
  187. if idx == 0:
  188. score += 5
  189. prev = idx
  190. if positions and positions[0] == 0 and positions[-1] == len(positions) - 1:
  191. score += 8 # contiguous prefix
  192. if lower == token:
  193. score += 20 # exact match dominates
  194. return score - len(lower) * 0.01 # slightly prefer shorter targets
  195. def _fuzzy_score(label: str, query: str) -> float | None:
  196. """Multi-token AND score (``fuzzyScoreMulti``): sum of per-token scores, None if any fails."""
  197. lower = label.lower()
  198. scores = [_token_score(label, lower, token) for token in query.lower().split()]
  199. return None if None in scores else sum(scores)
  200. def _filter_indices(items: list[str], query: str) -> list[int]:
  201. """Item indices matching *query*, best-first; ties keep catalog order. Empty query = all."""
  202. q = query.strip()
  203. if not q:
  204. return list(range(len(items)))
  205. scored = [(i, s) for i, label in enumerate(items) if (s := _fuzzy_score(label, q)) is not None]
  206. scored.sort(key=lambda pair: (-pair[1], pair[0]))
  207. return [i for i, _ in scored]
  208. @dataclass
  209. class _SearchState:
  210. """Mutable search state shared by curses picker loops."""
  211. active: bool = False
  212. query: str = ""
  213. def _reconcile_cursor(filtered: list[int], cursor: int) -> tuple[int, int]:
  214. """Return ``(cursor, cursor_pos)`` inside the filtered index list."""
  215. if not filtered:
  216. return cursor, 0
  217. return (cursor, filtered.index(cursor)) if cursor in filtered else (filtered[0], 0)
  218. def _move_filtered_cursor(filtered: list[int], cursor: int, cursor_pos: int, delta: int) -> int:
  219. """Move through the filtered index list, wrapping like the legacy menus."""
  220. return filtered[(cursor_pos + delta) % len(filtered)] if filtered else cursor
  221. def _scroll_for_cursor(
  222. scroll_offset: int, cursor_pos: int, visible_rows: int, total_rows: int) -> int:
  223. """Clamp scroll offset so the cursor remains visible."""
  224. visible_rows = max(1, visible_rows)
  225. if cursor_pos < scroll_offset:
  226. scroll_offset = cursor_pos
  227. elif cursor_pos >= scroll_offset + visible_rows:
  228. scroll_offset = cursor_pos - visible_rows + 1
  229. return max(0, min(scroll_offset, max(0, total_rows - visible_rows)))
  230. def _handle_active_search_key(
  231. curses_mod, key: int, search: _SearchState) -> tuple[bool, bool, bool]:
  232. """Handle a key while the search prompt is active -> ``(handled, confirm, changed)``."""
  233. if not search.active:
  234. return False, False, False
  235. if key == 27:
  236. # Esc stops search AND clears the query so a no-match filter can't strand the user on
  237. # an empty list; `changed` when there was a query so the driver resets scroll/cursor.
  238. had_query = bool(search.query)
  239. search.active = False
  240. search.query = ""
  241. return True, False, had_query
  242. if key in (curses_mod.KEY_ENTER, 10, 13):
  243. return True, True, False
  244. if key in (curses_mod.KEY_BACKSPACE, 127, 8):
  245. search.query = search.query[:-1]
  246. elif key == 21: # Ctrl+U
  247. search.query = ""
  248. elif 32 <= key < 127: # printable ASCII; avoids Latin-1 mojibake from 128-255
  249. search.query += chr(key)
  250. else:
  251. return False, False, False
  252. return True, False, True
  253. def flush_stdin() -> None:
  254. """Drain stray stdin bytes after ``curses.wrapper()`` and before the next ``input()``:
  255. ``curses.endwin()`` restores the terminal but does NOT drain the OS input buffer."""
  256. try:
  257. if sys.stdin.isatty():
  258. import termios
  259. termios.tcflush(sys.stdin, termios.TCIFLUSH)
  260. except Exception:
  261. pass
  262. # Normalized menu actions returned by ``read_menu_key``.
  263. NAV_UP, NAV_DOWN, NAV_BACK, NAV_SELECT = "up", "down", "back", "select"
  264. NAV_TOGGLE, NAV_CANCEL, NAV_INTERRUPT, NAV_NONE = "toggle", "cancel", "interrupt", "none"
  265. def read_menu_key(stdscr) -> str:
  266. """Read one keypress and normalize it to a ``NAV_*`` action: lone ESC (no continuation byte
  267. within a short window) and ``q`` cancel; unknown sequences map to ``NAV_NONE``."""
  268. return _decode_menu_key(stdscr, stdscr.getch())
  269. def _parse_int(value: str, default=0):
  270. try:
  271. return int(value)
  272. except ValueError:
  273. return default
  274. def _parse_csi_u_key(raw: str) -> tuple[int, int, int] | None:
  275. """Kitty/CSI-u key -> ``(codepoint, modifier, event_type)``; None without a codepoint."""
  276. parts = raw.split(";")
  277. codepoint = _parse_int(parts[0].split(":", 1)[0])
  278. if not codepoint:
  279. return None
  280. mod_fields = parts[1].split(":") if len(parts) > 1 else []
  281. modifier = _parse_int(mod_fields[0], 1) if mod_fields else 1
  282. event_type = _parse_int(mod_fields[1], 1) if len(mod_fields) > 1 else 1
  283. return codepoint, modifier, event_type
  284. def _parse_csi_numbers(raw: str) -> list[int]:
  285. """Semicolon-delimited CSI numbers for modifyOtherKeys."""
  286. return [_parse_int(part.split(":", 1)[0]) for part in raw.split(";")]
  287. _ENHANCED_NAV = {10: NAV_SELECT, 13: NAV_SELECT, 27: NAV_CANCEL, 32: NAV_TOGGLE}
  288. def _enhanced_key_action(codepoint: int, modifier: int = 1) -> str:
  289. """Map CSI-u/modifyOtherKeys codepoints to setup menu actions."""
  290. if codepoint in _ENHANCED_NAV:
  291. return _ENHANCED_NAV[codepoint]
  292. # CSI-u encodes Ctrl+C as `c` plus the Ctrl modifier bit; lock-state bits may be added, so
  293. # test the Ctrl bit rather than the canonical value 5.
  294. has_ctrl = bool((max(1, modifier) - 1) & 4)
  295. if codepoint == 3 or (codepoint in (99, 67) and has_ctrl):
  296. return NAV_INTERRUPT
  297. return NAV_CANCEL if codepoint == 4 or (codepoint in (100, 68) and has_ctrl) else NAV_NONE
  298. def _read_csi_tail(stdscr) -> tuple[str, int | None]:
  299. """Read CSI/SS3 parameter bytes through the final byte."""
  300. raw: list[str] = []
  301. for _ in range(32):
  302. value = stdscr.getch()
  303. if 0x40 <= value <= 0x7E:
  304. return "".join(raw), value
  305. if not 0x20 <= value <= 0x3F:
  306. break
  307. raw.append(chr(value))
  308. return "".join(raw), None
  309. _CSI_FINAL_NAV = {
  310. ord("A"): NAV_UP, ord("k"): NAV_UP, ord("B"): NAV_DOWN, ord("j"): NAV_DOWN, ord("D"): NAV_BACK}
  311. def _decode_escape_sequence(stdscr) -> str:
  312. """Decode the bytes after an ESC: lone ESC cancels, CSI/SS3 sequences map to actions."""
  313. nxt = stdscr.getch()
  314. if nxt == -1:
  315. return NAV_CANCEL # genuine lone ESC
  316. if nxt not in (ord("["), ord("O")): # not a CSI / SS3 introducer — swallow
  317. return NAV_NONE
  318. raw_params, final = _read_csi_tail(stdscr)
  319. if final in _CSI_FINAL_NAV:
  320. return _CSI_FINAL_NAV[final]
  321. if final == ord("u"):
  322. enhanced = _parse_csi_u_key(raw_params)
  323. if enhanced is not None:
  324. codepoint, modifier, event_type = enhanced
  325. if event_type == 3: # key release
  326. return NAV_NONE
  327. return _enhanced_key_action(codepoint, modifier)
  328. if final == ord("~"):
  329. params = _parse_csi_numbers(raw_params)
  330. if len(params) >= 3 and params[0] == 27:
  331. return _enhanced_key_action(params[2], params[1])
  332. return NAV_NONE
  333. def _decode_menu_key(stdscr, key: int) -> str:
  334. """Normalize an already-read keypress to a menu action (lets loops peek the raw key first)."""
  335. import curses
  336. plain = {
  337. curses.KEY_UP: NAV_UP, ord("k"): NAV_UP, curses.KEY_DOWN: NAV_DOWN, ord("j"): NAV_DOWN,
  338. curses.KEY_LEFT: NAV_BACK, 3: NAV_INTERRUPT, # 3 = Ctrl+C in raw/cbreak mode
  339. 4: NAV_CANCEL, # 4 = Ctrl+D (EOF) in raw mode: leaves the menu, as it does in cooked mode
  340. curses.KEY_ENTER: NAV_SELECT, 10: NAV_SELECT, 13: NAV_SELECT,
  341. ord(" "): NAV_TOGGLE, ord("q"): NAV_CANCEL}
  342. if key in plain:
  343. return plain[key]
  344. if key != 27:
  345. return NAV_NONE
  346. # ESC: wait briefly for a continuation byte. On slow PTYs (SSH/tmux) an arrow key's bytes
  347. # can arrive across separate reads, so a tiny timeout avoids misreading it as a bare ESC.
  348. try:
  349. stdscr.timeout(60)
  350. return _decode_escape_sequence(stdscr)
  351. finally:
  352. stdscr.timeout(-1) # restore blocking mode
  353. _KEEP = object() # on_action reducer result: keep looping (state changed, menu not resolved)
  354. _CONSUMED = object() # ``_route_key`` result: key eaten by the search prompt; redraw, no action
  355. _RESOLVING = frozenset({NAV_SELECT, NAV_TOGGLE, NAV_CANCEL, NAV_INTERRUPT, NAV_BACK})
  356. def _init_colors(curses, extra_color_pairs: bool) -> None:
  357. curses.curs_set(0)
  358. if curses.has_colors():
  359. curses.start_color()
  360. curses.use_default_colors()
  361. curses.init_pair(1, curses.COLOR_GREEN, -1)
  362. curses.init_pair(2, curses.COLOR_YELLOW, -1)
  363. try:
  364. curses.init_pair(4, curses.COLOR_RED, -1) # "red" gauge segments (usage nearly gone)
  365. except curses.error:
  366. pass # a terminal with few colour pairs keeps the menu; red gauges just render plain
  367. if extra_color_pairs:
  368. curses.init_pair(3, 8 if curses.COLORS > 8 else curses.COLOR_WHITE, -1)
  369. def _route_key(curses, stdscr, key: int, search: _SearchState, use_search: bool):
  370. """Turn a raw key into ``(action, changed)`` honoring an active ``/`` search prompt; ``action``
  371. may be ``_CONSUMED`` (redraw only), ``changed`` means the query changed."""
  372. if not use_search:
  373. return _decode_menu_key(stdscr, key), False
  374. if search.active and key == 27:
  375. # Enhanced keys (Ghostty/Kitty) also start with ESC: decode the full sequence before
  376. # treating a genuine Escape as "stop search".
  377. action = _decode_menu_key(stdscr, key)
  378. if action == NAV_CANCEL:
  379. search.active = False
  380. search.query = ""
  381. return _CONSUMED, True
  382. return (_CONSUMED if action == NAV_NONE else action), False
  383. if search.active:
  384. # Active search consumes query-editing keys; nav keys fall through.
  385. handled, confirm, changed = _handle_active_search_key(curses, key, search)
  386. if confirm:
  387. return NAV_SELECT, changed
  388. return (_CONSUMED if handled else _decode_menu_key(stdscr, key)), changed
  389. if key == ord("/"):
  390. search.active = True
  391. return _CONSUMED, False
  392. return _decode_menu_key(stdscr, key), False
  393. def _run_curses_menu(
  394. *, initial_cursor, item_count, draw_header, draw_row, on_action, reserve_bottom=1,
  395. draw_footer=None, extra_color_pairs=False, fallback, cancel_value, searchable=False,
  396. search_labels=None, selectable=None):
  397. """Shared curses single-/multi-select event loop: non-TTY guard, ``curses.wrapper`` setup,
  398. clear/refresh cycle, scroll math, key dispatch with cursor wrap, KeyboardInterrupt /
  399. curses-unavailable fallback.
  400. ``draw_row`` always receives the ORIGINAL item index; ``on_action`` returns ``_KEEP`` to
  401. continue or any other value to resolve; a ``draw_footer`` row budget must be included in
  402. ``reserve_bottom``; with ``searchable``, ``/`` filters over ``search_labels`` (length ==
  403. ``item_count``) and results are original indices. ``selectable(i)`` (default: every row)
  404. marks rows the cursor skips, e.g. section headings: drawn, never landed on.
  405. """
  406. navigation_handler = _MENU_NAVIGATION_HANDLER.get()
  407. def _notify(event, *value):
  408. if navigation_handler is not None:
  409. navigation_handler(event, *value)
  410. start = navigation_handler(MenuNavigationEvent.BEGIN) if navigation_handler else None
  411. if start is not None and not isinstance(start, MenuNavigationStart):
  412. raise TypeError("menu navigation 'begin' must return MenuNavigationStart")
  413. allow_back = bool(start and start.allow_back)
  414. if start is not None and start.should_replay:
  415. _notify(MenuNavigationEvent.RESOLVE, start.replay_value)
  416. return start.replay_value
  417. # Non-TTY stdin: curses and input() both hang or spin, so return the cancel value directly
  418. # (the numbered fallback is only for curses errors on a real TTY).
  419. if not sys.stdin.isatty():
  420. return cancel_value
  421. use_search = searchable and search_labels is not None and len(search_labels) == item_count
  422. def _run_fallback():
  423. back_token = _NUMBERED_BACK_ENABLED.set(allow_back)
  424. try:
  425. result = fallback()
  426. finally:
  427. _NUMBERED_BACK_ENABLED.reset(back_token)
  428. _notify(MenuNavigationEvent.RESOLVE, result)
  429. return result
  430. try:
  431. import curses
  432. except ImportError:
  433. return _run_fallback()
  434. try:
  435. result_holder = [_KEEP]
  436. def _draw(stdscr):
  437. _init_colors(curses, extra_color_pairs)
  438. cursor, scroll_offset, search = initial_cursor, 0, _SearchState()
  439. while True:
  440. stdscr.clear()
  441. max_y, max_x = stdscr.getmaxyx()
  442. filtered = (
  443. _filter_indices(search_labels, search.query) if use_search
  444. else list(range(item_count)))
  445. # The cursor only ever rests on selectable rows; every row is still drawn.
  446. nav = filtered if selectable is None else [i for i in filtered if selectable(i)]
  447. cursor, _nav_pos = _reconcile_cursor(nav, cursor)
  448. cursor_pos = filtered.index(cursor) if cursor in filtered else 0
  449. items_start = draw_header(
  450. stdscr, max_y, max_x, search=search, back_enabled=allow_back)
  451. visible_rows = max(1, max_y - items_start - reserve_bottom)
  452. scroll_offset = _scroll_for_cursor(
  453. scroll_offset, cursor_pos, visible_rows, len(filtered))
  454. if use_search and search.query and not nav:
  455. _addnstr(stdscr, items_start, 0, " No matches", max_x - 1, curses.A_DIM)
  456. for draw_i, i in enumerate(filtered[scroll_offset : scroll_offset + visible_rows]):
  457. y = draw_i + items_start
  458. if y >= max_y - reserve_bottom:
  459. break
  460. draw_row(stdscr, y, i, i == cursor, max_x)
  461. if draw_footer is not None:
  462. draw_footer(stdscr, max_y, max_x)
  463. stdscr.refresh()
  464. action, changed = _route_key(curses, stdscr, stdscr.getch(), search, use_search)
  465. if changed:
  466. scroll_offset = 0
  467. if search.active: # Esc-clear resets scroll only; the loop re-reconciles
  468. refiltered = _filter_indices(search_labels, search.query)
  469. cursor, _ = _reconcile_cursor(
  470. refiltered if selectable is None else [i for i in refiltered if selectable(i)],
  471. cursor)
  472. if action in (NAV_UP, NAV_DOWN):
  473. delta = -1 if action == NAV_UP else 1
  474. cursor = _move_filtered_cursor(nav, cursor, _nav_pos, delta)
  475. continue
  476. if action is _CONSUMED or action not in _RESOLVING or (
  477. action == NAV_BACK and not allow_back) or (
  478. action == NAV_SELECT and use_search and not nav):
  479. continue
  480. if action in (NAV_CANCEL, NAV_INTERRUPT):
  481. _notify(MenuNavigationEvent.CANCEL)
  482. elif action == NAV_BACK:
  483. _notify(MenuNavigationEvent.BACK)
  484. outcome = on_action(action, cursor)
  485. if outcome is not _KEEP:
  486. _notify(MenuNavigationEvent.RESOLVE, outcome)
  487. result_holder[0] = outcome
  488. return
  489. curses.wrapper(_draw)
  490. flush_stdin()
  491. return result_holder[0] if result_holder[0] is not _KEEP else cancel_value
  492. except KeyboardInterrupt:
  493. _notify(MenuNavigationEvent.CANCEL)
  494. return cancel_value
  495. except curses.error:
  496. return _run_fallback()
  497. def curses_checklist(
  498. title: str, items: list[str], selected: set[int], *, cancel_returns: set[int] | None = None,
  499. status_fn: Optional[Callable[[set[int]], str]] = None) -> set[int]:
  500. """Curses multi-select checklist -> set of selected indices. ``cancel_returns`` (default: the
  501. original *selected*) is returned on ESC/q; ``status_fn(chosen)`` renders on the bottom row
  502. for live aggregate info such as token estimates."""
  503. if cancel_returns is None:
  504. cancel_returns = set(selected)
  505. chosen = set(selected)
  506. def _draw_row(stdscr, y, i, is_cursor, max_x):
  507. line = f" {'→' if is_cursor else ' '} [{'✓' if i in chosen else ' '}] {items[i]}"
  508. _draw_plain_row(stdscr, y, line, max_x, is_cursor=is_cursor)
  509. def _draw_footer(stdscr, max_y, max_x):
  510. import curses
  511. status_text = status_fn(chosen)
  512. if status_text: # right-aligned on the bottom row
  513. sx = max(0, max_x - len(status_text) - 1)
  514. sattr = curses.A_DIM | (curses.color_pair(3) if curses.has_colors() else 0)
  515. _addnstr(stdscr, max_y - 1, sx, status_text, max_x - sx - 1, sattr)
  516. def _on_action(action, cursor):
  517. if action == NAV_TOGGLE:
  518. chosen.symmetric_difference_update({cursor})
  519. return _KEEP
  520. if action == NAV_SELECT:
  521. return set(chosen)
  522. return cancel_returns # NAV_CANCEL
  523. return _run_curses_menu(
  524. initial_cursor=0, item_count=len(items),
  525. draw_header=_simple_header(title, "SPACE toggle ENTER confirm", "ESC cancel", False),
  526. draw_row=_draw_row, on_action=_on_action, reserve_bottom=(2 if status_fn else 1),
  527. draw_footer=_draw_footer if status_fn else None, extra_color_pairs=bool(status_fn),
  528. fallback=lambda: _numbered_fallback(title, items, selected, cancel_returns, status_fn),
  529. cancel_value=cancel_returns)
  530. def _search_hint(search, searchable: bool, confirm: str, cancel: str, back_enabled: bool) -> str:
  531. """Key-hint row for menus, swapping to the search prompt while ``/`` is active."""
  532. if searchable and search is not None and search.active:
  533. hint = f" Search: {search.query}\u258e BACKSPACE edit Ctrl+U clear ESC stop"
  534. else:
  535. hint = f" \u2191\u2193 navigate {confirm} {'/ search ' if searchable else ''}{cancel}"
  536. if back_enabled:
  537. hint += " \u2190 previous"
  538. return hint
  539. def _simple_header(title: str, confirm: str, cancel: str, searchable: bool):
  540. """``draw_header`` callback: title on row 0, key hint on row 1, items start on row 3."""
  541. def _draw_header(stdscr, max_y, max_x, search=None, back_enabled=False):
  542. hint = _search_hint(search, searchable, confirm, cancel, back_enabled)
  543. _draw_title_and_hint(stdscr, title, hint, max_x)
  544. return 3
  545. return _draw_header
  546. def curses_radiolist(
  547. title: str, items: list[RadioItem], selected: int = 0, *, cancel_returns: int | None = None,
  548. description: str | None = None, searchable: bool = False,
  549. search_labels: list[str] | None = None, headings: Optional[dict[int, str]] = None) -> int:
  550. """Curses single-select radio list -> selected index.
  551. Items are plain strings or ``(text, style)`` segment sequences (``None``/``"yellow"``/
  552. ``"dim"``); the cursor row is forced green. ``description`` is shown between title and list
  553. so context survives the curses screen clear. With ``searchable``, ``/`` filters over
  554. ``search_labels`` (default: display labels); the return value is always the ORIGINAL index.
  555. ``headings`` (``{item_index: text}``) draws a dim section title above that item; it is never
  556. selectable and is hidden while a search query is active.
  557. """
  558. if headings:
  559. return _radiolist_with_headings(
  560. title, items, selected, headings, cancel_returns=cancel_returns, description=description,
  561. searchable=searchable, search_labels=search_labels)
  562. if cancel_returns is None:
  563. cancel_returns = selected
  564. desc_lines = description.splitlines() if description else []
  565. if searchable:
  566. search_labels = (
  567. list(search_labels) if search_labels is not None
  568. else [radio_item_plain(item) for item in items])
  569. def _draw_header(stdscr, max_y, max_x, search=None, back_enabled=False):
  570. row = 1
  571. # Reserve title, hint, spacer, bottom margin, and up to five choices.
  572. # A long description must not push the selected row off-screen.
  573. choice_rows = min(max(1, len(items)), 5)
  574. description_rows = max(0, max_y - 4 - choice_rows)
  575. visible_description = desc_lines[:description_rows]
  576. if len(desc_lines) > description_rows and visible_description:
  577. hidden = len(desc_lines) - description_rows + 1
  578. visible_description[-1] = f" ... {hidden} more description lines (enlarge terminal)"
  579. for dline in visible_description: # ★ painted yellow to match rows
  580. _draw_description_line(stdscr, row, dline, max_x)
  581. row += 1
  582. hint = _search_hint(search, searchable, "ENTER/SPACE select", "ESC cancel", back_enabled)
  583. _draw_title_and_hint(stdscr, title, hint, max_x, hint_row=row)
  584. return row + 2 # one blank row between the hint and the item list
  585. def _draw_row(stdscr, y, i, is_cursor, max_x):
  586. radio, arrow = "\u25cf" if i == selected else "\u25cb", "\u2192" if is_cursor else " "
  587. prefix = f" {arrow} ({radio}) "
  588. _draw_plain_row(stdscr, y, prefix, max_x, is_cursor=is_cursor)
  589. _draw_radio_item(stdscr, y, len(prefix), items[i], max_x, is_cursor=is_cursor)
  590. def _on_action(action, cursor):
  591. return cursor if action in (NAV_SELECT, NAV_TOGGLE) else cancel_returns # NAV_CANCEL
  592. return _run_curses_menu(
  593. initial_cursor=selected, item_count=len(items), draw_header=_draw_header,
  594. draw_row=_draw_row, on_action=_on_action,
  595. extra_color_pairs=True, # dim gray (pair 3) for unselected "was …" sale chrome
  596. fallback=lambda: _radio_numbered_fallback(title, items, selected, cancel_returns),
  597. cancel_value=cancel_returns, searchable=searchable,
  598. search_labels=search_labels if searchable else None)
  599. def _radiolist_with_headings(
  600. title: str, items: list[RadioItem], selected: int, headings: dict[int, str], *,
  601. cancel_returns: int | None, description: str | None, searchable: bool,
  602. search_labels: list[str] | None) -> int:
  603. """``curses_radiolist`` with dim, unselectable section titles (``{item_index: text}``) drawn
  604. above the given items. Headings carry an empty search label, so any query hides them. Returns
  605. the ORIGINAL item index, exactly like the plain list."""
  606. if cancel_returns is None:
  607. cancel_returns = selected
  608. rows: list[tuple[str, int]] = [] # ("h", heading_key) or ("i", original item index)
  609. for i in range(len(items)):
  610. if i in headings:
  611. rows.append(("h", i))
  612. rows.append(("i", i))
  613. row_of_item = {idx: r for r, (kind, idx) in enumerate(rows) if kind == "i"}
  614. labels = (list(search_labels) if search_labels is not None
  615. else [radio_item_plain(item) for item in items])
  616. row_labels = ["" if kind == "h" else labels[idx] for kind, idx in rows]
  617. desc_lines = description.splitlines() if description else []
  618. def _draw_header(stdscr, max_y, max_x, search=None, back_enabled=False):
  619. row = 1
  620. choice_rows = min(max(1, len(rows)), 5)
  621. description_rows = max(0, max_y - 4 - choice_rows)
  622. visible_description = desc_lines[:description_rows]
  623. if len(desc_lines) > description_rows and visible_description:
  624. hidden = len(desc_lines) - description_rows + 1
  625. visible_description[-1] = f" ... {hidden} more description lines (enlarge terminal)"
  626. for dline in visible_description:
  627. _draw_description_line(stdscr, row, dline, max_x)
  628. row += 1
  629. hint = _search_hint(search, searchable, "ENTER/SPACE select", "ESC cancel", back_enabled)
  630. _draw_title_and_hint(stdscr, title, hint, max_x, hint_row=row)
  631. return row + 2
  632. def _draw_row(stdscr, y, r, is_cursor, max_x):
  633. import curses
  634. kind, idx = rows[r]
  635. if kind == "h":
  636. _addnstr(stdscr, y, 0, f" {headings[idx]}", max_x - 1, curses.A_DIM | curses.A_BOLD)
  637. return
  638. radio, arrow = "\u25cf" if idx == selected else "\u25cb", "\u2192" if is_cursor else " "
  639. prefix = f" {arrow} ({radio}) "
  640. _draw_plain_row(stdscr, y, prefix, max_x, is_cursor=is_cursor)
  641. _draw_radio_item(stdscr, y, len(prefix), items[idx], max_x, is_cursor=is_cursor)
  642. def _on_action(action, cursor):
  643. if action in (NAV_SELECT, NAV_TOGGLE):
  644. return rows[cursor][1]
  645. return cancel_returns
  646. return _run_curses_menu(
  647. initial_cursor=row_of_item.get(selected, 0), item_count=len(rows), draw_header=_draw_header,
  648. draw_row=_draw_row, on_action=_on_action, extra_color_pairs=True,
  649. fallback=lambda: _radio_numbered_fallback(title, items, selected, cancel_returns, headings=headings),
  650. cancel_value=cancel_returns, searchable=searchable,
  651. search_labels=row_labels if searchable else None,
  652. selectable=lambda r: rows[r][0] == "i")
  653. _ANSI_STYLE = {"yellow": Colors.YELLOW, "dim": Colors.DIM, "green": Colors.GREEN, "red": Colors.RED}
  654. # Exactly the ``render_bar`` shape (``model_picker_usage.BAR_WIDTH`` = 10 cells of ``|`` then spaces), so
  655. # an unrelated ``[]`` / ``[ ]`` in a description is never painted as a gauge.
  656. _GAUGE_BAR_RE = re.compile(r"\[(?=[| ]{10}\])\|* *\]")
  657. def _gauge_bar_style(bar: str) -> str:
  658. """Map a ``[|||| ]`` cell to green/yellow/red from how full it is (what is USED)."""
  659. inner = bar[1:-1]
  660. used = inner.count("|") / len(inner) if inner else 0.0
  661. if used > 0.8:
  662. return "red"
  663. if used > 0.5:
  664. return "yellow"
  665. return "green"
  666. def _gauge_bar_segments(text: str) -> list[tuple[str, str | None]]:
  667. """Split *text* so each ``[|||| ]`` is its own styled segment."""
  668. segs: list[tuple[str, str | None]] = []
  669. last = 0
  670. for match in _GAUGE_BAR_RE.finditer(text):
  671. if match.start() > last:
  672. segs.append((text[last:match.start()], None))
  673. segs.append((match.group(), _gauge_bar_style(match.group())))
  674. last = match.end()
  675. if last < len(text):
  676. segs.append((text[last:], None))
  677. return segs or [(text, None)]
  678. def colorize_gauge_bars_ansi(text: str) -> str:
  679. """Color ``[|||| ]`` runs in a header/legend line (numbered-fallback path)."""
  680. return "".join(
  681. color(chunk, _ANSI_STYLE[style]) if style in _ANSI_STYLE else chunk
  682. for chunk, style in _gauge_bar_segments(text)
  683. )
  684. def format_radio_item_ansi(item: RadioItem) -> str:
  685. """Apply ANSI colors to a rich radiolist item (numbered fallback / prints)."""
  686. if isinstance(item, str):
  687. return item
  688. return "".join(
  689. color(text, _ANSI_STYLE[style]) if style in _ANSI_STYLE else text for text, style in item)
  690. def _radio_numbered_fallback(
  691. title: str, items: list[RadioItem], selected: int, cancel_returns: int, *,
  692. headings: Optional[dict[int, str]] = None) -> int:
  693. """Text-based numbered fallback for radio selection (section titles printed, never numbered)."""
  694. print(color(f"\n {title}", Colors.YELLOW))
  695. print(color(" Select by number, Enter to confirm.\n", Colors.DIM))
  696. for i, label in enumerate(items):
  697. if headings and i in headings:
  698. print(color(f" {headings[i]}", Colors.DIM))
  699. marker = color("(\u25cf)", Colors.GREEN) if i == selected else "(\u25cb)"
  700. print(f" {marker} {i + 1:>2}. {format_radio_item_ansi(label)}")
  701. print()
  702. idx = _read_numbered_choice(color(f" Choice [default {selected + 1}]: ", Colors.DIM))
  703. if idx is _NAV_ABORT:
  704. return cancel_returns
  705. return idx if idx is not None and 0 <= idx < len(items) else selected
  706. def curses_single_select(
  707. title: str, items: list[str], default_index: int = 0, *, cancel_label: str = "Cancel",
  708. searchable: bool = False) -> int | None:
  709. """Curses single-select menu -> selected index or None on cancel. With ``searchable``, ``/``
  710. opens a type-to-filter prompt; the return value is always the original item index."""
  711. all_items = list(items) + [cancel_label]
  712. cancel_idx = len(items)
  713. def _draw_row(stdscr, y, i, is_cursor, max_x):
  714. line = f" {'→' if is_cursor else ' '} {all_items[i]}"
  715. _draw_plain_row(stdscr, y, line, max_x, is_cursor=is_cursor)
  716. def _on_action(action, cursor):
  717. if action == NAV_SELECT: # the synthetic cancel row resolves to None
  718. return None if cursor >= cancel_idx else cursor
  719. if action in (NAV_CANCEL, NAV_INTERRUPT):
  720. return None
  721. return _KEEP # NAV_TOGGLE — no-op for this menu
  722. return _run_curses_menu(
  723. initial_cursor=min(default_index, len(all_items) - 1), item_count=len(all_items),
  724. draw_header=_simple_header(title, "ENTER confirm", "ESC/q cancel", searchable),
  725. draw_row=_draw_row, on_action=_on_action,
  726. fallback=lambda: _numbered_single_fallback(title, all_items, cancel_idx),
  727. cancel_value=None, searchable=searchable,
  728. search_labels=list(all_items) if searchable else None)
  729. def _numbered_single_fallback(title: str, items: list[str], cancel_idx: int) -> int | None:
  730. """Text-based numbered fallback for single-select."""
  731. print(f"\n {title}\n")
  732. for i, label in enumerate(items, 1):
  733. print(f" {i}. {label}")
  734. print()
  735. idx = _read_numbered_choice(f" Choice [1-{len(items)}]: ")
  736. return idx if isinstance(idx, int) and 0 <= idx < min(len(items), cancel_idx) else None
  737. def _numbered_fallback(
  738. title: str, items: list[str], selected: set[int], cancel_returns: set[int],
  739. status_fn: Optional[Callable[[set[int]], str]] = None) -> set[int]:
  740. """Text-based toggle fallback for terminals without curses."""
  741. chosen = set(selected)
  742. print(color(f"\n {title}", Colors.YELLOW))
  743. print(color(" Toggle by number, Enter to confirm.\n", Colors.DIM))
  744. while True:
  745. for i, label in enumerate(items):
  746. marker = color("[✓]", Colors.GREEN) if i in chosen else "[ ]"
  747. print(f" {marker} {i + 1:>2}. {label}")
  748. status_text = status_fn(chosen) if status_fn else ""
  749. if status_text:
  750. print(color(f"\n {status_text}", Colors.DIM))
  751. print()
  752. idx = _read_numbered_choice(color(" Toggle # (or Enter to confirm): ", Colors.DIM))
  753. if idx is _NAV_ABORT:
  754. return cancel_returns
  755. if idx is None:
  756. return chosen
  757. if 0 <= idx < len(items):
  758. chosen.symmetric_difference_update({idx})
  759. print()