printer-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prt/transport/snmp.py ADDED
@@ -0,0 +1,140 @@
1
+ """A deliberately tiny SNMPv1 GET client (BER encode/decode) — enough for printer counters.
2
+
3
+ Avoids pysnmp, whose API changes between releases and Python versions.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import socket
10
+ from typing import Any
11
+
12
+ INTEGER, OCTET_STRING, NULL, OID, SEQUENCE = 0x02, 0x04, 0x05, 0x06, 0x30
13
+ COUNTER32, GAUGE32, TIMETICKS, COUNTER64 = 0x41, 0x42, 0x43, 0x46
14
+ GET_REQUEST, GET_RESPONSE = 0xA0, 0xA2
15
+ NO_SUCH = {0x80, 0x81, 0x82}
16
+
17
+ # Standard Printer-MIB / MIB-II OIDs
18
+ SYS_DESCR = "1.3.6.1.2.1.1.1.0"
19
+ SYS_UPTIME = "1.3.6.1.2.1.1.3.0"
20
+ PRT_LIFETIME_COUNT = "1.3.6.1.2.1.43.10.2.1.4.1.1"
21
+
22
+
23
+ class SNMPError(Exception):
24
+ pass
25
+
26
+
27
+ def _len(n: int) -> bytes:
28
+ if n < 0x80:
29
+ return bytes([n])
30
+ out = n.to_bytes((n.bit_length() + 7) // 8, "big")
31
+ return bytes([0x80 | len(out)]) + out
32
+
33
+
34
+ def _tlv(tag: int, value: bytes) -> bytes:
35
+ return bytes([tag]) + _len(len(value)) + value
36
+
37
+
38
+ def _int(n: int) -> bytes:
39
+ length = max(1, (n.bit_length() + 8) // 8)
40
+ return _tlv(INTEGER, n.to_bytes(length, "big", signed=True))
41
+
42
+
43
+ def encode_oid(oid: str) -> bytes:
44
+ parts = [int(p) for p in oid.strip(".").split(".")]
45
+ if len(parts) < 2:
46
+ raise SNMPError(f"bad OID {oid!r}")
47
+ out = bytearray([parts[0] * 40 + parts[1]])
48
+ for p in parts[2:]:
49
+ chunk = [p & 0x7F]
50
+ p >>= 7
51
+ while p:
52
+ chunk.append(0x80 | (p & 0x7F))
53
+ p >>= 7
54
+ out += bytes(reversed(chunk))
55
+ return _tlv(OID, bytes(out))
56
+
57
+
58
+ def decode_oid(raw: bytes) -> str:
59
+ parts = [raw[0] // 40, raw[0] % 40]
60
+ n = 0
61
+ for b in raw[1:]:
62
+ n = (n << 7) | (b & 0x7F)
63
+ if not b & 0x80:
64
+ parts.append(n)
65
+ n = 0
66
+ return ".".join(map(str, parts))
67
+
68
+
69
+ def encode_get(oids: list[str], community: str = "public", request_id: int = 1) -> bytes:
70
+ varbinds = b"".join(_tlv(SEQUENCE, encode_oid(o) + _tlv(NULL, b"")) for o in oids)
71
+ pdu = _tlv(GET_REQUEST, _int(request_id) + _int(0) + _int(0) + _tlv(SEQUENCE, varbinds))
72
+ return _tlv(SEQUENCE, _int(0) + _tlv(OCTET_STRING, community.encode()) + pdu)
73
+
74
+
75
+ def _read(data: bytes, pos: int) -> tuple[int, bytes, int]:
76
+ tag = data[pos]
77
+ length = data[pos + 1]
78
+ pos += 2
79
+ if length & 0x80:
80
+ nbytes = length & 0x7F
81
+ length = int.from_bytes(data[pos : pos + nbytes], "big")
82
+ pos += nbytes
83
+ value = data[pos : pos + length]
84
+ if len(value) != length:
85
+ raise SNMPError("truncated SNMP message")
86
+ return tag, value, pos + length
87
+
88
+
89
+ def _children(data: bytes) -> list[tuple[int, bytes]]:
90
+ out, pos = [], 0
91
+ while pos < len(data):
92
+ tag, value, pos = _read(data, pos)
93
+ out.append((tag, value))
94
+ return out
95
+
96
+
97
+ def _value(tag: int, raw: bytes) -> Any:
98
+ if tag in (INTEGER,):
99
+ return int.from_bytes(raw, "big", signed=True)
100
+ if tag in (COUNTER32, GAUGE32, TIMETICKS, COUNTER64):
101
+ return int.from_bytes(raw, "big", signed=False)
102
+ if tag == OCTET_STRING:
103
+ return raw
104
+ if tag == OID:
105
+ return decode_oid(raw)
106
+ return None # NULL, noSuchObject, noSuchInstance, endOfMibView
107
+
108
+
109
+ def decode_response(data: bytes) -> dict[str, Any]:
110
+ tag, msg, _ = _read(data, 0)
111
+ if tag != SEQUENCE:
112
+ raise SNMPError("not an SNMP message")
113
+ parts = _children(msg)
114
+ if len(parts) < 3 or parts[2][0] != GET_RESPONSE:
115
+ raise SNMPError("not a GetResponse")
116
+ pdu = _children(parts[2][1])
117
+ error_status = _value(*pdu[1])
118
+ if error_status:
119
+ raise SNMPError(f"SNMP error-status {error_status}")
120
+ result: dict[str, Any] = {}
121
+ for _, vb in _children(pdu[3][1]):
122
+ (otag, oraw), (vtag, vraw) = _children(vb)[:2]
123
+ result[decode_oid(oraw)] = None if vtag in NO_SUCH else _value(vtag, vraw)
124
+ return result
125
+
126
+
127
+ def get(host: str, oids: list[str], community: str = "public", timeout: float = 2.0,
128
+ retries: int = 1, port: int = 161) -> dict[str, Any]:
129
+ request_id = int.from_bytes(os.urandom(3), "big")
130
+ packet = encode_get(oids, community, request_id)
131
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
132
+ sock.settimeout(timeout)
133
+ for _ in range(retries + 1):
134
+ try:
135
+ sock.sendto(packet, (host, port))
136
+ data, _ = sock.recvfrom(65535)
137
+ return decode_response(data)
138
+ except socket.timeout:
139
+ continue
140
+ raise SNMPError(f"no SNMP response from {host}")
prt/tui/__init__.py ADDED
File without changes
prt/tui/app.py ADDED
@@ -0,0 +1,495 @@
1
+ """prt TUI — the full-screen dashboard (`prt tui`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from pathlib import Path
7
+
8
+ from rich.text import Text
9
+ from textual import on, work
10
+ from textual.app import App, ComposeResult
11
+ from textual.binding import Binding
12
+ from textual.containers import Horizontal, Vertical
13
+ from textual.screen import ModalScreen
14
+ from textual.widgets import (Button, DataTable, Footer, Input, Label, RichLog, Select, Static, Switch,
15
+ TabbedContent, TabPane)
16
+
17
+ from prt import cache
18
+ from prt.config import Config
19
+ from prt.drivers.base import Driver, PrinterError, Unreachable
20
+ from prt.drivers.registry import make_driver
21
+ from prt.maintenance import Preflight, head_clean_preflight, nozzle_check_preflight
22
+ from prt.models import Capability, PrinterInfo, PrintOptions, ScanSettings, Status, Target
23
+ from prt.tui.widgets import (AMBER, GREEN, RED, Panel, render_alerts, render_paper, render_system,
24
+ render_tanks, render_topbar)
25
+
26
+ REFRESH_SECONDS = 10
27
+
28
+
29
+ class ConfirmScreen(ModalScreen[bool]):
30
+ """Yes/no dialog that lists what will happen and anything that blocks it."""
31
+
32
+ BINDINGS = [Binding("escape", "cancel", "Cancel")]
33
+
34
+ def __init__(self, question: str, preflight: Preflight | None = None, confirm: str = "Confirm",
35
+ danger: bool = False):
36
+ super().__init__()
37
+ self.question, self.preflight, self.confirm_label, self.danger = question, preflight, confirm, danger
38
+
39
+ def compose(self) -> ComposeResult:
40
+ details = Text()
41
+ if self.preflight:
42
+ for b in self.preflight.blockers:
43
+ details.append("✗ ", style=f"bold {RED}")
44
+ details.append(b + "\n")
45
+ for w in self.preflight.warnings:
46
+ details.append("▲ ", style=f"bold {AMBER}")
47
+ details.append(w + "\n")
48
+ with Vertical(id="dialog"):
49
+ yield Label(self.question, id="question")
50
+ yield Static(details, id="details")
51
+ with Horizontal(classes="actions"):
52
+ yield Button("Cancel", id="cancel")
53
+ label = self.confirm_label
54
+ if self.preflight and not self.preflight.ok:
55
+ label = f"{label} anyway"
56
+ yield Button(label, id="confirm", classes="danger" if self.danger or
57
+ (self.preflight and not self.preflight.ok) else "")
58
+
59
+ def on_mount(self) -> None:
60
+ self.query_one("#cancel", Button).focus() # the safe choice has focus
61
+
62
+ @on(Button.Pressed, "#confirm")
63
+ def _yes(self) -> None:
64
+ self.dismiss(True)
65
+
66
+ @on(Button.Pressed, "#cancel")
67
+ def _no(self) -> None:
68
+ self.dismiss(False)
69
+
70
+ def action_cancel(self) -> None:
71
+ self.dismiss(False)
72
+
73
+
74
+ class PrtApp(App):
75
+ CSS_PATH = "app.tcss"
76
+ TITLE = "prt"
77
+ ENABLE_COMMAND_PALETTE = False
78
+ BINDINGS = [
79
+ Binding("r", "refresh", "Refresh"),
80
+ Binding("d", "tab('dashboard')", "Dashboard", show=False),
81
+ Binding("m", "tab('maintain')", "Maintain", show=False),
82
+ Binding("p", "tab('print')", "Print"),
83
+ Binding("s", "tab('scan')", "Scan"),
84
+ Binding("j", "tab('jobs')", "Jobs"),
85
+ Binding("n", "nozzle", "Nozzle check"),
86
+ Binding("c", "clean", "Clean"),
87
+ Binding("i", "identify", "Identify"),
88
+ Binding("q", "quit", "Quit"),
89
+ *[Binding(str(k), f"switch({k - 1})", show=False) for k in range(1, 10)],
90
+ ]
91
+
92
+ def __init__(self, targets: list[Target], timeout: float = 5.0, notice: str | None = None):
93
+ super().__init__()
94
+ self.targets = targets
95
+ self.timeout = timeout
96
+ self.active = 0
97
+ self.drivers: dict[str, Driver] = {}
98
+ self.status: Status | None = None
99
+ self.info: PrinterInfo | None = None
100
+ self.busy = False
101
+ self.notice = notice
102
+
103
+ # --- layout -----------------------------------------------------------------
104
+ def compose(self) -> ComposeResult:
105
+ yield Static(id="topbar")
106
+ with TabbedContent(initial="dashboard"):
107
+ with TabPane("Dashboard", id="dashboard"):
108
+ with Vertical(id="dash"):
109
+ yield Panel("Ink", id="ink")
110
+ yield Panel("System", id="system")
111
+ yield Panel("Paper", id="paper")
112
+ yield Panel("Alerts", id="alerts")
113
+ with TabPane("Maintain", id="maintain"):
114
+ yield Static("Run a nozzle check first. Clean the head only if lines in the pattern are "
115
+ "broken — cleaning uses ink and fills the waste pad.", classes="hint")
116
+ with Horizontal(classes="actions"):
117
+ yield Button("Nozzle check", id="btn-nozzle")
118
+ yield Button("Head cleaning", id="btn-clean")
119
+ yield Button("Test page", id="btn-test")
120
+ yield Button("Identify", id="btn-identify")
121
+ yield RichLog(id="log", markup=False, highlight=False, wrap=True)
122
+ with TabPane("Print", id="print"):
123
+ yield Static("JPEG and PNG go straight to the printer; PDF and other files go through "
124
+ "this computer's print queue.", classes="hint")
125
+ with Vertical(classes="field"):
126
+ yield Label("File")
127
+ yield Input(placeholder="path to a file, e.g. ~/Pictures/photo.jpg", id="print-file")
128
+ with Horizontal(classes="field-row"):
129
+ with Vertical(classes="field"):
130
+ yield Label("Copies")
131
+ yield Input("1", id="print-copies", type="integer")
132
+ with Vertical(classes="field"):
133
+ yield Label("Paper")
134
+ yield Select([("A4", "a4"), ("Letter", "letter"), ("4×6 photo", "4x6"), ("5×7 photo", "5x7"),
135
+ ("8×10", "8x10"), ("A5", "a5")],
136
+ value="a4", id="print-media", allow_blank=False)
137
+ with Vertical(classes="field"):
138
+ yield Label("Tray")
139
+ yield Select([("Automatic", "auto"), ("Main tray", "main"), ("Photo tray", "photo")],
140
+ value="auto", id="print-tray", allow_blank=False)
141
+ with Vertical(classes="field"):
142
+ yield Label("Quality")
143
+ yield Select([("Draft", "draft"), ("Normal", "normal"), ("High", "high")], value="normal",
144
+ id="print-quality", allow_blank=False)
145
+ with Vertical(classes="field"):
146
+ yield Label("Black & white")
147
+ yield Switch(False, id="print-mono")
148
+ with Horizontal(classes="actions"):
149
+ yield Button("Print", id="btn-print")
150
+ yield Static("", id="print-result")
151
+ with TabPane("Scan", id="scan"):
152
+ yield Static("Place the document face down on the glass and close the lid.", classes="hint")
153
+ with Horizontal(classes="field-row"):
154
+ with Vertical(classes="field"):
155
+ yield Label("Type")
156
+ yield Select([("PDF", "pdf"), ("JPEG", "jpeg")], value="pdf", id="scan-format",
157
+ allow_blank=False)
158
+ with Vertical(classes="field"):
159
+ yield Label("Resolution")
160
+ yield Select([(f"{d} dpi", d) for d in (100, 200, 300, 600, 1200)], value=300,
161
+ id="scan-dpi", allow_blank=False)
162
+ with Vertical(classes="field"):
163
+ yield Label("Colour")
164
+ yield Select([("Colour", "color"), ("Grey", "gray"), ("Black & white", "bw")],
165
+ value="color", id="scan-mode", allow_blank=False)
166
+ with Vertical(classes="field"):
167
+ yield Label("Area")
168
+ yield Select([("A4", "a4"), ("Letter", "letter"), ("Whole glass", "full")],
169
+ value="a4", id="scan-area", allow_blank=False)
170
+ with Vertical(classes="field"):
171
+ yield Label("Save to folder")
172
+ yield Input(str(Path.cwd()), id="scan-dir")
173
+ with Horizontal(classes="actions"):
174
+ yield Button("Scan", id="btn-scan")
175
+ yield Static("", id="scan-result")
176
+ with TabPane("Jobs", id="jobs"):
177
+ with Horizontal(classes="actions"):
178
+ yield Button("Refresh jobs", id="btn-jobs")
179
+ yield Button("Cancel selected", id="btn-cancel-job", classes="danger")
180
+ yield DataTable(id="jobs-table", cursor_type="row", zebra_stripes=False)
181
+ yield Footer()
182
+
183
+ def on_mount(self) -> None:
184
+ table = self.query_one("#jobs-table", DataTable)
185
+ table.add_columns("ID", "Name", "State", "User", "Pages")
186
+ self.paint()
187
+ self.action_refresh()
188
+ self.set_interval(REFRESH_SECONDS, self.action_refresh)
189
+ if self.notice:
190
+ self.notify(self.notice, severity="warning", timeout=8)
191
+
192
+ def on_resize(self, event) -> None:
193
+ self.query_one("#dash").set_class(event.size.width < 100, "narrow")
194
+
195
+ # --- state ------------------------------------------------------------------------
196
+ @property
197
+ def target(self) -> Target:
198
+ return self.targets[self.active]
199
+
200
+ def driver(self) -> Driver:
201
+ t = self.target
202
+ if t.name not in self.drivers:
203
+ self.drivers[t.name] = make_driver(t, self.timeout)
204
+ return self.drivers[t.name]
205
+
206
+ def paint(self) -> None:
207
+ labels = [(t.name, True) for t in self.targets]
208
+ model = self.info.make_model if self.info else self.target.host
209
+ self.query_one("#topbar", Static).update(
210
+ render_topbar(self.target.name, model, self.status, labels, self.active, self.busy))
211
+ self.query_one("#ink", Panel).update(
212
+ render_tanks(self.status.inks if self.status else [], waste=self.status.waste if self.status else None))
213
+ self.query_one("#system", Panel).update(render_system(self.info))
214
+ self.query_one("#paper", Panel).update(render_paper(self.status))
215
+ self.query_one("#alerts", Panel).update(render_alerts(self.status))
216
+ caps = self.drivers.get(self.target.name)
217
+ for btn, cap in (("#btn-nozzle", Capability.NOZZLE_CHECK), ("#btn-clean", Capability.HEAD_CLEAN),
218
+ ("#btn-test", Capability.TEST_PAGE), ("#btn-identify", Capability.IDENTIFY),
219
+ ("#btn-print", Capability.PRINT), ("#btn-scan", Capability.SCAN)):
220
+ self.query_one(btn, Button).disabled = bool(caps) and not caps.supports(cap)
221
+
222
+ def log_line(self, level: str, message: str) -> None:
223
+ sym, colour = {"ok": ("●", GREEN), "warn": ("▲", AMBER), "err": ("✗", RED)}.get(level, ("◆", "#FFFFFF"))
224
+ line = Text(time.strftime("%H:%M:%S "))
225
+ line.append(f"{sym} ", style=f"bold {colour}")
226
+ line.append(message)
227
+ self.query_one("#log", RichLog).write(line)
228
+
229
+ # --- background work (drivers are synchronous) ------------------------------------
230
+ @work(thread=True, exclusive=True, group="refresh")
231
+ def action_refresh(self) -> None:
232
+ self.busy = True
233
+ self.call_from_thread(self.paint)
234
+ name = self.target.name
235
+ try:
236
+ d = self.driver()
237
+ st = d.status()
238
+ cache.save(name, st)
239
+ info = self.info if self.info and self.info.name == name else d.info()
240
+ self.call_from_thread(self._apply, name, st, info, None)
241
+ except Unreachable as exc:
242
+ st = cache.load(name)
243
+ self.call_from_thread(self._apply, name, st, self.info if self.info and self.info.name == name
244
+ else None, str(exc))
245
+ except PrinterError as exc:
246
+ self.call_from_thread(self._apply, name, None, None, str(exc))
247
+
248
+ def _apply(self, name: str, st: Status | None, info: PrinterInfo | None, error: str | None) -> None:
249
+ if name != self.target.name:
250
+ return # the user switched printers meanwhile
251
+ self.busy = False
252
+ self.status, self.info = st, info
253
+ if error and (st is None or st.stale):
254
+ if not getattr(self, "_warned", None) == (name, error):
255
+ self.notify(error + (" — showing last known status" if st else ""), severity="warning",
256
+ timeout=6)
257
+ self._warned = (name, error)
258
+ self.paint()
259
+
260
+ def action_tab(self, tab: str) -> None:
261
+ self.query_one(TabbedContent).active = tab
262
+ if tab == "jobs":
263
+ self.load_jobs()
264
+
265
+ def action_switch(self, index: int) -> None:
266
+ if index < len(self.targets) and index != self.active:
267
+ self.active = index
268
+ self.status, self.info = cache.load(self.target.name), None
269
+ self.paint()
270
+ self.action_refresh()
271
+
272
+ # --- maintenance --------------------------------------------------------------------
273
+ def action_nozzle(self) -> None:
274
+ self._maintenance("nozzle")
275
+
276
+ def action_clean(self) -> None:
277
+ self._maintenance("clean")
278
+
279
+ def action_identify(self) -> None:
280
+ self._run_action("identify")
281
+
282
+ @on(Button.Pressed, "#btn-nozzle")
283
+ def _b_nozzle(self) -> None:
284
+ self._maintenance("nozzle")
285
+
286
+ @on(Button.Pressed, "#btn-clean")
287
+ def _b_clean(self) -> None:
288
+ self._maintenance("clean")
289
+
290
+ @on(Button.Pressed, "#btn-test")
291
+ def _b_test(self) -> None:
292
+ self._maintenance("test")
293
+
294
+ @on(Button.Pressed, "#btn-identify")
295
+ def _b_identify(self) -> None:
296
+ self._run_action("identify")
297
+
298
+ def _maintenance(self, kind: str) -> None:
299
+ st = self.status or Status(state="unknown")
300
+ if st.stale:
301
+ st = Status(state="offline", inks=st.inks, trays=st.trays, waste=st.waste)
302
+ if kind == "clean":
303
+ pf, q, label = head_clean_preflight(st), "Clean the print head?", "Clean"
304
+ elif kind == "nozzle":
305
+ pf, q, label = nozzle_check_preflight(st), "Print a nozzle check pattern?", "Print pattern"
306
+ else:
307
+ pf, q, label = Preflight(ok=True, warnings=["prints one A4 page in colour"]), \
308
+ "Print the colour test page?", "Print"
309
+ if st.state == "offline" and kind != "clean":
310
+ pf.ok = False
311
+ self.query_one(TabbedContent).active = "maintain"
312
+
313
+ def done(confirmed: bool | None) -> None:
314
+ if confirmed:
315
+ if not pf.ok:
316
+ self.log_line("warn", f"{label} confirmed despite: {'; '.join(pf.blockers)}")
317
+ self._run_action(kind)
318
+ else:
319
+ self.log_line("info", "cancelled — nothing was sent")
320
+
321
+ self.push_screen(ConfirmScreen(q, pf, label, danger=kind == "clean"), done)
322
+
323
+ @work(thread=True, group="action")
324
+ def _run_action(self, kind: str) -> None:
325
+ messages = {"nozzle": "nozzle check sent — broken lines mean clogged nozzles",
326
+ "clean": "head cleaning started — wait until the printer is quiet, then run a nozzle check",
327
+ "test": "test page queued", "identify": "the printer should be flashing now"}
328
+ try:
329
+ d = self.driver()
330
+ if kind == "nozzle":
331
+ d.nozzle_check()
332
+ elif kind == "clean":
333
+ d.head_clean()
334
+ elif kind == "test":
335
+ job = d.test_page()
336
+ messages["test"] = f"test page queued as job {job}"
337
+ elif kind == "identify":
338
+ d.identify()
339
+ self.call_from_thread(self.log_line, "ok", messages[kind])
340
+ self.call_from_thread(self.notify, messages[kind])
341
+ except PrinterError as exc:
342
+ self.call_from_thread(self.log_line, "err", str(exc) + (f" — {exc.hint}" if exc.hint else ""))
343
+ self.call_from_thread(self.notify, str(exc), severity="error")
344
+
345
+ # --- print ---------------------------------------------------------------------------
346
+ @on(Button.Pressed, "#btn-print")
347
+ def _b_print(self) -> None:
348
+ raw = self.query_one("#print-file", Input).value.strip()
349
+ result = self.query_one("#print-result", Static)
350
+ if not raw:
351
+ result.update(Text("✗ choose a file to print first", style=f"bold {RED}"))
352
+ self.query_one("#print-file", Input).focus()
353
+ return
354
+ path = Path(raw).expanduser()
355
+ if not path.is_file():
356
+ result.update(Text(f"✗ file not found: {path}", style=f"bold {RED}"))
357
+ return
358
+ try:
359
+ copies = max(1, min(99, int(self.query_one("#print-copies", Input).value or "1")))
360
+ except ValueError:
361
+ copies = 1
362
+ tray = self.query_one("#print-tray", Select).value
363
+ opts = PrintOptions(copies=copies, media=str(self.query_one("#print-media", Select).value),
364
+ tray=None if tray == "auto" else str(tray),
365
+ quality=str(self.query_one("#print-quality", Select).value),
366
+ mono=self.query_one("#print-mono", Switch).value)
367
+ result.update(Text(f"sending {path.name}…"))
368
+ self._send_print(path, opts)
369
+
370
+ @work(thread=True, group="action")
371
+ def _send_print(self, path: Path, opts: PrintOptions) -> None:
372
+ result = self.query_one("#print-result", Static)
373
+ try:
374
+ job = self.driver().print_file(path, opts)
375
+ msg = Text("● ", style=f"bold {GREEN}")
376
+ msg.append(f"{path.name} sent" + (f" as job {job}" if job else ""))
377
+ self.call_from_thread(result.update, msg)
378
+ except PrinterError as exc:
379
+ self.call_from_thread(result.update, Text(f"✗ {exc}" + (f" — {exc.hint}" if exc.hint else ""),
380
+ style=f"bold {RED}"))
381
+
382
+ # --- scan -----------------------------------------------------------------------------
383
+ @on(Button.Pressed, "#btn-scan")
384
+ def _b_scan(self) -> None:
385
+ settings = ScanSettings(format=str(self.query_one("#scan-format", Select).value),
386
+ dpi=int(self.query_one("#scan-dpi", Select).value),
387
+ mode=str(self.query_one("#scan-mode", Select).value),
388
+ area=str(self.query_one("#scan-area", Select).value))
389
+ folder = Path(self.query_one("#scan-dir", Input).value.strip() or ".").expanduser()
390
+ if not folder.is_dir():
391
+ self.query_one("#scan-result", Static).update(Text(f"✗ folder not found: {folder}", style=f"bold {RED}"))
392
+ return
393
+ self.query_one("#btn-scan", Button).disabled = True
394
+ self._scan(settings, folder)
395
+
396
+ @work(thread=True, group="action")
397
+ def _scan(self, settings: ScanSettings, folder: Path) -> None:
398
+ result = self.query_one("#scan-result", Static)
399
+ start = time.monotonic()
400
+
401
+ def progress(stage: str) -> None:
402
+ self.call_from_thread(result.update, Text(f"{stage}… {time.monotonic() - start:.0f}s"))
403
+
404
+ try:
405
+ data = self.driver().scan(settings, progress)
406
+ path = folder / time.strftime(f"scan-%Y%m%d-%H%M%S.{settings.format}")
407
+ path.write_bytes(data)
408
+ msg = Text("● ", style=f"bold {GREEN}")
409
+ msg.append(f"saved {path} ({len(data) / 1024:,.0f} KiB, {time.monotonic() - start:.0f}s)")
410
+ self.call_from_thread(result.update, msg)
411
+ except Exception as exc: # scan errors come from several layers; show them all the same way
412
+ hint = getattr(exc, "hint", None)
413
+ self.call_from_thread(result.update, Text(f"✗ {exc}" + (f" — {hint}" if hint else ""),
414
+ style=f"bold {RED}"))
415
+ finally:
416
+ self.call_from_thread(setattr, self.query_one("#btn-scan", Button), "disabled", False)
417
+
418
+ # --- jobs -------------------------------------------------------------------------------
419
+ @on(Button.Pressed, "#btn-jobs")
420
+ def _b_jobs(self) -> None:
421
+ self.load_jobs()
422
+
423
+ @on(TabbedContent.TabActivated)
424
+ def _tab_changed(self, event: TabbedContent.TabActivated) -> None:
425
+ if event.pane.id == "jobs":
426
+ self.load_jobs()
427
+
428
+ @work(thread=True, exclusive=True, group="jobs")
429
+ def load_jobs(self) -> None:
430
+ try:
431
+ jobs = self.driver().jobs(include_completed=True)
432
+ except PrinterError as exc:
433
+ self.call_from_thread(self.notify, str(exc), severity="error")
434
+ return
435
+
436
+ def fill() -> None:
437
+ table = self.query_one("#jobs-table", DataTable)
438
+ table.clear()
439
+ for j in sorted(jobs, key=lambda x: -x.id):
440
+ colour = {"completed": GREEN, "canceled": AMBER, "aborted": RED}.get(j.state, "#FFFFFF")
441
+ table.add_row(str(j.id), j.name, Text(j.state, style=colour), j.user or "",
442
+ "" if j.pages is None else str(j.pages), key=str(j.id))
443
+ if not jobs:
444
+ table.add_row("—", "no jobs", "", "", "")
445
+
446
+ self.call_from_thread(fill)
447
+
448
+ @on(Button.Pressed, "#btn-cancel-job")
449
+ def _b_cancel(self) -> None:
450
+ table = self.query_one("#jobs-table", DataTable)
451
+ if not table.row_count:
452
+ return
453
+ row = table.get_row_at(table.cursor_row)
454
+ if not str(row[0]).isdigit():
455
+ return
456
+ job_id = int(row[0])
457
+
458
+ def done(ok: bool | None) -> None:
459
+ if ok:
460
+ self._cancel(job_id)
461
+
462
+ self.push_screen(ConfirmScreen(f"Cancel job {job_id}?", None, "Cancel job", danger=True), done)
463
+
464
+ @work(thread=True, group="jobs")
465
+ def _cancel(self, job_id: int) -> None:
466
+ try:
467
+ self.driver().cancel_job(job_id)
468
+ self.call_from_thread(self.notify, f"job {job_id} cancelled")
469
+ except PrinterError as exc:
470
+ self.call_from_thread(self.notify, str(exc), severity="error")
471
+ self.load_jobs()
472
+
473
+
474
+ def build_targets(cfg: Config, selector: str | None) -> tuple[list[Target], str | None]:
475
+ """Saved printers (default first); falls back to discovery, then to the demo printer."""
476
+ targets = list(cfg.printers.values())
477
+ notice = None
478
+ if selector and selector not in cfg.printers:
479
+ targets.insert(0, cfg.resolve(selector))
480
+ elif cfg.default in cfg.printers:
481
+ targets.sort(key=lambda t: t.name != (selector or cfg.default))
482
+ if selector in cfg.printers:
483
+ targets.sort(key=lambda t: t.name != selector)
484
+ if not targets:
485
+ try:
486
+ targets = [cfg.resolve(None)]
487
+ except PrinterError as exc:
488
+ targets = [Target(name="demo", host="demo", driver="fake")]
489
+ notice = f"{exc} — showing the demo printer. Add yours with `prt printers add`."
490
+ return targets, notice
491
+
492
+
493
+ def run(cfg: Config, selector: str | None = None, timeout: float | None = None) -> None:
494
+ targets, notice = build_targets(cfg, selector)
495
+ PrtApp(targets, timeout or cfg.timeout, notice).run()