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/models.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Vendor-neutral data models shared by drivers, the CLI and the TUI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Capability(str, Enum):
|
|
12
|
+
INFO = "info"
|
|
13
|
+
STATUS = "status"
|
|
14
|
+
PRINT = "print"
|
|
15
|
+
JOBS = "jobs"
|
|
16
|
+
SCAN = "scan"
|
|
17
|
+
IDENTIFY = "identify"
|
|
18
|
+
NOZZLE_CHECK = "nozzle_check"
|
|
19
|
+
HEAD_CLEAN = "head_clean"
|
|
20
|
+
TEST_PAGE = "test_page"
|
|
21
|
+
COUNTERS = "counters"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Severity(str, Enum):
|
|
25
|
+
INFO = "info"
|
|
26
|
+
WARNING = "warning"
|
|
27
|
+
ERROR = "error"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Target:
|
|
32
|
+
"""Where a printer lives and how to reach each of its services."""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
host: str
|
|
36
|
+
driver: str = "auto"
|
|
37
|
+
ipp_port: int = 631
|
|
38
|
+
ipp_path: str = "/ipp/print"
|
|
39
|
+
ipp_tls: bool = False
|
|
40
|
+
scan_port: int | None = None # None → probe 443 (TLS) then 80
|
|
41
|
+
scan_tls: bool | None = None
|
|
42
|
+
scan_path: str = "/eSCL"
|
|
43
|
+
snmp_community: str = "public"
|
|
44
|
+
raw_port: int = 9100
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Ink:
|
|
49
|
+
name: str
|
|
50
|
+
color: str # "#RRGGBB" as reported by the printer
|
|
51
|
+
level: int | None # 0–100, None when unknown
|
|
52
|
+
low: int = 15
|
|
53
|
+
high: int = 100
|
|
54
|
+
kind: str = "ink-cartridge"
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def short(self) -> str:
|
|
58
|
+
"""Two-letter label used by compact views (PB, BK, C, M, Y …)."""
|
|
59
|
+
n = self.name.lower().replace(" ink", "").replace(" toner", "").strip()
|
|
60
|
+
table = {"photo black": "PB", "black": "BK", "matte black": "MK", "cyan": "C",
|
|
61
|
+
"magenta": "M", "yellow": "Y", "light cyan": "LC", "light magenta": "LM",
|
|
62
|
+
"gray": "GY", "grey": "GY", "red": "R", "blue": "B", "green": "G"}
|
|
63
|
+
return table.get(n, "".join(w[0] for w in n.split()).upper()[:2] or "?")
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def state(self) -> str:
|
|
67
|
+
"""ok | low | replace | unknown."""
|
|
68
|
+
if self.level is None:
|
|
69
|
+
return "unknown"
|
|
70
|
+
if self.level <= max(3, self.low // 5):
|
|
71
|
+
return "replace"
|
|
72
|
+
if self.level <= self.low:
|
|
73
|
+
return "low"
|
|
74
|
+
return "ok"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class Tray:
|
|
79
|
+
source: str # main | photo | disc | manual | …
|
|
80
|
+
media: str | None = None # friendly size, e.g. "A4"
|
|
81
|
+
media_type: str | None = None # stationery | photographic | …
|
|
82
|
+
level: int | None = None # percentage, None = printer does not report it
|
|
83
|
+
status: str = "ok"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class Alert:
|
|
88
|
+
code: str
|
|
89
|
+
severity: Severity
|
|
90
|
+
message: str
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class Job:
|
|
95
|
+
id: int
|
|
96
|
+
name: str
|
|
97
|
+
state: str
|
|
98
|
+
user: str | None = None
|
|
99
|
+
pages: int | None = None
|
|
100
|
+
created: float | None = None # unix time
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass
|
|
104
|
+
class Status:
|
|
105
|
+
state: str # idle | processing | stopped | offline
|
|
106
|
+
accepting: bool = True
|
|
107
|
+
inks: list[Ink] = field(default_factory=list)
|
|
108
|
+
trays: list[Tray] = field(default_factory=list)
|
|
109
|
+
alerts: list[Alert] = field(default_factory=list)
|
|
110
|
+
reasons: list[str] = field(default_factory=list)
|
|
111
|
+
waste: str | None = None # ok | almost-full | full | None (unknown)
|
|
112
|
+
waste_level: int | None = None # percentage when a driver can read it
|
|
113
|
+
queued_jobs: int = 0
|
|
114
|
+
checked_at: float = field(default_factory=time.time)
|
|
115
|
+
stale: bool = False # True when served from the offline cache
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def worst(self) -> Severity | None:
|
|
119
|
+
order = [Severity.ERROR, Severity.WARNING, Severity.INFO]
|
|
120
|
+
for sev in order:
|
|
121
|
+
if any(a.severity == sev for a in self.alerts):
|
|
122
|
+
return sev
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class PrinterInfo:
|
|
128
|
+
name: str
|
|
129
|
+
make_model: str
|
|
130
|
+
vendor: str
|
|
131
|
+
host: str
|
|
132
|
+
driver: str
|
|
133
|
+
model: str | None = None
|
|
134
|
+
serial: str | None = None
|
|
135
|
+
firmware: str | None = None
|
|
136
|
+
uuid: str | None = None
|
|
137
|
+
uptime_seconds: int | None = None
|
|
138
|
+
page_count: int | None = None
|
|
139
|
+
color: bool | None = None
|
|
140
|
+
duplex: bool | None = None
|
|
141
|
+
ppm: int | None = None
|
|
142
|
+
ppm_color: int | None = None
|
|
143
|
+
formats: list[str] = field(default_factory=list)
|
|
144
|
+
media: list[str] = field(default_factory=list)
|
|
145
|
+
media_sources: list[str] = field(default_factory=list)
|
|
146
|
+
resolutions: list[str] = field(default_factory=list)
|
|
147
|
+
ipp_versions: list[str] = field(default_factory=list)
|
|
148
|
+
uris: list[str] = field(default_factory=list)
|
|
149
|
+
admin_url: str | None = None
|
|
150
|
+
capabilities: list[str] = field(default_factory=list)
|
|
151
|
+
scanner: dict[str, Any] = field(default_factory=dict)
|
|
152
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass
|
|
156
|
+
class ScanSettings:
|
|
157
|
+
format: str = "pdf" # pdf | jpeg
|
|
158
|
+
dpi: int = 300
|
|
159
|
+
mode: str = "color" # color | gray | bw
|
|
160
|
+
area: str = "a4" # a4 | letter | full
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass
|
|
164
|
+
class PrintOptions:
|
|
165
|
+
copies: int = 1
|
|
166
|
+
media: str | None = None
|
|
167
|
+
mono: bool = False
|
|
168
|
+
quality: str | None = None # draft | normal | high
|
|
169
|
+
duplex: bool = False
|
|
170
|
+
tray: str | None = None
|
|
171
|
+
direct: bool = False
|
|
172
|
+
job_name: str | None = None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def to_dict(obj: Any) -> Any:
|
|
176
|
+
"""JSON-ready dict for any model (enums become their values)."""
|
|
177
|
+
def convert(v: Any) -> Any:
|
|
178
|
+
if isinstance(v, Enum):
|
|
179
|
+
return v.value
|
|
180
|
+
if isinstance(v, dict):
|
|
181
|
+
return {k: convert(x) for k, x in v.items()}
|
|
182
|
+
if isinstance(v, (list, tuple)):
|
|
183
|
+
return [convert(x) for x in v]
|
|
184
|
+
return v
|
|
185
|
+
|
|
186
|
+
data = convert(asdict(obj))
|
|
187
|
+
if isinstance(obj, Ink):
|
|
188
|
+
data.update(short=obj.short, state=obj.state)
|
|
189
|
+
if isinstance(obj, Status):
|
|
190
|
+
data["inks"] = [to_dict(i) for i in obj.inks]
|
|
191
|
+
data["worst"] = obj.worst.value if obj.worst else None
|
|
192
|
+
return data
|
prt/printing.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Printing strategy.
|
|
2
|
+
|
|
3
|
+
Many printers (the Epson XP-6000 included) accept only JPEG / PWG-raster / URF over IPP —
|
|
4
|
+
not PDF. So:
|
|
5
|
+
1. JPEG / PWG / URF → sent directly with IPP Print-Job.
|
|
6
|
+
2. Other images → converted to JPEG with Pillow, then sent directly.
|
|
7
|
+
3. Everything else → handed to the local CUPS queue for the same printer (matched by UUID
|
|
8
|
+
or host), which converts PDF/text/office output for us.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import io
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from prt.drivers.base import PrinterError
|
|
20
|
+
from prt.models import PrintOptions
|
|
21
|
+
|
|
22
|
+
IMAGE_EXT = {".png", ".gif", ".bmp", ".tif", ".tiff", ".webp", ".heic"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def find_cups_queue(uuid: str | None, host: str) -> str | None:
|
|
26
|
+
"""Return the CUPS queue whose device URI points at this printer."""
|
|
27
|
+
if not shutil.which("lpstat"):
|
|
28
|
+
return None
|
|
29
|
+
try:
|
|
30
|
+
out = subprocess.run(["lpstat", "-v"], capture_output=True, text=True, timeout=5).stdout
|
|
31
|
+
except (OSError, subprocess.SubprocessError):
|
|
32
|
+
return None
|
|
33
|
+
return match_queue(out, uuid, host)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def match_queue(lpstat_v: str, uuid: str | None, host: str) -> str | None:
|
|
37
|
+
host_l = host.lower().removesuffix(".local")
|
|
38
|
+
for line in lpstat_v.splitlines():
|
|
39
|
+
m = re.match(r"device for (\S+?):\s+(\S+)", line)
|
|
40
|
+
if not m:
|
|
41
|
+
continue
|
|
42
|
+
queue, uri = m.group(1), m.group(2).lower()
|
|
43
|
+
if uuid and uuid.lower() in uri:
|
|
44
|
+
return queue
|
|
45
|
+
if host_l and host_l in uri:
|
|
46
|
+
return queue
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cups_print(queue: str, path: Path, options: PrintOptions) -> int:
|
|
51
|
+
cmd = ["lp", "-d", queue, "-n", str(max(1, options.copies)), "-t", options.job_name or path.name]
|
|
52
|
+
if options.media:
|
|
53
|
+
cmd += ["-o", f"media={options.media}"]
|
|
54
|
+
if options.mono:
|
|
55
|
+
cmd += ["-o", "print-color-mode=monochrome"]
|
|
56
|
+
if options.quality:
|
|
57
|
+
cmd += ["-o", f"print-quality={ {'draft': 3, 'normal': 4, 'high': 5}[options.quality] }"]
|
|
58
|
+
if options.duplex:
|
|
59
|
+
cmd += ["-o", "sides=two-sided-long-edge"]
|
|
60
|
+
if options.tray:
|
|
61
|
+
cmd += ["-o", f"media-source={options.tray}"]
|
|
62
|
+
cmd.append(str(path))
|
|
63
|
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
|
64
|
+
if res.returncode != 0:
|
|
65
|
+
raise PrinterError(f"CUPS refused the job: {res.stderr.strip() or res.stdout.strip()}")
|
|
66
|
+
m = re.search(r"request id is \S+-(\d+)", res.stdout)
|
|
67
|
+
return int(m.group(1)) if m else 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def print_file(driver, path: Path, options: PrintOptions) -> int:
|
|
71
|
+
from prt.drivers.ipp import DIRECT_FORMATS
|
|
72
|
+
|
|
73
|
+
if not path.is_file():
|
|
74
|
+
raise PrinterError(f"file not found: {path}", hint="check the path", exit_code=3)
|
|
75
|
+
options.job_name = options.job_name or path.name
|
|
76
|
+
ext = path.suffix.lower()
|
|
77
|
+
if ext in DIRECT_FORMATS:
|
|
78
|
+
return driver.submit(path.read_bytes(), DIRECT_FORMATS[ext], options)
|
|
79
|
+
if ext in IMAGE_EXT:
|
|
80
|
+
try:
|
|
81
|
+
from PIL import Image
|
|
82
|
+
with Image.open(path) as img:
|
|
83
|
+
buf = io.BytesIO()
|
|
84
|
+
img.convert("RGB").save(buf, "JPEG", quality=95)
|
|
85
|
+
except Exception as exc:
|
|
86
|
+
raise PrinterError(f"cannot read image {path.name}: {exc}", exit_code=3) from exc
|
|
87
|
+
return driver.submit(buf.getvalue(), "image/jpeg", options)
|
|
88
|
+
if options.direct:
|
|
89
|
+
raise PrinterError(f"{ext or 'this file type'} cannot be sent directly — the printer only "
|
|
90
|
+
"accepts JPEG, PWG-raster and URF", hint="drop --direct to print via CUPS",
|
|
91
|
+
exit_code=3)
|
|
92
|
+
info_uuid = None
|
|
93
|
+
try:
|
|
94
|
+
info_uuid = driver.info().uuid
|
|
95
|
+
except PrinterError:
|
|
96
|
+
pass
|
|
97
|
+
queue = find_cups_queue(info_uuid, driver.target.host)
|
|
98
|
+
if not queue:
|
|
99
|
+
raise PrinterError(
|
|
100
|
+
f"the printer cannot take {ext or 'this file'} directly and no CUPS queue was found for it",
|
|
101
|
+
hint="add the printer in System Settings → Printers (or `lpadmin`), or convert to JPEG",
|
|
102
|
+
exit_code=1)
|
|
103
|
+
return cups_print(queue, path, options)
|
prt/style.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""btop-inspired terminal styling, in prt's "mono + real ink" palette.
|
|
2
|
+
|
|
3
|
+
Layout vocabulary from btop (rounded boxes with the title notched into the border, cell
|
|
4
|
+
meters, status symbols); colour from prt's palette:
|
|
5
|
+
* chrome is monochrome — terminal default text, bold titles, gray (#6B7280) borders,
|
|
6
|
+
bright green (#22C55E) as the single accent;
|
|
7
|
+
* ink meters are drawn in the cartridge's real colour (the only colour on screen);
|
|
8
|
+
* status uses green / amber (#F59E0B) / red (#EF4444) for the *symbol*, and the word
|
|
9
|
+
beside it stays in the default text colour, so colour never carries meaning alone.
|
|
10
|
+
|
|
11
|
+
Every render function takes an explicit Mode, so tests can render each path without a TTY.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import io
|
|
17
|
+
import math
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import TextIO
|
|
23
|
+
|
|
24
|
+
from rich.cells import cell_len
|
|
25
|
+
from rich.console import Console
|
|
26
|
+
from rich.text import Text
|
|
27
|
+
|
|
28
|
+
# --- Palette roles (command code names roles, never escape codes) -------------
|
|
29
|
+
ROLES = {
|
|
30
|
+
"title": "bold",
|
|
31
|
+
"accent": "bold #22C55E",
|
|
32
|
+
"dim": "dim",
|
|
33
|
+
"border": "#6B7280",
|
|
34
|
+
"ok": "#22C55E",
|
|
35
|
+
"warn": "#F59E0B",
|
|
36
|
+
"err": "bold #EF4444",
|
|
37
|
+
"info": "#6B7280",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
TIERS = {"none": None, "16": "standard", "256": "256", "truecolor": "truecolor"}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Mode:
|
|
45
|
+
styled: bool = True
|
|
46
|
+
tier: str = "truecolor" # none | 16 | 256 | truecolor
|
|
47
|
+
unicode: bool = True
|
|
48
|
+
width: int = 80
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def color(self) -> bool:
|
|
52
|
+
return self.styled and self.tier != "none"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
PLAIN = Mode(styled=False, tier="none", unicode=False, width=80)
|
|
56
|
+
|
|
57
|
+
UNI = {"tl": "╭", "tr": "╮", "bl": "╰", "br": "╯", "h": "─", "v": "│", "nl": "┐", "nr": "┌",
|
|
58
|
+
"fl": "┘", "fr": "└", "lt": "├", "rt": "┤", "cell": "■", "ok": "●", "warn": "▲",
|
|
59
|
+
"err": "✗", "info": "◆", "off": "○", "ell": "…", "dot": "·", "check": "✓"}
|
|
60
|
+
ASC = {"tl": "+", "tr": "+", "bl": "+", "br": "+", "h": "-", "v": "|", "nl": "[", "nr": "]",
|
|
61
|
+
"fl": "[", "fr": "]", "lt": "+", "rt": "+", "cell": "#", "ok": "+", "warn": "!",
|
|
62
|
+
"err": "x", "info": "i", "off": "o", "ell": "...", "dot": "-", "check": "v"}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def glyphs(mode: Mode) -> dict[str, str]:
|
|
66
|
+
return UNI if mode.unicode else ASC
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# --- Section 2: the three decisions per stream ---------------------------------
|
|
70
|
+
|
|
71
|
+
def _truthy(name: str) -> bool:
|
|
72
|
+
return os.environ.get(name, "") not in ("", "0")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def decide(stream: TextIO, *, machine: bool = False, no_color: bool = False,
|
|
76
|
+
is_stdout: bool = True) -> Mode:
|
|
77
|
+
"""Styled-or-plain, colour tier and glyph set for one output stream."""
|
|
78
|
+
width = _width(stream)
|
|
79
|
+
term = os.environ.get("TERM", "")
|
|
80
|
+
try:
|
|
81
|
+
tty = stream.isatty()
|
|
82
|
+
except (AttributeError, ValueError):
|
|
83
|
+
tty = False
|
|
84
|
+
if (is_stdout and machine) or term == "dumb" or (not tty and not _truthy("FORCE_COLOR")):
|
|
85
|
+
return Mode(styled=False, tier="none", unicode=False, width=width)
|
|
86
|
+
if no_color or os.environ.get("NO_COLOR", "") != "":
|
|
87
|
+
tier = "none"
|
|
88
|
+
elif os.environ.get("COLORTERM", "") in ("truecolor", "24bit"):
|
|
89
|
+
tier = "truecolor"
|
|
90
|
+
elif "256color" in term:
|
|
91
|
+
tier = "256"
|
|
92
|
+
else:
|
|
93
|
+
tier = "16"
|
|
94
|
+
enc = (getattr(stream, "encoding", "") or "").lower().replace("-", "")
|
|
95
|
+
return Mode(styled=True, tier=tier, unicode=enc == "utf8", width=width)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _width(stream: TextIO) -> int:
|
|
99
|
+
if os.environ.get("COLUMNS", "").isdigit():
|
|
100
|
+
return int(os.environ["COLUMNS"])
|
|
101
|
+
try:
|
|
102
|
+
return os.get_terminal_size(stream.fileno()).columns
|
|
103
|
+
except (OSError, AttributeError, ValueError, io.UnsupportedOperation):
|
|
104
|
+
return 80
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# --- Text safety ---------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
def escape(value: object, plain: bool = False) -> str:
|
|
110
|
+
"""Make printer-supplied text safe: control characters become visible escapes."""
|
|
111
|
+
out = []
|
|
112
|
+
for ch in str(value):
|
|
113
|
+
o = ord(ch)
|
|
114
|
+
if ch == "\\" and plain:
|
|
115
|
+
out.append("\\\\")
|
|
116
|
+
elif ch == "\t":
|
|
117
|
+
out.append("\\t")
|
|
118
|
+
elif ch == "\n":
|
|
119
|
+
out.append("\\n")
|
|
120
|
+
elif o < 0x20 or o == 0x7F or 0x80 <= o <= 0x9F:
|
|
121
|
+
out.append(f"\\x{o:02x}")
|
|
122
|
+
else:
|
|
123
|
+
out.append(ch)
|
|
124
|
+
return "".join(out)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def plain_record(*fields: object) -> str:
|
|
128
|
+
return "\t".join(escape("" if f is None else f, plain=True) for f in fields)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def seg(text: str, role: str | None = None) -> Text:
|
|
132
|
+
"""Trusted (CLI-written) text with a style *span* — appending to it never inherits the style."""
|
|
133
|
+
out = Text()
|
|
134
|
+
out.append(text, style=ROLES.get(role, role) if role else "")
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def t(value: object, role: str | None = None) -> Text:
|
|
139
|
+
"""User/printer-supplied text as a rich Text (never parsed as markup)."""
|
|
140
|
+
return seg(escape(value), role)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# --- Rendering helpers ---------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
def render(mode: Mode, *items: Text | str) -> str:
|
|
146
|
+
"""Render rich Text objects to a string with exactly the escapes this mode allows."""
|
|
147
|
+
buf = io.StringIO()
|
|
148
|
+
console = Console(file=buf, force_terminal=mode.styled, color_system=TIERS[mode.tier] if mode.styled else None,
|
|
149
|
+
highlight=False, emoji=False, markup=False, width=max(mode.width, 20),
|
|
150
|
+
no_color=False, legacy_windows=False)
|
|
151
|
+
for item in items:
|
|
152
|
+
console.print(item, end="", soft_wrap=True, crop=False)
|
|
153
|
+
out = buf.getvalue()
|
|
154
|
+
return out if mode.unicode else to_ascii(out)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
ASCII_MAP = str.maketrans({"×": "x", "—": "-", "–": "-", "…": "...", "·": "-", "✓": "v", "✗": "x",
|
|
158
|
+
"●": "+", "▲": "!", "◆": "i", "○": "o", "■": "#", "→": "->", "°": "o"})
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def to_ascii(s: str) -> str:
|
|
162
|
+
"""ASCII glyph set: transliterate our own symbols; anything else non-ASCII becomes '?'."""
|
|
163
|
+
s = s.translate(ASCII_MAP)
|
|
164
|
+
return "".join(c if ord(c) < 0x80 else "?" for c in s)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _round(x: float) -> int:
|
|
168
|
+
return math.floor(x + 0.5)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def fit(text: Text, width: int, mode: Mode) -> Text:
|
|
172
|
+
"""Truncate with an ellipsis, then pad, measuring terminal cells."""
|
|
173
|
+
text = text.copy()
|
|
174
|
+
if cell_len(text.plain) > width:
|
|
175
|
+
ell = glyphs(mode)["ell"]
|
|
176
|
+
text.truncate(max(0, width - cell_len(ell)))
|
|
177
|
+
text.append(ell)
|
|
178
|
+
text.pad_right(max(0, width - cell_len(text.plain)))
|
|
179
|
+
return text
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# --- Components (section 4) -------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
_HEX = re.compile(r"#?([0-9A-Fa-f]{6})")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def ink_colors(value: str) -> list[str]:
|
|
188
|
+
"""Parse an IPP marker-colors value into '#RRGGBB' strings.
|
|
189
|
+
|
|
190
|
+
A single cartridge is '#RRGGBB'; a multi-colour one concatenates them
|
|
191
|
+
('#00FFFF#FF00FF#FFFF00' for an HP tri-colour); 'none' or junk gives []."""
|
|
192
|
+
return [f"#{m.upper()}" for m in _HEX.findall(value or "")]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def is_dark(hex_color: str) -> bool:
|
|
196
|
+
r, g, b = (int(hex_color[i : i + 2], 16) for i in (1, 3, 5))
|
|
197
|
+
return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 < 0.2
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def ink_style(color: str) -> str:
|
|
201
|
+
"""Real cartridge colour (the first, for a multi-colour cartridge); near-black inks use the
|
|
202
|
+
terminal's default foreground so they stay visible on dark terminals."""
|
|
203
|
+
colors = ink_colors(color)
|
|
204
|
+
if not colors or is_dark(colors[0]):
|
|
205
|
+
return "bold"
|
|
206
|
+
return colors[0]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def meter(value: int | None, width: int, mode: Mode, fill_style: str = "bold") -> Text:
|
|
210
|
+
"""btop meter: cell i is filled when value >= round(i*100/width)."""
|
|
211
|
+
g = glyphs(mode)
|
|
212
|
+
out = Text()
|
|
213
|
+
for i in range(1, width + 1):
|
|
214
|
+
filled = value is not None and value >= _round(i * 100 / width)
|
|
215
|
+
if filled:
|
|
216
|
+
out.append(g["cell"], style=fill_style if mode.color else "")
|
|
217
|
+
elif not mode.unicode:
|
|
218
|
+
out.append(".")
|
|
219
|
+
elif mode.color:
|
|
220
|
+
out.append(g["cell"], style="dim")
|
|
221
|
+
else:
|
|
222
|
+
out.append("·")
|
|
223
|
+
out.append(f" {value:>3}%" if value is not None else " ?%")
|
|
224
|
+
return out
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
SEVERITY_ROLE = {"ok": "ok", "info": "info", "warning": "warn", "warn": "warn", "error": "err", "err": "err",
|
|
228
|
+
"offline": "dim"}
|
|
229
|
+
SEVERITY_GLYPH = {"ok": "ok", "info": "info", "warning": "warn", "warn": "warn", "error": "err",
|
|
230
|
+
"err": "err", "offline": "off"}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def status(level: str, word: str, mode: Mode) -> Text:
|
|
234
|
+
g = glyphs(mode)
|
|
235
|
+
out = Text()
|
|
236
|
+
out.append(g[SEVERITY_GLYPH.get(level, "info")], style=ROLES[SEVERITY_ROLE.get(level, "info")])
|
|
237
|
+
out.append(" ")
|
|
238
|
+
out.append(escape(word))
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def box(title: str, rows: list[Text | str | None], mode: Mode, footer: str | None = None,
|
|
243
|
+
max_width: int = 100) -> str:
|
|
244
|
+
"""Rounded box with the title notched into the top border. ``None`` rows are dividers."""
|
|
245
|
+
g = glyphs(mode)
|
|
246
|
+
width = max(30, min(mode.width, max_width))
|
|
247
|
+
inner = width - 4 # "│ " + content + " │"
|
|
248
|
+
border = ROLES["border"]
|
|
249
|
+
|
|
250
|
+
def notch_line(left: str, right: str, nl: str, nr: str, label: str | None) -> Text:
|
|
251
|
+
line = seg(left + g["h"] + (nl if label else ""), border) # one span keeps "╭─┐" contiguous
|
|
252
|
+
if label:
|
|
253
|
+
label_t = fit(seg(escape(label), "title"), min(cell_len(escape(label)), width - 6), mode)
|
|
254
|
+
line.append_text(label_t)
|
|
255
|
+
line.append(nr, style=border)
|
|
256
|
+
rest = width - cell_len(line.plain) - 1
|
|
257
|
+
line.append(g["h"] * max(0, rest) + right, style=border)
|
|
258
|
+
return line
|
|
259
|
+
|
|
260
|
+
lines = [notch_line(g["tl"], g["tr"], g["nl"], g["nr"], title)]
|
|
261
|
+
for row in rows:
|
|
262
|
+
if row is None:
|
|
263
|
+
lines.append(seg(g["lt"] + g["h"] * (width - 2) + g["rt"], border))
|
|
264
|
+
continue
|
|
265
|
+
content = row if isinstance(row, Text) else Text(row)
|
|
266
|
+
line = seg(g["v"] + " ", border)
|
|
267
|
+
line.append_text(fit(content, inner, mode))
|
|
268
|
+
line.append(" " + g["v"], style=border)
|
|
269
|
+
lines.append(line)
|
|
270
|
+
lines.append(notch_line(g["bl"], g["br"], g["fl"], g["fr"], footer))
|
|
271
|
+
return "\n".join(render(mode, ln) for ln in lines) + "\n"
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def table_rows(header: list[str], rows: list[list[Text | str]], mode: Mode,
|
|
275
|
+
right: set[int] | None = None, gap: int = 2) -> list[Text]:
|
|
276
|
+
"""Column-aligned rows (header in the title role, no rule under it — like btop's proc list)."""
|
|
277
|
+
right = right or set()
|
|
278
|
+
cells = [[c if isinstance(c, Text) else Text(escape(c)) for c in r] for r in rows]
|
|
279
|
+
widths = [cell_len(h) for h in header]
|
|
280
|
+
for r in cells:
|
|
281
|
+
for i, c in enumerate(r):
|
|
282
|
+
widths[i] = max(widths[i], cell_len(c.plain))
|
|
283
|
+
out = []
|
|
284
|
+
head = Text()
|
|
285
|
+
for i, h in enumerate(header):
|
|
286
|
+
cell = seg(h, "title")
|
|
287
|
+
pad = widths[i] - cell_len(h)
|
|
288
|
+
head.append_text(Text(" " * pad) + cell if i in right else cell + Text(" " * pad))
|
|
289
|
+
if i < len(header) - 1:
|
|
290
|
+
head.append(" " * gap)
|
|
291
|
+
out.append(head)
|
|
292
|
+
for r in cells:
|
|
293
|
+
line = Text()
|
|
294
|
+
for i, c in enumerate(r):
|
|
295
|
+
pad = widths[i] - cell_len(c.plain)
|
|
296
|
+
line.append_text(Text(" " * pad) + c if i in right else c + Text(" " * pad))
|
|
297
|
+
if i < len(r) - 1:
|
|
298
|
+
line.append(" " * gap)
|
|
299
|
+
out.append(line)
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def error(message: str, hint: str | None, mode: Mode) -> str:
|
|
304
|
+
g = glyphs(mode)
|
|
305
|
+
first = Text()
|
|
306
|
+
first.append(f"{g['err']} error:", style=ROLES["err"])
|
|
307
|
+
first.append(" " + escape(message))
|
|
308
|
+
out = render(mode, first) + "\n"
|
|
309
|
+
if hint:
|
|
310
|
+
out += render(mode, seg("hint: " + escape(hint), "dim")) + "\n"
|
|
311
|
+
return out
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def line(mode: Mode, level: str, message: str, detail: str | None = None) -> str:
|
|
315
|
+
text = status(level, message, mode)
|
|
316
|
+
if detail:
|
|
317
|
+
text.append(" " + escape(detail), style=ROLES["dim"])
|
|
318
|
+
return render(mode, text) + "\n"
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def progress_enabled() -> bool:
|
|
322
|
+
try:
|
|
323
|
+
return sys.stderr.isatty()
|
|
324
|
+
except (AttributeError, ValueError):
|
|
325
|
+
return False
|
prt/testpage.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Built-in colour test page: ink bars, gradients, grey steps and fine lines (A4 @ 150 dpi JPEG)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
9
|
+
|
|
10
|
+
W, H = 1240, 1754 # A4 at 150 dpi
|
|
11
|
+
MARGIN = 90
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _font(size: int):
|
|
15
|
+
try:
|
|
16
|
+
return ImageFont.load_default(size=size)
|
|
17
|
+
except TypeError: # Pillow < 10.1
|
|
18
|
+
return ImageFont.load_default()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render(title: str = "printer") -> Image.Image:
|
|
22
|
+
img = Image.new("RGB", (W, H), "white")
|
|
23
|
+
d = ImageDraw.Draw(img)
|
|
24
|
+
d.text((MARGIN, MARGIN), "prt test page", fill="black", font=_font(56))
|
|
25
|
+
d.text((MARGIN, MARGIN + 74), f"{title} · {time.strftime('%Y-%m-%d %H:%M')}", fill=(90, 90, 90),
|
|
26
|
+
font=_font(26))
|
|
27
|
+
y = MARGIN + 150
|
|
28
|
+
|
|
29
|
+
# Primary ink bars (C M Y K) and secondary mixes (R G B)
|
|
30
|
+
bars = [("C", (0, 255, 255)), ("M", (255, 0, 255)), ("Y", (255, 255, 0)), ("K", (0, 0, 0)),
|
|
31
|
+
("R", (255, 0, 0)), ("G", (0, 160, 0)), ("B", (0, 0, 255))]
|
|
32
|
+
bw = (W - 2 * MARGIN) // len(bars)
|
|
33
|
+
for i, (label, rgb) in enumerate(bars):
|
|
34
|
+
x = MARGIN + i * bw
|
|
35
|
+
d.rectangle([x + 6, y, x + bw - 6, y + 220], fill=rgb)
|
|
36
|
+
d.text((x + 6, y + 232), label, fill="black", font=_font(28))
|
|
37
|
+
y += 300
|
|
38
|
+
|
|
39
|
+
# Smooth gradients per channel — banding here means clogged nozzles or low ink.
|
|
40
|
+
for rgb in [(0, 255, 255), (255, 0, 255), (255, 255, 0), (0, 0, 0)]:
|
|
41
|
+
for x in range(W - 2 * MARGIN):
|
|
42
|
+
t = x / (W - 2 * MARGIN - 1)
|
|
43
|
+
col = tuple(round(255 - (255 - c) * t) for c in rgb)
|
|
44
|
+
d.line([(MARGIN + x, y), (MARGIN + x, y + 70)], fill=col)
|
|
45
|
+
y += 90
|
|
46
|
+
y += 30
|
|
47
|
+
|
|
48
|
+
# Grey steps 0–100 %
|
|
49
|
+
steps = 11
|
|
50
|
+
sw = (W - 2 * MARGIN) // steps
|
|
51
|
+
for i in range(steps):
|
|
52
|
+
g = round(255 * (1 - i / (steps - 1)))
|
|
53
|
+
d.rectangle([MARGIN + i * sw, y, MARGIN + (i + 1) * sw - 4, y + 110], fill=(g, g, g),
|
|
54
|
+
outline=(180, 180, 180))
|
|
55
|
+
d.text((MARGIN + i * sw + 4, y + 118), f"{i * 10}%", fill="black", font=_font(20))
|
|
56
|
+
y += 190
|
|
57
|
+
|
|
58
|
+
# Fine-line pattern for alignment: 1px, 2px, 3px lines
|
|
59
|
+
for width in (1, 2, 3):
|
|
60
|
+
for k in range(0, W - 2 * MARGIN, 12 * width):
|
|
61
|
+
d.line([(MARGIN + k, y), (MARGIN + k, y + 90)], fill="black", width=width)
|
|
62
|
+
y += 120
|
|
63
|
+
d.text((MARGIN, H - MARGIN - 30), "Check: solid bars, smooth gradients, crisp lines. "
|
|
64
|
+
"Streaks → run `prt maintain nozzle-check`.", fill=(90, 90, 90), font=_font(22))
|
|
65
|
+
return img
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render_jpeg(title: str = "printer") -> bytes:
|
|
69
|
+
buf = io.BytesIO()
|
|
70
|
+
render(title).save(buf, "JPEG", quality=92, dpi=(150, 150))
|
|
71
|
+
return buf.getvalue()
|
|
File without changes
|