diff --git a/app/labeldesigner/cable_flag.py b/app/labeldesigner/cable_flag.py
index ac4341814..9b99b878f 100644
--- a/app/labeldesigner/cable_flag.py
+++ b/app/labeldesigner/cable_flag.py
@@ -46,6 +46,12 @@ def flag_strip(half: Image.Image, wrap: int, dpi: int, along: bool) -> Image.Ima
return strip.transpose(Image.Transpose.ROTATE_270)
+def flag_size(size: tuple, wrap: int, along: bool) -> tuple[int, int]:
+ """The size of the flag flag_strip() makes of a label of size."""
+ width, height = size
+ return (2 * width + wrap, height) if along else (width, 2 * height + wrap)
+
+
def flag_box(box: list, size: tuple, wrap: int, along: bool) -> list:
"""Where box [x0, y0, x1, y1] on a label of size is on the second label
of the flag flag_strip() makes of it."""
diff --git a/app/labeldesigner/label.py b/app/labeldesigner/label.py
index f23a78fc6..43eb331af 100644
--- a/app/labeldesigner/label.py
+++ b/app/labeldesigner/label.py
@@ -1,6 +1,6 @@
from .enums import LabelContent, LabelOrientation, LabelType
from . import codes, icons
-from .cable_flag import flag_box, flag_strip
+from .cable_flag import flag_box, flag_size, flag_strip
from app.fonts import EMOJI_FONT_PATH, font_info, has_glyphs
from .dates import LANGUAGES as DATE_LANGUAGES, format_date
import os
@@ -921,12 +921,13 @@ def _generate(self):
along = self._label_orientation == LabelOrientation.ROTATED
half = img.size
img = flag_strip(img, self._flag_wrap, self._flag_dpi, along)
- check_image_size(*img.size)
# Its parts are on both labels
self.parts += [dict(part, box=flag_box(part['box'], half, self._flag_wrap, along)) for part in self.parts]
return img.rotate(180) if self.turned else img
- def _generate_label(self):
+ def _generate_label(self, drawn: bool = True):
+ """The label drawn. Not drawn, it is laid out and refused as drawing
+ it refuses it, see check()."""
# Process possible templates in the text and the code
self.process_templates()
# A preview shows a code of the blanks still to fill in, printed it
@@ -1126,6 +1127,21 @@ def across(name):
logger.debug(f"Image resolution: {width} x {height} px")
check_image_size(width, height)
+ # A cable flag is the label twice and the part around the cable
+ if self._flag_wrap:
+ check_image_size(*flag_size((width, height), self._flag_wrap, self._label_orientation == LabelOrientation.ROTATED))
+ # Calculate border rectangle (inside the image, respecting thickness)
+ rect = [self._border_distance[0],
+ self._border_distance[1],
+ width - self._border_distance[0] - 1,
+ height - self._border_distance[1] - 1]
+ # Validity checks on rect:
+ # - x1 >= x0
+ # - y1 >= y0
+ if self._border_thickness > 0 and (rect[2] < rect[0] or rect[3] < rect[1]):
+ raise ValueError("Invalid border rectangle")
+ if not drawn:
+ return None
imgResult = Image.new('RGB', (width, height), 'white')
if img is not None:
@@ -1140,17 +1156,6 @@ def across(name):
# Draw border if thickness > 0
if self._border_thickness > 0:
draw = ImageDraw.Draw(imgResult)
- # Calculate border rectangle (inside the image, respecting thickness)
- rect = [self._border_distance[0],
- self._border_distance[1],
- imgResult.width - self._border_distance[0] - 1,
- imgResult.height - self._border_distance[1] - 1]
- # Validity checks on rect:
- # - x1 >= x0
- # - y1 >= y0
- if rect[2] < rect[0] or rect[3] < rect[1]:
- raise ValueError("Invalid border rectangle")
-
# Draw (rounded) rectangle
draw.rounded_rectangle(rect, radius=self._border_roundness, outline=self._border_color, width=self._border_thickness)
# Left and right swapped as the text reads, the preview shows it so
@@ -1285,6 +1290,13 @@ def _crop_image_to_content(img: Image.Image) -> Image.Image:
return img
return img.crop(bbox)
+ def check(self) -> None:
+ """Raise what drawing the label raises, e.g. for a value that is none
+ of the choices of its blank, a wrong check digit or a label too
+ large, without drawing it: it is laid out as drawn, its code made
+ once, for the drawing as well."""
+ self._generate_label(drawn=False)
+
def _generate_barcode(self):
# An unknown type is refused before the value is looked at
barcode_class = codes.barcode_class(self.barcode_type)
diff --git a/app/labeldesigner/openapi.json b/app/labeldesigner/openapi.json
index 57c9be6af..3c81b206c 100644
--- a/app/labeldesigner/openapi.json
+++ b/app/labeldesigner/openapi.json
@@ -47,6 +47,10 @@
"fields": {
"$ref": "#/components/schemas/BlankSettings"
},
+ "list": {
+ "type": "string",
+ "description": "A list as `/labeldesigner/api/print` takes it: the preview shows its first line, `X-Label-Sheet`, `{{total}}` and the whole sheet count all its labels, `X-List-Filled` tells the blanks every line fills. More than `PRINT_MAX_COUNT` labels are refused."
+ },
"mark_blanks": {
"type": "string",
"enum": [
@@ -123,6 +127,10 @@
"fields": {
"$ref": "#/components/schemas/BlankSettings"
},
+ "list": {
+ "type": "string",
+ "description": "A list as `/labeldesigner/api/print` takes it: the preview shows its first line, `X-Label-Sheet`, `{{total}}` and the whole sheet count all its labels, `X-List-Filled` tells the blanks every line fills. More than `PRINT_MAX_COUNT` labels are refused."
+ },
"mark_blanks": {
"type": "string",
"enum": [
@@ -194,6 +202,12 @@
"type": "string"
}
},
+ "X-List-Filled": {
+ "description": "With `list` on a label with blanks, those every line of it fills, as JSON, e.g. `[\"Name\"]`. The label designer asks for the others.",
+ "schema": {
+ "type": "string"
+ }
+ },
"X-PDF-Pages": {
"description": "Number of pages of an uploaded PDF.",
"schema": {
@@ -291,11 +305,26 @@
}
},
"400": {
- "description": "Invalid parameters, e.g. \"Font size is required\".",
+ "description": "Invalid parameters, e.g. \"Font size is required\". `of` is `list` where the `list` is refused rather than the label, e.g. for more labels than `PRINT_MAX_COUNT`.",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/Result"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Result"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "of": {
+ "type": "string",
+ "enum": [
+ "list"
+ ]
+ }
+ }
+ }
+ ]
}
}
}
@@ -858,6 +887,9 @@
},
"fields": {
"$ref": "#/components/schemas/BlankSettings"
+ },
+ "list": {
+ "$ref": "#/components/schemas/PrintList"
}
}
},
@@ -925,6 +957,9 @@
},
"fields": {
"$ref": "#/components/schemas/BlankSettings"
+ },
+ "list": {
+ "$ref": "#/components/schemas/PrintList"
}
}
},
@@ -2900,6 +2935,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
+ },
+ "list": {
+ "$ref": "#/components/schemas/PrintList"
}
}
},
@@ -2973,6 +3011,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
+ },
+ "list": {
+ "$ref": "#/components/schemas/PrintList"
}
}
},
@@ -3443,6 +3484,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
+ },
+ "list": {
+ "$ref": "#/components/schemas/PrintList"
}
}
}
@@ -3506,6 +3550,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
+ },
+ "list": {
+ "$ref": "#/components/schemas/PrintList"
}
}
},
@@ -4027,6 +4074,20 @@
}
},
"schemas": {
+ "PrintList": {
+ "oneOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ ],
+ "description": "One label for each line, e.g. names pasted from a spreadsheet. The cells of a line, split at tabs, fill the blanks of the label in order, those of the text, then those of a code it draws; a label without blanks takes them as its lines of text, each with its settings. A cell is inserted as it is, its templates are none. An empty cell is not given: its blank keeps its value of `blanks` or its default, its line its text, as do those beyond the cells; cells beyond them are left out. Pasted from a spreadsheet, with tabs and a cell that starts with a quote, cells it quotes, e.g. `\"5\"\" pot\"` or one with a line break, are read as it writes them; another list keeps its quotes. A count at the end of a line, in its last cell after a word without digits, e.g. `Basil x 20`, `Basil x20` or `Basil X 20`, prints it that many times; `M3 x 10`, `Box 2 x 3` or a cell of `x 5` alone print once, as written. Each line prints its count times `print_count` labels in a row, each of every file and PDF page as `collate` orders them; `{{counter}}` counts all labels of the list and `{{total}}` is their number. On sheets of labels they fill the labels in order. Empty lines are left out, a list without lines prints as without it. In a JSON body also a list of its lines, any other value, e.g. null, is refused. More than `PRINT_MAX_COUNT` labels are refused, and so is the whole list where one of its lines is, e.g. with a value that is none of the choices of its blank."
+ },
"ScanRequest": {
"type": "object",
"required": ["name", "code"],
diff --git a/app/labeldesigner/print_list.py b/app/labeldesigner/print_list.py
new file mode 100644
index 000000000..678b10c1f
--- /dev/null
+++ b/app/labeldesigner/print_list.py
@@ -0,0 +1,75 @@
+"""A list printed as labels, one for each line, e.g. plant names pasted from
+a spreadsheet. The cells of a line, split at tabs, fill the label in order,
+a count at its end prints it that many times."""
+
+import csv
+import io
+import re
+
+# A count at the end of a cell after a word, e.g. "Basil x 20", "Basil x20"
+# or "Basil X 20"
+COUNT = re.compile(r'(?s)(.*\S)\s+[xX]\s*(\d+)\s*')
+# More digits make more labels than any job takes
+COUNT_DIGITS = 9
+
+NO_PLACE = 'Add text or a blank to the label to print a list'
+NOT_TEXT = 'list must be a text or a list of texts'
+
+
+class Refused(ValueError):
+ """A list refused, not the label it is printed on."""
+
+
+def too_many(most: int) -> str:
+ """The refusal of a list of more than most labels."""
+ return f'A list prints at most {most} labels. Split it.'
+
+
+def _rows(text: str) -> list[list[str]]:
+ """The cells of each line, split at tabs. A spreadsheet quotes a cell
+ with quotes or line breaks, e.g. "5"" pot": where a cell starts with a
+ quote and all read so, they are read as it writes them. Typed, e.g.
+ "Best" tomatoes, or a quote left open, a list keeps its quotes."""
+ lines = [line.split('\t') for line in text.splitlines()]
+ if any(cell.startswith('"') for cells in lines for cell in cells):
+ try:
+ return list(csv.reader(io.StringIO(text, newline=''), dialect='excel-tab', strict=True))
+ except csv.Error:
+ # E.g. a quote left open, or a cell longer than any line of a label
+ pass
+ return lines
+
+
+def _counted(cells: list[str], most: int) -> tuple[list[str], int]:
+ """The cells of a line without its count and the count, else 1. Only a
+ count in the last cell after a word without digits counts: "M3 x 10",
+ "Box 2 x 3" or a cell of "x 5" alone are names, printed once."""
+ counted = COUNT.fullmatch(cells[-1])
+ digits = counted.group(2).lstrip('0') if counted else ''
+ if not digits or any(char.isdigit() for char in counted.group(1).split()[-1]):
+ return cells, 1
+ return cells[:-1] + [counted.group(1)], int(digits) if len(digits) <= COUNT_DIGITS else most + 1
+
+
+def parse(text, most: int) -> list[tuple[list[str], int]]:
+ """The lines of a list, text or its lines as a JSON body gives them: the
+ cells of each and the labels it prints. Empty lines are left out, and
+ so are empty cells at the end. Refused for another value, e.g. null,
+ and where they print more than most labels."""
+ if isinstance(text, list) and all(isinstance(line, str) for line in text):
+ text = '\n'.join(text)
+ if not isinstance(text, str):
+ raise Refused(NOT_TEXT)
+ lines, labels = [], 0
+ for row in _rows(text):
+ cells = [cell.strip() for cell in row]
+ while cells and not cells[-1]:
+ cells.pop()
+ if not cells:
+ continue
+ cells, count = _counted(cells, most)
+ labels += count
+ if labels > most:
+ raise Refused(too_many(most))
+ lines.append((cells, count))
+ return lines
diff --git a/app/labeldesigner/refusals.py b/app/labeldesigner/refusals.py
index 47a47e6c8..f19930260 100644
--- a/app/labeldesigner/refusals.py
+++ b/app/labeldesigner/refusals.py
@@ -14,7 +14,7 @@
from pdf2image.exceptions import PDFInfoNotInstalledError, PDFPageCountError, PDFPopplerTimeoutError, PDFSyntaxError
from PIL import Image
-from . import adding, ipp, scan, sheets
+from . import adding, ipp, print_list, scan, sheets
from .cable_flag import CABLE_DIAMETER_REFUSED, CABLE_FLAG_REFUSED
from .codes import BARCODE_TOO_LONG, TYPES as BARCODE_TYPES, check_digit_problems, code_problems
from .label import (LETTER_SPACING_REFUSED, MAX_BLANK_CHOICE_LENGTH, MAX_BLANK_CHOICES, MAX_COUNTER_START_LENGTH, MAX_COUNTER_STEP, MAX_IMAGE_SCALING_FACTOR,
@@ -135,6 +135,8 @@
OTHER_LABEL,
SAME_NUMBERS,
'print_count must be greater than 0',
+ print_list.NO_PLACE,
+ print_list.NOT_TEXT,
*sorted({sheets.start_problem(sheets.per_sheet(label)) for label in LABELS if sheets.is_paper(label)}),
*check_digit_problems(),
*code_problems(),
@@ -211,7 +213,7 @@ def _limits() -> tuple:
max_count = current_app.config['PRINT_MAX_COUNT']
# At least a whole sheet of labels
counts = sorted({max_count} | {sheets.per_sheet(label) for label in LABELS if sheets.is_paper(label) and sheets.per_sheet(label) > max_count})
- return (tuple(f'print_count must not exceed {count}' for count in counts),
+ return (tuple(f'print_count must not exceed {count}' for count in counts) + tuple(print_list.too_many(count) for count in counts),
tuple((re.compile(rf'(?s)A print job must not have more than {count} labels, .*'), f'A print job must not have more than {count} labels')
for count in counts))
diff --git a/app/labeldesigner/routes.py b/app/labeldesigner/routes.py
index 89300caee..311f5cdfc 100755
--- a/app/labeldesigner/routes.py
+++ b/app/labeldesigner/routes.py
@@ -16,7 +16,7 @@
from io import BytesIO
from typing import BinaryIO
from urllib.parse import urlparse
-from . import adding, bp, codes, demos, icons, ipp, paperless, print_queue, print_store, printer_settings, problem_report, refusals, scan, sheets, tape, unknown
+from . import adding, bp, codes, demos, icons, ipp, paperless, print_list, print_queue, print_store, printer_settings, problem_report, refusals, scan, sheets, tape, unknown
from .refusals import IMAGE_MODE_REFUSED, UNKNOWN_MODEL
from app import get_fonts
from app.fonts import FontNotFound, sample as font_sample
@@ -968,7 +968,7 @@ def _cutting(requested, stored: dict | None = None) -> tuple[str, bool, bool]:
def _queue_labels(printer, data: dict, images: list, order: list, high_res: bool, fast: bool, starts: list,
printed_for: float | None = None, dates: dict | None = None, total: int | None = None,
- sizes: list | None = None) -> None:
+ sizes: list | None = None, listed: dict | None = None) -> list:
"""Adds the labels of order to the queue, each with its image by its
index in images, None without, the printer cuts them as printer.cut
says. They are added once for each archive serial number in starts, the
@@ -977,18 +977,95 @@ def _queue_labels(printer, data: dict, images: list, order: list, high_res: bool
dates the label settings they are written with, see _dates_set(). total
is the number {{total}} shows, of order where it is not given. sizes are
those of the pictures smaller copies in images were made of, see
- _kept_copy()."""
+ _kept_copy(). listed is a list printed, see _kept_list(). Returns the
+ labels added."""
if printed_for is not None:
data = dict(data, timestamp=int(printed_for))
# The copies share the text measured, alike where nothing changes
- layouts = {}
+ layouts, filled, added = {}, {}, []
for asn in starts:
for i, index in enumerate(order):
- # {{total}}: the counter counts each copy of each file and PDF page, as sets or grouped
- label = create_label_from_request(data, {}, i, None if index is None else images[index], layouts=layouts, asn=asn,
+ made = data
+ if listed:
+ row = listed['rows'][i]
+ if row not in filled:
+ filled[row] = _list_filled(data, listed['lines'][row][0])
+ made = filled[row]
+ # {{total}}: the counter counts each copy of each file and PDF page, as sets or grouped, over all lines of a list
+ label = create_label_from_request(made, {}, i, None if index is None else images[index], layouts=layouts, asn=asn,
total=total or len(order), dates=dates,
image_size=sizes[index] if sizes and index is not None else None)
printer.add_label_to_queue(label, high_res=high_res, fast=fast)
+ added.append(label)
+ return added
+
+
+# Print types that draw a code: a list fills its blanks as well
+CODE_PRINT_TYPES = ('qrcode', 'qrcode_text', 'image_qrcode_text')
+
+
+def _list_blanks(data: dict) -> list[str]:
+ """The blanks a list fills, in order: those of the text, then those of a
+ code the label draws."""
+ return _blank_names(data if data.get('print_type', 'text') in CODE_PRINT_TYPES else dict(data, code_text=''))
+
+
+def _list_filled(data: dict, cells: list[str]) -> dict:
+ """data as a line of a list prints it: its cells fill the blanks in
+ order, see _list_blanks(), of a label without blanks its lines of text,
+ each with its settings. An empty cell is not given, the blank or line
+ stays as it is, as do those beyond the cells. A cell is inserted as it
+ is, also into a line of text: its templates are none, as those of the
+ value of a blank."""
+ names = _list_blanks(data)
+ if names:
+ return dict(data, blanks={**_blank_values(data.get('blanks')), **{name: cell for name, cell in zip(names, cells) if cell}})
+ text = data.get('text') or '[]'
+ lines = json.loads(text if isinstance(text, str) else json.dumps(text))
+ shown = [line for line in lines if isinstance(line, dict)] if isinstance(lines, list) else []
+ if not shown:
+ raise print_list.Refused(print_list.NO_PLACE)
+ # The value of a blank of its own for each cell, a text without a default
+ blanks, fields = _blank_values(data.get('blanks')), _blank_fields(data.get('fields'))
+ for number, (line, cell) in enumerate(zip(shown, cells), 1):
+ if cell:
+ name = f'list:{number}'
+ line['text'], blanks[name], fields[name] = f'{{{{blank:{name}}}}}', cell, {'type': 'text'}
+ return dict(data, text=json.dumps(lines), blanks=blanks, fields=fields)
+
+
+def _list_reaches(data: dict, lines: list) -> list[str]:
+ """The blanks every line of a list fills, see _list_filled()."""
+ names = _list_blanks(data)
+ return [name for i, name in enumerate(names) if all(i < len(cells) and cells[i] for cells, _ in lines)]
+
+
+def _list_labels(lines: list, copies: int, images: list, collate: bool) -> tuple[list, list]:
+ """The labels of a list, see print_list.parse(): their images as order
+ of _queue_labels() has them and the line each takes. A line prints its
+ count times copies labels in a row, each of every file or page of
+ images, as sets or grouped as collate says."""
+ taken = [row for row, (_, count) in enumerate(lines) for _ in range(count * copies)]
+ files = list(range(len(images))) or [None]
+ labels = [(file, row) for row in taken for file in files] if collate else [(file, row) for file in files for row in taken]
+ return [file for file, _ in labels], [row for _, row in labels]
+
+
+def _check_lines(labels: list, rows: list):
+ """Check the first label of each line of a list but the first one, which
+ printer.check() draws, without drawing it: a line refused, e.g. with a
+ code that is no EAN, refuses the job before any of its labels prints."""
+ first = {}
+ for label, row in zip(labels, rows):
+ first.setdefault(row, label)
+ for label in list(first.values())[1:]:
+ label.check()
+
+
+def _kept_list(lines: list, rows: list) -> dict:
+ """A list printed as its job keeps it: the cells and count of each line
+ and the line each label takes."""
+ return {'lines': [[cells, count] for cells, count in lines], 'rows': rows}
# The preview of a job in the queue, at most this many pixels on its long side
@@ -1160,7 +1237,7 @@ def _rebuilt(record: dict, device: str, model: str) -> PrinterQueue:
printer.add_label_to_queue(_image_label_of(shape, images[shape['image']]), high_res=record['high_res'], fast=record['fast'])
elif record['kind'] == 'request':
_queue_labels(printer, record['data'], images, record['order'], record['high_res'], record['fast'], [record['asn']],
- record.get('printed_for'), record.get('dates'), record.get('total'), record.get('sizes'))
+ record.get('printed_for'), record.get('dates'), record.get('total'), record.get('sizes'), record.get('list'))
return printer
@@ -1397,7 +1474,7 @@ def _preview_response(data: dict, image_dir: str, image_bytes: bytes | None = No
def repo_print():
# Print a saved repository template by name. The server will load the JSON
# and perform the same printing logic as the /api/print endpoint.
- return _saved_response(lambda data, image_bytes: _print_stored_label(data, _get_repo_dir(), image_bytes, named=True),
+ return _saved_response(lambda data, image_bytes: _print_stored_label(data, _get_repo_dir(), image_bytes, named=True, with_list=True),
'Failed to load file')
@@ -1457,11 +1534,12 @@ def _stored_as_printed(data: dict, device: str, model: str) -> tuple[dict, dict]
def _print_stored_label(data: dict, image_dir: str, image_bytes: bytes | None = None, blanks: dict[str, str] | None = None,
- return_format=None, named: bool = False):
+ return_format=None, named: bool = False, with_list: bool = False):
"""Print a stored label whose image is in image_dir, or image_bytes where
it was read with the label, like /api/print, of a saved one (named) kept
with the name it is saved under. With blanks, they fill the blanks
- instead of the request."""
+ instead of the request. with_list prints the list of the request, see
+ print_list."""
try:
data['blanks'] = _with_blanks(data, blanks)
printer, data, high_res, fast = _stored_job(data)
@@ -1469,10 +1547,18 @@ def _print_stored_label(data: dict, image_dir: str, image_bytes: bytes | None =
# Saved with the label, the request overrides it, else as set for labels
collate = _requested('collate')
collate = _whole_or(collate if collate is not None else data.get('collate'), _label_settings()['collate'] or 1) != 0
+ listed = print_list.parse(_requested_list(), _max_count(data['label_size'])) if with_list else None
except Exception as e:
return _refused('Print job', e, refusals.PRINT_FAILED)
return _print_job(printer, data, {}, print_count, collate, high_res, fast, return_format or _requested('return_format'),
- named=data.get('name') if named else None, image_dir=image_dir, image_bytes=image_bytes)
+ named=data.get('name') if named else None, listed=listed, image_dir=image_dir, image_bytes=image_bytes)
+
+
+def _requested_list():
+ """The list of a request, see print_list.parse(): of the form or query,
+ else of a JSON body as it is there, e.g. null; empty without one."""
+ value = _requested('list')
+ return _json_body().get('list', '') if value is None else value
def _stored_job(data: dict) -> tuple[PrinterQueue, dict, bool, bool]:
@@ -1496,31 +1582,41 @@ def _stored_job(data: dict) -> tuple[PrinterQueue, dict, bool, bool]:
def _print_job(printer: PrinterQueue, data: dict, files, print_count: int, collate: bool, high_res: bool, fast: bool,
- return_format, named: str | None = None, **stored):
+ return_format, named: str | None = None, listed: list | None = None, **stored):
"""Queue print_count copies of the label, of each of its images, see
_copies(), to be printed. stored tells where the image of a stored label
is, see load_label_images(). named is the saved label printed, kept with
- the job."""
+ the job. listed are the lines of a list, see print_list.parse(), each
+ printed as _list_labels() says."""
# Refused before archive serial numbers are taken for it
if full := print_queue.full(printer.device_specifier):
return _line_full(printer, full)
- job_id, staged = uuid.uuid4().hex, None
+ job_id, staged, kept_list = uuid.uuid4().hex, None, None
try:
# Decode the image once, all labels of the job share it. Of a PDF
# each selected page is a label of its own.
- images, _ = load_label_images(data, files, copies=print_count, **stored)
+ copies = print_count * sum(count for _, count in listed) if listed else print_count
+ images, _ = load_label_images(data, files, copies=copies, **stored)
if full := print_queue.full(printer.device_specifier, print_queue.image_bytes(images)):
return _line_full(printer, full)
images = [image for image in images if image is not None]
- order = _copies(list(range(len(images))) or [None], print_count, collate)
+ if listed:
+ order, rows = _list_labels(listed, print_count, images, collate)
+ if len(order) > (most := _max_count(printer.label_size)):
+ raise print_list.Refused(print_list.too_many(most))
+ kept_list = _kept_list(listed, rows)
+ else:
+ order = _copies(list(range(len(images))) or [None], print_count, collate)
# Written while the label is drawn, loaded or copied here: two
# threads must not read one picture from its file at once
kept = [_kept_copy(image, data) for image in images]
staged = print_store.stage(job_id, [copy for copy, _ in kept])
# Taken before printing: labels of a job that fails may have come out
asn = paperless.next_asn(current_app.config, _get_repo_dir(), len(order)) if paperless.uses_asn(data) else None
- _queue_labels(printer, data, images, order, high_res, fast, [asn])
+ labels = _queue_labels(printer, data, images, order, high_res, fast, [asn], listed=kept_list)
drawn = printer.check()
+ if kept_list:
+ _check_lines(labels, kept_list['rows'])
except Exception as e:
print_store.discard(job_id, staged)
return _refused('Print job', e, refusals.PRINT_FAILED)
@@ -1528,7 +1624,8 @@ def _print_job(printer: PrinterQueue, data: dict, files, print_count: int, colla
title = _job_title(data, drawn, upload=uploads[0].filename if uploads else None)
return _queued(printer, run=_noting_sheet(printer, len(order)), title=title, source=_job_source('api'), labels=len(order),
recipe={'kind': 'request', 'data': data, 'order': order, 'asn': asn, 'high_res': high_res, 'fast': fast, 'named': named,
- 'copies': print_count, 'collate': collate, 'sizes': [size for _, size in kept], 'dates': _dates_set()},
+ 'copies': print_count, 'collate': collate, 'sizes': [size for _, size in kept], 'dates': _dates_set(),
+ **({'list': kept_list} if kept_list else {})},
images=[copy for copy, _ in kept], drawn=drawn, return_format=return_format, job_id=job_id, staged=staged)
@@ -1619,7 +1716,7 @@ def demo_preview():
@bp.route('/api/demos/print', methods=['POST'])
def demo_print():
- return _demo_response(_requested_name('id'), lambda data: _print_stored_label(data, demos.IMAGE_DIR))
+ return _demo_response(_requested_name('id'), lambda data: _print_stored_label(data, demos.IMAGE_DIR, with_list=True))
def _copies(images: list, count: int, collate: bool) -> list:
@@ -1925,6 +2022,8 @@ def preview_from_image():
values = _sized(values, _loaded_tape(device, model, settings))
values = printer_settings.for_printing(settings, model, values)
files = request.files.to_dict(flat=True)
+ # A label for each line of a list, see print_list
+ listed = print_list.parse(values.pop('list', ''), _max_count(values.get('label_size')))
# Of a PDF the first selected page
images, page_count = load_label_images(values, files, first_only=True)
# Only its previews show the blanks still to fill in, never a label
@@ -1933,12 +2032,23 @@ def preview_from_image():
# As many labels as printed: the copies of the files and pages the request tells, else of those sent
copies = _count(values.get('print_count'))
per_copy = _count(values.get('labels_per_copy'), _labels_per_copy(values, page_count, request.files.getlist('image')))
+ rows = None
+ if listed:
+ # Each copy prints every line of a list its count times, as printed
+ files_per_copy, per_copy = per_copy, per_copy * sum(count for _, count in listed)
+ if copies * per_copy > (most := _max_count(values.get('label_size'))):
+ raise print_list.Refused(print_list.too_many(most))
+ collate = _whole_or(values.get('collate'), _label_settings()['collate'] or 1) != 0
+ _, rows = _list_labels(listed, copies, [None] * files_per_copy, collate)
# A job printed before tells its number of labels, a page of it shows the first label only
total = _count(values.get('total'), copies * per_copy)
# Dates written as a label printed before wrote them, else as set
asked = {name: values[name] for name in DATE_SETTINGS if name in values}
dates = printer_settings.checked_label_settings(asked, ()) if asked else None
- label = create_label_from_request(values, files, image=images[0], mark_blanks=marks, asn=asn, total=total, dates=dates)
+ # The labels of a list each with its line, the first one shown
+ def shown(i: int) -> dict:
+ return _list_filled(values, listed[rows[i]][0]) if listed else values
+ label = create_label_from_request(shown(0), files, image=images[0], mark_blanks=marks, asn=asn, total=total, dates=dates)
im = label.generate()
size, state = label_of(values.get('label_size', DEFAULT_LABEL_SIZE)), None
paper = sheets.is_paper(size)
@@ -1961,7 +2071,7 @@ def preview_from_image():
state = sheets.fill_state(size, sheets.lying(size, im), copies, per_copy, _max_count(size.identifier), start)
if whole:
layouts = {}
- more = [create_label_from_request(values, files, i, image=images[0], mark_blanks=marks, layouts=layouts, asn=asn,
+ more = [create_label_from_request(shown(i), files, i, image=images[0], mark_blanks=marks, layouts=layouts, asn=asn,
total=total, dates=dates).generate()
for i in range(1, min(sheets.per_sheet(size) - (start - 1), copies * per_copy))]
im = sheets.page_view(size, [im] + more, start - 1)
@@ -1983,6 +2093,9 @@ def preview_from_image():
response.headers.set('X-PDF-Selected-Pages', str(len(selected_pdf_pages(str(values.get('pdf_pages') or ''), page_count))))
if state:
response.headers.set('X-Label-Sheet', json.dumps(state, separators=(',', ':')))
+ # The blanks every line of a list fills, the label designer asks for the others
+ if listed and _list_blanks(values):
+ response.headers.set('X-List-Filled', json.dumps(_list_reaches(values, listed), separators=(',', ':')))
# It suggests stronger contrast for a light image on the tapes of the VC-500W
if (images[0] is not None and _palette(values.get('label_size', DEFAULT_LABEL_SIZE)) == 'color'
and not _image_contrast(values) and looks_faint(images[0])):
@@ -2051,7 +2164,11 @@ def _preview_refused(error: Exception):
"""The answer to a preview that cannot be made: a fixed message, the
details are in the log."""
_log_refused_request('Preview', error)
- return _fail(refusals.message(error, refusals.PREVIEW_FAILED), 413 if isinstance(error, TextTooLong) else 400)
+ message, status = refusals.message(error, refusals.PREVIEW_FAILED), 413 if isinstance(error, TextTooLong) else 400
+ # Of the list, not of the label: the label designer tells it as it is
+ if isinstance(error, print_list.Refused):
+ return make_response(jsonify({'success': False, 'message': message, 'of': 'list'}), status)
+ return _fail(message, status)
# The X-Label-Parts header at most, in bytes: nginx takes 4 KB of headers by
@@ -3095,21 +3212,28 @@ def history_print(job_id):
same_values = _filled_blanks(data) == _filled_blanks(printed_data)
printer, data, high_res, fast = _stored_job(data)
collate = entry.get('collate', True)
- order = _copies(list(range(len(images))) or [None], copies, collate)
+ # A list prints all its lines again
+ listed = entry.get('list')
+ if listed:
+ order, rows = _list_labels(listed['lines'], copies, images, collate)
+ listed = _kept_list(listed['lines'], rows)
+ else:
+ order = _copies(list(range(len(images))) or [None], copies, collate)
if len(order) > (max_count := _max_count(printer.label_size)):
raise ValueError(f"A print job must not have more than {max_count} labels, "
f"{copies} copies would be {len(order)}")
+ same_labels = order == entry['order'][:len(order)] and (not listed or listed['rows'] == entry['list']['rows'][:len(order)])
# Each number on the label it was printed on, none that was not printed
- if as_before and entry.get('asn') is not None and order != entry['order'][:len(order)]:
+ if as_before and entry.get('asn') is not None and not same_labels:
raise ValueError(refusals.SAME_NUMBERS)
# Kept apart from the label: printed again, it asks again
printed_for = _dates_of(entry) if as_before and _timestamp(data) <= 0 else None
dates = entry.get('dates') if as_before else None
# The first labels as they were count as they did, e.g. Box 1 of 3
- total = (entry.get('total') or len(entry['order'])) if as_before and same_values and order == entry['order'][:len(order)] else None
+ total = (entry.get('total') or len(entry['order'])) if as_before and same_values and same_labels else None
recipe = {'kind': 'request', 'data': data, 'order': order, 'high_res': high_res, 'fast': fast, 'printed_for': printed_for,
'copies': copies, 'collate': collate, 'sizes': entry.get('sizes'), 'dates': dates or _dates_set(), 'total': total,
- 'named': entry.get('named')}
+ 'named': entry.get('named'), **({'list': listed} if listed else {})}
# Named as it printed before only while it prints as before, a
# title the request told it always
told = ' '.join(str(data.get('title') or '').split())[:MAX_TITLE_LENGTH]
@@ -3122,9 +3246,11 @@ def history_print(job_id):
if asn is None and paperless.uses_asn(recipe['data']):
asn = paperless.next_asn(current_app.config, _get_repo_dir(), len(recipe['order']))
recipe['asn'] = asn
- _queue_labels(printer, recipe['data'], images, recipe['order'], recipe['high_res'], recipe['fast'], [asn], printed_for,
- recipe['dates'], total, recipe['sizes'])
+ labels = _queue_labels(printer, recipe['data'], images, recipe['order'], recipe['high_res'], recipe['fast'], [asn], printed_for,
+ recipe['dates'], total, recipe['sizes'], recipe.get('list'))
drawn = printer.check()
+ if recipe.get('list'):
+ _check_lines(labels, recipe['list']['rows'])
except Exception as e:
return _refused('Print job', e, refusals.PRINT_FAILED)
# Named as before, unless the request names it, else as it printed now
@@ -3212,6 +3338,8 @@ def print_label():
fast = _whole_or(values.get('fast_printing'), 0) != 0
collate = _whole_or(values.get('collate'), _label_settings()['collate'] or 1) != 0
printer.leaves_first = _leaves_first(values.get('leaves_first'))
+ # A label for each line of a list, else today's print
+ listed = print_list.parse(values.pop('list', ''), _max_count(values['label_size']))
except HTTPException:
raise
except PrinterUnreachable as e:
@@ -3219,7 +3347,8 @@ def print_label():
except Exception as e:
return _refused('Print job', e, refusals.PRINT_FAILED)
# Every uploaded image, not only the first
- return _print_job(printer, values, request.files, print_count, collate, high_res, fast, request.values.get('return_format'))
+ return _print_job(printer, values, request.files, print_count, collate, high_res, fast, request.values.get('return_format'),
+ listed=listed)
def _log_refused_request(what: str, error: Exception):
@@ -3769,7 +3898,7 @@ def _blank_fields(value) -> dict:
# Parameters of the requests for stored labels, never values of blanks of
# the same name
-STORED_LABEL_PARAMETERS = ('name', 'id', 'printer', 'model', 'print_count', 'cut', 'cut_once', 'half_cut', 'chain',
+STORED_LABEL_PARAMETERS = ('name', 'id', 'printer', 'model', 'print_count', 'list', 'cut', 'cut_once', 'half_cut', 'chain',
'high_res', 'fast_printing', 'collate', 'leaves_first', 'mirror', 'blanks', 'return_format')
diff --git a/app/labeldesigner/templates/designer.html b/app/labeldesigner/templates/designer.html
index 3173b2546..a82a3665d 100644
--- a/app/labeldesigner/templates/designer.html
+++ b/app/labeldesigner/templates/designer.html
@@ -130,6 +130,7 @@
+
@@ -149,6 +150,7 @@
+
diff --git a/app/static/designer/core.js b/app/static/designer/core.js
index 44fa04140..e6f6e8446 100644
--- a/app/static/designer/core.js
+++ b/app/static/designer/core.js
@@ -589,12 +589,14 @@ export function sheetNote(sheet, max = 100) {
const shownColors = (p = S.printer) => p && p.colors && p.colors.tape && p.colors.ink ? `${p.colors.tape.hex},${p.colors.ink.hex}` : '';
// total: the number of labels of a job printed before, for {{total}} only;
-// onTapeColors: shown on the tape in the printer, in its colors where it tells them
-export async function preview(design, values, copies = 1, perCopy = 0, total = 0, onTapeColors = false) {
+// onTapeColors: shown on the tape in the printer, in its colors where it tells them;
+// list: one label for each line, the server shows the first one and counts them all,
+// and tells the blanks every line fills (listFilled)
+export async function preview(design, values, copies = 1, perCopy = 0, total = 0, onTapeColors = false, list = '') {
const asked = Object.assign({}, onTape(design), { high_res: highRes() ? '1' : '0' });
// On a roll with several labels to a page the server tells how the copies fill the last one,
// on a sheet of labels also from which label on
- const sheet = isSheet(asked.label_size) || isPaper(asked.label_size), counted = sheet || withTotal(asked);
+ const sheet = isSheet(asked.label_size) || isPaper(asked.label_size), counted = sheet || withTotal(asked) || !!list;
if (isPaper(asked.label_size) && takesSheets()) asked.sheet_start = String(sheetStartOf(S.printer, asked.label_size));
const blanks = blankRequest(asked, values || {});
for (const [name, f] of Object.entries(blanks.fields)) {
@@ -606,7 +608,7 @@ export async function preview(design, values, copies = 1, perCopy = 0, total = 0
// Several printers can share a path, e.g. simulators of other models
const colors = onTapeColors ? shownColors() : '';
const key = JSON.stringify([shown, blanks, S.printer && S.printer.path, S.printer && S.printer.model, dated ? Math.floor(Date.now() / 60000) : 0, S.settings.date_format, S.settings.date_language,
- counted ? [copies, perCopy, total] : 0, colors]);
+ counted ? [copies, perCopy, total] : 0, colors, list]);
if (previewCache.has(key)) {
const p = previewCache.get(key);
previewCache.delete(key);
@@ -621,14 +623,16 @@ export async function preview(design, values, copies = 1, perCopy = 0, total = 0
if (counted && perCopy > 0) fd.append('labels_per_copy', String(perCopy));
if (counted && total > 0) fd.append('total', String(total));
if (colors) fd.append('tape_colors', '1');
+ if (list) fd.append('list', list);
r = await post('/preview', fd, AbortSignal.timeout ? AbortSignal.timeout(60000) : undefined);
} catch (e) {
throw new Error(['TimeoutError', 'AbortError'].includes(e.name) ? 'The preview took too long' : 'The preview could not be made');
}
if (!r.ok) {
- let msg = 'The preview could not be made';
- try { msg = (await r.json()).message || msg; } catch (e) { }
- throw Object.assign(new Error(msg), { refused: true });
+ let msg = 'The preview could not be made', of = '';
+ try { const told = await r.json(); msg = told.message || msg; of = told.of || ''; } catch (e) { }
+ // ofList: the list is refused, not the label
+ throw Object.assign(new Error(msg), { refused: true, ofList: of === 'list' });
}
const blob = await r.blob();
return {
@@ -637,7 +641,7 @@ export async function preview(design, values, copies = 1, perCopy = 0, total = 0
order: r.headers.get('X-Label-Parts-Order') || '', direction: r.headers.get('X-Label-Parts-Direction') || '', faint: r.headers.get('X-Image-Faint') === '1',
pages: +(r.headers.get('X-PDF-Selected-Pages') || 1), pageCount: +(r.headers.get('X-PDF-Pages') || 0), parts: partsOf(r.headers.get('X-Label-Parts')),
printedAs: colorsOf(r.headers.get('X-Label-Colors')), labelSize: asked.label_size, sheet: sheetOf(r.headers.get('X-Label-Sheet')),
- tapeColors: (r.headers.get('X-Label-Tape-Colors') || '').split(',').filter(Boolean),
+ tapeColors: (r.headers.get('X-Label-Tape-Colors') || '').split(',').filter(Boolean), listFilled: namesOf(r.headers.get('X-List-Filled')),
along: runsAlong(asked)
};
})();
@@ -651,6 +655,13 @@ export async function preview(design, values, copies = 1, perCopy = 0, total = 0
return p;
}
+// Names the server tells as a JSON list, e.g. of blanks
+function namesOf(header) {
+ try {
+ const told = JSON.parse(header || '[]');
+ return Array.isArray(told) ? told.map(String) : [];
+ } catch (e) { return []; }
+}
// The colors the tape prints otherwise, as the server tells them
function colorsOf(header) {
try {
@@ -1185,8 +1196,9 @@ function hooked(hook, ...args) {
told(e);
}
}
-// job: { title, design, values, copies, source, name }, name to name it
-// where the label has no text of its own. Kept in the history of
+// job: { title, design, values, copies, source, name, list }, name to name
+// it where the label has no text of its own, list to print a label for each
+// line. Kept in the history of
// this browser for its search and the values of blanks. Printed on printer,
// the one chosen unless another is given. onAccepted(entry) once the server
// took it, onDone(entry) with its outcome.
@@ -1209,7 +1221,7 @@ export async function printJob(job, onDone, printer = S.printer, onAccepted = nu
// On a sheet of labels (sheet), which a print tried again goes on on
const entry = Object.assign(newEntry(printer, job.copies || 1), {
title: job.title, design: clone(job.design), values: Object.assign({}, job.values || {}), source: job.source || null
- }, start ? { sheet: true } : {});
+ }, start ? { sheet: true } : {}, job.list ? { list: job.list } : {});
S.history.unshift(entry);
saveHistory();
return await sendJob(entry, printer, () => {
@@ -1222,12 +1234,16 @@ export async function printJob(job, onDone, printer = S.printer, onAccepted = nu
if (name) form.set('title', name);
form.set('source', 'designer');
if (start) form.set('sheet_start', String(start));
+ if (job.list) form.set('list', job.list);
return ['/print', form];
}, onDone, onAccepted, turn);
} finally {
turn.end();
}
}
+// The labels of a print as its messages tell them: as the server counted them, e.g. of a list or
+// of several files, else the copies
+export const labelCount = entry => entry.labels || entry.copies;
const newEntry = (printer, copies) => ({
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), time: Date.now(), copies,
printer: printer ? printer.model : '', printerName: (printer && printer.name) || '', path: (printer && printer.path) || '', state: 'printing', message: ''
@@ -1237,7 +1253,9 @@ const newEntry = (printer, copies) => ({
async function sendJob(entry, printer, request, onDone, onAccepted = null, turn = null) {
const behind = lineBusy(printer), path = entry.path;
const answered = () => { if (turn) turn.end(); };
- const printing = toast(`Printing ${entry.copies} ${entry.copies === 1 ? 'label' : 'labels'}...`, null, 120000);
+ // Told again as the server counts the labels; a list only then
+ const printingText = n => `Printing ${n} ${n === 1 ? 'label' : 'labels'}...`;
+ let told = entry.list ? 0 : labelCount(entry), printing = told ? toast(printingText(told), null, 120000) : 0;
const shown = () => !!S.printer && S.printer.path === path;
QUEUE.follow();
try {
@@ -1254,6 +1272,10 @@ async function sendJob(entry, printer, request, onDone, onAccepted = null, turn
// Named by the server as the list of the labels printed names it
if (r.ok && data.title) entry.told = data.title;
const ok = r.ok && data.success !== false;
+ if (ok && labelCount(entry) !== told && (!told || printing === toastId)) {
+ told = labelCount(entry);
+ printing = toast(printingText(told), null, 120000);
+ }
if (ok && entry.sheet && printHooks.taken) hooked(printHooks.taken, printer, data);
answered();
if (!ok) {
@@ -1395,12 +1417,14 @@ export function printAgain(h, onDone = announcePrint) {
if (h.noImage) { toast(NO_IMAGE); return null; }
// Tried again, a print on a sheet goes on after the labels used meanwhile
const again = h.sheet && h.state !== 'printed' ? { sheetStart: 'next' } : {};
- return printJob({ title: h.title, design: h.design, values: h.values, copies: h.copies, source: h.source, ...again }, onDone);
+ const list = h.list ? { list: h.list } : {};
+ return printJob({ title: h.title, design: h.design, values: h.values, copies: h.copies, source: h.source, ...list, ...again }, onDone);
}
export function announcePrint(entry, again = () => printAgain(entry)) {
if (untold(entry)) return;
hideToast();
- if (entry.state === 'printed') toast(`Printed ${entry.copies === 1 ? '1 label' : `${entry.copies} labels`}: ${entryName(entry)}`, { label: 'Print again', run: again });
+ const n = labelCount(entry);
+ if (entry.state === 'printed') toast(`Printed ${n === 1 ? '1 label' : `${n} labels`}: ${entryName(entry)}`, { label: 'Print again', run: again });
else if (entry.state === 'unknown') toast(`Maybe not printed: ${entry.message}`, { label: 'Print again', run: again }, 10000);
else toast(`Not printed: ${entry.message}`, { label: 'Try again', run: again }, 10000);
}
@@ -1485,7 +1509,7 @@ export async function keptLabel(h) {
const shows = (name, value) => new RegExp(`(^|[^\\p{L}\\p{N}])${value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|[^\\p{L}\\p{N}])`, 'u').test(name);
// What a label printed before is listed with: its copies, the values
// printed, when
-export const printedSub = h => h.state === 'failed' ? `Not printed: ${h.message}` : h.state === 'unknown' ? `Maybe not printed: ${h.message}` : [`${h.copies} x`, ...Object.values(h.values || {}).filter(v => String(v).trim() && !shows(entryName(h), String(v).trim())), fmtTime(h.time)].join(', ');
+export const printedSub = h => h.state === 'failed' ? `Not printed: ${h.message}` : h.state === 'unknown' ? `Maybe not printed: ${h.message}` : [`${labelCount(h)} x`, ...Object.values(h.values || {}).filter(v => String(v).trim() && !shows(entryName(h), String(v).trim())), fmtTime(h.time)].join(', ');
// --- Overlays ----------------------------------------------------------------
diff --git a/app/static/designer/editor.js b/app/static/designer/editor.js
index 6f2141dc6..e073c92d0 100644
--- a/app/static/designer/editor.js
+++ b/app/static/designer/editor.js
@@ -9,7 +9,7 @@ import {
fieldType, blankChoices, startOf,
valuesNow, choicesMissing, printJob, entryName, openLayer, closeLayer, cutOf, printerCut, sizeCaps, noCutter, noCutterWhy, neverWhy,
cutShort, cutStrip, CUTS, halfOf, chainOf, imageKey, printerCaps, saveLabel, savedAs, leavesFirst, printerState, printerLabel, printerName, designSig,
- loadSaved, roomFrom, isSheet, withTotal, sheetNote, untold, isPaper, maxCopies, takesSheets, printAgain, marginPreset, setMargins
+ loadSaved, roomFrom, isSheet, withTotal, sheetNote, untold, isPaper, maxCopies, takesSheets, printAgain, marginPreset, setMargins, labelCount
} from './core.js';
import { paperLine, openSheet, sheetShown, chosenSheet, sheetHooks } from './sheet.js';
import { mountField, renderField, markLine, focusLine, closePop } from './field.js';
@@ -50,6 +50,7 @@ export function setEdit(edit) {
ui.fixedLength = false;
ui.customMargins = false;
ui.customFrame = false;
+ ui.listFilled = [];
}
// Another label in the editor: one with changes not saved asks first, as New
@@ -314,6 +315,7 @@ export function renderEditor() {
+
@@ -348,6 +350,7 @@ export function renderEditor() {
updateActions();
updateHistoryButtons();
drawFill();
+ drawList();
drawTape();
drawPrinter();
// Open before another view was shown, e.g. Settings, it is open again
@@ -451,7 +454,7 @@ function pick(p, fromLabel) {
function updateActions() {
const E = S.edit, empty = isEmptyDesign(E.design), missing = choicesMissing(editItem(E)).length > 0;
- $('#print').disabled = empty || ui.failed || missing;
+ $('#print').disabled = (empty && !listOf(E)) || ui.failed || missing || !!ui.sending;
$('#save').disabled = empty || missing;
$('#save').title = E.origin && E.origin.kind === 'saved' ? `Save "${E.title}"` : 'Save to your labels';
if (document.activeElement !== $('#title')) $('#title').value = E.title;
@@ -518,11 +521,55 @@ function drawFill() {
const v = valueOf(inp.dataset.blank);
if (document.activeElement !== inp && (inp.tagName !== 'SELECT' || [...inp.options].some(o => o.value === v))) inp.value = v;
});
- const open = $$('input[data-blank]', box).filter(inp => { const empty = !inp.value.trim(); inp.classList.toggle('need', empty); return empty; }).length;
+ // Those every line of a list fills, as the last preview made told it, wait for nothing
+ const filled = listOf(E) ? ui.listFilled || [] : [];
+ const open = $$('input[data-blank]', box).filter(inp => { const empty = !inp.value.trim() && !filled.includes(inp.dataset.blank); inp.classList.toggle('need', empty); return empty; }).length;
const n = $('#fillN', box);
if (n) { n.textContent = `${open} to fill in`; n.hidden = !open; }
}
+// --- A list to print, one label for each line --------------------------------------------
+
+// The list to print, empty where its box is closed or has no line: the print is as without it
+const listOf = E => E && typeof E.list === 'string' && E.list.trim() ? E.list : '';
+// Opened from the menu of Print, a label of the editor keeps it until it is closed
+export function openList() {
+ if (!S.edit || !$('#stage')) return;
+ if (typeof S.edit.list !== 'string') S.edit.list = '';
+ drawList();
+ $('#printList').focus();
+}
+function closeList() {
+ delete S.edit.list;
+ drawList();
+ listChanged();
+}
+function listChanged() {
+ updateActions();
+ drawFill();
+ markBusy();
+ drawPreview();
+}
+function drawList() {
+ const E = S.edit, box = $('#listBox');
+ if (!box) return;
+ box.hidden = typeof E.list !== 'string';
+ if (box.hidden) { box.innerHTML = ''; return; }
+ if (!$('#printList', box)) {
+ box.innerHTML = `
Add x 3 for 3 labels
+
+ `;
+ $('#printList', box).addEventListener('input', e => {
+ const was = listOf(S.edit);
+ S.edit.list = e.target.value;
+ // The preview shows the first line and counts them all
+ if (listOf(S.edit) !== was) listChanged();
+ });
+ $('#listClose', box).onclick = closeList;
+ }
+ if ($('#printList', box).value !== E.list) $('#printList', box).value = E.list;
+}
+
function fillField(item, name, value, i) {
const kind = fieldType(item, name), id = 'fill' + i;
const head = ``;
@@ -576,14 +623,14 @@ const nextPreview = latest(async () => {
const E = S.edit;
if (!E || !$('#labelImg')) return;
const me = ++seq, upTo = asked;
- const empty = isEmptyDesign(E.design);
+ const empty = isEmptyDesign(E.design) && !listOf(E);
// An empty label shows as large as a line of its first size makes it
const shown = empty ? Object.assign(clone(Object.assign({}, E.design, { image: undefined, more_images: undefined })), { text: E.design.text.slice(0, 1).map(l => Object.assign({}, l, { text: 'Ag' })) })
: hooks.shown ? hooks.shown(E.design) : E.design;
const values = previewValues(E);
let p;
try {
- p = await preview(shown, values, copies(), hooks.perCopy ? hooks.perCopy() : 0, 0, true);
+ p = await preview(shown, values, copies(), hooks.perCopy ? hooks.perCopy() : 0, 0, true, listOf(E));
} catch (e) {
if (me < shownSeq) return;
shownSeq = me;
@@ -593,7 +640,7 @@ const nextPreview = latest(async () => {
$('#labelbox').classList.add('failed');
$('#picks').innerHTML = '';
drawSheet(null);
- fitsNote('', e.message);
+ fitsNote('', e.message, e.ofList);
updateActions();
laidOut(true);
return;
@@ -606,6 +653,8 @@ const nextPreview = latest(async () => {
shownSeq = me;
ui.failed = false;
ui.last = Object.assign({}, p, { w: img.naturalWidth, h: img.naturalHeight, empty });
+ ui.listFilled = p.listFilled;
+ if (listOf(E)) drawFill();
// A color the tape prints otherwise is said next to it
const colorsTold = JSON.stringify(S.printedAs) !== JSON.stringify(p.printedAs);
S.printedAs = p.printedAs;
@@ -678,9 +727,9 @@ function drawSheet(sheet) {
if (paper) sheetShown();
if ($('#copies')) $('#copies').max = maxCopies(id);
}
-// Only pages of several labels and the number of labels preview the copies
+// Only pages of several labels, the number of labels and a list preview the copies
export function copiesChanged() {
- if ((ui.last && (isSheet(ui.last.labelSize) || isPaper(ui.last.labelSize))) || (S.edit && withTotal(S.edit.design))) drawPreview();
+ if ((ui.last && (isSheet(ui.last.labelSize) || isPaper(ui.last.labelSize))) || (S.edit && (withTotal(S.edit.design) || listOf(S.edit)))) drawPreview();
}
function previewValues(E) {
@@ -878,7 +927,8 @@ function layoutProblem(d) {
if (parts.some(c => c !== 'red')) return 'This tape prints black and red only, other colors print in one of them.';
return '';
}
-function fitsNote(warning, error) {
+// ofList: the error is of the list to print, told on its own
+function fitsNote(warning, error, ofList = false) {
const el = $('#fits'), d = S.edit.design;
if (warning === null) { el.className = 'fits'; el.innerHTML = ''; return; }
if (!warning && !error) warning = layoutProblem(onTape(d));
@@ -886,7 +936,7 @@ function fitsNote(warning, error) {
if (missing.length && !error) warning = `Give [${missing[0]}] its choices: click it in the text.`;
if (error) {
el.className = 'fits warn';
- el.innerHTML = `${icon('warn')}Fix the label to print it. ${esc(error)}`;
+ el.innerHTML = `${icon('warn')}${ofList ? '' : 'Fix the label to print it. '}${esc(error)}`;
return;
}
// The server finds an image light on color tape, stronger contrast helps
@@ -1282,14 +1332,30 @@ export async function printNow() {
if ($('#print').disabled) return;
const item = editItem(E);
const values = valuesNow(previewValues(E), defaults(item), item);
- const entry = await printJob({ title: E.title, design: madeDesign(E), values, copies: copies(), source: E.origin }, announce);
- return entry;
+ const list = listOf(E) ? { list: listOf(E) } : {};
+ // A list is sent once: Print waits for its answer, which a long one takes
+ // a while for. Other prints may follow before, they wait for their turn.
+ const answered = () => {
+ if (!ui.sending) return;
+ ui.sending = false;
+ if ($('#stage')) updateActions();
+ };
+ if (list.list) {
+ ui.sending = true;
+ updateActions();
+ }
+ try {
+ return await printJob({ title: E.title, design: madeDesign(E), values, copies: copies(), source: E.origin, ...list }, announce, S.printer,
+ list.list ? answered : null);
+ } finally {
+ answered();
+ }
}
function announce(entry) {
if (untold(entry)) return;
hideToast();
- const n = entry.copies, what = `${n} ${n === 1 ? 'label' : 'labels'}`;
+ const n = labelCount(entry), what = `${n} ${n === 1 ? 'label' : 'labels'}`;
if (entry.state === 'printed') {
toast(`Printed ${what}: ${entryName(entry)}`, { label: 'Print again', run: () => printJob(Object.assign({}, entry), announce) });
return;
diff --git a/app/static/designer/main.css b/app/static/designer/main.css
index 1227ef048..ac4fa9e96 100644
--- a/app/static/designer/main.css
+++ b/app/static/designer/main.css
@@ -129,6 +129,10 @@ small, .small { font-size: 12px; }
.printbtn .cnt input::-webkit-inner-spin-button { -webkit-appearance: none; }
.printbtn .go { border: 0; background: transparent; color: inherit; font-weight: 600; display: flex; align-items: center; gap: 8px; padding: 9px 16px 9px 13px; }
.printbtn .go:disabled { opacity: .45; }
+.printbtn .more { border: 0; border-left: 1px solid color-mix(in srgb, currentColor 22%, transparent); background: transparent; color: inherit; display: grid; place-items: center; padding: 0 9px; }
+.printbtn .more .ic { opacity: .8; }
+.printbtn .more:hover .ic, .printbtn .more[aria-expanded="true"] .ic { opacity: 1; }
+.print-menu { position: fixed; min-width: 200px; }
/* --- Stage --- */
#view { min-height: 0; overflow: hidden; }
@@ -149,7 +153,7 @@ small, .small { font-size: 12px; }
#undo { position: relative; }
#undo .n { position: absolute; top: 2px; right: 0; min-width: 15px; height: 15px; padding: 0 4px; border-radius: 99px; background: var(--surface-2); color: var(--muted); font-size: 10px; line-height: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
.fill { width: min(720px, 100%); margin-top: 22px; background: var(--surface); border: 1px solid var(--line); border-radius: 16px; box-shadow: var(--sh); padding: 10px 14px 14px; }
-.fill:not([hidden]) + .composer { margin-top: 12px; }
+.fill:not([hidden]) + .composer, .fill:not([hidden]) + .fill[hidden] + .composer, .fill:not([hidden]) + .fill { margin-top: 12px; }
.fill-h { display: flex; align-items: center; gap: 8px; }
.fill-h h4 { font-size: 11.5px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); font-weight: 600; }
.badge { font-size: 11.5px; border-radius: 99px; padding: 1px 8px; background: var(--warn-soft); color: var(--warn); font-weight: 600; }
@@ -159,6 +163,8 @@ small, .small { font-size: 12px; }
.fill-grid .in.need { border-color: var(--warn); background: var(--warn-soft); }
.reuse { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 2px; }
.reuse .pill { padding: 2px 9px; font-size: 12px; }
+.printlist .iconbtn { width: 28px; height: 28px; margin: -4px -6px -4px 0; }
+.printlist textarea { display: block; margin-top: 8px; min-height: 88px; font-size: 14px; line-height: 1.5; padding: 7px 10px; }
.fits.ok { color: var(--ok); }
.fits.warn { color: var(--warn); background: var(--warn-soft); border-radius: 10px; padding: 6px 10px; }
.fits.warn b { font-weight: 600; }
@@ -716,6 +722,7 @@ textarea.scan-field { width: 100%; min-height: 96px; resize: none; padding: 14px
.printbtn { flex: 1; height: 44px; min-width: 0; }
.printbtn .cnt button { width: 36px; }
.printbtn .go { flex: 1; justify-content: center; }
+ .printbtn .more { padding: 0 12px; }
.stage { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto 1fr; align-items: start; }
.stage-head { position: static; grid-column: 1; grid-row: 1; max-width: none; margin: 8px 0 0 14px; min-width: 0; }
@@ -748,9 +755,9 @@ textarea.scan-field { width: 100%; min-height: 96px; resize: none; padding: 14px
.ochip { height: 40px; padding: 0 14px 0 8px; }
.oswap { width: 36px; height: 40px; }
- .line-menu, .media-menu, .color-menu, .font-menu, .chip-pop, .chip-pop.wide { position: fixed; left: 0 !important; right: 0; top: auto !important; bottom: 0; width: auto; max-height: 78vh; overflow: auto; z-index: 36;
+ .line-menu, .media-menu, .color-menu, .font-menu, .chip-pop, .chip-pop.wide, .print-menu { position: fixed; left: 0 !important; right: 0; top: auto !important; bottom: 0; width: auto; max-height: 78vh; overflow: auto; z-index: 36;
border-width: 1px 0 0; border-radius: 20px 20px 0 0; padding: 10px 12px calc(14px + env(safe-area-inset-bottom)); box-shadow: 0 -12px 32px rgba(16, 24, 40, .18); }
- .line-menu::before, .media-menu::before, .color-menu::before, .font-menu::before, .chip-pop::before, .adv::before { content: ""; display: block; flex: none; width: 40px; height: 4px; border-radius: 4px; background: var(--line-2); margin: 0 auto 8px; }
+ .line-menu::before, .media-menu::before, .color-menu::before, .font-menu::before, .chip-pop::before, .print-menu::before, .adv::before { content: ""; display: block; flex: none; width: 40px; height: 4px; border-radius: 4px; background: var(--line-2); margin: 0 auto 8px; }
.menu > button, .menu .mi { min-height: 44px; }
/* The label stays in sight above the sheet */
.font-menu { max-height: 82vh; }
diff --git a/app/static/designer/main.js b/app/static/designer/main.js
index 41c55265f..a484da988 100644
--- a/app/static/designer/main.js
+++ b/app/static/designer/main.js
@@ -9,7 +9,7 @@ import {
loadLabelSettings, savedNow, forgetGoneKeys, printAgain, printedSub, followPrinter, resolvePending, maxCopies, onTape, tapeColors, withColors, STATUS_WAITS
} from './core.js';
import { calibrationHTML, bindCalibration } from './calibration.js';
-import { renderEditor, openEditor, stepHistory, printNow, saveNow, printerChanged, drawPrinter, hooks, editorUI, newEdit, setEdit, loadEdit, copiesChanged } from './editor.js';
+import { renderEditor, openEditor, stepHistory, printNow, saveNow, printerChanged, drawPrinter, hooks, editorUI, newEdit, setEdit, loadEdit, copiesChanged, openList } from './editor.js';
import { closePop } from './field.js';
import { mountGallery, openTemplates, openFill, savedSub } from './gallery.js';
import { renderSettings, redrawSettings, redrawLabelSettings } from './settings.js';
@@ -389,7 +389,7 @@ export { setTheme };
// Menus and popovers close on a press elsewhere: Esc presses there for them
function closeMenus() {
- if (!$('.line-menu, .media-menu, .color-menu, .chip-pop')) return false;
+ if (!$('.line-menu, .media-menu, .color-menu, .chip-pop, .print-menu')) return false;
document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
return true;
}
@@ -413,10 +413,35 @@ document.addEventListener('keydown', e => {
if (mod && own && e.key.toLowerCase() === 'y') { e.preventDefault(); stepHistory(1); }
});
+// More ways to print, from the arrow beside Print: a list
+function openPrintMenu() {
+ if ($('.print-menu')) { closePrintMenu(); return; }
+ const more = $('#printMore'), el = document.createElement('div');
+ el.className = 'menu print-menu';
+ el.innerHTML = ``;
+ document.body.appendChild(el);
+ const r = more.getBoundingClientRect();
+ el.style.left = `${Math.max(8, r.right - el.offsetWidth)}px`;
+ el.style.top = `${r.bottom + 8}px`;
+ more.setAttribute('aria-expanded', 'true');
+ $('#printListOpen').onclick = () => { closePrintMenu(); openList(); };
+ document.addEventListener('mousedown', outsidePrintMenu, true);
+}
+function outsidePrintMenu(e) {
+ if (!e.target.closest('.print-menu, #printMore')) closePrintMenu();
+}
+function closePrintMenu() {
+ const el = $('.print-menu');
+ if (el) el.remove();
+ $('#printMore').setAttribute('aria-expanded', 'false');
+ document.removeEventListener('mousedown', outsidePrintMenu, true);
+}
+
function bindTop() {
$('#openSearch').onclick = openSearch;
$('#printerChip').onclick = openPrinters;
$('#print').onclick = () => printNow();
+ $('#printMore').onclick = openPrintMenu;
$('#save').onclick = () => saveNow(saveDialog);
hooks.save = then => saveNow(saveDialog, then);
$$('.printbtn [data-step]').forEach(b => b.onclick = () => {
diff --git a/docs/api.md b/docs/api.md
index ad68abae5..45e4e656d 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -17,6 +17,10 @@ curl -X POST http://localhost:8013/labeldesigner/api/print \
curl -X POST http://localhost:8013/labeldesigner/api/preview \
-F 'text=[{"text": "Hello", "size": "70"}]' -o label.png
+# Print a label for each line of plants.txt, e.g. "Basil x 20" 20 times
+curl -X POST http://localhost:8013/labeldesigner/api/print \
+ -F 'text=[{"text": "{{blank:Plant}}", "size": "70"}]' -F 'list= list:
+ return [texts for queued, texts in drawn if queued]
+
+
+def print_the_list(client, listed, **values):
+ """The answer to a print of the list, printed."""
+ response = client.post(f'{API}/print', data={**EXAMPLE_FORMDATA, 'printer': 'simulation', 'text': lines('{{blank:Name}}'),
+ 'list': listed, **values})
+ assert response.status_code == 200, response.get_json()
+ assert outcome(client, response) == ('printed', '')
+ return response.get_json()
+
+
+def refused(client, path='print', **values) -> str:
+ response = client.post(f'{API}/{path}', data={**EXAMPLE_FORMDATA, 'printer': 'simulation', 'text': lines('{{blank:Name}}'), **values})
+ assert response.status_code == 400
+ return response.get_json()['message']
+
+
+@pytest.mark.parametrize('text, parsed', [
+ ('Basil', [(['Basil'], 1)]),
+ ('Basil x 20', [(['Basil'], 20)]),
+ ('Basil x20\nThyme X 3', [(['Basil'], 20), (['Thyme'], 3)]),
+ ('Sweet basil x 2', [(['Sweet basil'], 2)]),
+ # Only a count at the end, after a space and a word without digits
+ ('Box 2x3', [(['Box 2x3'], 1)]),
+ ('x 3', [(['x 3'], 1)]),
+ ('Basil x 03', [(['Basil'], 3)]),
+ # Sizes, not counts of labels: part of the line
+ ('Box 2 x 3', [(['Box 2 x 3'], 1)]),
+ ('M3 x 10', [(['M3 x 10'], 1)]),
+ ('2 x 4', [(['2 x 4'], 1)]),
+ ('Photo 10 x 15', [(['Photo 10 x 15'], 1)]),
+ ('Screw\tM3 x 10', [(['Screw', 'M3 x 10'], 1)]),
+ # A count only in its cell after a word, not a cell of a count alone
+ ('M3\tx 10', [(['M3', 'x 10'], 1)]),
+ ('Car\tX5', [(['Car', 'X5'], 1)]),
+ ('Car\t\tX5', [(['Car', '', 'X5'], 1)]),
+ ('x20', [(['x20'], 1)]),
+ ('Basil x 0', [(['Basil x 0'], 1)]),
+ ('Basil x -2', [(['Basil x -2'], 1)]),
+ ('Basil x 2.5', [(['Basil x 2.5'], 1)]),
+ # Empty lines are left out, cells are split at tabs and trimmed
+ ('\nBasil \r\n \n\t\n Thyme\r\n', [(['Basil'], 1), (['Thyme'], 1)]),
+ ('Basil\tOcimum basilicum x 2', [(['Basil', 'Ocimum basilicum'], 2)]),
+ ('Basil\tx 2', [(['Basil', 'x 2'], 1)]),
+ # Empty cells at the end are none, an empty one between stays
+ ('\tOcimum\t\t', [(['', 'Ocimum'], 1)]),
+ ('Basil\t\tMay x 2', [(['Basil', '', 'May'], 2)]),
+ # Cells as a spreadsheet quotes them
+ ('"5"" pot"\tlarge x 2\n"Line 1\nLine 2"\tsmall', [(['5" pot', 'large'], 2), (['Line 1\nLine 2', 'small'], 1)]),
+ ('""\t""\nBasil', [(['Basil'], 1)]),
+ # One column of a spreadsheet, without tabs
+ ('"5"" pot"\n"Line 1\nLine 2"\nBasil x 2', [(['5" pot'], 1), (['Line 1\nLine 2'], 1), (['Basil'], 2)]),
+ # Typed, or not as a spreadsheet quotes them, the quotes stay
+ ('12" ruler\nTape', [(['12" ruler'], 1), (['Tape'], 1)]),
+ ('"Best" tomatoes x 2', [(['"Best" tomatoes'], 2)]),
+ ('"Best" tomatoes\tred', [(['"Best" tomatoes', 'red'], 1)]),
+ ('"Basil\tsweet\nThyme', [(['"Basil', 'sweet'], 1), (['Thyme'], 1)]),
+ ('Basil\t"sweet', [(['Basil', '"sweet'], 1)]),
+ # The lines of a JSON body
+ (['Basil x 2', 'Thyme\tThymus'], [(['Basil'], 2), (['Thyme', 'Thymus'], 1)]),
+ ([], []),
+ ('', []),
+])
+def test_lines_and_their_counts(text, parsed):
+ assert print_list.parse(text, 100) == parsed
+
+
+@pytest.mark.parametrize('text', ['Basil x 101', 'Basil x 60\nThyme x 41', '\n'.join(['Basil'] * 101), 'Basil x 99999999999999999999'])
+def test_more_labels_than_a_job_takes_are_refused(text):
+ with pytest.raises(ValueError) as refusal:
+ print_list.parse(text, 100)
+ assert str(refusal.value) == 'A list prints at most 100 labels. Split it.'
+
+
+@pytest.mark.parametrize('value', [None, 7, 2.5, True, {'Name': 'Basil'}, ['Basil', 7], ['Basil', None]])
+def test_a_list_of_no_text_is_refused(value):
+ with pytest.raises(print_list.Refused) as refusal:
+ print_list.parse(value, 100)
+ assert str(refusal.value) == 'list must be a text or a list of texts'
+
+
+def test_as_many_labels_as_a_job_takes():
+ assert print_list.parse('Basil x 60\nThyme x 40', 100) == [(['Basil'], 60), (['Thyme'], 40)]
+
+
+def test_each_line_fills_the_blanks(client, drawn):
+ answer = print_the_list(client, 'Basil x 2\n\nThyme\n', text=lines('Plant: {{blank:Name}}', 'Garden'))
+ assert printed(drawn) == [['Plant: Basil', 'Garden'], ['Plant: Basil', 'Garden'], ['Plant: Thyme', 'Garden']]
+ # Named by its first label, counted with all
+ assert (answer['labels'], answer['title']) == (3, 'Plant: Basil')
+
+
+def test_cells_fill_the_blanks_in_order(client, drawn):
+ text = lines('{{blank:Name}} {{blank:Latin}}', 'Sown {{blank:Sown}}')
+ print_the_list(client, 'Basil\tOcimum\tMay\tleft out\nThyme\tThymus\nMint', text=text,
+ blanks=json.dumps({'Sown': 'April', 'Latin': '?'}))
+ # Blanks beyond the cells keep the values given, cells beyond the blanks are left out
+ assert printed(drawn) == [['Basil Ocimum', 'Sown May'], ['Thyme Thymus', 'Sown April'], ['Mint ?', 'Sown April']]
+
+
+def test_an_empty_cell_is_not_given(client, drawn):
+ text = lines('[{{blank:Name}}] {{blank:Latin}} {{blank:Pot}}')
+ fields = json.dumps({'Pot': {'type': 'choice', 'choices': ['small', 'large'], 'default': 'large'}})
+ # The value filled in, else the default, also of a choice from a spreadsheet's empty cells
+ print_the_list(client, '\tOcimum\t\nThyme\t\tsmall\t', text=text, fields=fields, blanks=json.dumps({'Name': 'Basil'}))
+ assert printed(drawn) == [['[Basil] Ocimum large'], ['[Thyme] small']]
+
+
+def test_an_empty_cell_leaves_a_line_of_text(client, drawn):
+ print_the_list(client, '\tOcimum', text=lines('Plant', 'Latin'))
+ assert printed(drawn) == [['Plant', 'Ocimum']]
+
+
+def test_a_cell_with_a_line_break_is_one_label(client, drawn):
+ print_the_list(client, '"Basil\nsweet"\tnorth bed x 2', text=lines('{{blank:Name}}', '{{blank:Bed}}'))
+ assert printed(drawn) == [['Basil', 'sweet', 'north bed']] * 2
+
+
+def test_a_label_without_blanks_takes_the_line_as_its_text(client, drawn):
+ print_the_list(client, 'Basil\nMint x 2', text=lines('Plant', 'Garden 2026'))
+ assert printed(drawn) == [['Basil', 'Garden 2026'], ['Mint', 'Garden 2026'], ['Mint', 'Garden 2026']]
+
+
+def test_a_cell_is_inserted_as_it_is(client, drawn):
+ # Its templates are none, also where the label has no blanks
+ answer = print_the_list(client, '{{counter}} of {{total}}\nASN {{asn}}', text=lines('Plant', 'Box {{counter}}'))
+ assert printed(drawn) == [['{{counter}} of {{total}}', 'Box 1'], ['ASN {{asn}}', 'Box 2']]
+ assert answer['title'] == '{{counter}} of {{total}}'
+
+
+def test_cells_fill_the_lines_of_a_label_without_blanks(client, drawn):
+ print_the_list(client, 'Basil\tOcimum\nMint\tMentha\tSpearmint\tleft out', text=lines('Plant', 'Latin', 'Garden 2026'))
+ assert printed(drawn) == [['Basil', 'Ocimum', 'Garden 2026'], ['Mint', 'Mentha', 'Spearmint']]
+
+
+def test_each_line_keeps_the_settings_of_the_line_it_fills(client, monkeypatch):
+ sizes = []
+ original = SimpleLabel.process_templates
+
+ def keep(self):
+ original(self)
+ if printing():
+ sizes.append([(line['text'], line['size']) for line in self.text])
+ monkeypatch.setattr(SimpleLabel, 'process_templates', keep)
+ text = json.dumps([{'font': 'DejaVu Sans,Bold', 'text': 'Plant', 'size': '60'}, {'font': 'DejaVu Sans,Book', 'text': 'x', 'size': '30'}])
+ print_the_list(client, 'Basil\tOcimum', text=text)
+ assert sizes == [[('Basil', '60'), ('Ocimum', '30')]]
+
+
+def test_a_code_that_takes_the_text_takes_the_line(client, monkeypatch):
+ codes, made = [], label._barcode_image
+
+ def keep(barcode_class, barcode_type, value, *args):
+ if printing():
+ codes.append(value)
+ return made(barcode_class, barcode_type, value, *args)
+ monkeypatch.setattr(label, '_barcode_image', keep)
+ print_the_list(client, 'Basil\nThyme', text=lines('Plant'), print_type='qrcode_text', barcode_type='code128', code_text='')
+ assert codes == ['Basil', 'Thyme']
+
+
+def test_blanks_of_the_code_are_filled_after_those_of_the_text(client, drawn):
+ print_the_list(client, 'Basil\tB-1\nThyme\tT-2', text=lines('{{blank:Name}}'), print_type='qrcode_text', code_text='SKU {{blank:SKU}}')
+ assert printed(drawn) == [['Basil', 'SKU B-1'], ['Thyme', 'SKU T-2']]
+
+
+def test_a_code_not_drawn_takes_none_of_the_cells(client, drawn):
+ # A text label keeps the code of another layout, its blanks are not shown
+ print_the_list(client, 'Basil', text=lines('Plant'), print_type='text', code_text='{{blank:SKU}}')
+ assert printed(drawn) == [['Basil']]
+
+
+def test_a_line_refused_refuses_the_whole_list(client, drawn):
+ fields = json.dumps({'Pot': {'type': 'choice', 'choices': ['small', 'large']}})
+ assert refused(client, text=lines('{{blank:Pot}}'), fields=fields, list='small x 2\nlarge\nhuge') == 'A value is none of the choices of its blank'
+ assert refused(client, text=lines('Item'), print_type='qrcode_text', barcode_type='ean13', code_text='{{blank:EAN}}',
+ list='4006381333931\n4006381333932') == 'The check digit of EAN-13 must be 1'
+ assert refused(client, text=lines('Item'), print_type='qrcode_text', barcode_type='code39', code_text='{{blank:Part}}',
+ list='AB-1\nab!c') == 'The barcode has characters its type does not allow'
+ assert refused(client, text=lines('Item'), print_type='qrcode_text', barcode_type='MICROQR', code_text='{{blank:Code}}',
+ list='A1\n' + 'A' * 40) == 'The Micro QR code holds too much text'
+ assert printed(drawn) == []
+
+
+def test_a_line_too_large_refuses_the_whole_list(client, drawn):
+ # Along the tape the label grows with its text, the long cell beyond what a label may be
+ assert refused(client, orientation='rotated', list='Basil\n' + 'B' * 9000 + '\nThyme') == 'Label is too large'
+ assert printed(drawn) == []
+
+
+def test_a_line_too_small_for_the_frame_refuses_the_whole_list(client, drawn):
+ # Along the tape the label is as long as its text, the frame keeps its distance from the ends
+ assert refused(client, orientation='rotated', border_thickness='2', border_distance_x='300',
+ list='Basil basil basil basil basil\nB') == 'Invalid border rectangle'
+ assert printed(drawn) == []
+
+
+def test_each_line_is_checked_without_being_drawn(client, monkeypatch):
+ drawn, checked = [], []
+ generate, check = SimpleLabel.generate, SimpleLabel.check
+ monkeypatch.setattr(SimpleLabel, 'generate', lambda self: drawn.append(printing()) or generate(self))
+ monkeypatch.setattr(SimpleLabel, 'check', lambda self: checked.append(printing()) or check(self))
+ print_the_list(client, 'A1\nB2 x 2\nC3', text=lines('{{blank:Code}}'), print_type='qrcode_text', code_text='')
+ # The request draws the first label, the other lines are only checked, the queue draws them
+ assert (drawn.count(False), checked) == (1, [False, False]) and drawn.count(True) >= 3
+
+
+def test_a_label_without_text_or_blanks_takes_no_list(client):
+ assert refused(client, text='[]', list='Basil') == print_list.NO_PLACE
+
+
+def test_an_empty_list_prints_as_without_one(client, drawn):
+ answer = print_the_list(client, ' \n\t\n', text=lines('Plant {{blank:Name}}'), blanks=json.dumps({'Name': 'Sage'}), print_count='2')
+ assert answer['labels'] == 2 and printed(drawn) == [['Plant Sage'], ['Plant Sage']]
+
+
+def test_copies_print_each_line_as_often(client, drawn):
+ answer = print_the_list(client, 'Basil\nThyme x 2', print_count='2')
+ assert answer['labels'] == 6
+ assert printed(drawn) == [['Basil']] * 2 + [['Thyme']] * 4
+
+
+def test_the_counter_counts_every_label_of_the_list(client, drawn):
+ print_the_list(client, 'Basil x 2\nThyme', text=lines('{{blank:Name}} {{counter}} of {{total}}'))
+ assert printed(drawn) == [['Basil 1 of 3'], ['Basil 2 of 3'], ['Thyme 3 of 3']]
+
+
+@pytest.mark.parametrize('collate, names', [('1', ['Basil', 'Basil', 'Thyme', 'Thyme']), ('0', ['Basil', 'Thyme', 'Basil', 'Thyme'])])
+def test_each_line_prints_every_file(client, drawn, collate, names):
+ black = Image.new('L', (300, 200), 'black')
+ files = [(io.BytesIO(_upload(black, name).stream.read()), name, 'image/png') for name in ('a.png', 'b.png')]
+ answer = print_the_list(client, 'Basil\nThyme', print_type='image', image=files, collate=collate)
+ assert answer['labels'] == 4 and printed(drawn) == [[name] for name in names]
+
+
+@pytest.mark.parametrize('values', [{'list': '\n'.join(f'Plant {n}' for n in range(101))}, {'list': 'Basil x 60\nThyme', 'print_count': '2'}])
+def test_a_list_of_more_labels_than_a_job_takes_is_refused(client, drawn, values):
+ assert refused(client, **values) == 'A list prints at most 100 labels. Split it.'
+ assert printed(drawn) == []
+
+
+def test_the_limit_is_the_one_configured(client):
+ client.application.config['PRINT_MAX_COUNT'] = 3
+ told = 'A list prints at most 3 labels. Split it.'
+ assert refused(client, list='Basil x 4') == told
+ assert refused(client, path='preview', list='Basil\nThyme', print_count='2') == told
+
+
+@pytest.mark.parametrize('values, told', [
+ ({'list': 'Basil x 200'}, 'A list prints at most 100 labels. Split it.'),
+ ({'list': 'Basil', 'text': '[]'}, 'Add text or a blank to the label to print a list'),
+])
+def test_a_refused_list_is_told_apart_from_the_label(client, values, told):
+ response = client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': lines('{{blank:Name}}'), **values})
+ assert response.status_code == 400 and response.get_json() == {'success': False, 'message': told, 'of': 'list'}
+ label = client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': lines('{{blank:Name}}'), 'list': 'Basil', 'border_distance_x': '9999',
+ 'border_thickness': '1'})
+ assert label.status_code == 400 and 'of' not in label.get_json()
+
+
+def test_the_preview_shows_the_first_line(client, drawn):
+ response = client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': lines('Plant {{blank:Name}}'), 'list': '\nBasil x 2\nThyme',
+ 'print_count': '2'})
+ assert response.status_code == 200
+ assert [texts for _, texts in drawn] == [['Plant Basil']]
+
+
+@pytest.mark.parametrize('listed, filled', [
+ ('Basil\tOcimum\nThyme', ['Name']),
+ ('Basil\tOcimum\nThyme\tThymus\tMay', ['Name', 'Latin']),
+ ('\tOcimum\nThyme\tThymus', ['Latin']),
+ ('Basil x 2', ['Name']),
+])
+def test_the_preview_tells_the_blanks_every_line_fills(client, listed, filled):
+ text = lines('{{blank:Name}} {{blank:Latin}}', 'Sown {{blank:Sown}}')
+ response = client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': text, 'list': listed})
+ assert json.loads(response.headers['X-List-Filled']) == filled
+
+
+def test_the_preview_tells_no_blanks_without_them_or_a_list(client):
+ without_blanks = client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': lines('Plant'), 'list': 'Basil'})
+ without_list = client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': lines('{{blank:Name}}')})
+ assert 'X-List-Filled' not in without_blanks.headers and 'X-List-Filled' not in without_list.headers
+
+
+def test_the_preview_counts_the_labels_of_the_list(client, drawn):
+ client.post(f'{API}/preview', data={**EXAMPLE_FORMDATA, 'text': lines('{{blank:Name}} {{counter}}/{{total}}'), 'list': 'Basil x 3\nThyme'})
+ assert [texts for _, texts in drawn] == [['Basil 1/4']]
+
+
+@pytest.fixture
+def office(client):
+ for setting in ({'demo_model': 'Other/Office'}, {'label_size': 'sheet-l7160'}):
+ assert client.post(f'{API}/settings', data={'printer': 'simulation', **setting}).status_code == 200
+ return client
+
+
+@pytest.fixture
+def pages(monkeypatch):
+ """The pages the demo printer got."""
+ kept = []
+ monkeypatch.setattr(printer._Simulator, '__call__', lambda self, image, name: kept.append(image))
+ return kept
+
+
+def inked(page: Image.Image) -> list[bool]:
+ return [page.convert('L').crop((x + 10, y + 10, x + 740, y + 440)).getextrema()[0] < 128
+ for x, y in sheets.spots(SIZES['sheet-l7160'], False)]
+
+
+def test_a_list_fills_the_labels_of_a_sheet_in_order(office, drawn, pages):
+ text = json.dumps([{'font': 'DejaVu Sans,Book', 'text': '{{blank:Name}}', 'size': '40', 'inverted': True}])
+ response = office.post(f'{API}/print', data={'label_size': 'sheet-l7160', 'text': text, **OFFICE, 'sheet_start': 20, 'list': 'Basil\nThyme x 2'})
+ assert outcome(office, response) == ('printed', '')
+ assert printed(drawn) == [['Basil'], ['Thyme'], ['Thyme']]
+ assert [inked(page) for page in pages] == [[False] * 19 + [True, True], [True] + [False] * 20]
+ assert office.get(f'{API}/settings', query_string={'printer': 'simulation'}).get_json()['continue_at'] == {'sheet-l7160': 2}
+
+
+def test_the_preview_of_a_sheet_tells_the_labels_of_the_list(office, drawn):
+ data = {'label_size': 'sheet-l7160', 'text': lines('{{blank:Name}}'), **OFFICE, 'sheet_start': 20, 'list': 'Basil\nThyme x 2'}
+ response = office.post(f'{API}/preview', data=data)
+ state = json.loads(response.headers['X-Label-Sheet'])
+ assert {key: state[key] for key in ('start', 'filled', 'sheets')} == {'start': 20, 'filled': 1, 'sheets': 2}
+ # The whole sheet shows each label with its line
+ drawn.clear()
+ assert office.post(f'{API}/preview', data={**data, 'whole_sheet': 1}).status_code == 200
+ assert [texts for _, texts in drawn] == [['Basil'], ['Thyme']]
+
+
+@pytest.mark.parametrize('collate, names', [('1', ['Basil', 'Basil', 'Thyme', 'Thyme']), ('0', ['Basil', 'Thyme', 'Basil', 'Thyme'])])
+def test_the_whole_sheet_shows_the_lines_as_they_print(office, drawn, collate, names):
+ # Of several files as sets or grouped, as the print orders them
+ data = {'label_size': 'sheet-l7160', 'text': lines('{{blank:Name}}'), **OFFICE, 'list': 'Basil\nThyme', 'labels_per_copy': 2,
+ 'collate': collate, 'whole_sheet': 1}
+ assert office.post(f'{API}/preview', data=data).status_code == 200
+ assert [texts for _, texts in drawn] == [[name] for name in names]
+
+
+def test_the_history_tells_the_labels_and_prints_the_list_again(client, drawn):
+ answer = print_the_list(client, 'Basil\nThyme x 2', text=lines('{{blank:Name}} {{counter}}/{{total}}'))
+ entry = next(told for told in client.get(f'{API}/history').get_json()['entries'] if told['id'] == answer['job'])
+ assert (entry['labels'], entry['copies']) == (3, 1)
+ drawn.clear()
+ again = client.post(f'{API}/history/{answer["job"]}/print', data={'printer': 'simulation'})
+ assert outcome(client, again) == ('printed', '')
+ assert printed(drawn) == [['Basil 1/3'], ['Thyme 2/3'], ['Thyme 3/3']]
+ drawn.clear()
+ twice = client.post(f'{API}/history/{answer["job"]}/print', data={'printer': 'simulation', 'print_count': '2'})
+ assert outcome(client, twice) == ('printed', '') and twice.get_json()['labels'] == 6
+ assert printed(drawn) == [[f'Basil {n}/6'] for n in (1, 2)] + [[f'Thyme {n}/6'] for n in (3, 4, 5, 6)]
+
+
+@pytest.mark.parametrize('path, name', [('repository/print', 'Plant'), ('demos/print', None)])
+def test_a_saved_or_demo_label_prints_a_list(client, drawn, path, name):
+ if name:
+ saved = client.post(f'{API}/repository/save', json={'name': name, 'label_size': '62', 'text': json.loads(lines('Plant {{blank:Name}}'))})
+ assert saved.status_code == 200, saved.get_json()
+ else:
+ name = next(label['id'] for category in client.get(f'{API}/demos/list').get_json()['categories'] for label in category['labels']
+ if label['label_size_id'] == '62')
+ key = 'name' if path.startswith('repository') else 'id'
+ # In a JSON body also as its lines
+ response = client.post(f'{API}/{path}', json={key: name, 'printer': 'simulation', 'list': ['Basil x 2', 'Thyme'], 'print_count': 1})
+ assert outcome(client, response) == ('printed', ''), response.get_json()
+ assert response.get_json()['labels'] == 3
+ form = client.post(f'{API}/{path}', data={key: name, 'printer': 'simulation', 'list': 'Sage'})
+ assert outcome(client, form) == ('printed', '') and form.get_json()['labels'] == 1
+ refusal = client.post(f'{API}/{path}', data={key: name, 'printer': 'simulation', 'list': 'Sage x 200'})
+ assert (refusal.status_code, refusal.get_json()['message']) == (400, 'A list prints at most 100 labels. Split it.')
+ for value in (None, 7, ['Sage', 7]):
+ refusal = client.post(f'{API}/{path}', json={key: name, 'printer': 'simulation', 'list': value})
+ assert (refusal.status_code, refusal.get_json()['message']) == (400, 'list must be a text or a list of texts')
+
+
+def test_a_saved_label_fills_its_blanks_from_the_list(client, drawn):
+ saved = client.post(f'{API}/repository/save', json={'name': 'Plant', 'label_size': '62', 'text': json.loads(lines('Plant {{blank:Name}}'))})
+ assert saved.status_code == 200
+ response = client.post(f'{API}/repository/print', data={'name': 'Plant', 'printer': 'simulation', 'list': 'Basil\nThyme'})
+ assert outcome(client, response) == ('printed', '')
+ assert printed(drawn) == [['Plant Basil'], ['Plant Thyme']]
+
+
+def test_a_list_job_left_in_the_queue_prints_its_lines_after_a_restart(tmp_path, monkeypatch, queued, drawn):
+ monkeypatch.setattr(print_store, 'ENABLED', True)
+ monkeypatch.setattr(print_store, 'FOLDER', None)
+ monkeypatch.setattr(print_queue, 'STOP_WAIT', 0.1)
+ client = make_client(tmp_path, empty_repo=True)
+ print_queue.stop()
+ response = client.post(f'{API}/print', data={**EXAMPLE_FORMDATA, 'printer': 'simulation', 'text': lines('{{blank:Name}}'), 'list': 'Basil\nThyme'})
+ job = response.get_json()['job']
+ queue = os.path.join(client.application.config['LABEL_REPOSITORY_DIR'], print_store.QUEUE)
+ with open(os.path.join(queue, f'{job}.json')) as kept:
+ assert json.load(kept)['list'] == {'lines': [[['Basil'], 1], [['Thyme'], 1]], 'rows': [0, 1]}
+ print_queue.reset()
+ print_store.close()
+ make_client(tmp_path, empty_repo=True)
+ assert print_queue.get(job).done.wait(10)
+ assert printed(drawn) == [['Basil'], ['Thyme']]
+ print_store.close()
diff --git a/tests/browser/test_print_list.py b/tests/browser/test_print_list.py
new file mode 100644
index 000000000..1d600b8b8
--- /dev/null
+++ b/tests/browser/test_print_list.py
@@ -0,0 +1,172 @@
+"""Print a list from the label designer: the arrow beside Print opens a box
+for the list, the preview shows its first line, Print sends it and the
+server prints a label for each line. Closed, Print prints as before."""
+import json
+
+from tests.browser.test_editor import editor, sent, type_label, wait_for_preview # noqa: F401
+from tests.browser.test_media import pdf
+
+
+def preview_after(page, action, listed=None) -> dict:
+ """The fields of the preview request an action leads to, with listed of
+ the one that sends that list, e.g. typed key by key."""
+ def asked(r):
+ return r.url.endswith('/api/preview') and r.method == 'POST' and (listed is None or sent(r).get('list') == listed)
+ with page.expect_request(asked) as request:
+ action()
+ wait_for_preview(page)
+ return sent(request.value)
+
+
+def printed(page) -> tuple[dict, dict]:
+ """The fields of the print request Print sends and its answer."""
+ with page.expect_response('**/api/print') as answer:
+ page.click('#print')
+ assert answer.value.ok
+ return sent(answer.value.request), answer.value.json()
+
+
+def open_list(page):
+ page.click('#printMore')
+ page.wait_for_selector('.print-menu')
+ assert page.get_attribute('#printMore', 'aria-expanded') == 'true'
+ assert page.inner_text('.print-menu') == 'Print a list'
+ page.click('#printListOpen')
+ page.wait_for_selector('#listBox:not([hidden]) #printList')
+ assert page.locator('.print-menu').count() == 0 and page.get_attribute('#printMore', 'aria-expanded') == 'false'
+
+
+def marked(page) -> list:
+ """The blanks Fill in marks as still to fill in."""
+ return page.eval_on_selector_all('#fill input.need', 'inputs => inputs.map(i => i.dataset.blank)')
+
+
+def test_print_a_list_of_names(editor): # noqa: F811
+ type_label(editor, 'Plant [Name] [Kind]')
+ editor.wait_for_function("() => labelEditor.S.edit.design.text[0].text === 'Plant {{blank:Name}} {{blank:Kind}}'")
+ wait_for_preview(editor)
+ # Hidden until it is asked for
+ assert editor.locator('#listBox').is_hidden()
+ open_list(editor)
+ assert editor.evaluate('() => document.activeElement.id') == 'printList'
+ assert editor.text_content('#listBox label') == 'One label per line'
+ assert editor.inner_text('#listBox small') == 'Add x 3 for 3 labels'
+ assert marked(editor) == ['Name', 'Kind']
+ # The server shows the first line; the blank no line fills still waits to be filled in
+ request = preview_after(editor, lambda: editor.keyboard.type('Basil x 2\nThyme'), 'Basil x 2\nThyme')
+ assert request['print_count'] == '1'
+ editor.wait_for_function("() => document.querySelectorAll('#fill input.need').length === 1")
+ assert marked(editor) == ['Kind'] and editor.inner_text('#fillN') == '1 to fill in'
+ # A list refused is told on its own, the blanks known to be filled stay so
+ editor.fill('#printList', 'Basil x 500')
+ editor.wait_for_selector('#labelbox.failed')
+ assert editor.inner_text('#fits') == 'A list prints at most 100 labels. Split it.'
+ assert marked(editor) == ['Kind'] and editor.is_disabled('#print')
+ # Cells from a spreadsheet fill both
+ listed = 'Basil\tsweet x 2\nThyme\tcommon'
+ preview_after(editor, lambda: editor.fill('#printList', listed), listed)
+ editor.wait_for_function("() => !document.querySelector('#fill input.need')")
+ assert editor.is_hidden('#fillN')
+ fields, answer = printed(editor)
+ assert fields['list'] == listed and json.loads(fields['text'])[0]['text'] == 'Plant {{blank:Name}} {{blank:Kind}}'
+ assert (answer['labels'], answer['title']) == (3, 'Plant Basil sweet')
+ editor.wait_for_selector('#toast:has-text("Printed 3 labels")')
+ entry = editor.evaluate('() => labelEditor.S.history[0]')
+ assert (entry['list'], entry['labels'], entry['copies']) == (listed, 3, 1)
+ # Printed again from its message, the whole list
+ with editor.expect_request('**/api/print') as again:
+ editor.click('#toast button')
+ assert sent(again.value)['list'] == listed
+ editor.wait_for_function("() => labelEditor.S.history.length === 2 && labelEditor.S.history[0].state === 'printed'")
+ # Closed, Print prints as before; the preview without it is the one shown before
+ editor.click('#listClose')
+ wait_for_preview(editor)
+ assert editor.locator('#listBox').is_hidden() and marked(editor) == ['Name', 'Kind']
+ fields, answer = printed(editor)
+ assert 'list' not in fields and answer['labels'] == 1
+
+
+def test_copies_of_a_list_are_counted_by_the_server(editor): # noqa: F811
+ type_label(editor, 'Plant [Name]')
+ open_list(editor)
+ preview_after(editor, lambda: editor.fill('#printList', 'Basil\nThyme x 2'), 'Basil\nThyme x 2')
+ request = preview_after(editor, lambda: (editor.fill('#copies', '2'), editor.dispatch_event('#copies', 'input')))
+ assert request['print_count'] == '2' and request['list'] == 'Basil\nThyme x 2'
+ fields, answer = printed(editor)
+ assert fields['print_count'] == '2' and answer['labels'] == 6
+ editor.wait_for_selector('#toast:has-text("Printed 6 labels")')
+ assert editor.evaluate('() => labelEditor.S.history[0].labels') == 6
+
+
+def test_the_message_counts_the_labels_of_the_pages_printed(editor): # noqa: F811
+ editor.set_input_files('#imageFile', files=[{'name': 'two.pdf', 'mimeType': 'application/pdf', 'buffer': pdf((200, 100), (100, 200))}])
+ editor.wait_for_selector('#addImage:has-text("PDF added")')
+ editor.click('#ltb [data-more]')
+ editor.wait_for_selector('.media-menu:has-text("This PDF has 2 pages")')
+ preview_after(editor, lambda: editor.click('.media-menu [data-allpages]'))
+ editor.keyboard.press('Escape')
+ # One copy of both pages, as the print answer tells it
+ _, answer = printed(editor)
+ assert answer['labels'] == 2 and editor.input_value('#copies') == '1'
+ editor.wait_for_selector('#toast:has-text("Printed 2 labels")')
+
+
+def test_an_empty_label_prints_the_lines_of_a_list(editor): # noqa: F811
+ assert editor.is_disabled('#print')
+ open_list(editor)
+ # A list without a line prints nothing more than the empty label
+ editor.keyboard.type(' \n')
+ assert editor.is_disabled('#print')
+ preview_after(editor, lambda: editor.keyboard.type('Basil\nThyme'), ' \nBasil\nThyme')
+ editor.wait_for_function("() => !document.querySelector('#print').disabled")
+ fields, answer = printed(editor)
+ assert answer['labels'] == 2 and answer['title'] == 'Basil'
+ # Too many for one job: the preview says so and Print waits
+ editor.fill('#printList', 'Basil x 500')
+ editor.wait_for_selector('#labelbox.failed')
+ assert editor.inner_text('#fits') == 'A list prints at most 100 labels. Split it.'
+ assert editor.is_disabled('#print')
+
+
+def test_print_waits_for_the_answer_to_send_again(editor): # noqa: F811
+ type_label(editor, 'Plant [Name]')
+ open_list(editor)
+ preview_after(editor, lambda: editor.fill('#printList', 'Basil\nThyme'), 'Basil\nThyme')
+ held = []
+ editor.route('**/api/print', lambda route: held.append(route))
+ editor.click('#print')
+ editor.wait_for_function("() => document.querySelector('#print').disabled")
+ # Neither Print nor Ctrl+Enter sends it once more meanwhile
+ editor.click('#print', force=True)
+ editor.keyboard.press('Control+Enter')
+ editor.wait_for_timeout(300)
+ assert len(held) == 1
+ with editor.expect_response('**/api/print') as answer:
+ held[0].continue_()
+ assert answer.value.json()['labels'] == 2
+ editor.wait_for_function("() => !document.querySelector('#print').disabled")
+ editor.wait_for_selector('#toast:has-text("Printed 2 labels")')
+ assert len(held) == 1
+
+
+def test_escape_and_a_click_elsewhere_close_the_menu(editor): # noqa: F811
+ editor.click('#printMore')
+ editor.wait_for_selector('.print-menu')
+ editor.keyboard.press('Escape')
+ editor.wait_for_selector('.print-menu', state='detached')
+ editor.click('#printMore')
+ editor.wait_for_selector('.print-menu')
+ editor.click('#stage', position={'x': 20, 'y': 300})
+ editor.wait_for_selector('.print-menu', state='detached')
+ assert editor.locator('#listBox').is_hidden()
+
+
+def test_another_label_starts_without_the_list(editor): # noqa: F811
+ type_label(editor, 'Plant [Name]')
+ open_list(editor)
+ preview_after(editor, lambda: editor.keyboard.type('Basil'), 'Basil')
+ editor.click('#newLabel')
+ editor.wait_for_selector('.dialog #newDiscard')
+ editor.click('#newDiscard')
+ editor.wait_for_function("() => labelEditor.S.edit.design.text[0].text === ''")
+ assert editor.locator('#listBox').is_hidden() and editor.evaluate('() => labelEditor.S.edit.list') is None
diff --git a/tests/label/test_cable_flag.py b/tests/label/test_cable_flag.py
index 2d8842138..96e190d4e 100644
--- a/tests/label/test_cable_flag.py
+++ b/tests/label/test_cable_flag.py
@@ -8,7 +8,7 @@
from PIL import Image, ImageChops
from app.labeldesigner import label as label_module
-from app.labeldesigner.cable_flag import wrap_dots
+from app.labeldesigner.cable_flag import flag_size, wrap_dots
from app.labeldesigner.routes import create_label_from_request
from tests.helpers import _red_square, _upload, EXAMPLE_FORMDATA, make_client, outcome, TEXT
@@ -186,3 +186,19 @@ def test_too_large_flag_is_refused(client, monkeypatch):
monkeypatch.setattr(label_module, 'MAX_LABEL_PIXELS', 2 * plain.width * plain.height)
with pytest.raises(ValueError, match='Label is too large'):
_render(client, cable_flag='1')
+
+
+@pytest.mark.parametrize('orientation', ['standard', 'rotated'])
+def test_the_size_of_a_flag_is_known_before_it_is_drawn(client, orientation):
+ flag, plain = _flag_and_plain(client, orientation=orientation)
+ assert flag_size(plain.size, WRAP, orientation == 'rotated') == flag.size
+
+
+def test_a_check_refuses_a_too_large_flag_without_drawing_it(client, monkeypatch):
+ plain = _render(client)
+ monkeypatch.setattr(label_module, 'MAX_LABEL_PIXELS', 2 * plain.width * plain.height)
+ monkeypatch.setattr(label_module, 'flag_strip', lambda *args: pytest.fail('The flag was drawn'))
+ with client.application.test_request_context():
+ label = create_label_from_request(_data(cable_flag='1'))
+ with pytest.raises(ValueError, match='Label is too large'):
+ label.check()