"""Locally-printed informational labels (ready / need Wi-Fi), drawn with Pillow.""" from __future__ import annotations from datetime import datetime from PIL import Image, ImageDraw, ImageFont from .label import LabelSpec FONT_DIRS = ( "/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/dejavu", "/System/Library/Fonts", ) def _font(size: int, bold: bool = False) -> ImageFont.ImageFont: name = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf" for base in FONT_DIRS: try: return ImageFont.truetype(f"{base}/{name}", size) except OSError: continue return ImageFont.load_default(size) def _size(font: ImageFont.ImageFont) -> int: return int(getattr(font, "size", 16) or 16) def _fit(text: str, max_width: int, size: int, bold: bool) -> ImageFont.ImageFont: font = _font(size, bold) while size > 14 and font.getlength(text) > max_width: size -= 4 font = _font(size, bold) return font def _render_lines(spec: LabelSpec, headline: str, lines: list[str]) -> Image.Image: if spec.die_cut: width, height = spec.width_px, spec.height_px else: width = spec.width_px # ~60 mm of endless tape, but never shorter than half the label width. height = max(int(60 * 300 / 25.4), width // 2) img = Image.new("RGB", (width, height), "white") draw = ImageDraw.Draw(img) margin = width // 20 text_width = width - 2 * margin y = margin font = _fit(headline, text_width, width // 9, True) draw.text((margin, y), headline, fill="black", font=font) y += int(_size(font) * 1.6) for line in lines: font = _fit(line, text_width, width // 16, False) draw.text((margin, y), line, fill="black", font=font) y += int(_size(font) * 1.6) return img def ready_label(spec: LabelSpec, station: str, network: dict, version: str, now: datetime) -> Image.Image: lines = [f"Station: {station}"] if network.get("ssid"): lines.append(f"Wi-Fi: {network['ssid']}") if network.get("ip"): lines.append(f"IP: {network['ip']}") lines.append(now.strftime("%Y-%m-%d %H:%M")) lines.append(f"v{version}") return _render_lines(spec, "Convivo printer ready", lines) def need_wifi_label(spec: LabelSpec, ap_ssid: str) -> Image.Image: return _render_lines( spec, "No network", ["Connect a phone to the open Wi-Fi", ap_ssid, "then open http://10.41.0.1"], )