From 05d0c80dc06aaada2d73b63bfc599b6874a60b06 Mon Sep 17 00:00:00 2001 From: Derek Stotz Date: Mon, 5 May 2025 13:08:22 -0500 Subject: [PATCH] Add measurement labels with new label_format option Adds a new label_format option that can be used to specify an option to allow for displaying measurements of a part instead of or in addition to the generators provided label. Made description the default option to preserve existing behavior. --- boxes/__init__.py | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/boxes/__init__.py b/boxes/__init__.py index 7ce138be4..6b1c79280 100755 --- a/boxes/__init__.py +++ b/boxes/__init__.py @@ -374,6 +374,10 @@ def __init__(self) -> None: defaultgroup.add_argument( "--labels", action="store", type=boolarg, default=True, help="label the parts (where available)") + defaultgroup.add_argument( + "--label_format", action="store", type=str, default="label", + choices=["label", "measurements", "label (measurements)"], + help="information to include as label on parts") defaultgroup.add_argument( "--reference", action="store", type=float, default=100.0, help="print reference rectangle with given length (in mm)(zero to disable) [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#reference)") @@ -444,7 +448,7 @@ def open(self): else: self.text(f"{self.reference:.1f}mm, burn:{self.burn:.2f}mm", self.reference / 2.0, 5, fontsize=6, align="middle center", color=Color.ANNOTATIONS) - self.move(self.reference, 10, "up") + self.move(self.reference, 10, "up", label=False) if self.qr_code: self.renderQrCode() self.ctx.stroke() @@ -718,6 +722,25 @@ def adjustSize(self, l, e1=True, e2=True): except TypeError: return l - walls + def formatLabel(self, label: str | bool, width, height): + # Allows passing False to skip labeling + if label == False: + return + + label_format = getattr(self, "label_format", "label") + measurements = f"({width:.2f}mm x {height:.2f}mm)" + + if label_format == "label": + return label + elif label_format == "measurements": + return measurements + elif label_format == "label (measurements)": + if not label: + return measurements + return f"{label}\n{measurements}" + else: + raise ValueError("Unknown label format", label_format) + def render(self): """Implement this method in your subclass. @@ -1218,6 +1241,7 @@ def move(self, x, y, where, before=False, label=""): terms = where.split() dontdraw = before and "only" in terms + width, height = x, y x += self.spacing y += self.spacing @@ -1237,8 +1261,10 @@ def move(self, x, y, where, before=False, label=""): if not before: # restore position self.ctx.restore() - if self.labels and label: - self.text(label, x/2, y/2, align="middle center", color=Color.ANNOTATIONS, fontsize=4) + if self.labels: + contents = self.formatLabel(label, width, height) + if contents: + self.text(contents, x/2, y/2, align="middle center", color=Color.ANNOTATIONS, fontsize=4) self.ctx.stroke() for term in terms: