#!/usr/bin/env python3 """Textual TUI for the receipt printer; launched via `./receipt.py tui`.""" from __future__ import annotations import argparse import contextlib import io import os import subprocess from pathlib import Path from rich.text import Text from textual import work from textual.app import App, ComposeResult from textual.containers import Horizontal, Vertical from textual.widgets import ( Button, ContentSwitcher, Footer, Header, Input, Label, ListItem, ListView, RichLog, Switch, TextArea, ) import receipt ACTIONS = [ ("note", "Note"), ("image", "Random image"), ("print", "Print file"), ("qr", "QR code"), ("reprint", "Reprint cached"), ("status", "Printer status"), ("cache", "Image cache"), ] def setup_network_quiet(args: argparse.Namespace) -> None: """Run the connect script with output captured so it can't corrupt the TUI.""" env = os.environ.copy() env["RECEIPT_PRINTER_IP"] = args.ip env["RECEIPT_PRINTER_PORT"] = str(args.port) result = subprocess.run( ["bash", str(receipt.CONNECT_SCRIPT)], env=env, capture_output=True, text=True ) if result.stdout: print(result.stdout, end="") if result.stderr: print(result.stderr, end="") if result.returncode != 0: raise RuntimeError(f"connect script failed (exit {result.returncode})") def run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, str]: """Run a receipt.py command handler, capturing its terminal output. Mirrors main(): every action connects fresh, so a dropped printer never leaves the TUI holding a dead handle. """ args = argparse.Namespace(**{**vars(base), **params, "command": command}) buf = io.StringIO() with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): try: rc = _dispatch(command, args) except Exception as e: print(f"Error: {e}") rc = 1 return rc, buf.getvalue().rstrip() def _dispatch(command: str, args: argparse.Namespace) -> int: if command == "list": return receipt.cmd_list() # No TTY in the worker thread: the button press is the confirmation. if command == "clean": return receipt.cmd_clean(yes=True) if command == "status": return receipt.cmd_status(args) if not args.usb: setup_network_quiet(args) handlers = { "image": receipt.cmd_image, "note": receipt.cmd_note, "print": receipt.cmd_print, "qr": receipt.cmd_qr, "reprint": receipt.cmd_reprint, } with contextlib.closing(receipt.get_printer(args)) as p: return handlers[command](p, args) class ReceiptApp(App): TITLE = "Receipt Maker" BINDINGS = [("q", "quit", "Quit")] CSS = """ #nav { width: 22; border-right: solid $primary; } #panes { padding: 1 2; } #panes Label { margin-top: 1; } #panes Button { margin-top: 1; } #note-text { height: 8; } #reprint-list { height: 10; border: solid $primary; } .row { height: auto; margin-top: 1; } .row Label { margin: 1 0 0 2; } #log { dock: bottom; height: 30%; border-top: solid $primary; } """ def __init__(self, base_args: argparse.Namespace): super().__init__() self.base_args = base_args self.last_failure = 0 # exit code of the most recent failed action def compose(self) -> ComposeResult: yield Header() with Horizontal(): yield ListView( *(ListItem(Label(label), name=key) for key, label in ACTIONS), id="nav", ) with ContentSwitcher(initial="pane-note", id="panes"): with Vertical(id="pane-note"): yield Label("Note text") yield TextArea(id="note-text") with Horizontal(classes="row"): yield Switch(id="note-timestamp") yield Label("Date/time header") yield Button("Print note", id="do-note", variant="primary") with Vertical(id="pane-image"): yield Label("How many random /bant/ images") yield Input(value="1", id="image-count", type="integer") yield Button("Print", id="do-image", variant="primary") with Vertical(id="pane-print"): yield Label("Path to image file") yield Input(id="print-path", placeholder="/path/to/image.jpg") yield Label("Caption (optional)") yield Input(id="print-caption") yield Button("Print", id="do-print", variant="primary") with Vertical(id="pane-qr"): yield Label("Text or URL to encode") yield Input(id="qr-content", placeholder="https://example.com") yield Label("Caption (optional)") yield Input(id="qr-caption") yield Button("Print QR", id="do-qr", variant="primary") with Vertical(id="pane-reprint"): yield Label("Cached images (newest first)") yield ListView(id="reprint-list") yield Button("Reprint selected", id="do-reprint", variant="primary") with Vertical(id="pane-status"): yield Label("Check whether the printer is reachable") yield Button("Check status", id="do-status", variant="primary") with Vertical(id="pane-cache"): yield Label("Downloaded image cache") yield Button("List cache", id="do-list", variant="primary") yield Button("Clean cache", id="do-clean", variant="error") yield RichLog(id="log", wrap=True, markup=True) yield Footer() def on_mount(self) -> None: target = "USB" if self.base_args.usb else f"{self.base_args.ip}:{self.base_args.port}" self.log_panel.write(f"[dim]Printer target: {target}[/dim]") self.refresh_cache_list() @property def log_panel(self) -> RichLog: return self.query_one("#log", RichLog) def refresh_cache_list(self) -> None: lv = self.query_one("#reprint-list", ListView) lv.clear() lv.extend(ListItem(Label(f.name), name=f.name) for f in receipt.cached_images()) def on_list_view_highlighted(self, event: ListView.Highlighted) -> None: if event.list_view.id != "nav" or event.item is None: return key = event.item.name self.query_one("#panes", ContentSwitcher).current = f"pane-{key}" if key == "reprint": self.refresh_cache_list() def on_button_pressed(self, event: Button.Pressed) -> None: button_id = event.button.id if button_id == "do-note": text = self.query_one("#note-text", TextArea).text.strip() if not text: self.log_panel.write("[red]Nothing to print.[/red]") return timestamp = self.query_one("#note-timestamp", Switch).value self.run_action_worker("note", text=text, timestamp=timestamp) elif button_id == "do-image": raw = self.query_one("#image-count", Input).value or "1" try: count = receipt.positive_int(raw) except (ValueError, argparse.ArgumentTypeError): self.log_panel.write("[red]Count must be a positive integer.[/red]") return self.run_action_worker("image", count=count) elif button_id == "do-print": path = self.query_one("#print-path", Input).value.strip() if not path: self.log_panel.write("[red]Enter a file path.[/red]") return caption = self.query_one("#print-caption", Input).value.strip() or None self.run_action_worker( "print", path=Path(path).expanduser(), message=caption ) elif button_id == "do-qr": content = self.query_one("#qr-content", Input).value.strip() if not content: self.log_panel.write("[red]Enter something to encode.[/red]") return caption = self.query_one("#qr-caption", Input).value.strip() or None self.run_action_worker("qr", content=content, message=caption) elif button_id == "do-reprint": selected = self.query_one("#reprint-list", ListView).highlighted_child self.run_action_worker("reprint", name=selected.name if selected else None) elif button_id == "do-status": self.run_action_worker("status") elif button_id == "do-list": self.run_action_worker("list") elif button_id == "do-clean": self.run_action_worker("clean") def set_buttons_disabled(self, disabled: bool) -> None: for button in self.query(Button): button.disabled = disabled @work(thread=True, exclusive=True) def run_action_worker(self, command: str, **params) -> None: self.call_from_thread(self.set_buttons_disabled, True) self.call_from_thread(self.log_panel.write, f"[bold]$ {command}[/bold]") try: rc, output = run_action(command, self.base_args, **params) finally: self.call_from_thread(self.set_buttons_disabled, False) self.call_from_thread(self.report, command, rc, output) def report(self, command: str, rc: int, output: str) -> None: if output: # Captured output is arbitrary text; Text() stops stray [..] parsing as markup. self.log_panel.write(Text(output)) if rc == 0: self.log_panel.write("[green]done[/green]") else: self.log_panel.write(f"[red]failed (exit {rc})[/red]") if rc != 0: self.last_failure = rc if command in ("image", "clean"): self.refresh_cache_list() def run_tui(args: argparse.Namespace) -> int: app = ReceiptApp(args) app.run() return app.last_failure