#!/usr/bin/env python3 """Textual TUI for the receipt printer; launched via `./receipt.py tui`.""" from __future__ import annotations import argparse 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"), ] 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 = receipt.PrinterConfig.from_args(self.base_args).target 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: result = receipt.run_action(command, self.base_args, **params) finally: self.call_from_thread(self.set_buttons_disabled, False) self.call_from_thread(self.report, command, result.rc, result.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]") self.last_failure = rc # only the most recent action decides the exit code 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