Coverage for src/scixplorer/cli/tui.py: 95%
446 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""The results browser of the ``scix`` command.
3:class:`Browser` holds what is on the screen and changes it one key at a time;
4it draws itself as lines of text and never touches the terminal, so it can be
5driven and read without one. :func:`run` connects it to a terminal.
6"""
8from __future__ import annotations
10import os
11import re
12import shutil
13import subprocess
14import sys
15import webbrowser
16from collections.abc import Callable
17from dataclasses import dataclass, field
18from typing import Any, TextIO
20from ..exceptions import SciXError
21from ..models.document import Document
22from .interpret import Interpretation, interpret
23from .output import (
24 SORTS,
25 Style,
26 abstract_of,
27 authors_line,
28 facts,
29 fit,
30 page_url,
31 pdf_url,
32 reference,
33 short_authors,
34 title_of,
35 wrap,
36)
37from .session import Session
39__all__ = ["Browser", "decode_key", "decode_keys", "run"]
41#: How many documents are fetched at a time.
42PAGE = 50
44_KEYS = "↑↓ move ⏎ read o open f full text b BibTeX c cited by r references s sort / search ? help q quit"
46_HELP = """\
47↑ ↓ j k move PgUp PgDn g G a page, the first, the last
48⏎ → read the abstract ← Esc back
49o open the SciX page f open the full text
50c papers that cite it r papers it cites
51space mark b copy BibTeX (of the marked)
52y copy the bibcode s change the order
53/ search again q quit"""
55_ESCAPES = {
56 "[A": "up", "OA": "up", "[B": "down", "OB": "down", "[C": "right", "OC": "right", "[D": "left", "OD": "left",
57 "[5~": "pgup", "[6~": "pgdn", "[H": "home", "OH": "home", "[1~": "home", "[F": "end", "OF": "end", "[4~": "end",
58} # fmt: skip
60_CONTROLS = {
61 "\r": "enter", "\n": "enter", "\x7f": "backspace", "\x08": "backspace", "\t": "tab",
62 "\x03": "ctrl-c", "\x04": "ctrl-d", "\x15": "ctrl-u", "\x17": "ctrl-w",
63} # fmt: skip
66_ESCAPE = re.compile(r"\x1b(?:\[[0-9;?]*[ -/]*[@-~]|O[@-~])?")
69def decode_keys(data: bytes) -> list[str]:
70 """The keys a terminal sent as ``data``, in order.
72 Each is the name of a key (``"up"``, ``"enter"``, ``"esc"``, ``"ctrl-u"``)
73 or the text typed; text that arrives together (a paste) stays together.
74 Escape sequences that name no key here are left out.
75 """
76 text = data.decode("utf-8", "replace")
77 keys: list[str] = []
78 typed = ""
79 position = 0
80 while position < len(text):
81 character = text[position]
82 if character.isprintable():
83 typed += character
84 position += 1
85 continue
86 if typed:
87 keys.append(typed)
88 typed = ""
89 if character == "\x1b":
90 sequence = _ESCAPE.match(text, position)
91 assert sequence is not None
92 keys.append("esc" if len(sequence[0]) == 1 else _ESCAPES.get(sequence[0][1:], ""))
93 position = sequence.end()
94 else:
95 keys.append(_CONTROLS.get(character, ""))
96 position += 1
97 if typed:
98 keys.append(typed)
99 return [key for key in keys if key]
102def decode_key(data: bytes) -> str:
103 """The first key of :func:`decode_keys`, or ``""`` if there is none."""
104 keys = decode_keys(data)
105 return keys[0] if keys else ""
108def copy_to_clipboard(text: str) -> bool:
109 """Put ``text`` on the system clipboard; ``False`` if no clipboard program is installed."""
110 commands = (["pbcopy"], ["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "-ib"], ["clip.exe"])
111 for command in commands:
112 if shutil.which(command[0]) is None:
113 continue
114 try:
115 subprocess.run(command, input=text.encode("utf-8"), check=True, timeout=5)
116 except (OSError, subprocess.SubprocessError):
117 continue
118 return True
119 return False
122def _bibtex(documents: list[Document], client: Any) -> str:
123 from ..services import export
125 return export.bibtex(documents, client=client)
128@dataclass
129class _View:
130 """One search and where the reader is in its results."""
132 interpretation: Interpretation
133 documents: list[Document]
134 total: int
135 sort: str
136 selected: int = 0
137 top: int = 0
138 marked: set[str] = field(default_factory=set)
139 widened_from: Interpretation | None = None
142class Browser:
143 """A list of results with the selected document's abstract below it.
145 :param session: runs the searches.
146 :param sort: the order of the results (a key of ``SORTS``); ``None`` lets each search
147 choose: the most cited first if it names a year, else the newest.
148 :param style: how text is emphasised.
149 :param opener: opens a URL (default: the web browser).
150 :param copier: copies text to the clipboard, returning whether it could.
151 """
153 def __init__(
154 self,
155 session: Session,
156 *,
157 sort: str | None = None,
158 style: Style | None = None,
159 opener: Callable[[str], Any] = webbrowser.open,
160 copier: Callable[[str], bool] = copy_to_clipboard,
161 ) -> None:
162 self.session = session
163 self.sort = sort or "date"
164 self._fixed_sort = sort is not None
165 self.style = style or Style()
166 self.opener = opener
167 self.copier = copier
168 self.views: list[_View] = []
169 self.mode = "prompt"
170 self.buffer = ""
171 self.message = ""
172 self.scroll = 0
173 self.rows = 10
174 #: Called just before a request is sent, so that the screen can say so.
175 self.on_busy: Callable[[], None] | None = None
177 # State.
179 @property
180 def view(self) -> _View | None:
181 return self.views[-1] if self.views else None
183 @property
184 def document(self) -> Document | None:
185 view = self.view
186 if view is None or not view.documents:
187 return None
188 return view.documents[view.selected]
190 def _busy(self, message: str) -> None:
191 self.message = message
192 if self.on_busy is not None:
193 self.on_busy()
195 def search(self, query: str | Interpretation) -> bool:
196 """Run a search and show its results; on an error, say so and keep what is shown."""
197 try:
198 interpretation = interpret(query) if isinstance(query, str) else query
199 if interpretation.expr is None: 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true
200 self.message = "Type what to search for."
201 return False
202 if not self._fixed_sort:
203 self.sort = "citations" if any(r.kind == "year" for r in interpretation.readings) else "date"
204 self._busy(f"Searching: {interpretation} …")
205 found = self.session.find(interpretation, self.sort, limit=PAGE)
206 except (SciXError, ValueError) as error:
207 self.message = str(error)
208 return False
209 view = _View(found.interpretation, found.documents, found.total, self.sort)
210 if found.widened:
211 view.widened_from = interpretation
212 self.views.append(view)
213 self.mode, self.scroll = "list", 0
214 self.message = "" if found.total else "No documents."
215 return True
217 def _reload(self) -> None:
218 """Fetch the current search again in the current order."""
219 view = self.view
220 if view is None: 220 ↛ 221line 220 didn't jump to line 221 because the condition on line 220 was never true
221 return
222 try:
223 self._busy(f"Sorting, {SORTS[self.sort][2]} …")
224 documents, total = self.session.fetch(view.interpretation, self.sort, limit=PAGE)
225 except SciXError as error:
226 self.message = str(error)
227 return
228 self.views[-1] = _View(view.interpretation, documents, total, self.sort, widened_from=view.widened_from)
229 self.message = ""
231 def _more(self) -> None:
232 """Fetch the next documents when the selection nears the end of those loaded."""
233 view = self.view
234 if view is None or len(view.documents) >= view.total or view.selected < len(view.documents) - 5:
235 return
236 try:
237 self._busy("Loading more …")
238 documents, total = self.session.fetch(
239 view.interpretation, view.sort, limit=PAGE, offset=len(view.documents)
240 )
241 except SciXError as error:
242 self.message = str(error)
243 view.total = len(view.documents)
244 return
245 view.documents.extend(documents)
246 view.total = total if documents else len(view.documents)
247 self.message = ""
249 def _move(self, step: int) -> None:
250 view = self.view
251 if view is None or not view.documents:
252 return
253 view.selected = max(0, min(len(view.documents) - 1, view.selected + step))
254 self.scroll = 0
255 self._more()
257 # Keys.
259 def key(self, key: str) -> bool:
260 """Act on one key; ``False`` means the reader has quit."""
261 if key == "ctrl-c":
262 return False
263 if self.mode == "prompt":
264 return self._prompt_key(key)
265 self.message = ""
266 if self.mode == "help":
267 self.mode = "list"
268 return key != "q"
269 if key in ("q", "ctrl-d"):
270 return False
271 if self.mode == "read":
272 return self._read_key(key)
273 return self._list_key(key)
275 def _prompt_key(self, key: str) -> bool:
276 if key == "esc" or (key == "ctrl-d" and not self.buffer):
277 if not self.views:
278 return False
279 self.mode, self.message = "list", ""
280 elif key == "enter":
281 if self.buffer.strip():
282 self.search(self.buffer)
283 elif key == "backspace":
284 self.buffer = self.buffer[:-1]
285 elif key == "ctrl-u":
286 self.buffer = ""
287 elif key == "ctrl-w":
288 self.buffer = self.buffer.rstrip().rpartition(" ")[0]
289 self.buffer += " " if self.buffer else ""
290 elif key and key not in _ESCAPES.values() and key not in _CONTROLS.values():
291 self.buffer += key
292 return True
294 def _read_key(self, key: str) -> bool:
295 if key in ("esc", "left", "h", "backspace", "enter"):
296 self.mode, self.scroll = "list", 0
297 elif key in ("down", "j"):
298 self.scroll += 1
299 elif key in ("up", "k"):
300 self.scroll = max(0, self.scroll - 1)
301 elif key in ("pgdn", " "):
302 self.scroll += max(1, self.rows - 2)
303 elif key == "pgup":
304 self.scroll = max(0, self.scroll - max(1, self.rows - 2))
305 elif key == "n":
306 self._move(1)
307 elif key == "p":
308 self._move(-1)
309 else:
310 self._act(key)
311 return True
313 def _list_key(self, key: str) -> bool:
314 view = self.view
315 if key in ("down", "j"):
316 self._move(1)
317 elif key in ("up", "k"):
318 self._move(-1)
319 elif key == "pgdn":
320 self._move(self.rows)
321 elif key == "pgup":
322 self._move(-self.rows)
323 elif key in ("home", "g"):
324 self._move(-(10**9))
325 elif key in ("end", "G"):
326 self._move(10**9)
327 elif key in ("enter", "right", "l") and self.document is not None:
328 self.mode, self.scroll = "read", 0
329 elif key in ("esc", "left", "h", "backspace"):
330 if len(self.views) > 1:
331 self.views.pop()
332 self.sort = self.views[-1].sort
333 elif key == " " and view is not None and self.document is not None:
334 bibcode = self.document.bibcode
335 if bibcode: 335 ↛ 337line 335 didn't jump to line 337 because the condition on line 335 was always true
336 view.marked.symmetric_difference_update({bibcode})
337 self._move(1)
338 else:
339 self._act(key)
340 return True
342 def _act(self, key: str) -> None:
343 """The keys that mean the same in the list and while reading."""
344 document, view = self.document, self.view
345 if key == "/":
346 self.mode = "prompt"
347 self.buffer = view.interpretation.text if view is not None else ""
348 elif key == "?":
349 self.mode = "help"
350 elif key == "s":
351 names = list(SORTS)
352 self.sort = names[(names.index(self.sort) + 1) % len(names)]
353 self._fixed_sort = True
354 self._reload()
355 elif document is None or not document.bibcode:
356 return
357 elif key == "o":
358 url = page_url(document)
359 if url is not None: 359 ↛ exitline 359 didn't return from function '_act' because the condition on line 359 was always true
360 self.opener(url)
361 self.message = f"Opened {url}"
362 elif key == "f":
363 url = pdf_url(document)
364 if url is None:
365 self.message = "SciX lists no full text for this document."
366 else:
367 self.opener(url)
368 self.message = f"Opened {url}"
369 elif key == "c":
370 self.search(f"citations:{document.bibcode}")
371 elif key == "r":
372 self.search(f"references:{document.bibcode}")
373 elif key == "y":
374 self._copy(document.bibcode, f"Copied {document.bibcode}")
375 elif key == "b" and view is not None: 375 ↛ exitline 375 didn't return from function '_act' because the condition on line 375 was always true
376 chosen = [each for each in view.documents if each.bibcode in view.marked] or [document]
377 try:
378 self._busy("Exporting BibTeX …")
379 text = _bibtex(chosen, self.session.client)
380 except SciXError as error:
381 self.message = str(error)
382 return
383 noun = "document" if len(chosen) == 1 else "documents"
384 self._copy(text, f"Copied BibTeX for {len(chosen)} {noun}")
386 def _copy(self, text: str, done: str) -> None:
387 self.message = done if self.copier(text) else "No clipboard program found (pbcopy, wl-copy, xclip or xsel)."
389 # Drawing.
391 def render(self, width: int, height: int) -> list[str]:
392 """The screen as exactly ``height`` lines of at most ``width`` columns."""
393 width, height = max(width, 20), max(height, 6)
394 if self.mode == "help":
395 body = self._help(width)
396 elif self.mode == "read" and self.document is not None:
397 body = self._reading(width, height - 3)
398 else:
399 body = self._list(width, height - 3)
400 lines = [*self._header(width), *body][: height - 1]
401 lines += [""] * (height - 1 - len(lines))
402 if self.mode == "prompt" and self.message:
403 lines[-1] = self.style.warn(fit(" " + self.message, width))
404 lines.append(self._footer(width))
405 return lines
407 def _header(self, width: int) -> list[str]:
408 style, view = self.style, self.view
409 if view is None:
410 return [style.bold(" scix"), style.dim(fit(" Search SciX in plain words: Kewley 2008 · exoplanets since 2020 · ApJ 608 119", width))]
411 position = f"{view.selected + 1 if view.documents else 0}/{view.total} "
412 read = fit(f" {view.interpretation}", width - len(position) - 1, pad=True)
413 order = f" {SORTS[view.sort][2]}" if view.total > 1 else ""
414 if view.marked:
415 order += f" · {len(view.marked)} marked"
416 if view.widened_from is not None:
417 order += f" · nothing for: {view.widened_from}"
418 return [style.bold(style.accent(read)) + " " + style.dim(position), style.dim(fit(order, width))]
420 def _footer(self, width: int) -> str:
421 style = self.style
422 if self.mode == "prompt":
423 return fit(" search: " + self.buffer, width - 1) + style.selected(" ")
424 if self.message:
425 return style.warn(fit(" " + self.message, width))
426 if self.mode == "read":
427 return style.dim(fit(" ↑↓ scroll n p next, previous ← back o open f full text b BibTeX c cited by r references q quit", width))
428 return style.dim(fit(" " + _KEYS, width))
430 def _row(self, document: Document, width: int, marked: bool) -> str:
431 data = document._data
432 year = str(data.get("year") or "")
433 cited = str(data.get("citation_count") or 0)
434 who = 16 if width >= 70 else 10
435 where = fit(reference(document).split(" ")[0], 6, pad=True, right=True) if width >= 86 else ""
436 title = width - 2 - 5 - who - 2 - (len(where) + 2 if where else 0) - 7
437 row = (
438 ("● " if marked else " ")
439 + fit(year, 4, pad=True)
440 + " "
441 + fit(short_authors(document), who, pad=True)
442 + " "
443 + fit(title_of(document), title, pad=True)
444 )
445 if where:
446 row += " " + where
447 return fit(row + fit(cited, 7, pad=True, right=True), width)
449 def _list(self, width: int, height: int) -> list[str]:
450 view, style = self.view, self.style
451 if view is None or not view.documents:
452 return []
453 preview = (height - 1) // 2 if height >= 13 else 0
454 rows = max(1, height - (preview + 1 if preview else 0))
455 self.rows = rows
456 view.top = max(min(view.top, view.selected), view.selected - rows + 1, 0)
457 lines: list[str] = []
458 for index in range(view.top, min(view.top + rows, len(view.documents))):
459 document = view.documents[index]
460 row = self._row(document, width, document.bibcode in view.marked)
461 lines.append(style.selected(row) if index == view.selected else row)
462 if preview:
463 lines += [""] * (rows - len(lines))
464 lines.append(style.dim("─" * width))
465 lines.extend(self._details(view.documents[view.selected], width, limit=preview))
466 return lines
468 def _details(self, document: Document, width: int, *, limit: int | None = None, authors: int = 8) -> list[str]:
469 """A document in full: title, authors, where it appeared, abstract; cut to ``limit`` lines."""
470 style = self.style
471 inner = width - 2
472 title = wrap(title_of(document), inner)
473 if limit is not None:
474 title = title[:2]
475 lines = [" " + style.bold(line) for line in title]
476 who = authors_line(document, authors)
477 lines.extend(" " + line for line in ([fit(who, inner)] if limit is not None else wrap(who, inner)))
478 lines.append(" " + style.accent(fit(facts(document), inner)))
479 abstract = wrap(abstract_of(document) or "(no abstract)", inner)
480 lines.append("")
481 if limit is not None and len(lines) + len(abstract) > limit: 481 ↛ 482line 481 didn't jump to line 482 because the condition on line 481 was never true
482 abstract = abstract[: max(0, limit - len(lines))]
483 if abstract:
484 abstract[-1] = fit(abstract[-1] + " …", inner)
485 lines.extend(" " + line for line in abstract)
486 return lines if limit is None else lines[:limit]
488 def _reading(self, width: int, height: int) -> list[str]:
489 document = self.document
490 if document is None: 490 ↛ 491line 490 didn't jump to line 491 because the condition on line 490 was never true
491 return []
492 self.rows = height
493 lines = self._details(document, min(width, 100), authors=40)
494 data = document._data
495 extra = [f"doi:{doi}" for doi in (data.get("doi") or [])[:1]]
496 extra += [each for each in (data.get("identifier") or []) if each.lower().startswith("arxiv:")][:1]
497 url = page_url(document)
498 lines.append("")
499 lines.extend(" " + self.style.dim(fit(each, width - 2)) for each in (*extra, url) if each)
500 self.scroll = max(0, min(self.scroll, len(lines) - height))
501 return lines[self.scroll : self.scroll + height]
503 def _help(self, width: int) -> list[str]:
504 style, view = self.style, self.view
505 lines: list[str] = []
506 if view is not None: 506 ↛ 519line 506 didn't jump to line 519 because the condition on line 506 was always true
507 lines.append(style.bold(fit(" How the search was read", width)))
508 typed = max(len(reading.source) for reading in view.interpretation.readings)
509 for reading in view.interpretation.readings:
510 lines.append(fit(f" {reading.source:<{typed}} {reading.kind}: {reading.value}", width))
511 try:
512 from ..search import to_solr
514 lines.append(style.dim(fit(" sent as: " + to_solr(self.session.query(view.interpretation, view.sort)), width)))
515 except SciXError:
516 pass
517 lines.extend(style.warn(line) for note in view.interpretation.notes for line in wrap(" " + note, width))
518 lines.append("")
519 lines.append(style.bold(fit(" Keys", width)))
520 lines.extend(fit(" " + line, width) for line in _HELP.splitlines())
521 lines.append("")
522 lines.append(style.dim(fit(" The number at the end of each row is how often the document is cited.", width)))
523 return lines
526# The terminal.
529def _read_keys(descriptor: int, timeout: float) -> list[str] | None:
530 """The keys typed since the last call, or ``None`` if none arrives within ``timeout`` seconds."""
531 import select
533 ready, _, _ = select.select([descriptor], [], [], timeout)
534 if not ready:
535 return None
536 try:
537 data = os.read(descriptor, 1024)
538 except OSError:
539 data = b""
540 if not data:
541 return ["ctrl-c"] # the terminal went away
542 if data.endswith(b"\x1b"):
543 # An escape sequence can arrive in pieces; a lone Esc is followed by nothing.
544 more, _, _ = select.select([descriptor], [], [], 0.03)
545 if more: 545 ↛ 546line 545 didn't jump to line 546 because the condition on line 545 was never true
546 data += os.read(descriptor, 1024)
547 return decode_keys(data)
550def run(
551 browser: Browser,
552 interpretation: Interpretation | None = None,
553 *,
554 stdin: TextIO | None = None,
555 stdout: TextIO | None = None,
556) -> int:
557 """Show ``browser`` on the terminal until the reader quits; returns the exit status.
559 Starts with the results of ``interpretation``, or with the search prompt
560 if there is none. The terminal is put back as it was, whatever happens.
561 """
562 import termios
563 import tty
565 stdin, stdout = stdin or sys.stdin, stdout or sys.stdout
566 descriptor = stdin.fileno()
567 saved = termios.tcgetattr(descriptor)
568 size = (0, 0)
570 def draw() -> None:
571 nonlocal size
572 size = tuple(shutil.get_terminal_size()) # type: ignore[assignment]
573 lines = browser.render(*size)
574 stdout.write("\x1b[H" + "\x1b[K\r\n".join(lines) + "\x1b[K\x1b[J")
575 stdout.flush()
577 try:
578 tty.setcbreak(descriptor, termios.TCSANOW) # not TCSAFLUSH: keep what was typed ahead
579 stdout.write("\x1b[?1049h\x1b[?25l")
580 browser.on_busy = draw
581 if interpretation is not None: 581 ↛ 586line 581 didn't jump to line 586 because the condition on line 581 was always true
582 browser.mode = "list"
583 if not browser.search(interpretation):
584 browser.mode = "prompt"
585 browser.buffer = interpretation.text
586 draw()
587 alive = True
588 while alive:
589 keys = _read_keys(descriptor, 0.25)
590 if keys is None:
591 if tuple(shutil.get_terminal_size()) != size: 591 ↛ 592line 591 didn't jump to line 592 because the condition on line 591 was never true
592 draw()
593 continue
594 for key in keys:
595 alive = alive and browser.key(key)
596 draw()
597 except KeyboardInterrupt:
598 pass
599 finally:
600 browser.on_busy = None
601 stdout.write("\x1b[?25h\x1b[?1049l")
602 stdout.flush()
603 try:
604 termios.tcsetattr(descriptor, termios.TCSADRAIN, saved)
605 except termios.error:
606 pass # the terminal went away: there is nothing left to put back
607 return 0