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.
- printer_cli-0.1.0.dist-info/METADATA +229 -0
- printer_cli-0.1.0.dist-info/RECORD +33 -0
- printer_cli-0.1.0.dist-info/WHEEL +4 -0
- printer_cli-0.1.0.dist-info/entry_points.txt +3 -0
- printer_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- prt/__init__.py +3 -0
- prt/__main__.py +3 -0
- prt/cache.py +43 -0
- prt/cli.py +834 -0
- prt/config.py +127 -0
- prt/discovery.py +121 -0
- prt/drivers/__init__.py +0 -0
- prt/drivers/base.py +90 -0
- prt/drivers/epson.py +88 -0
- prt/drivers/fake.py +86 -0
- prt/drivers/ipp.py +335 -0
- prt/drivers/registry.py +54 -0
- prt/fixtures/__init__.py +0 -0
- prt/fixtures/epson-xp6000.json +62 -0
- prt/maintenance.py +49 -0
- prt/media.py +60 -0
- prt/models.py +192 -0
- prt/printing.py +103 -0
- prt/style.py +325 -0
- prt/testpage.py +71 -0
- prt/transport/__init__.py +0 -0
- prt/transport/escl.py +201 -0
- prt/transport/ipp.py +364 -0
- prt/transport/snmp.py +140 -0
- prt/tui/__init__.py +0 -0
- prt/tui/app.py +495 -0
- prt/tui/app.tcss +308 -0
- prt/tui/widgets.py +181 -0
prt/cli.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
1
|
+
"""prt — command-line control for network printers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Callable, Optional
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
from rich.text import Text
|
|
15
|
+
|
|
16
|
+
from prt import __version__, cache, style
|
|
17
|
+
from prt.config import Config
|
|
18
|
+
from prt.drivers.base import Driver, PrinterError, Unreachable
|
|
19
|
+
from prt.drivers.registry import driver_names, make_driver
|
|
20
|
+
from prt.maintenance import head_clean_preflight, nozzle_check_preflight
|
|
21
|
+
from prt.models import Capability, PrintOptions, ScanSettings, Severity, Status, to_dict
|
|
22
|
+
from prt.style import ROLES, Mode, t
|
|
23
|
+
|
|
24
|
+
# --- App state ----------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Fmt(str, Enum):
|
|
28
|
+
text = "text"
|
|
29
|
+
json = "json"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class State:
|
|
34
|
+
printer: str | None = None
|
|
35
|
+
fmt: Fmt = Fmt.text
|
|
36
|
+
verbose: bool = False
|
|
37
|
+
quiet: bool = False
|
|
38
|
+
timeout: float | None = None
|
|
39
|
+
config_path: str | None = None
|
|
40
|
+
no_color: bool = False
|
|
41
|
+
out: Mode = field(default_factory=lambda: style.PLAIN)
|
|
42
|
+
err: Mode = field(default_factory=lambda: style.PLAIN)
|
|
43
|
+
_cfg: Config | None = None
|
|
44
|
+
_driver: Driver | None = None
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def cfg(self) -> Config:
|
|
48
|
+
if self._cfg is None:
|
|
49
|
+
self._cfg = Config.load(self.config_path)
|
|
50
|
+
return self._cfg
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def json(self) -> bool:
|
|
54
|
+
return self.fmt == Fmt.json
|
|
55
|
+
|
|
56
|
+
def driver(self) -> Driver:
|
|
57
|
+
if self._driver is None:
|
|
58
|
+
target = self.cfg.resolve(self.printer)
|
|
59
|
+
self._driver = make_driver(target, self.timeout or self.cfg.timeout)
|
|
60
|
+
return self._driver
|
|
61
|
+
|
|
62
|
+
# output helpers
|
|
63
|
+
def write(self, s: str) -> None:
|
|
64
|
+
sys.stdout.write(s)
|
|
65
|
+
sys.stdout.flush()
|
|
66
|
+
|
|
67
|
+
def note(self, level: str, message: str, detail: str | None = None) -> None:
|
|
68
|
+
if not self.quiet:
|
|
69
|
+
sys.stderr.write(style.line(self.err, level, message, detail))
|
|
70
|
+
|
|
71
|
+
def emit(self, data: Any, text: Callable[[], str], plain: Callable[[], list[str]]) -> None:
|
|
72
|
+
if self.json:
|
|
73
|
+
self.write(json.dumps(data, indent=2, default=str) + "\n")
|
|
74
|
+
elif self.out.styled:
|
|
75
|
+
self.write(text())
|
|
76
|
+
else:
|
|
77
|
+
self.write("".join(line + "\n" for line in plain()))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
STATE = State()
|
|
81
|
+
|
|
82
|
+
app = typer.Typer(
|
|
83
|
+
name="prt",
|
|
84
|
+
help="Control network printers from the terminal: status, ink, maintenance, printing and scanning.",
|
|
85
|
+
epilog="Examples: prt status · prt ink -f json · prt scan -o doc.pdf · prt tui",
|
|
86
|
+
no_args_is_help=True,
|
|
87
|
+
add_completion=True,
|
|
88
|
+
pretty_exceptions_enable=False,
|
|
89
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
90
|
+
)
|
|
91
|
+
printers_app = typer.Typer(help="Manage saved printers.", no_args_is_help=True)
|
|
92
|
+
maintain_app = typer.Typer(help="Maintenance: nozzle check, head cleaning, test page, identify.",
|
|
93
|
+
no_args_is_help=True)
|
|
94
|
+
jobs_app = typer.Typer(help="List or cancel print jobs.", invoke_without_command=True)
|
|
95
|
+
app.add_typer(printers_app, name="printers")
|
|
96
|
+
app.add_typer(maintain_app, name="maintain")
|
|
97
|
+
app.add_typer(jobs_app, name="jobs")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _version(value: bool) -> None:
|
|
101
|
+
if value:
|
|
102
|
+
sys.stdout.write(f"prt {__version__}\n")
|
|
103
|
+
raise typer.Exit()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@app.callback()
|
|
107
|
+
def root(
|
|
108
|
+
printer: Optional[str] = typer.Option(None, "--printer", "-p", envvar="PRT_PRINTER",
|
|
109
|
+
help="Saved printer name, hostname or IP (or 'demo')."),
|
|
110
|
+
fmt: Fmt = typer.Option(Fmt.text, "--format", "-f", help="Output format."),
|
|
111
|
+
no_color: bool = typer.Option(False, "--no-color", help="Disable colour (also: NO_COLOR=1)."),
|
|
112
|
+
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show protocol details on stderr."),
|
|
113
|
+
quiet: bool = typer.Option(False, "--quiet", "-q", help="Only print results, no notes."),
|
|
114
|
+
timeout: Optional[float] = typer.Option(None, "--timeout", min=0.5, help="Network timeout in seconds (default 5)."),
|
|
115
|
+
config: Optional[str] = typer.Option(None, "--config", envvar="PRT_CONFIG", help="Config file path."),
|
|
116
|
+
version: bool = typer.Option(False, "--version", callback=_version, is_eager=True,
|
|
117
|
+
help="Show the version and exit."),
|
|
118
|
+
) -> None:
|
|
119
|
+
STATE._cfg, STATE._driver = None, None # fresh per invocation (tests call main() repeatedly)
|
|
120
|
+
STATE._stale_exit = False # type: ignore[attr-defined]
|
|
121
|
+
STATE.printer, STATE.fmt, STATE.verbose, STATE.quiet = printer, fmt, verbose, quiet
|
|
122
|
+
STATE.timeout, STATE.config_path, STATE.no_color = timeout, config, no_color
|
|
123
|
+
from prt.transport import ipp as _ipp
|
|
124
|
+
_ipp.TRACE = verbose
|
|
125
|
+
STATE.out = style.decide(sys.stdout, machine=fmt == Fmt.json, no_color=no_color, is_stdout=True)
|
|
126
|
+
STATE.err = style.decide(sys.stderr, no_color=no_color, is_stdout=False)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# --- Formatting helpers ------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _uptime(seconds: int | None) -> str:
|
|
133
|
+
if seconds is None:
|
|
134
|
+
return "—"
|
|
135
|
+
d, rem = divmod(seconds, 86400)
|
|
136
|
+
h, rem = divmod(rem, 3600)
|
|
137
|
+
m = rem // 60
|
|
138
|
+
return f"{d}d {h}h{m:02d}m" if d else f"{h}h{m:02d}m"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _clock(ts: float) -> str:
|
|
142
|
+
return time.strftime("%H:%M", time.localtime(ts))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
INK_STATE_WORD = {"ok": ("ok", ""), "low": ("warn", "low"), "replace": ("err", "replace"),
|
|
146
|
+
"unknown": ("info", "unknown")}
|
|
147
|
+
SEV_LEVEL = {Severity.ERROR: "err", Severity.WARNING: "warn", Severity.INFO: "info"}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _state_level(st: Status) -> str:
|
|
151
|
+
if st.state == "offline":
|
|
152
|
+
return "offline"
|
|
153
|
+
if st.state == "stopped":
|
|
154
|
+
return "err"
|
|
155
|
+
return "ok"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _ink_rows(st: Status, mode: Mode, inner: int) -> list[Text]:
|
|
159
|
+
name_w = max([len("ink")] + [len(i.name.replace(" ink", "")) for i in st.inks]) + 2
|
|
160
|
+
meter_w = max(10, min(40, inner - name_w - 5 - 12))
|
|
161
|
+
rows = []
|
|
162
|
+
for ink in st.inks:
|
|
163
|
+
row = Text(f"{style.escape(ink.name.replace(' ink', '')):<{name_w}}")
|
|
164
|
+
row.append_text(style.meter(ink.level, meter_w, mode, style.ink_style(ink.color)))
|
|
165
|
+
level, word = INK_STATE_WORD[ink.state]
|
|
166
|
+
if word:
|
|
167
|
+
row.append(" ")
|
|
168
|
+
row.append_text(style.status(level, word, mode))
|
|
169
|
+
rows.append(row)
|
|
170
|
+
return rows
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def render_status(st: Status, name: str, model: str, mode: Mode, firmware: str | None = None,
|
|
174
|
+
uptime: int | None = None, pages: int | None = None) -> str:
|
|
175
|
+
g = style.glyphs(mode)
|
|
176
|
+
inner = max(30, min(mode.width, 100)) - 4
|
|
177
|
+
head = style.status(_state_level(st), st.state, mode)
|
|
178
|
+
facts = []
|
|
179
|
+
if firmware:
|
|
180
|
+
facts.append(f"firmware {firmware}")
|
|
181
|
+
if uptime is not None:
|
|
182
|
+
facts.append(f"up {_uptime(uptime)}")
|
|
183
|
+
if pages is not None:
|
|
184
|
+
facts.append(f"{pages:,} pages")
|
|
185
|
+
if st.queued_jobs:
|
|
186
|
+
facts.append(f"{st.queued_jobs} queued")
|
|
187
|
+
if st.stale:
|
|
188
|
+
facts.append(f"last seen {_clock(st.checked_at)} (cached)")
|
|
189
|
+
if facts:
|
|
190
|
+
head.append(" " + f" {g['dot']} ".join(style.escape(f) for f in facts), style=ROLES["dim"])
|
|
191
|
+
rows: list[Text | None] = [head, None, style.seg("ink", "title")]
|
|
192
|
+
rows += _ink_rows(st, mode, inner)
|
|
193
|
+
rows.append(None)
|
|
194
|
+
paper = style.seg("paper ", "title")
|
|
195
|
+
if st.trays:
|
|
196
|
+
for i, tray in enumerate(st.trays):
|
|
197
|
+
if i:
|
|
198
|
+
paper.append(" ")
|
|
199
|
+
paper.append(style.escape(tray.source) + " ", style=ROLES["dim"])
|
|
200
|
+
paper.append(style.escape(tray.media or "?"))
|
|
201
|
+
paper.append(" " + g["check"], style=ROLES["ok"])
|
|
202
|
+
if tray.level is not None:
|
|
203
|
+
paper.append(f" {tray.level}%")
|
|
204
|
+
if all(tr.level is None for tr in st.trays):
|
|
205
|
+
paper.append(" (levels not reported)", style=ROLES["dim"])
|
|
206
|
+
else:
|
|
207
|
+
paper.append("no media reported", style=ROLES["dim"])
|
|
208
|
+
rows.append(paper)
|
|
209
|
+
waste = style.seg("waste ", "title")
|
|
210
|
+
waste_word = {"ok": ("ok", "ok"), "almost-full": ("warn", "almost full — service soon"),
|
|
211
|
+
"full": ("err", "full — service required"), None: ("info", "not reported")}
|
|
212
|
+
wl, ww = waste_word.get(st.waste, ("info", st.waste or "?"))
|
|
213
|
+
waste.append_text(style.status(wl, ww + (f" ({st.waste_level}%)" if st.waste_level is not None else ""), mode))
|
|
214
|
+
rows.append(waste)
|
|
215
|
+
other = [a for a in st.alerts if not a.code.startswith(("ink-", "marker-waste"))]
|
|
216
|
+
if other:
|
|
217
|
+
rows.append(None)
|
|
218
|
+
for a in other:
|
|
219
|
+
r = style.seg("alert ", "title")
|
|
220
|
+
r.append_text(style.status(SEV_LEVEL[a.severity], a.message, mode))
|
|
221
|
+
rows.append(r)
|
|
222
|
+
n_alerts = len(st.alerts)
|
|
223
|
+
footer = (f"{n_alerts} alert{'s' if n_alerts != 1 else ''} {g['dot']} "
|
|
224
|
+
f"{'cached ' if st.stale else 'checked '}{_clock(st.checked_at)}")
|
|
225
|
+
return style.box(f"{model} {g['dot']} {name}", rows, mode, footer=footer)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def status_plain(st: Status) -> list[str]:
|
|
229
|
+
out = [style.plain_record("state", st.state, "stale" if st.stale else "live")]
|
|
230
|
+
out += [style.plain_record("ink", i.name, "" if i.level is None else i.level, i.state) for i in st.inks]
|
|
231
|
+
out += [style.plain_record("tray", tr.source, tr.media or "", tr.media_type or "",
|
|
232
|
+
"" if tr.level is None else tr.level) for tr in st.trays]
|
|
233
|
+
out.append(style.plain_record("waste", st.waste or "unknown"))
|
|
234
|
+
out += [style.plain_record("alert", a.severity.value, a.message) for a in st.alerts]
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _fetch_status(d: Driver | None = None) -> tuple[Driver | None, Status]:
|
|
239
|
+
"""Live status, or the cached one when the printer does not answer (even during auto-detection)."""
|
|
240
|
+
target = d.target if d else STATE.cfg.resolve(STATE.printer)
|
|
241
|
+
try:
|
|
242
|
+
d = d or STATE.driver()
|
|
243
|
+
st = d.status()
|
|
244
|
+
except Unreachable:
|
|
245
|
+
cached = cache.load(target.name)
|
|
246
|
+
if cached is None:
|
|
247
|
+
raise
|
|
248
|
+
STATE.note("warn", f"{target.name} is not answering — showing last known status",
|
|
249
|
+
f"from {time.strftime('%Y-%m-%d %H:%M', time.localtime(cached.checked_at))}")
|
|
250
|
+
STATE._stale_exit = True # type: ignore[attr-defined]
|
|
251
|
+
return d, cached
|
|
252
|
+
cache.save(target.name, st)
|
|
253
|
+
return d, st
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _quick_facts(d: Driver | None) -> tuple[str, str | None, int | None, int | None]:
|
|
257
|
+
"""Model, firmware, uptime (already-fetched attributes) and page count (SNMP, when available)."""
|
|
258
|
+
from prt.drivers.ipp import IPPDriver
|
|
259
|
+
if d is None:
|
|
260
|
+
return STATE.cfg.resolve(STATE.printer).name, None, None, None
|
|
261
|
+
pages = None
|
|
262
|
+
if d.supports(Capability.COUNTERS) and hasattr(d, "snmp_page_count"):
|
|
263
|
+
pages = d.snmp_page_count() # type: ignore[attr-defined]
|
|
264
|
+
if isinstance(d, IPPDriver) and d._attrs_cache:
|
|
265
|
+
info = d.parse_info(d._attrs_cache)
|
|
266
|
+
return info.make_model, info.firmware, info.uptime_seconds, pages
|
|
267
|
+
return d.display_name, None, None, pages
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _finish_stale() -> None:
|
|
271
|
+
if getattr(STATE, "_stale_exit", False):
|
|
272
|
+
raise typer.Exit(1)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# --- Read commands -------------------------------------------------------------------
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@app.command()
|
|
279
|
+
def status(
|
|
280
|
+
watch: Optional[float] = typer.Option(None, "--watch", "-w", min=2,
|
|
281
|
+
help="Repeat every N seconds, one line per sample (Ctrl-C to stop)."),
|
|
282
|
+
) -> None:
|
|
283
|
+
"""State, alerts, ink levels and paper — what the printer's panel should be telling you."""
|
|
284
|
+
if watch:
|
|
285
|
+
_watch(STATE.driver(), watch)
|
|
286
|
+
return
|
|
287
|
+
d, st = _fetch_status()
|
|
288
|
+
name = STATE.cfg.resolve(STATE.printer).name
|
|
289
|
+
model, fw, up, pages = _quick_facts(d) if not st.stale else (name, None, None, None)
|
|
290
|
+
STATE.emit(
|
|
291
|
+
{"printer": name, "model": model, "page_count": pages, **to_dict(st)},
|
|
292
|
+
lambda: render_status(st, name, model, STATE.out, fw, up, pages),
|
|
293
|
+
lambda: status_plain(st),
|
|
294
|
+
)
|
|
295
|
+
_finish_stale()
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _watch(d: Driver, every: float) -> None:
|
|
299
|
+
while True:
|
|
300
|
+
try:
|
|
301
|
+
st = d.status()
|
|
302
|
+
cache.save(d.target.name, st)
|
|
303
|
+
except Unreachable:
|
|
304
|
+
st = Status(state="offline", accepting=False)
|
|
305
|
+
stamp = time.strftime("%H:%M:%S")
|
|
306
|
+
if STATE.json:
|
|
307
|
+
STATE.write(json.dumps({"time": stamp, **to_dict(st)}, default=str) + "\n")
|
|
308
|
+
elif STATE.out.styled:
|
|
309
|
+
line = style.seg(stamp + " ", "dim")
|
|
310
|
+
line.append_text(style.status(_state_level(st), f"{st.state:<10}", STATE.out))
|
|
311
|
+
for ink in st.inks:
|
|
312
|
+
line.append(f" {ink.short} ", style=ROLES["dim"])
|
|
313
|
+
line.append(f"{ink.level if ink.level is not None else '?':>3}",
|
|
314
|
+
style=style.ink_style(ink.color) if STATE.out.color else "")
|
|
315
|
+
line.append(f" {len(st.alerts)} alerts", style=ROLES["dim"])
|
|
316
|
+
STATE.write(style.render(STATE.out, line) + "\n")
|
|
317
|
+
else:
|
|
318
|
+
STATE.write(style.plain_record(stamp, st.state,
|
|
319
|
+
*[f"{i.short}={i.level}" for i in st.inks],
|
|
320
|
+
f"alerts={len(st.alerts)}") + "\n")
|
|
321
|
+
time.sleep(every)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@app.command()
|
|
325
|
+
def ink() -> None:
|
|
326
|
+
"""Ink levels only (compact)."""
|
|
327
|
+
_, st = _fetch_status()
|
|
328
|
+
name = STATE.cfg.resolve(STATE.printer).name
|
|
329
|
+
mode = STATE.out
|
|
330
|
+
|
|
331
|
+
def text() -> str:
|
|
332
|
+
inner = max(30, min(mode.width, 100)) - 4
|
|
333
|
+
g = style.glyphs(mode)
|
|
334
|
+
foot = f"{'cached ' if st.stale else ''}{_clock(st.checked_at)}"
|
|
335
|
+
return style.box(f"ink {g['dot']} {name}", list(_ink_rows(st, mode, inner)), mode, footer=foot)
|
|
336
|
+
|
|
337
|
+
STATE.emit({"printer": name, "stale": st.stale, "inks": [to_dict(i) for i in st.inks]},
|
|
338
|
+
text, lambda: [style.plain_record(i.name, "" if i.level is None else i.level, i.state)
|
|
339
|
+
for i in st.inks])
|
|
340
|
+
_finish_stale()
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@app.command()
|
|
344
|
+
def overview() -> None:
|
|
345
|
+
"""System, software and hardware: model, serial, firmware, uptime, counters, capabilities."""
|
|
346
|
+
d = STATE.driver()
|
|
347
|
+
info = d.info()
|
|
348
|
+
scanner: dict[str, Any] = {}
|
|
349
|
+
if d.supports(Capability.SCAN):
|
|
350
|
+
scanner = _scanner_info(d)
|
|
351
|
+
info.scanner = scanner
|
|
352
|
+
pairs: list[tuple[str, list[tuple[str, Any]]]] = [
|
|
353
|
+
("system", [("model", info.make_model), ("vendor", info.vendor), ("serial", info.serial),
|
|
354
|
+
("uuid", info.uuid), ("driver", info.driver)]),
|
|
355
|
+
("software", [("firmware", info.firmware), ("ipp", ", ".join(info.ipp_versions)),
|
|
356
|
+
("formats", ", ".join(f.removeprefix("image/").removeprefix("application/")
|
|
357
|
+
for f in info.formats)),
|
|
358
|
+
("admin page", info.admin_url)]),
|
|
359
|
+
("hardware", [("uptime", _uptime(info.uptime_seconds)),
|
|
360
|
+
("pages printed", f"{info.page_count:,}" if info.page_count is not None else None),
|
|
361
|
+
("colour", _yn(info.color)), ("duplex", _yn(info.duplex)),
|
|
362
|
+
("speed", f"{info.ppm} ppm" if info.ppm else None),
|
|
363
|
+
("resolutions", ", ".join(info.resolutions)),
|
|
364
|
+
("trays", ", ".join(s for s in info.media_sources if s != "auto")),
|
|
365
|
+
("media", ", ".join(info.media[:10]) + (" …" if len(info.media) > 10 else ""))]),
|
|
366
|
+
("network", [("host", info.host), ("uris", " ".join(info.uris))]),
|
|
367
|
+
]
|
|
368
|
+
if scanner:
|
|
369
|
+
pairs.append(("scanner", [("source", ", ".join(scanner.get("sources", []))),
|
|
370
|
+
("resolutions", ", ".join(f"{r}" for r in scanner.get("resolutions", [])) + " dpi"),
|
|
371
|
+
("modes", ", ".join(scanner.get("color_modes", []))),
|
|
372
|
+
("formats", ", ".join(scanner.get("formats", [])))]))
|
|
373
|
+
pairs.append(("capabilities", [("supported", ", ".join(c.replace("_", "-") for c in info.capabilities))]))
|
|
374
|
+
mode = STATE.out
|
|
375
|
+
|
|
376
|
+
def text() -> str:
|
|
377
|
+
rows: list[Text | None] = []
|
|
378
|
+
key_w = 15
|
|
379
|
+
for i, (section, items) in enumerate(pairs):
|
|
380
|
+
if i:
|
|
381
|
+
rows.append(None)
|
|
382
|
+
rows.append(style.seg(section, "title"))
|
|
383
|
+
for k, v in items:
|
|
384
|
+
if v in (None, ""):
|
|
385
|
+
continue
|
|
386
|
+
r = style.seg(f" {k:<{key_w}}", "dim")
|
|
387
|
+
r.append(style.escape(v))
|
|
388
|
+
rows.append(r)
|
|
389
|
+
return style.box(f"{info.make_model} {style.glyphs(mode)['dot']} {info.name}", rows, mode,
|
|
390
|
+
footer=f"driver {info.driver}")
|
|
391
|
+
|
|
392
|
+
def plain() -> list[str]:
|
|
393
|
+
return [style.plain_record(section, k, v) for section, items in pairs for k, v in items
|
|
394
|
+
if v not in (None, "")]
|
|
395
|
+
|
|
396
|
+
STATE.emit(to_dict(info), text, plain)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _yn(v: bool | None) -> str | None:
|
|
400
|
+
return None if v is None else ("yes" if v else "no")
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _scanner_info(d: Driver) -> dict[str, Any]:
|
|
404
|
+
if hasattr(d, "scanner_info"):
|
|
405
|
+
return d.scanner_info() # type: ignore[attr-defined]
|
|
406
|
+
from prt.transport.escl import ESCLClient
|
|
407
|
+
try:
|
|
408
|
+
caps = ESCLClient.for_target(d.target, min(d.timeout, 4)).capabilities()
|
|
409
|
+
except Exception:
|
|
410
|
+
return {}
|
|
411
|
+
return {"make_model": caps.make_model, "sources": caps.sources, "resolutions": caps.resolutions,
|
|
412
|
+
"color_modes": caps.color_modes, "formats": caps.formats}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
app.command("info", hidden=True, help="Alias for overview.")(overview)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@app.command()
|
|
419
|
+
def discover(timeout: float = typer.Option(3.0, "--wait", help="Seconds to listen for mDNS answers.")) -> None:
|
|
420
|
+
"""Find printers and scanners on the local network (mDNS / Bonjour)."""
|
|
421
|
+
from prt.discovery import discover as run
|
|
422
|
+
if STATE.err.styled and not STATE.quiet:
|
|
423
|
+
sys.stderr.write(style.render(STATE.err, Text(f"listening for printers for {timeout:g}s…",
|
|
424
|
+
style=ROLES["dim"])) + "\n")
|
|
425
|
+
found = run(timeout)
|
|
426
|
+
if not found:
|
|
427
|
+
STATE.note("warn", "no printers answered",
|
|
428
|
+
"a sleeping printer does not reply to discovery — wake it (press a button) and retry")
|
|
429
|
+
mode = STATE.out
|
|
430
|
+
saved = {p.host.lower(): n for n, p in STATE.cfg.printers.items()}
|
|
431
|
+
|
|
432
|
+
def text() -> str:
|
|
433
|
+
if not found:
|
|
434
|
+
return style.box("discover", [style.seg("no printers answered", "dim")], mode,
|
|
435
|
+
footer="0 found")
|
|
436
|
+
rows = [[f.make_model or f.name, f.host, f.addresses[0] if f.addresses else "",
|
|
437
|
+
" ".join(f.services), saved.get(f.host.lower(), "")] for f in found]
|
|
438
|
+
body = style.table_rows(["model", "host", "address", "services", "saved as"], rows, mode)
|
|
439
|
+
hint = Text(f"save one: prt printers add {found[0].suggested_name()} {found[0].host} --default",
|
|
440
|
+
style=ROLES["dim"])
|
|
441
|
+
return style.box("discover", [*body, None, hint], mode, footer=f"{len(found)} found")
|
|
442
|
+
|
|
443
|
+
STATE.emit([f.__dict__ | {"services": f.services} for f in found], text,
|
|
444
|
+
lambda: [style.plain_record(f.make_model or f.name, f.host,
|
|
445
|
+
f.addresses[0] if f.addresses else "", ",".join(f.services))
|
|
446
|
+
for f in found])
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
# --- printers ---------------------------------------------------------------------------
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
@printers_app.command("list")
|
|
453
|
+
def printers_list(check: bool = typer.Option(False, "--check", help="Ping each printer over IPP.")) -> None:
|
|
454
|
+
"""Saved printers, their driver and which one is the default."""
|
|
455
|
+
cfg = STATE.cfg
|
|
456
|
+
rows_data = []
|
|
457
|
+
for name, tgt in cfg.printers.items():
|
|
458
|
+
reach = None
|
|
459
|
+
if check:
|
|
460
|
+
try:
|
|
461
|
+
make_driver(tgt, min(cfg.timeout, 3)).status()
|
|
462
|
+
reach = "online"
|
|
463
|
+
except PrinterError:
|
|
464
|
+
reach = "offline"
|
|
465
|
+
rows_data.append({"name": name, "host": tgt.host, "driver": tgt.driver,
|
|
466
|
+
"default": name == cfg.default, "reachable": reach})
|
|
467
|
+
mode = STATE.out
|
|
468
|
+
|
|
469
|
+
def text() -> str:
|
|
470
|
+
if not rows_data:
|
|
471
|
+
return style.box("printers", [style.seg("no saved printers — run `prt discover`", "dim")],
|
|
472
|
+
mode, footer=str(cfg.path))
|
|
473
|
+
g = style.glyphs(mode)
|
|
474
|
+
rows = []
|
|
475
|
+
for r in rows_data:
|
|
476
|
+
mark = style.seg(g["ok"] if r["default"] else " ", "accent")
|
|
477
|
+
reach = (style.status("ok" if r["reachable"] == "online" else "offline", r["reachable"], mode)
|
|
478
|
+
if r["reachable"] else Text(""))
|
|
479
|
+
rows.append([mark, t(r["name"]), t(r["host"]), t(r["driver"]), reach])
|
|
480
|
+
return style.box("printers", style.table_rows(["", "name", "host", "driver", "state"], rows, mode),
|
|
481
|
+
mode, footer=f"{len(rows_data)} saved {g['dot']} {g['ok']} default")
|
|
482
|
+
|
|
483
|
+
STATE.emit(rows_data, text, lambda: [style.plain_record(r["name"], r["host"], r["driver"],
|
|
484
|
+
"default" if r["default"] else "",
|
|
485
|
+
r["reachable"] or "") for r in rows_data])
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
@printers_app.command("add")
|
|
489
|
+
def printers_add(
|
|
490
|
+
name: str = typer.Argument(..., help="Short name to refer to this printer."),
|
|
491
|
+
host: str = typer.Argument(..., help="Hostname or IP, e.g. EPSON721655.local or 192.168.1.70."),
|
|
492
|
+
driver: str = typer.Option("auto", "--driver", "-d", help="auto, ipp, epson or fake."),
|
|
493
|
+
default: bool = typer.Option(False, "--default", help="Make it the default printer."),
|
|
494
|
+
port: int = typer.Option(631, "--port", help="IPP port."),
|
|
495
|
+
) -> None:
|
|
496
|
+
"""Save a printer under a short name."""
|
|
497
|
+
if driver not in driver_names():
|
|
498
|
+
raise PrinterError(f"unknown driver '{driver}'", hint="choose: " + ", ".join(driver_names()), exit_code=2)
|
|
499
|
+
from prt.models import Target
|
|
500
|
+
cfg = STATE.cfg
|
|
501
|
+
cfg.printers[name] = Target(name=name, host=host, driver=driver, ipp_port=port)
|
|
502
|
+
if default or not cfg.default:
|
|
503
|
+
cfg.default = name
|
|
504
|
+
cfg.save()
|
|
505
|
+
STATE.note("ok", f"saved '{name}' → {host}", f"{'default · ' if cfg.default == name else ''}{cfg.path}")
|
|
506
|
+
if STATE.json:
|
|
507
|
+
STATE.write(json.dumps({"name": name, "host": host, "driver": driver, "default": cfg.default == name}) + "\n")
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
@printers_app.command("remove")
|
|
511
|
+
def printers_remove(name: str = typer.Argument(..., help="Saved printer name.")) -> None:
|
|
512
|
+
"""Forget a saved printer."""
|
|
513
|
+
cfg = STATE.cfg
|
|
514
|
+
if name not in cfg.printers:
|
|
515
|
+
raise PrinterError(f"no saved printer named '{name}'", hint="see `prt printers list`", exit_code=2)
|
|
516
|
+
del cfg.printers[name]
|
|
517
|
+
if cfg.default == name:
|
|
518
|
+
cfg.default = next(iter(cfg.printers), None)
|
|
519
|
+
cfg.save()
|
|
520
|
+
STATE.note("ok", f"removed '{name}'")
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
@printers_app.command("default")
|
|
524
|
+
def printers_default(name: str = typer.Argument(..., help="Saved printer name.")) -> None:
|
|
525
|
+
"""Choose the printer used when --printer is not given."""
|
|
526
|
+
cfg = STATE.cfg
|
|
527
|
+
if name not in cfg.printers:
|
|
528
|
+
raise PrinterError(f"no saved printer named '{name}'", hint="see `prt printers list`", exit_code=2)
|
|
529
|
+
cfg.default = name
|
|
530
|
+
cfg.save()
|
|
531
|
+
STATE.note("ok", f"'{name}' is now the default printer")
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
# --- maintain --------------------------------------------------------------------------------
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _confirm(question: str, yes: bool) -> None:
|
|
538
|
+
if yes:
|
|
539
|
+
return
|
|
540
|
+
if not sys.stdin.isatty():
|
|
541
|
+
raise PrinterError("confirmation needed but stdin is not a terminal", hint="re-run with --yes",
|
|
542
|
+
exit_code=2)
|
|
543
|
+
if not typer.confirm(question, default=False, err=True):
|
|
544
|
+
STATE.note("info", "cancelled — nothing was sent")
|
|
545
|
+
raise typer.Exit(1)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _show_preflight(pf) -> None:
|
|
549
|
+
for b in pf.blockers:
|
|
550
|
+
STATE.note("err", b)
|
|
551
|
+
for w in pf.warnings:
|
|
552
|
+
STATE.note("warn", w)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
@maintain_app.command("nozzle-check")
|
|
556
|
+
def nozzle_check(yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt.")) -> None:
|
|
557
|
+
"""Print the nozzle check pattern (1 sheet, a little ink). Gaps in a line = clogged nozzles."""
|
|
558
|
+
d = STATE.driver()
|
|
559
|
+
d.require(Capability.NOZZLE_CHECK)
|
|
560
|
+
pf = nozzle_check_preflight(_fetch_status(d)[1])
|
|
561
|
+
_show_preflight(pf)
|
|
562
|
+
if not pf.ok:
|
|
563
|
+
raise PrinterError("nozzle check not sent", hint="fix the issues above and retry")
|
|
564
|
+
_confirm(f"Print a nozzle check on {d.display_name}?", yes)
|
|
565
|
+
d.nozzle_check()
|
|
566
|
+
STATE.note("ok", "nozzle check sent", "broken lines in the pattern → run `prt maintain clean`")
|
|
567
|
+
if STATE.json:
|
|
568
|
+
STATE.write(json.dumps({"action": "nozzle_check", "sent": True}) + "\n")
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
@maintain_app.command("clean")
|
|
572
|
+
def head_clean(
|
|
573
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt."),
|
|
574
|
+
force: bool = typer.Option(False, "--force", help="Clean even if ink is low or the waste pad is near full."),
|
|
575
|
+
) -> None:
|
|
576
|
+
"""Clean the print head. Uses ink and fills the waste pad — run a nozzle check first."""
|
|
577
|
+
d = STATE.driver()
|
|
578
|
+
d.require(Capability.HEAD_CLEAN)
|
|
579
|
+
pf = head_clean_preflight(_fetch_status(d)[1])
|
|
580
|
+
_show_preflight(pf)
|
|
581
|
+
if not pf.ok and not force:
|
|
582
|
+
raise PrinterError("head cleaning refused for safety",
|
|
583
|
+
hint="replace low cartridges first, or pass --force if you understand the risk")
|
|
584
|
+
_confirm(f"Start head cleaning on {d.display_name}? (takes ~1 minute, uses ink)", yes)
|
|
585
|
+
d.head_clean()
|
|
586
|
+
STATE.note("ok", "head cleaning started", "wait until the printer is quiet, then run a nozzle check")
|
|
587
|
+
if STATE.json:
|
|
588
|
+
STATE.write(json.dumps({"action": "head_clean", "sent": True, "forced": force and not pf.ok}) + "\n")
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
@maintain_app.command("test-page")
|
|
592
|
+
def test_page(yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt.")) -> None:
|
|
593
|
+
"""Print prt's colour test page: ink bars, gradients, grey steps, fine lines (A4)."""
|
|
594
|
+
d = STATE.driver()
|
|
595
|
+
d.require(Capability.TEST_PAGE)
|
|
596
|
+
_confirm(f"Print a colour test page on {d.display_name}?", yes)
|
|
597
|
+
job = d.test_page()
|
|
598
|
+
STATE.note("ok", f"test page queued as job {job}")
|
|
599
|
+
if STATE.json:
|
|
600
|
+
STATE.write(json.dumps({"action": "test_page", "job_id": job}) + "\n")
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
@maintain_app.command("identify")
|
|
604
|
+
def identify() -> None:
|
|
605
|
+
"""Flash the printer's panel so you can find it."""
|
|
606
|
+
d = STATE.driver()
|
|
607
|
+
d.require(Capability.IDENTIFY)
|
|
608
|
+
d.identify()
|
|
609
|
+
STATE.note("ok", f"{d.display_name} should be flashing now")
|
|
610
|
+
if STATE.json:
|
|
611
|
+
STATE.write(json.dumps({"action": "identify", "sent": True}) + "\n")
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
# --- print / jobs / scan -------------------------------------------------------------------
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
class Quality(str, Enum):
|
|
618
|
+
draft = "draft"
|
|
619
|
+
normal = "normal"
|
|
620
|
+
high = "high"
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
@app.command("print")
|
|
624
|
+
def print_cmd(
|
|
625
|
+
files: list[Path] = typer.Argument(..., help="Files to print (JPEG/PNG direct; PDF and others via CUPS)."),
|
|
626
|
+
copies: int = typer.Option(1, "--copies", "-n", min=1, max=99, help="Number of copies."),
|
|
627
|
+
media: Optional[str] = typer.Option(None, "--media", "-m", help="Paper size: a4, letter, 4x6, 5x7, …"),
|
|
628
|
+
mono: bool = typer.Option(False, "--mono", help="Print in black & white."),
|
|
629
|
+
quality: Optional[Quality] = typer.Option(None, "--quality", help="draft, normal or high."),
|
|
630
|
+
duplex: bool = typer.Option(False, "--duplex", help="Print on both sides."),
|
|
631
|
+
tray: Optional[str] = typer.Option(None, "--tray", "-t", help="Input tray: main, photo, disc."),
|
|
632
|
+
direct: bool = typer.Option(False, "--direct", help="Send straight to the printer, never via CUPS."),
|
|
633
|
+
) -> None:
|
|
634
|
+
"""Print one or more files."""
|
|
635
|
+
d = STATE.driver()
|
|
636
|
+
d.require(Capability.PRINT)
|
|
637
|
+
results = []
|
|
638
|
+
for f in files:
|
|
639
|
+
opts = PrintOptions(copies=copies, media=media, mono=mono, quality=quality.value if quality else None,
|
|
640
|
+
duplex=duplex, tray=tray, direct=direct, job_name=f.name)
|
|
641
|
+
job = d.print_file(f, opts)
|
|
642
|
+
results.append({"file": str(f), "job_id": job})
|
|
643
|
+
STATE.note("ok", f"{f.name} → job {job}" if job else f"{f.name} sent", d.display_name)
|
|
644
|
+
if STATE.json:
|
|
645
|
+
STATE.write(json.dumps(results) + "\n")
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
@jobs_app.callback()
|
|
649
|
+
def jobs(ctx: typer.Context,
|
|
650
|
+
all_: bool = typer.Option(False, "--all", "-a", help="Include completed jobs.")) -> None:
|
|
651
|
+
"""List print jobs (active only unless --all)."""
|
|
652
|
+
if ctx.invoked_subcommand:
|
|
653
|
+
return
|
|
654
|
+
d = STATE.driver()
|
|
655
|
+
d.require(Capability.JOBS)
|
|
656
|
+
items = d.jobs(include_completed=all_)
|
|
657
|
+
mode = STATE.out
|
|
658
|
+
|
|
659
|
+
def text() -> str:
|
|
660
|
+
if not items:
|
|
661
|
+
return style.box("jobs", [style.seg("no active jobs" if not all_ else "no jobs", "dim")],
|
|
662
|
+
mode, footer=d.target.name)
|
|
663
|
+
rows = []
|
|
664
|
+
for j in items:
|
|
665
|
+
lvl = {"completed": "ok", "processing": "info", "pending": "info", "canceled": "warn",
|
|
666
|
+
"aborted": "err"}.get(j.state, "info")
|
|
667
|
+
rows.append([str(j.id), t(j.name), style.status(lvl, j.state, mode), t(j.user or ""),
|
|
668
|
+
str(j.pages if j.pages is not None else "")])
|
|
669
|
+
body = style.table_rows(["id", "name", "state", "user", "pages"], rows, mode, right={0, 4})
|
|
670
|
+
return style.box(f"jobs {style.glyphs(mode)['dot']} {d.target.name}", body, mode,
|
|
671
|
+
footer=f"{len(items)} job{'s' if len(items) != 1 else ''}")
|
|
672
|
+
|
|
673
|
+
STATE.emit([to_dict(j) for j in items], text,
|
|
674
|
+
lambda: [style.plain_record(j.id, j.name, j.state, j.user or "",
|
|
675
|
+
"" if j.pages is None else j.pages) for j in items])
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
@jobs_app.command("cancel")
|
|
679
|
+
def jobs_cancel(job_id: int = typer.Argument(..., help="Job id from `prt jobs`.")) -> None:
|
|
680
|
+
"""Cancel a print job."""
|
|
681
|
+
d = STATE.driver()
|
|
682
|
+
d.require(Capability.JOBS)
|
|
683
|
+
d.cancel_job(job_id)
|
|
684
|
+
STATE.note("ok", f"job {job_id} cancelled")
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
class ScanFormat(str, Enum):
|
|
688
|
+
pdf = "pdf"
|
|
689
|
+
jpeg = "jpeg"
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
class ScanMode(str, Enum):
|
|
693
|
+
color = "color"
|
|
694
|
+
gray = "gray"
|
|
695
|
+
bw = "bw"
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
class ScanArea(str, Enum):
|
|
699
|
+
a4 = "a4"
|
|
700
|
+
letter = "letter"
|
|
701
|
+
full = "full"
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
@app.command()
|
|
705
|
+
def scan(
|
|
706
|
+
output: Optional[str] = typer.Option(None, "--output", "-o",
|
|
707
|
+
help="Output file ('-' for stdout) [default: scan-<time>.<ext>]."),
|
|
708
|
+
fmt: ScanFormat = typer.Option(ScanFormat.pdf, "--format", "--type", "-T", help="File type: pdf or jpeg."),
|
|
709
|
+
dpi: int = typer.Option(300, "--dpi", "-r", help="Resolution: 100, 200, 300, 600 or 1200."),
|
|
710
|
+
mode_: ScanMode = typer.Option(ScanMode.color, "--mode", help="color, gray or bw."),
|
|
711
|
+
area: ScanArea = typer.Option(ScanArea.a4, "--area", help="Scan area: a4, letter or full glass."),
|
|
712
|
+
) -> None:
|
|
713
|
+
"""Scan from the flatbed (eSCL / AirScan)."""
|
|
714
|
+
d = STATE.driver()
|
|
715
|
+
d.require(Capability.SCAN)
|
|
716
|
+
if output == "-" and sys.stdout.isatty():
|
|
717
|
+
raise PrinterError("refusing to write binary scan data to the terminal",
|
|
718
|
+
hint="redirect stdout (`> file.pdf`) or use -o FILE", exit_code=2)
|
|
719
|
+
path = None if output == "-" else Path(output or time.strftime(f"scan-%Y%m%d-%H%M%S.{fmt.value}"))
|
|
720
|
+
started = time.monotonic()
|
|
721
|
+
show = style.progress_enabled() and not STATE.quiet
|
|
722
|
+
|
|
723
|
+
def progress(stage: str) -> None:
|
|
724
|
+
if show:
|
|
725
|
+
sys.stderr.write(f"\r\x1b[2K{stage}… {time.monotonic() - started:4.1f}s" if STATE.err.styled
|
|
726
|
+
else f"\r{stage}... {time.monotonic() - started:4.1f}s ")
|
|
727
|
+
sys.stderr.flush()
|
|
728
|
+
|
|
729
|
+
from prt.transport.escl import ScanError
|
|
730
|
+
try:
|
|
731
|
+
data = d.scan(ScanSettings(format=fmt.value, dpi=dpi, mode=mode_.value, area=area.value), progress)
|
|
732
|
+
except ScanError as exc:
|
|
733
|
+
raise PrinterError(str(exc), hint="check that the lid is closed and the scanner is idle") from exc
|
|
734
|
+
finally:
|
|
735
|
+
if show:
|
|
736
|
+
sys.stderr.write("\r\x1b[2K" if STATE.err.styled else "\r" + " " * 40 + "\r")
|
|
737
|
+
if path is None:
|
|
738
|
+
sys.stdout.buffer.write(data)
|
|
739
|
+
sys.stdout.buffer.flush()
|
|
740
|
+
return
|
|
741
|
+
path.write_bytes(data)
|
|
742
|
+
STATE.note("ok", f"saved {path}", f"{len(data) / 1024:,.0f} KiB · {time.monotonic() - started:.1f}s")
|
|
743
|
+
if STATE.json:
|
|
744
|
+
STATE.write(json.dumps({"file": str(path), "bytes": len(data)}) + "\n")
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
@app.command()
|
|
748
|
+
def tui() -> None:
|
|
749
|
+
"""Full-screen dashboard (keyboard driven)."""
|
|
750
|
+
from prt.tui.app import run
|
|
751
|
+
run(STATE.cfg, STATE.printer, STATE.timeout)
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
app.command("dash", hidden=True, help="Alias for tui.")(tui)
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
# --- Entry point ---------------------------------------------------------------------------------
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _configure_help(argv: list[str]) -> None:
|
|
761
|
+
"""Pass the same colour decision to Typer's rich help (btop style §4: help text)."""
|
|
762
|
+
import typer.rich_utils as ru
|
|
763
|
+
mode = style.decide(sys.stdout, no_color="--no-color" in argv, is_stdout=True)
|
|
764
|
+
ru.FORCE_TERMINAL = mode.styled
|
|
765
|
+
ru.COLOR_SYSTEM = style.TIERS[mode.tier] if mode.styled else None
|
|
766
|
+
ru.STYLE_OPTION = ru.STYLE_SWITCH = ROLES["accent"]
|
|
767
|
+
ru.STYLE_COMMANDS_TABLE_FIRST_COLUMN = ROLES["accent"]
|
|
768
|
+
ru.STYLE_USAGE = ROLES["title"]
|
|
769
|
+
ru.STYLE_OPTIONS_PANEL_BORDER = ru.STYLE_COMMANDS_PANEL_BORDER = ROLES["border"]
|
|
770
|
+
ru.STYLE_ERRORS_PANEL_BORDER = ROLES["err"]
|
|
771
|
+
ru.STYLE_METAVAR = ROLES["dim"] if hasattr(ru, "STYLE_METAVAR") else None
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
GLOBAL_WITH_VALUE = {"-p", "--printer", "-f", "--format", "--timeout", "--config"}
|
|
775
|
+
GLOBAL_FLAGS = {"--no-color", "-q", "--quiet", "-v", "--verbose"}
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def hoist_globals(argv: list[str]) -> list[str]:
|
|
779
|
+
"""Allow global options anywhere (`prt ink -f json` == `prt -f json ink`)."""
|
|
780
|
+
front: list[str] = []
|
|
781
|
+
rest: list[str] = []
|
|
782
|
+
i = 0
|
|
783
|
+
while i < len(argv):
|
|
784
|
+
a = argv[i]
|
|
785
|
+
if a == "--":
|
|
786
|
+
rest += argv[i:]
|
|
787
|
+
break
|
|
788
|
+
key = a.split("=", 1)[0]
|
|
789
|
+
if a in GLOBAL_FLAGS:
|
|
790
|
+
front.append(a)
|
|
791
|
+
elif key in ("-f", "--format") and (a.split("=", 1)[1] if "=" in a else
|
|
792
|
+
argv[i + 1] if i + 1 < len(argv) else "") not in ("text", "json"):
|
|
793
|
+
rest.append(a) # e.g. `scan --format jpeg` belongs to the command, not the global flag
|
|
794
|
+
elif key in GLOBAL_WITH_VALUE and "=" in a:
|
|
795
|
+
front.append(a)
|
|
796
|
+
elif a in GLOBAL_WITH_VALUE and i + 1 < len(argv):
|
|
797
|
+
front += [a, argv[i + 1]]
|
|
798
|
+
i += 1
|
|
799
|
+
else:
|
|
800
|
+
rest.append(a)
|
|
801
|
+
i += 1
|
|
802
|
+
return front + rest
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def main(argv: list[str] | None = None) -> int:
|
|
806
|
+
argv = hoist_globals(list(sys.argv[1:] if argv is None else argv))
|
|
807
|
+
_configure_help(argv)
|
|
808
|
+
try:
|
|
809
|
+
rv = app(args=argv, prog_name="prt", standalone_mode=False)
|
|
810
|
+
return rv if isinstance(rv, int) else 0
|
|
811
|
+
except PrinterError as exc:
|
|
812
|
+
sys.stderr.write(style.error(str(exc), exc.hint, STATE.err))
|
|
813
|
+
return exc.exit_code
|
|
814
|
+
except typer.Exit as exc:
|
|
815
|
+
return exc.exit_code
|
|
816
|
+
except (KeyboardInterrupt, typer.Abort):
|
|
817
|
+
sys.stderr.write("\n")
|
|
818
|
+
return 130
|
|
819
|
+
except BrokenPipeError:
|
|
820
|
+
return 0
|
|
821
|
+
except Exception as exc:
|
|
822
|
+
# Usage errors from Typer's (vendored) click: they know how to print themselves.
|
|
823
|
+
if hasattr(exc, "show") and hasattr(exc, "exit_code"):
|
|
824
|
+
exc.show()
|
|
825
|
+
return int(exc.exit_code)
|
|
826
|
+
raise
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def entry() -> None:
|
|
830
|
+
sys.exit(main())
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
if __name__ == "__main__":
|
|
834
|
+
entry()
|