فهرست منبع

Inventory: a long name continues on the next line of a label (#3621)
- Every label line was one line, cut off with an ellipsis, also with
room below it; a Chinese filament name on the 40 x 30 box label
lost all but five to seven characters
- A line now continues on up to three lines while every ticked line
below still gets its own, breaking at spaces and between Chinese
or Japanese characters, never splitting a Latin word next to them
or a closing bracket or comma from its word

maziggy 1 روز پیش
والد
کامیت
6677343ad8
3فایلهای تغییر یافته به همراه155 افزوده شده و 7 حذف شده
  1. 1 0
      CHANGELOG.md
  2. 56 7
      backend/app/services/label_renderer.py
  3. 98 0
      backend/tests/unit/services/test_label_renderer_fields.py

+ 1 - 0
CHANGELOG.md

@@ -15,6 +15,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **A long colour or filament name continues on the next line of a spool label (#3621, reported by @mohan456-wqs)** — Every line of a label got one line of text, cut off with "…" when it was too wide, also where the label had room below it. On the 40 × 30 box label the column beside the QR code holds only five to seven Chinese characters, so a Chinese filament name was cut after a few. A line that is too wide now continues on up to three lines, as long as every line ticked below it still gets its own; only what still doesn't fit is cut. Lines break at spaces, and between Chinese or Japanese characters, which have none, without separating a closing bracket or comma from the word before it. Labels whose lines fit look as before.
 - **The QR scanner reads a photo of a small spool label (#3616, reported by @balin77)** — **Take photo** answered "No QR code found in the photo" when the label filled only a small part of the photo, although the phone's camera app read it at once. Where the browser has no QR decoder of its own (every iPhone, and every phone with Bambuddy opened over plain HTTP, where the photo is the only way to scan), the photo was scaled down to 1600 pixels before it was read, and a small label lost too much detail. When that finds nothing, the photo is now read again at its own size, up to 4096 pixels on the long side, which phone browsers can still handle. This takes under a second more, and only for a photo the first read could not read.
 - **An archive printed more than once shows what all its prints cost (#3609, reported by @RafalHo)** — Each plate of a multi-plate file printed one at a time is a print of the same archive, and so is a reprint. The archive card showed the file's filament and cost (all plates together) next to the first print's energy, so a seven-plate print showed the electricity of plate 1 only and matched neither one plate nor Statistics. An archive with more than one print now shows the totals of all of them: the filament they used, its cost, the energy and the wear, as Statistics adds them up, with "Total of N prints" on hover. An energy total is left out when no print was measured by a smart plug. Each print's own figures stay in the Print Log behind the prints badge; archives printed once are unchanged.
 - **A spool's slicer preset can be removed, and opening the field no longer loses its name (#3596, reported by @dertbv)** — the Slicer Preset field in the spool form had no way to remove a preset, so a configured spool could not go back to Stock, in an edit or a copy. Clicking into the field also emptied it, and saving then kept the preset but stored no name for it when the preset was not in the current list, for example a Bambu Cloud preset while the cloud list was unavailable. The spool then showed the raw preset code. The field now has a remove button, closing the list without picking shows the preset again, and text typed to search is never saved as the preset's name. The same applies to the SpoolBuddy write-tag page.

+ 56 - 7
backend/app/services/label_renderer.py

@@ -44,6 +44,7 @@ for label-printer software that takes images.
 from __future__ import annotations
 
 import io
+import unicodedata
 from dataclasses import dataclass
 from datetime import date
 from pathlib import Path
@@ -366,6 +367,48 @@ def _truncate_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, m
     return text + ell if text else ell
 
 
+def _is_wide(ch: str) -> bool:
+    return unicodedata.east_asian_width(ch) in ("W", "F")
+
+
+# Punctuation that never starts a line, nor ends one, in Chinese and Japanese.
+_NO_LINE_START = frozenset("、。,.,.:;!?)】」』〉》〕}ー々")
+_NO_LINE_END = frozenset("(【「『〈《〔{")
+
+
+def _breaks_before(text: str, p: int) -> bool:
+    """Whether a line may break before ``text[p]``."""
+    if text[p] == " ":
+        return True
+    if text[p] in _NO_LINE_START or text[p - 1] in _NO_LINE_END:
+        return False
+    return _is_wide(text[p - 1]) or _is_wide(text[p])
+
+
+def _wrap_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, max_w: float, max_lines: int) -> list[str]:
+    """Break ``text`` into at most ``max_lines`` lines of ``max_w`` points
+    (#3621). A line breaks at its last space, or next to a Chinese, Japanese
+    or Korean character, which run on without spaces; a word too long for a
+    line breaks inside it. What is left after the last line is cut with an
+    ellipsis."""
+    lines: list[str] = []
+    rest = text
+    while len(lines) < max_lines - 1 and _text_width(rest, font, size) > max_w:
+        cut = 1  # at least one character a line, however narrow the column
+        while cut < len(rest) and _text_width(rest[: cut + 1], font, size) <= max_w:
+            cut += 1
+        at = next((p for p in range(cut, 0, -1) if _breaks_before(rest, p)), cut)
+        lines.append(rest[:at].rstrip())
+        rest = rest[at:].lstrip()
+    if rest:
+        lines.append(_truncate_to_width(c, rest, font, size, max_w))
+    return lines
+
+
+# The most lines one row of the roomy layout may take.
+_ROW_MAX_LINES = 3
+
+
 def _draw_label(
     c: rl_canvas.Canvas,
     x: float,
@@ -558,16 +601,22 @@ def _draw_label_roomy(
         ("added", data.added.isoformat() if data.added else "", FONT_REGULAR, 6.5, 1.2),
     ]
 
+    active = [row for row in rows if row[0] in fields and row[1]]
     cursor_y = y + h - pad
-    for field, text, font, size, gap in rows:
-        if field not in fields or not text:
-            continue
+    for i, (_field, text, font, size, gap) in enumerate(active):
         if cursor_y - size < floor_y:
             break
-        c.setFont(font, size)
-        cursor_y -= size
-        _draw_text(c, text_x, cursor_y, _truncate_to_width(c, text, font, size, text_w), font, size)
-        cursor_y -= gap
+        # A row too wide for the column continues on further lines, as long
+        # as every row below it still gets a line of its own (#3621).
+        below = sum(s + g for _f, _t, _fo, s, g in active[i + 1 :])
+        room = 1
+        while room < _ROW_MAX_LINES and cursor_y - (room + 1) * (size + gap) - below >= floor_y:
+            room += 1
+        for line in _wrap_to_width(c, text, font, size, text_w, room):
+            c.setFont(font, size)
+            cursor_y -= size
+            _draw_text(c, text_x, cursor_y, line, font, size)
+            cursor_y -= gap
 
     if show_id:
         c.setFont(FONT_BOLD, id_size)

+ 98 - 0
backend/tests/unit/services/test_label_renderer_fields.py

@@ -20,6 +20,7 @@ from backend.app.services.label_renderer import (
     ALL_LABEL_FIELDS,
     DEFAULT_LABEL_FIELDS,
     LabelData,
+    _breaks_before,
     _draw_label,
     label_size_mm,
     pdf_to_pngs,
@@ -210,3 +211,100 @@ def test_qr_stays_black_and_white_in_the_png():
     qr_region = image.crop((w // 2, 0, w, h))
     greys = sum(1 for v in qr_region.getdata() if 40 < v < 215)
     assert greys / (qr_region.width * qr_region.height) < 0.02
+
+
+# ── Long rows continue on further lines (#3621) ──────────────────────────────
+
+ZH_NAME = "【快打】亚光PETG 哑光黑色 高速"
+
+
+def _lines(
+    data: LabelData, fields=DEFAULT_LABEL_FIELDS, monochrome: bool = True, size_mm: tuple[int, int] = (40, 30)
+) -> list[str]:
+    """The text drawn on a label, 40 x 30 unless given, one entry per line, top to bottom.
+    A line with Chinese is drawn in pieces, one per font, on one baseline."""
+    drawn: dict[float, str] = {}
+    real = rl_canvas.Canvas.drawString
+
+    def record(self, x, y, text, *args, **kwargs):
+        drawn[round(y, 2)] = drawn.get(round(y, 2), "") + text
+        return real(self, x, y, text, *args, **kwargs)
+
+    w, h = size_mm[0] * mm, size_mm[1] * mm
+    c = rl_canvas.Canvas(io.BytesIO(), pagesize=(w, h))
+    with patch.object(rl_canvas.Canvas, "drawString", record):
+        _draw_label(c, 0, 0, w, h, data, monochrome, fields)
+    return [drawn[y] for y in sorted(drawn, reverse=True)]
+
+
+def _name_lines(lines: list[str]) -> list[str]:
+    """The lines between the hex code and the next row or the spool ID."""
+    start = lines.index("#E8F0E0") + 1
+    return [line for line in lines[start:] if line not in ("Shelf 2", "#128")]
+
+
+def test_a_long_chinese_name_continues_on_the_next_lines():
+    lines = _name_lines(_lines(_data(name=ZH_NAME, storage_location=None)))
+
+    assert len(lines) > 1
+    # Nothing is lost but a space where a line breaks.
+    assert "".join(lines).replace(" ", "") == ZH_NAME.replace(" ", "")
+    assert not any(line.endswith("…") for line in lines)
+
+
+def test_a_latin_word_is_not_broken_next_to_chinese():
+    lines = _name_lines(_lines(_data(name=ZH_NAME, storage_location=None)))
+
+    assert any(line.startswith("PETG") or line.endswith("PETG") for line in lines)
+    assert not any(line.startswith("】") for line in lines)
+
+
+def test_a_long_latin_name_breaks_at_spaces():
+    name = "Matte Charcoal Black"
+    lines = _name_lines(_lines(_data(name=name, storage_location=None)))
+
+    assert len(lines) > 1
+    assert " ".join(lines) == name
+
+
+def test_the_row_below_keeps_its_line():
+    """The name takes no line the location needs: it is cut sooner instead."""
+    lines = _lines(_data(name=ZH_NAME, storage_location="Shelf 2"))
+
+    assert "Shelf 2" in lines
+    assert "#128" in lines
+    assert _name_lines(lines)[-1].endswith("…")
+
+
+def test_a_row_takes_at_most_three_lines():
+    """Also on a label with room for more."""
+    lines = _name_lines(_lines(_data(name="Charcoal " * 30, storage_location=None), size_mm=(75, 55)))
+
+    assert len(lines) == 3
+    assert lines[-1].endswith("…")
+
+
+def test_wrapped_lines_stay_above_the_spool_id():
+    drawn: list[tuple[float, str]] = []
+    real = rl_canvas.Canvas.drawString
+
+    def record(self, x, y, text, *args, **kwargs):
+        drawn.append((y, text))
+        return real(self, x, y, text, *args, **kwargs)
+
+    with patch.object(rl_canvas.Canvas, "drawString", record):
+        _text("box_40x30", _data(name="Charcoal " * 12, storage_location=None, note="Dry first " * 6), ALL)
+
+    id_y = next(y for y, text in drawn if text == "#128")
+    assert min(y for y, text in drawn if text != "#128") >= id_y + 16
+
+
+def test_chinese_punctuation_stays_with_its_word():
+    """A line never starts with a closing bracket or comma, nor ends with an
+    opening bracket."""
+    assert not _breaks_before("快打】", 2)
+    assert not _breaks_before("快,打", 1)
+    assert not _breaks_before("【快", 1)
+    assert _breaks_before("快打", 1)
+    assert _breaks_before("光PETG", 1)
+    assert not _breaks_before("PETG", 1)