-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.py
More file actions
427 lines (324 loc) · 13.9 KB
/
Copy pathrender.py
File metadata and controls
427 lines (324 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
"""Compose a receipt into a single PIL image, ready for an ESC/POS printer.
The thermal tape is continuous, so there is no pagination: blocks are drawn top
to bottom on a tall scratch canvas, which is cropped to the used height at the end.
Bold is faked with a 1px stroke so a separate bold TTF isn't required.
"""
import logging
from datetime import datetime
from pathlib import Path
from PIL import Image, ImageDraw
import config
from blocks import (
Banner, Barcode, Block, Checkbox, Divider, Footer, Item, Spacer,
Total, Underline, UpsideDown,
)
from images import fit_size, generate_barcode, load_font, render_text_block, render_upside_down
logger = logging.getLogger(__name__)
WIDTH = config.PAPER_WIDTH_PX
MARGIN = 10
# Keep drawing one column inside the right edge so box borders aren't clipped.
RIGHT_INSET = 4
CONTENT_W = WIDTH - RIGHT_INSET
_MAX_CANVAS_H = 16000 # scratch height; cropped to actual content on finish()
BLACK = 0
WHITE = 255
# Font sizes in PIL pixels. Tuned for an 80 mm / 576 px tape — adjust to taste.
FONT_LABEL = 34 # boxed note/photo label
FONT_BODY = 28 # body text
FONT_SMALL = 24 # muted lines & dates
# Printed header labels (no emoji — monospaced TTFs don't carry color glyphs).
LABEL_NOTE = "NEW MESSAGE"
LABEL_PHOTO = "PHOTO"
SUBTITLE_PAPER = "positive vibes only"
LOGO_MAX_HEIGHT = 250
# ── Canvas ──────────────────────────────────────────────────────────────────
class Canvas:
"""Thin drawing surface. A 'font' is an (ImageFont, stroke_width) pair."""
def __init__(self, width: int):
self.width = width
self.img = Image.new("L", (width, _MAX_CANVAS_H), WHITE)
self.draw = ImageDraw.Draw(self.img)
self._font = load_font(FONT_BODY)
self._stroke = 0
def select_font(self, font: tuple) -> None:
self._font, self._stroke = font
def text(self, x: int, y: int, s: str, fill: int = BLACK) -> None:
self.draw.text((x, y), s, font=self._font, fill=fill,
stroke_width=self._stroke, stroke_fill=fill)
def text_width(self, s: str) -> int:
return int(self.draw.textlength(s, font=self._font))
def hline(self, x1: int, y: int, x2: int, thickness: int = 1, fill: int = BLACK) -> None:
self.draw.rectangle([x1, y, x2, y + thickness - 1], fill=fill)
def fill_rect(self, x1: int, y1: int, x2: int, y2: int, fill: int) -> None:
self.draw.rectangle([x1, y1, x2, y2], fill=fill)
def border(self, x1: int, y1: int, x2: int, y2: int, thickness: int = 3, fill: int = BLACK) -> None:
for i in range(thickness):
self.draw.rectangle([x1 + i, y1 + i, x2 - i, y2 - i], outline=fill)
def paste(self, pil: Image.Image, x: int, y: int) -> None:
if pil.mode != "L":
pil = pil.convert("L")
self.img.paste(pil, (x, y))
def finish(self, used_height: int) -> Image.Image:
h = min(max(1, used_height + MARGIN), _MAX_CANVAS_H)
return self.img.crop((0, 0, self.width, h))
def _font(size: int, bold: bool = False) -> tuple:
return (load_font(size), 1 if bold else 0)
def _line_height(size: int) -> int:
font = load_font(size)
ascent, descent = font.getmetrics()
return ascent + descent + 8
# ── Low-level draws (canvas-based ports of the win32 helpers) ────────────────
def _draw_centered(c: Canvas, y: int, content_w: int, text: str, step: int) -> int:
x = (content_w - c.text_width(text)) // 2
c.text(max(0, x), y, text)
return y + step
def _draw_left_right(c: Canvas, y: int, content_w: int, left: str, right: str,
step: int, leader: str = "") -> int:
"""Left text at x=0, right flush right, optional dot-leader filling the gap."""
right_w = c.text_width(right)
right_x = max(0, content_w - right_w)
left_w = c.text_width(left)
if left_w + 20 > right_x:
c.text(0, y, left)
y += step
c.text(right_x, y, right)
return y + step
c.text(0, y, left)
c.text(right_x, y, right)
if leader:
gap_left = left_w + 8
gap_right = right_x - 8
leader_w = c.text_width(leader)
if leader_w > 0 and gap_right > gap_left:
n = (gap_right - gap_left) // leader_w
if n >= 3:
c.text(gap_left, y, leader * n)
return y + step
def _draw_banner(c: Canvas, y: int, content_w: int, text: str, font: tuple, step: int) -> int:
"""Black bar with white text, snug-fit around the text."""
pad_x = 24
pad_y = 5
side_inset_min = 60
c.select_font(font)
text_w = c.text_width(text)
text_h = step
bar_w = text_w + pad_x * 2
bar_x1 = (content_w - bar_w) // 2
bar_x2 = bar_x1 + bar_w
if bar_x1 < side_inset_min:
bar_x1 = side_inset_min
bar_x2 = content_w - side_inset_min
bar_h = step + pad_y * 2
bar_y1 = y
bar_y2 = y + bar_h
c.fill_rect(bar_x1, bar_y1, bar_x2, bar_y2, BLACK)
text_x = bar_x1 + ((bar_x2 - bar_x1) - text_w) // 2
text_y = bar_y1 + (bar_h - text_h) // 2
c.text(text_x, text_y, text, fill=WHITE)
return bar_y2 + 4
def _draw_underline(c: Canvas, y: int, content_w: int, text: str, step: int) -> int:
"""Centered text with thin lines hugging it top and bottom (text-width)."""
text_w = c.text_width(text)
x = max(0, (content_w - text_w) // 2)
right = x + text_w
c.hline(x, y, right, thickness=1)
text_y = y + 2
c.text(x, text_y, text)
bot_y = text_y + step - 6
c.hline(x, bot_y, right, thickness=1)
return bot_y + 4
def _draw_divider(c: Canvas, y: int, content_w: int, body_step: int, style: str) -> int:
"""Horizontal divider — solid, dashed, or dotted."""
if style == "solid":
c.hline(0, y + 4, content_w, thickness=2)
return y + 12
line_y = y + body_step // 2
if style == "dot":
seg, gap = 2, 4
else: # dash
seg, gap = 10, 6
x = 0
while x < content_w:
c.hline(x, line_y, min(x + seg, content_w), thickness=1)
x += seg + gap
return y + body_step
def _wrap_with_indent(text: str, width: int, hang: int = 0) -> list[str]:
"""Wrap a logical line; continuation lines indented by `hang` spaces."""
import textwrap
if not text:
return [""]
if hang > 0:
wrapper = textwrap.TextWrapper(
width=width,
subsequent_indent=" " * hang,
break_long_words=False,
break_on_hyphens=False,
)
return wrapper.wrap(text) or [""]
return textwrap.wrap(text, width=width, break_long_words=False, break_on_hyphens=False) or [text]
def _paste_centered(c: Canvas, y: int, content_w: int, pil: Image.Image,
max_w: int, max_h: int | None = None) -> int:
new_w, new_h = fit_size(pil.width, pil.height, max_w, max_h)
if (new_w, new_h) != (pil.width, pil.height):
pil = pil.resize((new_w, new_h), Image.LANCZOS)
x = max(0, (content_w - new_w) // 2)
c.paste(pil, x, y)
return y + new_h
# ── Block dispatch ──────────────────────────────────────────────────────────
def _render_block(c: Canvas, y: int, content_w: int, cols: int, block: Block,
fonts: dict, steps: dict) -> int:
body_step = steps["body"]
total_step = steps["total"]
if isinstance(block, Spacer):
return y + body_step * block.lines
if isinstance(block, Divider):
return _draw_divider(c, y, content_w, body_step, block.style)
if isinstance(block, Banner):
return _draw_banner(c, y, content_w, block.text, fonts["bold_small"], body_step)
if isinstance(block, Item):
c.select_font(fonts["bold"] if block.bold else fonts["body"])
leader = "" if block.bold else "·"
return _draw_left_right(c, y, content_w, block.name, block.value, body_step, leader=leader)
if isinstance(block, Total):
if block.big:
c.select_font(fonts["total"])
step = total_step
else:
c.select_font(fonts["body"])
step = body_step
text = f"{block.label}: {block.value}"
text_w = c.text_width(text)
c.text(max(0, content_w - text_w), y, text)
return y + step + (4 if block.big else 0)
if isinstance(block, Underline):
c.select_font(fonts["body"])
return _draw_underline(c, y, content_w, block.text, body_step)
if isinstance(block, Footer):
c.select_font(fonts["bold"])
return _draw_centered(c, y, content_w, block.text, body_step) + 4
if isinstance(block, Checkbox):
c.select_font(fonts["body"])
text = f"[ ] {block.text}"
for line in _wrap_with_indent(text, cols, hang=4):
c.text(0, y, line)
y += body_step
return y
if isinstance(block, UpsideDown):
try:
pil = render_upside_down(block.text, FONT_SMALL, content_w - 80)
except Exception as e:
logger.warning(f"Upside-down rendering failed: {e}")
return y
return _paste_centered(c, y, content_w, pil, max_w=content_w - 60, max_h=400)
if isinstance(block, Barcode):
try:
pil = generate_barcode(block.text)
except Exception as e:
logger.warning(f"Barcode generation failed: {e}")
return y
return _paste_centered(c, y, content_w, pil, max_w=content_w - 60, max_h=160)
return y # unknown block — ignore
# ── Headers ─────────────────────────────────────────────────────────────────
def _draw_note_header(c: Canvas, content_w: int, label: str, sender_name: str | None) -> int:
font_bold = _font(FONT_LABEL, bold=True)
font_small = _font(FONT_SMALL)
box_y1 = MARGIN
box_y2 = box_y1 + FONT_LABEL + 16
c.border(0, box_y1, content_w, box_y2, thickness=3)
c.select_font(font_bold)
label_w = c.text_width(label)
c.text((content_w - label_w) // 2, box_y1 + 8, label)
now = datetime.now()
meta = f"{now:%a}, {now:%d %B %Y} {now:%H:%M}"
small_step = FONT_SMALL + 8
y = box_y2 + 8
c.select_font(font_small)
c.text(0, y, meta)
y += small_step
if sender_name:
c.text(0, y, f"from {sender_name}")
y += small_step
return y + 4
def _logo_path() -> Path | None:
if config.LOGO_PATH and Path(config.LOGO_PATH).exists():
return Path(config.LOGO_PATH)
return None
def _draw_receipt_header(c: Canvas, content_w: int) -> int:
logo = _logo_path()
y = MARGIN
if logo is not None:
try:
y = _paste_centered(c, MARGIN, content_w, Image.open(logo),
max_w=content_w, max_h=LOGO_MAX_HEIGHT)
except Exception as e:
logger.warning(f"Logo load failed: {e}")
else:
logger.warning("No logo found — set LOGO_PATH or add media/logo.png")
y += 14
font_small = _font(FONT_SMALL)
c.select_font(font_small)
sub_w = c.text_width(SUBTITLE_PAPER)
sub_x = max(0, (content_w - sub_w) // 2)
c.text(sub_x, y, SUBTITLE_PAPER)
c.hline(sub_x, y + FONT_SMALL - 2, sub_x + sub_w, thickness=1)
y += FONT_SMALL + 10
now = datetime.now()
meta = f"{now:%a}, {now:%d %B %Y} {now:%H:%M:%S}"
meta_w = c.text_width(meta)
c.text(max(0, (content_w - meta_w) // 2), y, meta)
y += FONT_SMALL + 6
return y + 6
# ── Public API ──────────────────────────────────────────────────────────────
def render_note(text: str, sender_name: str | None = None) -> Image.Image:
c = Canvas(WIDTH)
content_w = CONTENT_W
gap = FONT_BODY // 2
y = _draw_note_header(c, content_w, LABEL_NOTE, sender_name)
# Dashed divider just below the header.
line_y = y + gap
x = 0
while x < content_w:
c.hline(x, line_y, min(x + 10, content_w), thickness=1)
x += 16
y += gap * 2
body = render_text_block(text, FONT_BODY, content_w)
new_w, new_h = fit_size(body.width, body.height, content_w)
if (new_w, new_h) != (body.width, body.height):
body = body.resize((new_w, new_h), Image.LANCZOS)
c.paste(body, 0, y)
y += new_h
return c.finish(y)
def render_photo(image_data, sender_name: str | None = None) -> Image.Image:
c = Canvas(WIDTH)
content_w = CONTENT_W
y = _draw_note_header(c, content_w, LABEL_PHOTO, sender_name)
img = Image.open(image_data)
new_w, new_h = fit_size(img.width, img.height, content_w)
img = img.resize((new_w, new_h), Image.LANCZOS).convert("1")
x = max(0, (content_w - new_w) // 2)
c.paste(img, x, y)
y += new_h
return c.finish(y)
def render_blocks(blocks: list[Block]) -> Image.Image:
if not blocks:
raise ValueError("render_blocks called with no blocks")
c = Canvas(WIDTH)
content_w = CONTENT_W
fonts = {
"body": _font(FONT_BODY),
"bold": _font(FONT_BODY, bold=True),
"bold_small": _font(FONT_SMALL, bold=True),
"total": _font(FONT_LABEL, bold=True),
}
steps = {"body": _line_height(FONT_BODY), "total": _line_height(FONT_LABEL)}
c.select_font(fonts["body"])
# Widest glyph across Cyrillic, Latin and digits — a conservative cell width
# for the monospace column grid (checkbox wrapping uses `cols`).
glyph_w = max(c.text_width(ch) for ch in "ШЩМЮW0")
cols = max(1, int(content_w * 0.96) // max(glyph_w, 1))
y = _draw_receipt_header(c, content_w)
y += steps["body"] // 2
for block in blocks:
y = _render_block(c, y, content_w, cols, block, fonts, steps)
logger.info(f"Receipt rendered: {len(blocks)} blocks")
return c.finish(y)