Initial commit: Avery Label Studio desktop app.
Windows designer for Avery templates with Avery.com Word download, print, and PyInstaller build. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
389e68ab08
26 files changed
+3922
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""Avery Label Studio package."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Avery Label Studio — open-source desktop designer for Avery 60504."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Allow running as `python -m avery_studio` from src/
|
||||
if __package__ is None or __package__ == "":
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
# Stable scaling on Windows high-DPI displays (before QApplication)
|
||||
os.environ.setdefault("QT_ENABLE_HIGHDPI_SCALING", "1")
|
||||
os.environ.setdefault("QT_AUTO_SCREEN_SCALE_FACTOR", "1")
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QGuiApplication
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from avery_studio.main_window import MainWindow
|
||||
|
||||
|
||||
def main() -> int:
|
||||
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
|
||||
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
|
||||
)
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName("Avery Label Studio")
|
||||
app.setOrganizationName("AveryLabelStudio")
|
||||
window = MainWindow()
|
||||
window.show()
|
||||
return app.exec()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
"""App data / template storage paths (Windows LocalAppData)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
APP_FOLDER_NAME = "AveryLabelStudio"
|
||||
|
||||
|
||||
def user_data_dir() -> Path:
|
||||
"""Writable app data root, e.g. %LOCALAPPDATA%\\AveryLabelStudio."""
|
||||
if sys.platform == "win32":
|
||||
base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
||||
else:
|
||||
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
|
||||
path = base / APP_FOLDER_NAME
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def user_templates_dir() -> Path:
|
||||
"""Installed / user-loaded templates live here permanently."""
|
||||
path = user_data_dir() / "templates"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def temp_imports_dir() -> Path:
|
||||
"""
|
||||
Scratch folder for rasterized PDF/Word pages during a session.
|
||||
|
||||
Lives under the OS temp directory — NOT AppData. Cleared/replaced freely.
|
||||
Saved projects copy needed images next to the .json instead.
|
||||
"""
|
||||
path = Path(tempfile.gettempdir()) / APP_FOLDER_NAME / "imports"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def cleanup_legacy_appdata_imports() -> None:
|
||||
"""Remove old permanent AppData\\imports cache if present."""
|
||||
legacy = user_data_dir() / "imports"
|
||||
if legacy.is_dir():
|
||||
try:
|
||||
shutil.rmtree(legacy, ignore_errors=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def bundled_templates_dir() -> Path | None:
|
||||
"""Legacy helper — app no longer ships templates."""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
path = Path(sys._MEIPASS) / "TEMPLATES" # type: ignore[attr-defined]
|
||||
return path if path.is_dir() else None
|
||||
repo = Path(__file__).resolve().parents[2] / "TEMPLATES"
|
||||
return repo if repo.is_dir() else None
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Download official Avery blank Word templates from avery.com."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from .app_paths import user_templates_dir
|
||||
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
# Avery "Download as a Guest" uses this marketing signup before redirecting
|
||||
# to the signed Word blank URL. Email matches the app's guest continue flow.
|
||||
GUEST_EMAIL = "a@a.com"
|
||||
GUEST_SOURCE_ID = "21046"
|
||||
_AVERY_AES_SECRET = "wwjH7clZ8E5v5BsgCqQ5zHYf9OlZ8dCB"
|
||||
|
||||
|
||||
class AveryDownloadError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def avery_template_page_url(product_number: str) -> str:
|
||||
num = product_number.strip()
|
||||
return f"https://www.avery.com/templates/{num}"
|
||||
|
||||
|
||||
def _request_headers(referer: str | None = None) -> dict[str, str]:
|
||||
headers = {
|
||||
"User-Agent": USER_AGENT,
|
||||
"Accept": "application/json, text/html, */*",
|
||||
"Origin": "https://www.avery.com",
|
||||
}
|
||||
if referer:
|
||||
headers["Referer"] = referer
|
||||
return headers
|
||||
|
||||
|
||||
def _fetch_html(url: str) -> str:
|
||||
req = urllib.request.Request(url, headers=_request_headers())
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.read().decode("utf-8", "replace")
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
raise AveryDownloadError(
|
||||
f"No Avery template page found for that number.\n{url}"
|
||||
) from exc
|
||||
raise AveryDownloadError(f"Could not open Avery page ({exc.code}):\n{url}") from exc
|
||||
except Exception as exc:
|
||||
raise AveryDownloadError(f"Network error fetching Avery page:\n{exc}") from exc
|
||||
|
||||
|
||||
def _unescape_avery_html(html: str) -> str:
|
||||
"""Normalize JSON / HTML escapes Avery embeds in template pages."""
|
||||
return (
|
||||
html.replace("\\u0026", "&")
|
||||
.replace("\\/", "/")
|
||||
.replace('\\"', '"')
|
||||
)
|
||||
|
||||
|
||||
def find_word_download_url(html: str) -> tuple[str, str]:
|
||||
"""
|
||||
Return (download_url, suggested_filename) from an Avery template page.
|
||||
|
||||
Avery embeds signed S3 links for Microsoft Word blanks in the page HTML.
|
||||
"""
|
||||
text = _unescape_avery_html(html)
|
||||
# Path must stop at '?' so the signed query (X-Amz-*) is kept — without it
|
||||
# S3 returns 400 for anonymous GETs that use response-content-disposition.
|
||||
match = re.search(
|
||||
r'https://s3\.amazonaws\.com/[^\s"\'<>?]+Downloadables/doc/[^\s"\'<>?]+\.doc'
|
||||
r'(?:\?[^\s"\'<>]*)?',
|
||||
text,
|
||||
re.I,
|
||||
)
|
||||
if not match:
|
||||
raise AveryDownloadError(
|
||||
"Could not find a Microsoft Word blank on that Avery page.\n"
|
||||
"Open the page in your browser and use Import Template File… instead."
|
||||
)
|
||||
url = match.group(0).rstrip("\\").rstrip('"').rstrip("'")
|
||||
fname = "AveryTemplate.doc"
|
||||
fm = re.search(r"filename%3D([^&\"'\\]+)", url, re.I)
|
||||
if fm:
|
||||
from urllib.parse import unquote
|
||||
|
||||
fname = unquote(fm.group(1))
|
||||
else:
|
||||
fm2 = re.search(r"filename=([^&\"'\\]+)", url, re.I)
|
||||
if fm2:
|
||||
from urllib.parse import unquote
|
||||
|
||||
fname = unquote(fm2.group(1))
|
||||
if not fname.lower().endswith(".doc"):
|
||||
fname += ".doc"
|
||||
return url, fname
|
||||
|
||||
|
||||
def _avery_encrypt(plaintext: str) -> str:
|
||||
"""
|
||||
Match Avery avylib CryptoJS AES-128-CBC encrypt used by guest signup.
|
||||
|
||||
Key/IV are Utf8 of the first/second 16 chars of their shared secret;
|
||||
Base64 ciphertext with '/' replaced by 'Avy21Ld'.
|
||||
"""
|
||||
try:
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.primitives import padding
|
||||
except ImportError as exc:
|
||||
raise AveryDownloadError(
|
||||
"Missing dependency 'cryptography' (needed for Avery guest download).\n"
|
||||
"Install it with: pip install cryptography"
|
||||
) from exc
|
||||
|
||||
key = _AVERY_AES_SECRET[:16].encode("utf-8")
|
||||
iv = _AVERY_AES_SECRET[16:32].encode("utf-8")
|
||||
padder = padding.PKCS7(128).padder()
|
||||
padded = padder.update(plaintext.encode("utf-8")) + padder.finalize()
|
||||
encryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
|
||||
ct = encryptor.update(padded) + encryptor.finalize()
|
||||
return base64.b64encode(ct).decode("ascii").replace("/", "Avy21Ld")
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict, referer: str) -> tuple[int, bytes]:
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
headers = _request_headers(referer)
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.status, resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, exc.read() if exc.fp else b""
|
||||
|
||||
|
||||
def continue_as_guest(email: str = GUEST_EMAIL, referer: str | None = None) -> bool:
|
||||
"""
|
||||
Perform Avery's "Download as a Guest" email signup.
|
||||
|
||||
Returns True if Avery acknowledged the guest signup (HTTP 200).
|
||||
checkUser 404 (unknown email) is expected for a guest address.
|
||||
"""
|
||||
ref = referer or "https://www.avery.com/templates"
|
||||
email = email.strip().lower()
|
||||
if not email or "@" not in email:
|
||||
return False
|
||||
|
||||
# Same check the site runs before showing guest vs sign-in
|
||||
_post_json(
|
||||
"https://www.avery.com/account/checkUser",
|
||||
{"email": _avery_encrypt(email)},
|
||||
ref,
|
||||
)
|
||||
|
||||
payload = {
|
||||
"email": email,
|
||||
"optIn": True,
|
||||
"messageTypes": ["promotions"],
|
||||
"sourceid": GUEST_SOURCE_ID,
|
||||
}
|
||||
status, raw = _post_json(
|
||||
"https://www.avery.com/account/email-signup",
|
||||
{"data": _avery_encrypt(json.dumps(payload, separators=(",", ":")))},
|
||||
ref,
|
||||
)
|
||||
if status != 200:
|
||||
return False
|
||||
try:
|
||||
data = json.loads(raw.decode("utf-8", "replace"))
|
||||
except Exception:
|
||||
return True
|
||||
if isinstance(data, dict) and data.get("httpStatusCode") not in (None, 200):
|
||||
return data.get("httpStatusCode") == 200
|
||||
return True
|
||||
|
||||
|
||||
def download_avery_word_template(
|
||||
product_number: str,
|
||||
dest_dir: Path | None = None,
|
||||
guest_email: str = GUEST_EMAIL,
|
||||
) -> Path:
|
||||
"""
|
||||
Open avery.com/templates/{number}, continue as guest, download the Word blank.
|
||||
|
||||
Returns the local .doc path under AppData templates (or dest_dir).
|
||||
"""
|
||||
num = re.sub(r"[^0-9A-Za-z\-]", "", product_number.strip())
|
||||
if not num:
|
||||
raise AveryDownloadError("Enter an Avery product / template number (e.g. 60504).")
|
||||
|
||||
page_url = avery_template_page_url(num)
|
||||
html = _fetch_html(page_url)
|
||||
doc_url, filename = find_word_download_url(html)
|
||||
|
||||
# Avery's UI requires guest continue before navigating to the Word URL.
|
||||
continue_as_guest(guest_email, referer=page_url)
|
||||
|
||||
# Prefer product number in the saved name when Avery uses a long filename
|
||||
safe_name = filename
|
||||
if num not in filename:
|
||||
safe_name = f"Avery{num}_{filename}"
|
||||
|
||||
folder = dest_dir or user_templates_dir()
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
dest = folder / safe_name
|
||||
|
||||
# S3 signed URLs: avoid Origin/extra headers that can break the signature.
|
||||
req = urllib.request.Request(doc_url, headers={"User-Agent": USER_AGENT})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
data = resp.read()
|
||||
except Exception as exc:
|
||||
raise AveryDownloadError(f"Download failed:\n{exc}") from exc
|
||||
|
||||
if len(data) < 1000:
|
||||
raise AveryDownloadError("Downloaded file looks empty or invalid.")
|
||||
|
||||
dest.write_bytes(data)
|
||||
return dest
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Interactive QGraphicsView canvas for a single Avery label panel."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QRectF, Qt, Signal
|
||||
from PySide6.QtGui import QBrush, QColor, QFont, QPen, QPixmap
|
||||
from PySide6.QtWidgets import (
|
||||
QGraphicsItem,
|
||||
QGraphicsPixmapItem,
|
||||
QGraphicsRectItem,
|
||||
QGraphicsScene,
|
||||
QGraphicsTextItem,
|
||||
QGraphicsView,
|
||||
)
|
||||
|
||||
from .models import LabelDesign, LabelElement
|
||||
from .template_60504 import TEMPLATE
|
||||
|
||||
# Scene units: 1 unit = 1 inch (scaled in the view for comfortable editing)
|
||||
DPI_PREVIEW = 96
|
||||
|
||||
|
||||
def inches_to_scene(inches: float) -> float:
|
||||
return inches * DPI_PREVIEW
|
||||
|
||||
|
||||
def scene_to_inches(scene_units: float) -> float:
|
||||
return scene_units / DPI_PREVIEW
|
||||
|
||||
|
||||
class ElementItem(QGraphicsRectItem):
|
||||
"""Selectable / movable / resizable wrapper around a label element."""
|
||||
|
||||
def __init__(self, element: LabelElement, parent=None):
|
||||
super().__init__(parent)
|
||||
self.element = element
|
||||
self.setFlags(
|
||||
QGraphicsItem.GraphicsItemFlag.ItemIsSelectable
|
||||
| QGraphicsItem.GraphicsItemFlag.ItemIsMovable
|
||||
| QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges
|
||||
)
|
||||
self.setAcceptHoverEvents(True)
|
||||
self._content: QGraphicsItem | None = None
|
||||
self._rebuild_content()
|
||||
self._apply_geometry_from_element()
|
||||
|
||||
def _apply_geometry_from_element(self) -> None:
|
||||
self.setRect(0, 0, inches_to_scene(self.element.width), inches_to_scene(self.element.height))
|
||||
self.setPos(inches_to_scene(self.element.x), inches_to_scene(self.element.y))
|
||||
self.setPen(QPen(QColor("#3b82f6"), 1.5, Qt.PenStyle.DashLine))
|
||||
if not self.isSelected():
|
||||
self.setPen(QPen(QColor(0, 0, 0, 40), 1))
|
||||
|
||||
def _rebuild_content(self) -> None:
|
||||
for child in list(self.childItems()):
|
||||
child.setParentItem(None)
|
||||
if child.scene():
|
||||
child.scene().removeItem(child)
|
||||
self._content = None
|
||||
|
||||
el = self.element
|
||||
if el.type == "text":
|
||||
text_item = QGraphicsTextItem(self)
|
||||
text_item.setPlainText(el.text)
|
||||
font = QFont("Arial", int(el.font_size))
|
||||
font.setBold(el.font_bold)
|
||||
text_item.setFont(font)
|
||||
text_item.setDefaultTextColor(QColor(el.color))
|
||||
text_item.setTextWidth(inches_to_scene(el.width))
|
||||
text_item.setAcceptedMouseButtons(Qt.MouseButton.NoButton)
|
||||
self._content = text_item
|
||||
self.setBrush(QBrush(Qt.BrushStyle.NoBrush))
|
||||
elif el.type == "image":
|
||||
pix_item = QGraphicsPixmapItem(self)
|
||||
if el.image_path and Path(el.image_path).is_file():
|
||||
pixmap = QPixmap(el.image_path)
|
||||
if not pixmap.isNull():
|
||||
target_w = max(1, int(inches_to_scene(el.width)))
|
||||
target_h = max(1, int(inches_to_scene(el.height)))
|
||||
# Fill the element box exactly. Aspect was already decided at import
|
||||
# (contain / cover / stretch) via fitted_rect — KeepAspectRatio here
|
||||
# was the stretch bug.
|
||||
pix_item.setPixmap(
|
||||
pixmap.scaled(
|
||||
target_w,
|
||||
target_h,
|
||||
Qt.AspectRatioMode.IgnoreAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
)
|
||||
)
|
||||
pix_item.setAcceptedMouseButtons(Qt.MouseButton.NoButton)
|
||||
self._content = pix_item
|
||||
self.setBrush(QBrush(QColor(240, 240, 240, 80)))
|
||||
elif el.type == "rect":
|
||||
self.setBrush(QBrush(QColor(el.fill)))
|
||||
self.setPen(QPen(QColor(el.stroke), max(1.0, el.stroke_width)))
|
||||
self._content = None
|
||||
|
||||
def refresh(self) -> None:
|
||||
self._rebuild_content()
|
||||
self._apply_geometry_from_element()
|
||||
|
||||
def sync_to_model(self) -> None:
|
||||
self.element.x = scene_to_inches(self.pos().x())
|
||||
self.element.y = scene_to_inches(self.pos().y())
|
||||
self.element.width = scene_to_inches(self.rect().width())
|
||||
self.element.height = scene_to_inches(self.rect().height())
|
||||
|
||||
def itemChange(self, change, value):
|
||||
if change == QGraphicsItem.GraphicsItemChange.ItemSelectedHasChanged:
|
||||
if value:
|
||||
self.setPen(QPen(QColor("#3b82f6"), 1.5, Qt.PenStyle.DashLine))
|
||||
elif self.element.type != "rect":
|
||||
self.setPen(QPen(QColor(0, 0, 0, 40), 1))
|
||||
if change == QGraphicsItem.GraphicsItemChange.ItemPositionHasChanged:
|
||||
self.sync_to_model()
|
||||
scene = self.scene()
|
||||
if scene and hasattr(scene, "design_changed"):
|
||||
scene.design_changed.emit()
|
||||
return super().itemChange(change, value)
|
||||
|
||||
|
||||
class LabelScene(QGraphicsScene):
|
||||
design_changed = Signal()
|
||||
selection_changed_element = Signal(object) # LabelElement | None
|
||||
|
||||
def __init__(self, design: LabelDesign, parent=None):
|
||||
super().__init__(parent)
|
||||
self.design = design
|
||||
self._items: dict[str, ElementItem] = {}
|
||||
w = inches_to_scene(TEMPLATE.label_width_in)
|
||||
h = inches_to_scene(TEMPLATE.label_height_in)
|
||||
self.setSceneRect(0, 0, w, h)
|
||||
self._bg = self.addRect(0, 0, w, h, QPen(QColor("#94a3b8"), 2), QBrush(QColor(design.background)))
|
||||
self._bg.setZValue(-100)
|
||||
self._bg.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
||||
self.selectionChanged.connect(self._on_selection)
|
||||
self.reload_from_design()
|
||||
|
||||
def reload_from_design(self) -> None:
|
||||
for item in list(self._items.values()):
|
||||
self.removeItem(item)
|
||||
self._items.clear()
|
||||
self._bg.setBrush(QBrush(QColor(self.design.background)))
|
||||
for el in self.design.elements:
|
||||
item = ElementItem(el)
|
||||
self.addItem(item)
|
||||
self._items[el.id] = item
|
||||
self.design_changed.emit()
|
||||
|
||||
def resize_to_active_template(self) -> None:
|
||||
"""Call after switching Avery template geometry."""
|
||||
from .template_60504 import TEMPLATE as T
|
||||
|
||||
w = inches_to_scene(T.label_width_in)
|
||||
h = inches_to_scene(T.label_height_in)
|
||||
self.setSceneRect(0, 0, w, h)
|
||||
self._bg.setRect(0, 0, w, h)
|
||||
self.reload_from_design()
|
||||
|
||||
def add_element(self, element: LabelElement) -> ElementItem:
|
||||
self.design.elements.append(element)
|
||||
item = ElementItem(element)
|
||||
self.addItem(item)
|
||||
self._items[element.id] = item
|
||||
self.clearSelection()
|
||||
item.setSelected(True)
|
||||
self.design_changed.emit()
|
||||
return item
|
||||
|
||||
def remove_selected(self) -> None:
|
||||
for item in list(self.selectedItems()):
|
||||
if isinstance(item, ElementItem):
|
||||
self.design.elements = [e for e in self.design.elements if e.id != item.element.id]
|
||||
self.removeItem(item)
|
||||
self._items.pop(item.element.id, None)
|
||||
self.design_changed.emit()
|
||||
|
||||
def selected_element(self) -> LabelElement | None:
|
||||
for item in self.selectedItems():
|
||||
if isinstance(item, ElementItem):
|
||||
return item.element
|
||||
return None
|
||||
|
||||
def selected_item(self) -> ElementItem | None:
|
||||
for item in self.selectedItems():
|
||||
if isinstance(item, ElementItem):
|
||||
return item
|
||||
return None
|
||||
|
||||
def sync_all(self) -> None:
|
||||
for item in self._items.values():
|
||||
item.sync_to_model()
|
||||
|
||||
def _on_selection(self) -> None:
|
||||
self.selection_changed_element.emit(self.selected_element())
|
||||
|
||||
|
||||
class LabelCanvas(QGraphicsView):
|
||||
def __init__(self, scene: LabelScene, parent=None):
|
||||
super().__init__(scene, parent)
|
||||
from PySide6.QtGui import QPainter
|
||||
|
||||
self.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
self.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True)
|
||||
self.setBackgroundBrush(QBrush(QColor("#e2e8f0")))
|
||||
self.setDragMode(QGraphicsView.DragMode.RubberBandDrag)
|
||||
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
||||
self.setViewportUpdateMode(QGraphicsView.ViewportUpdateMode.BoundingRectViewportUpdate)
|
||||
self._user_zoomed = False
|
||||
self.reset_zoom()
|
||||
|
||||
def reset_zoom(self) -> None:
|
||||
self._user_zoomed = False
|
||||
self._fit_label()
|
||||
|
||||
def _fit_label(self) -> None:
|
||||
self.resetTransform()
|
||||
margin = 16
|
||||
self.fitInView(
|
||||
self.sceneRect().adjusted(-margin, -margin, margin, margin),
|
||||
Qt.AspectRatioMode.KeepAspectRatio,
|
||||
)
|
||||
|
||||
def wheelEvent(self, event):
|
||||
if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
|
||||
self._user_zoomed = True
|
||||
factor = 1.15 if event.angleDelta().y() > 0 else 1 / 1.15
|
||||
self.scale(factor, factor)
|
||||
event.accept()
|
||||
else:
|
||||
super().wheelEvent(event)
|
||||
|
||||
def resizeEvent(self, event):
|
||||
super().resizeEvent(event)
|
||||
# Always keep the label panel fitted unless the user Ctrl+scroll zoomed
|
||||
if not self._user_zoomed:
|
||||
self._fit_label()
|
||||
|
||||
def showEvent(self, event):
|
||||
super().showEvent(event)
|
||||
if not self._user_zoomed:
|
||||
self._fit_label()
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Import PDF / Word documents and rasterize pages for Avery 60504 labels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from .app_paths import temp_imports_dir
|
||||
from .import_settings import ImportSettings, fitted_rect
|
||||
from .models import LABELS_PER_SHEET, LabelDesign, LabelElement
|
||||
from .template_60504 import TEMPLATE
|
||||
|
||||
SUPPORTED_PDF = {".pdf"}
|
||||
SUPPORTED_WORD = {".docx", ".doc"}
|
||||
SUPPORTED_IMPORT = SUPPORTED_PDF | SUPPORTED_WORD
|
||||
|
||||
|
||||
class DocumentImportError(Exception):
|
||||
"""Raised when a document cannot be imported."""
|
||||
|
||||
|
||||
def _cache_dir(project_dir: Path | None = None) -> Path:
|
||||
"""Session temp cache for rasterized pages (not AppData)."""
|
||||
if project_dir is not None:
|
||||
out = Path(project_dir) / "imports"
|
||||
else:
|
||||
out = temp_imports_dir()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
return out
|
||||
|
||||
|
||||
def word_to_pdf(path: Path, out_pdf: Path) -> Path:
|
||||
"""Convert .doc/.docx to PDF using Microsoft Word (Windows COM)."""
|
||||
path = path.resolve()
|
||||
out_pdf = out_pdf.resolve()
|
||||
out_pdf.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
try:
|
||||
import win32com.client # type: ignore
|
||||
import pythoncom
|
||||
except ImportError as exc:
|
||||
raise DocumentImportError(
|
||||
"Word import needs pywin32 and Microsoft Word installed.\n"
|
||||
"Install with: pip install pywin32\n"
|
||||
"Or save/export the document as PDF and import the PDF."
|
||||
) from exc
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
word = None
|
||||
doc = None
|
||||
try:
|
||||
word = win32com.client.Dispatch("Word.Application")
|
||||
word.Visible = False
|
||||
word.DisplayAlerts = 0
|
||||
doc = word.Documents.Open(str(path), ReadOnly=True)
|
||||
doc.SaveAs(str(out_pdf), FileFormat=17)
|
||||
except Exception as exc:
|
||||
raise DocumentImportError(
|
||||
f"Could not convert Word document with Microsoft Word:\n{exc}\n\n"
|
||||
"Save the file as PDF from Word, then import the PDF."
|
||||
) from exc
|
||||
finally:
|
||||
if doc is not None:
|
||||
doc.Close(False)
|
||||
if word is not None:
|
||||
word.Quit()
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
if not out_pdf.is_file():
|
||||
raise DocumentImportError("Word conversion finished but no PDF was created.")
|
||||
return out_pdf
|
||||
|
||||
|
||||
def render_pdf_pages(
|
||||
pdf_path: Path,
|
||||
*,
|
||||
settings: ImportSettings,
|
||||
cache_dir: Path | None = None,
|
||||
max_pages: int | None = None,
|
||||
) -> list[Path]:
|
||||
"""Rasterize PDF pages to PNG files (from start_page through end / max)."""
|
||||
try:
|
||||
import fitz # PyMuPDF
|
||||
except ImportError as exc:
|
||||
raise DocumentImportError(
|
||||
"PyMuPDF is required for PDF import. Run: pip install pymupdf"
|
||||
) from exc
|
||||
|
||||
pdf_path = Path(pdf_path)
|
||||
if not pdf_path.is_file():
|
||||
raise DocumentImportError(f"File not found: {pdf_path}")
|
||||
|
||||
out_dir = _cache_dir(cache_dir)
|
||||
stem = pdf_path.stem.replace(" ", "_")[:40]
|
||||
images: list[Path] = []
|
||||
|
||||
doc = fitz.open(pdf_path)
|
||||
try:
|
||||
start = max(0, settings.start_page - 1)
|
||||
if settings.end_page and settings.end_page > 0:
|
||||
end = min(len(doc), settings.end_page)
|
||||
else:
|
||||
end = len(doc)
|
||||
if max_pages is not None:
|
||||
end = min(end, start + max_pages)
|
||||
if start >= len(doc):
|
||||
raise DocumentImportError(
|
||||
f"Start page {settings.start_page} is beyond the document "
|
||||
f"({len(doc)} page(s))."
|
||||
)
|
||||
if start >= end:
|
||||
raise DocumentImportError("No pages selected (check start/end page).")
|
||||
|
||||
zoom = settings.render_dpi / 72.0
|
||||
matrix = fitz.Matrix(zoom, zoom)
|
||||
for page_index in range(start, end):
|
||||
page = doc[page_index]
|
||||
pix = page.get_pixmap(matrix=matrix, alpha=False)
|
||||
dest = out_dir / f"{stem}_p{page_index + 1}_{settings.render_dpi}.png"
|
||||
pix.save(str(dest))
|
||||
images.append(dest)
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
if not images:
|
||||
raise DocumentImportError("No pages were rendered from the PDF.")
|
||||
return images
|
||||
|
||||
|
||||
def resolve_to_images(
|
||||
path: Path,
|
||||
*,
|
||||
settings: ImportSettings,
|
||||
cache_dir: Path | None = None,
|
||||
max_pages: int | None = None,
|
||||
) -> list[Path]:
|
||||
"""Accept PDF or Word path and return raster page images for ALL selected pages."""
|
||||
path = Path(path)
|
||||
suffix = path.suffix.lower()
|
||||
if suffix not in SUPPORTED_IMPORT:
|
||||
raise DocumentImportError(
|
||||
f"Unsupported file type: {suffix}\n"
|
||||
"Supported: PDF (.pdf), Word (.docx, .doc)"
|
||||
)
|
||||
|
||||
if suffix in SUPPORTED_WORD:
|
||||
out_pdf = _cache_dir(cache_dir) / f"{path.stem}_converted.pdf"
|
||||
path = word_to_pdf(path, out_pdf)
|
||||
|
||||
return render_pdf_pages(
|
||||
path,
|
||||
settings=settings,
|
||||
cache_dir=cache_dir,
|
||||
max_pages=max_pages,
|
||||
)
|
||||
|
||||
|
||||
def image_to_label_element(image_path: Path, settings: ImportSettings) -> LabelElement:
|
||||
"""Create a label image element fitted to the 60504 panel."""
|
||||
with Image.open(image_path) as im:
|
||||
px_w, px_h = im.size
|
||||
src_w = px_w / float(settings.render_dpi)
|
||||
src_h = px_h / float(settings.render_dpi)
|
||||
x, y, w, h = fitted_rect(
|
||||
src_w,
|
||||
src_h,
|
||||
TEMPLATE.label_width_in,
|
||||
TEMPLATE.label_height_in,
|
||||
settings,
|
||||
)
|
||||
return LabelElement.new_image(str(image_path), x=x, y=y, width=w, height=h)
|
||||
|
||||
|
||||
def _label_from_image(image_path: Path, settings: ImportSettings, name: str | None = None) -> LabelDesign:
|
||||
el = image_to_label_element(image_path, settings)
|
||||
return LabelDesign(
|
||||
name=name or Path(image_path).stem,
|
||||
elements=[el],
|
||||
)
|
||||
|
||||
|
||||
def build_labels_from_images(
|
||||
image_paths: list[Path],
|
||||
settings: ImportSettings,
|
||||
*,
|
||||
active_slots: list[bool] | None = None,
|
||||
) -> list[LabelDesign]:
|
||||
"""
|
||||
Turn all imported page images into a flat label list.
|
||||
|
||||
one_per_label:
|
||||
PDF page N → label N. Sheets auto-created (4 labels / Letter page).
|
||||
all_slots_per_page:
|
||||
PDF page N → one full sheet of 4 copies (respecting active_slots).
|
||||
"""
|
||||
if not image_paths:
|
||||
raise DocumentImportError("No images to apply.")
|
||||
|
||||
active = active_slots or [True, True, True, True]
|
||||
mode = settings.normalized_fill_mode()
|
||||
labels: list[LabelDesign] = []
|
||||
|
||||
if mode == "all_slots_per_page":
|
||||
for img in image_paths:
|
||||
for slot in range(LABELS_PER_SHEET):
|
||||
if slot < len(active) and active[slot]:
|
||||
labels.append(_label_from_image(img, settings, f"{Path(img).stem} (slot {slot + 1})"))
|
||||
else:
|
||||
labels.append(LabelDesign(name=f"Skipped slot {slot + 1}"))
|
||||
return labels
|
||||
|
||||
# one_per_label — every PDF page becomes one label; pad final sheet to 4
|
||||
for img in image_paths:
|
||||
labels.append(_label_from_image(img, settings))
|
||||
return labels
|
||||
|
||||
|
||||
def import_document_to_labels(
|
||||
path: Path,
|
||||
settings: ImportSettings,
|
||||
*,
|
||||
active_slots: list[bool] | None = None,
|
||||
cache_dir: Path | None = None,
|
||||
) -> tuple[list[LabelDesign], list[Path], int]:
|
||||
"""
|
||||
Full pipeline: file → ALL selected pages → labels (+ sheet count).
|
||||
|
||||
Returns (labels, image_paths, sheet_count).
|
||||
"""
|
||||
images = resolve_to_images(path, settings=settings, cache_dir=cache_dir, max_pages=None)
|
||||
labels = build_labels_from_images(images, settings, active_slots=active_slots)
|
||||
sheet_count = max(1, math.ceil(len(labels) / LABELS_PER_SHEET))
|
||||
return labels, images, sheet_count
|
||||
|
||||
|
||||
# Back-compat name used by older callers
|
||||
def import_document_to_slots(
|
||||
path: Path,
|
||||
settings: ImportSettings,
|
||||
*,
|
||||
active_slots: list[bool] | None = None,
|
||||
existing: list[LabelDesign] | None = None,
|
||||
cache_dir: Path | None = None,
|
||||
) -> tuple[list[LabelDesign], list[Path]]:
|
||||
labels, images, _sheets = import_document_to_labels(
|
||||
path,
|
||||
settings,
|
||||
active_slots=active_slots,
|
||||
cache_dir=cache_dir,
|
||||
)
|
||||
return labels, images
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Dialog to download an Avery Word blank by product number."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QUrl, Qt
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
from .avery_download import AveryDownloadError, avery_template_page_url, download_avery_word_template
|
||||
|
||||
|
||||
class DownloadAveryTemplateDialog(QDialog):
|
||||
def __init__(self, parent=None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Download Avery template")
|
||||
self.setMinimumWidth(420)
|
||||
self.downloaded_path: Path | None = None
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
intro = QLabel(
|
||||
"Enter an Avery product / template number (from the package).\n"
|
||||
"We’ll download the official Microsoft Word blank from avery.com\n"
|
||||
"and install it into this app."
|
||||
)
|
||||
intro.setWordWrap(True)
|
||||
layout.addWidget(intro)
|
||||
|
||||
form = QFormLayout()
|
||||
self.txt_number = QLineEdit()
|
||||
self.txt_number.setPlaceholderText("e.g. 60504")
|
||||
self.txt_number.setClearButtonEnabled(True)
|
||||
form.addRow("Template number", self.txt_number)
|
||||
layout.addLayout(form)
|
||||
|
||||
link_row = QHBoxLayout()
|
||||
self.btn_browse_web = QPushButton("Open avery.com/templates…")
|
||||
self.btn_browse_web.clicked.connect(self._open_avery_site)
|
||||
link_row.addWidget(self.btn_browse_web)
|
||||
link_row.addStretch(1)
|
||||
layout.addLayout(link_row)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.button(QDialogButtonBox.StandardButton.Ok).setText("Download & Install")
|
||||
buttons.accepted.connect(self._download)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
def _open_avery_site(self) -> None:
|
||||
num = self.txt_number.text().strip()
|
||||
url = avery_template_page_url(num) if num else "https://www.avery.com/templates"
|
||||
QDesktopServices.openUrl(QUrl(url))
|
||||
|
||||
def _download(self) -> None:
|
||||
num = self.txt_number.text().strip()
|
||||
if not num:
|
||||
QMessageBox.warning(self, "Template number", "Enter an Avery template number.")
|
||||
return
|
||||
try:
|
||||
self.setEnabled(False)
|
||||
path = download_avery_word_template(num)
|
||||
self.downloaded_path = path
|
||||
self.accept()
|
||||
except AveryDownloadError as exc:
|
||||
QMessageBox.critical(self, "Download failed", str(exc))
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "Download failed", str(exc))
|
||||
finally:
|
||||
self.setEnabled(True)
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Dialog to import PDF/Word and auto-fill Avery 60504 labels (multi-sheet)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QDoubleSpinBox,
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QSpinBox,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
from .import_settings import ImportSettings
|
||||
|
||||
|
||||
class ImportDocumentDialog(QDialog):
|
||||
def __init__(self, settings: ImportSettings | None = None, parent=None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Import PDF / Word → Auto-fill 60504 labels")
|
||||
self.setMinimumWidth(520)
|
||||
self.file_path: Path | None = None
|
||||
self.settings = settings or ImportSettings()
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
|
||||
file_row = QHBoxLayout()
|
||||
self.txt_path = QLineEdit()
|
||||
self.txt_path.setPlaceholderText("Choose a PDF or Word document…")
|
||||
self.txt_path.setReadOnly(True)
|
||||
btn_browse = QPushButton("Browse…")
|
||||
btn_browse.clicked.connect(self._browse)
|
||||
file_row.addWidget(self.txt_path, stretch=1)
|
||||
file_row.addWidget(btn_browse)
|
||||
root.addLayout(file_row)
|
||||
|
||||
fill = QGroupBox("Auto-fill mode (uses ALL pages)")
|
||||
fill_l = QFormLayout(fill)
|
||||
self.cmb_fill = QComboBox()
|
||||
self.cmb_fill.addItem(
|
||||
"One PDF page → one label (auto-add Letter sheets, 4/sheet)",
|
||||
"one_per_label",
|
||||
)
|
||||
self.cmb_fill.addItem(
|
||||
"Each PDF page → full sheet of 4 copies",
|
||||
"all_slots_per_page",
|
||||
)
|
||||
# Map legacy saved modes
|
||||
mode = self.settings.normalized_fill_mode()
|
||||
idx = self.cmb_fill.findData(mode)
|
||||
self.cmb_fill.setCurrentIndex(max(0, idx))
|
||||
fill_l.addRow("Fill", self.cmb_fill)
|
||||
|
||||
self.spin_start = QSpinBox()
|
||||
self.spin_start.setRange(1, 9999)
|
||||
self.spin_start.setValue(self.settings.start_page)
|
||||
fill_l.addRow("Start page", self.spin_start)
|
||||
|
||||
self.spin_end = QSpinBox()
|
||||
self.spin_end.setRange(0, 9999)
|
||||
self.spin_end.setSpecialValueText("End of file")
|
||||
self.spin_end.setValue(self.settings.end_page)
|
||||
fill_l.addRow("End page (0 = all)", self.spin_end)
|
||||
root.addWidget(fill)
|
||||
|
||||
place = QGroupBox("Placement on each label")
|
||||
place_l = QFormLayout(place)
|
||||
self.cmb_fit = QComboBox()
|
||||
self.cmb_fit.addItem("Contain (fit inside, keep aspect)", "contain")
|
||||
self.cmb_fit.addItem("Cover (fill label, may crop)", "cover")
|
||||
self.cmb_fit.addItem("Stretch (fill label, may distort)", "stretch")
|
||||
idx = self.cmb_fit.findData(self.settings.fit_mode)
|
||||
self.cmb_fit.setCurrentIndex(max(0, idx))
|
||||
place_l.addRow("Fit", self.cmb_fit)
|
||||
|
||||
self.spin_scale = QDoubleSpinBox()
|
||||
self.spin_scale.setRange(0.25, 3.0)
|
||||
self.spin_scale.setSingleStep(0.05)
|
||||
self.spin_scale.setDecimals(2)
|
||||
self.spin_scale.setValue(self.settings.scale)
|
||||
place_l.addRow("Scale", self.spin_scale)
|
||||
|
||||
self.spin_inset = QDoubleSpinBox()
|
||||
self.spin_inset.setRange(0.0, 0.5)
|
||||
self.spin_inset.setSingleStep(0.01)
|
||||
self.spin_inset.setDecimals(3)
|
||||
self.spin_inset.setSuffix(" in")
|
||||
self.spin_inset.setValue(self.settings.inset_in)
|
||||
place_l.addRow("Inset", self.spin_inset)
|
||||
|
||||
self.spin_cx = QDoubleSpinBox()
|
||||
self.spin_cy = QDoubleSpinBox()
|
||||
for spin, val in (
|
||||
(self.spin_cx, self.settings.content_offset_x_in),
|
||||
(self.spin_cy, self.settings.content_offset_y_in),
|
||||
):
|
||||
spin.setRange(-1.0, 1.0)
|
||||
spin.setSingleStep(0.01)
|
||||
spin.setDecimals(3)
|
||||
spin.setSuffix(" in")
|
||||
spin.setValue(val)
|
||||
place_l.addRow("Content offset X", self.spin_cx)
|
||||
place_l.addRow("Content offset Y", self.spin_cy)
|
||||
|
||||
self.spin_dpi = QSpinBox()
|
||||
self.spin_dpi.setRange(150, 600)
|
||||
self.spin_dpi.setSingleStep(50)
|
||||
self.spin_dpi.setValue(self.settings.render_dpi)
|
||||
place_l.addRow("Render DPI", self.spin_dpi)
|
||||
root.addWidget(place)
|
||||
|
||||
note = QLabel(
|
||||
"Example: a 10-page PDF → 10 labels → 3 Letter sheets (4+4+2).\n"
|
||||
"Export creates one print PDF with every sheet included.\n"
|
||||
"Word needs Microsoft Word installed (or export to PDF first)."
|
||||
)
|
||||
note.setWordWrap(True)
|
||||
note.setStyleSheet("color: #64748b;")
|
||||
root.addWidget(note)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.accepted.connect(self._accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
root.addWidget(buttons)
|
||||
|
||||
def _browse(self) -> None:
|
||||
path, _ = QFileDialog.getOpenFileName(
|
||||
self,
|
||||
"Import PDF or Word",
|
||||
"",
|
||||
"Documents (*.pdf *.docx *.doc);;PDF (*.pdf);;Word (*.docx *.doc)",
|
||||
)
|
||||
if path:
|
||||
self.file_path = Path(path)
|
||||
self.txt_path.setText(path)
|
||||
|
||||
def result_settings(self) -> ImportSettings:
|
||||
return ImportSettings(
|
||||
fill_mode=self.cmb_fill.currentData(),
|
||||
fit_mode=self.cmb_fit.currentData(),
|
||||
scale=float(self.spin_scale.value()),
|
||||
content_offset_x_in=float(self.spin_cx.value()),
|
||||
content_offset_y_in=float(self.spin_cy.value()),
|
||||
inset_in=float(self.spin_inset.value()),
|
||||
start_page=int(self.spin_start.value()),
|
||||
end_page=int(self.spin_end.value()),
|
||||
render_dpi=int(self.spin_dpi.value()),
|
||||
)
|
||||
|
||||
def _accept(self) -> None:
|
||||
if not self.file_path or not self.file_path.is_file():
|
||||
QMessageBox.warning(self, "Import", "Please choose a PDF or Word file.")
|
||||
return
|
||||
if self.spin_end.value() and self.spin_end.value() < self.spin_start.value():
|
||||
QMessageBox.warning(self, "Import", "End page must be ≥ start page (or 0 for all).")
|
||||
return
|
||||
self.accept()
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Import settings and helpers for fitting artwork onto Avery 60504 labels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
FitMode = Literal["contain", "cover", "stretch"]
|
||||
# one_per_label: each PDF page → one label; auto-create Letter sheets (4/sheet)
|
||||
# all_slots_per_page: each PDF page → a full sheet of 4 identical copies
|
||||
FillMode = Literal["one_per_label", "all_slots_per_page", "all_slots", "one_per_slot"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImportSettings:
|
||||
"""How imported PDF/Word pages are placed onto 60504 label panels."""
|
||||
|
||||
fill_mode: FillMode = "one_per_label"
|
||||
fit_mode: FitMode = "contain"
|
||||
scale: float = 1.0
|
||||
content_offset_x_in: float = 0.0
|
||||
content_offset_y_in: float = 0.0
|
||||
inset_in: float = 0.0
|
||||
start_page: int = 1
|
||||
# 0 = through end of document
|
||||
end_page: int = 0
|
||||
render_dpi: int = 300
|
||||
|
||||
def normalized_fill_mode(self) -> str:
|
||||
"""Map legacy mode names to current ones."""
|
||||
if self.fill_mode in ("one_per_slot", "one_per_label"):
|
||||
return "one_per_label"
|
||||
if self.fill_mode in ("all_slots", "all_slots_per_page"):
|
||||
return "all_slots_per_page"
|
||||
return "one_per_label"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> ImportSettings:
|
||||
return cls(
|
||||
fill_mode=data.get("fill_mode", "one_per_label"), # type: ignore[arg-type]
|
||||
fit_mode=data.get("fit_mode", "contain"), # type: ignore[arg-type]
|
||||
scale=float(data.get("scale", 1.0)),
|
||||
content_offset_x_in=float(data.get("content_offset_x_in", 0.0)),
|
||||
content_offset_y_in=float(data.get("content_offset_y_in", 0.0)),
|
||||
inset_in=float(data.get("inset_in", 0.0)),
|
||||
start_page=max(1, int(data.get("start_page", 1))),
|
||||
end_page=max(0, int(data.get("end_page", 0))),
|
||||
render_dpi=max(72, int(data.get("render_dpi", 300))),
|
||||
)
|
||||
|
||||
|
||||
def fitted_rect(
|
||||
src_w: float,
|
||||
src_h: float,
|
||||
label_w: float,
|
||||
label_h: float,
|
||||
settings: ImportSettings,
|
||||
) -> tuple[float, float, float, float]:
|
||||
"""Return (x, y, w, h) in inches for artwork inside a label panel."""
|
||||
inset = max(0.0, settings.inset_in)
|
||||
avail_w = max(0.01, label_w - 2 * inset)
|
||||
avail_h = max(0.01, label_h - 2 * inset)
|
||||
|
||||
if src_w <= 0 or src_h <= 0:
|
||||
return inset, inset, avail_w, avail_h
|
||||
|
||||
if settings.fit_mode == "stretch":
|
||||
w, h = avail_w * settings.scale, avail_h * settings.scale
|
||||
else:
|
||||
scale_w = avail_w / src_w
|
||||
scale_h = avail_h / src_h
|
||||
scale = max(scale_w, scale_h) if settings.fit_mode == "cover" else min(scale_w, scale_h)
|
||||
scale *= settings.scale
|
||||
w = src_w * scale
|
||||
h = src_h * scale
|
||||
|
||||
x = inset + (avail_w - w) / 2 + settings.content_offset_x_in
|
||||
y = inset + (avail_h - h) / 2 + settings.content_offset_y_in
|
||||
return x, y, w, h
|
||||
@@ -0,0 +1,961 @@
|
||||
"""Main application window — Avery label designer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt, QTimer
|
||||
from PySide6.QtGui import QAction, QColor, QKeySequence
|
||||
from PySide6.QtWidgets import (
|
||||
QCheckBox,
|
||||
QColorDialog,
|
||||
QComboBox,
|
||||
QDoubleSpinBox,
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QMainWindow,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QSpinBox,
|
||||
QTextEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
QWidgetAction,
|
||||
)
|
||||
|
||||
from .app_paths import cleanup_legacy_appdata_imports, user_templates_dir
|
||||
from .canvas import LabelCanvas, LabelScene
|
||||
from .document_import import DocumentImportError, import_document_to_labels
|
||||
from .download_dialog import DownloadAveryTemplateDialog
|
||||
from .import_dialog import ImportDocumentDialog
|
||||
from .models import LABELS_PER_SHEET, LabelDesign, LabelElement, SheetProject
|
||||
from .pdf_export import export_pdf
|
||||
from .preferences import get_last_template_path, set_last_template_path
|
||||
from .printing import print_preview_project, print_project, print_via_system_pdf
|
||||
from .sheet_preview import SheetPreview
|
||||
from .template_60504 import TEMPLATE, UNSET_TEMPLATE, assert_geometry, set_active_template
|
||||
from .template_loader import (
|
||||
TemplateLoadError,
|
||||
activate_template_file,
|
||||
ensure_templates_dir,
|
||||
list_installed_templates,
|
||||
)
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.template_ready = False
|
||||
self.setWindowTitle("Avery Label Studio — Select a template")
|
||||
self.resize(1460, 880)
|
||||
self.setMinimumSize(1100, 700)
|
||||
|
||||
set_active_template(UNSET_TEMPLATE)
|
||||
self.project = SheetProject(name="Untitled labels")
|
||||
self.project_path: Path | None = None
|
||||
|
||||
self.scene = LabelScene(self.project.current)
|
||||
self.canvas = LabelCanvas(self.scene)
|
||||
self.sheet_preview = SheetPreview()
|
||||
self.sheet_preview.set_project(self.project)
|
||||
|
||||
# Debounce sheet-preview rebuilds (drag was reloading full images every move)
|
||||
self._preview_timer = QTimer(self)
|
||||
self._preview_timer.setSingleShot(True)
|
||||
self._preview_timer.setInterval(120)
|
||||
self._preview_timer.timeout.connect(self._do_refresh_sheet_preview)
|
||||
|
||||
self._build_ui()
|
||||
self._build_menu()
|
||||
self._wire()
|
||||
self._sync_slot_ui()
|
||||
self._do_refresh_sheet_preview()
|
||||
|
||||
ensure_templates_dir()
|
||||
cleanup_legacy_appdata_imports()
|
||||
self._refresh_template_combo(select_path=None)
|
||||
if not self._restore_last_template():
|
||||
self._show_welcome(True)
|
||||
self.statusBar().showMessage("Select or download a template to get started")
|
||||
else:
|
||||
self.statusBar().showMessage(self._status_template_text())
|
||||
|
||||
def _status_template_text(self) -> str:
|
||||
if not self.template_ready or not TEMPLATE.id:
|
||||
return "No template selected — download from Avery.com or import a Word blank"
|
||||
return (
|
||||
f"{TEMPLATE.name}: panel {TEMPLATE.label_width_in:.4f}\" · "
|
||||
f"top {TEMPLATE.top_margin_in:.3f}\" · v-gap {TEMPLATE.vertical_gap_in:.3f}\" · "
|
||||
f"{TEMPLATE.labels_per_sheet}/sheet"
|
||||
)
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
root = QWidget()
|
||||
layout = QHBoxLayout(root)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.setSpacing(10)
|
||||
|
||||
left = QVBoxLayout()
|
||||
|
||||
tools = QGroupBox("Tools")
|
||||
tools_l = QVBoxLayout(tools)
|
||||
self.btn_import = QPushButton("Import")
|
||||
self.btn_import.setStyleSheet("font-weight: 600;")
|
||||
self.btn_text = QPushButton("Add Text")
|
||||
self.btn_image = QPushButton("Add Image…")
|
||||
self.btn_rect = QPushButton("Add Rectangle")
|
||||
self.btn_delete = QPushButton("Delete Selected")
|
||||
self.btn_recenter = QPushButton("Recenter Selected")
|
||||
for b in (
|
||||
self.btn_import,
|
||||
self.btn_text,
|
||||
self.btn_image,
|
||||
self.btn_rect,
|
||||
self.btn_recenter,
|
||||
self.btn_delete,
|
||||
):
|
||||
tools_l.addWidget(b)
|
||||
left.addWidget(tools)
|
||||
|
||||
edit_slot = QGroupBox("Editing slot")
|
||||
edit_l = QHBoxLayout(edit_slot)
|
||||
self.slot_edit_buttons: list[QPushButton] = []
|
||||
for i in range(4):
|
||||
btn = QPushButton(str(i + 1))
|
||||
btn.setCheckable(True)
|
||||
btn.setChecked(i == 0)
|
||||
edit_l.addWidget(btn)
|
||||
self.slot_edit_buttons.append(btn)
|
||||
left.addWidget(edit_slot)
|
||||
|
||||
props = QGroupBox("Selected element")
|
||||
form = QFormLayout(props)
|
||||
self.txt_content = QTextEdit()
|
||||
self.txt_content.setPlaceholderText("Text content…")
|
||||
self.txt_content.setFixedHeight(80)
|
||||
self.spin_font = QSpinBox()
|
||||
self.spin_font.setRange(6, 144)
|
||||
self.spin_font.setValue(18)
|
||||
self.chk_bold = QCheckBox("Bold")
|
||||
self.cmb_align = QComboBox()
|
||||
self.cmb_align.addItems(["left", "center", "right"])
|
||||
self.btn_text_color = QPushButton("Text color…")
|
||||
self.btn_fill_color = QPushButton("Fill color…")
|
||||
form.addRow("Text", self.txt_content)
|
||||
form.addRow("Font size", self.spin_font)
|
||||
form.addRow("", self.chk_bold)
|
||||
form.addRow("Align", self.cmb_align)
|
||||
form.addRow(self.btn_text_color)
|
||||
form.addRow(self.btn_fill_color)
|
||||
left.addWidget(props)
|
||||
|
||||
sheet = QGroupBox("Print settings")
|
||||
sheet_l = QFormLayout(sheet)
|
||||
self.slot_checks: list[QCheckBox] = []
|
||||
slots = QHBoxLayout()
|
||||
for i in range(4):
|
||||
cb = QCheckBox(str(i + 1))
|
||||
cb.setChecked(True)
|
||||
self.slot_checks.append(cb)
|
||||
slots.addWidget(cb)
|
||||
sheet_l.addRow("Print slots", slots)
|
||||
|
||||
self.spin_off_x = QDoubleSpinBox()
|
||||
self.spin_off_y = QDoubleSpinBox()
|
||||
for spin in (self.spin_off_x, self.spin_off_y):
|
||||
spin.setRange(-0.5, 0.5)
|
||||
spin.setSingleStep(0.01)
|
||||
spin.setDecimals(3)
|
||||
spin.setSuffix(" in")
|
||||
sheet_l.addRow("Sheet offset X", self.spin_off_x)
|
||||
sheet_l.addRow("Sheet offset Y", self.spin_off_y)
|
||||
self.btn_bg = QPushButton("Label background…")
|
||||
sheet_l.addRow(self.btn_bg)
|
||||
left.addWidget(sheet)
|
||||
left.addStretch(1)
|
||||
|
||||
left_wrap = QWidget()
|
||||
left_wrap.setMinimumWidth(260)
|
||||
left_wrap.setMaximumWidth(320)
|
||||
left_wrap.setLayout(left)
|
||||
|
||||
center = QVBoxLayout()
|
||||
self.editor_title = QLabel("Edit slot 1")
|
||||
self.editor_title.setStyleSheet("font-weight: 600; font-size: 14px;")
|
||||
center.addWidget(self.editor_title)
|
||||
|
||||
# Editor stack: welcome (Select template) vs canvas
|
||||
self.editor_stack = QWidget()
|
||||
stack_l = QVBoxLayout(self.editor_stack)
|
||||
stack_l.setContentsMargins(0, 0, 0, 0)
|
||||
self.welcome = self._build_welcome_panel()
|
||||
stack_l.addWidget(self.welcome)
|
||||
stack_l.addWidget(self.canvas, stretch=1)
|
||||
# Default: Select a template (until last-used restore or user picks one)
|
||||
self.canvas.hide()
|
||||
self.welcome.show()
|
||||
center.addWidget(self.editor_stack, stretch=1)
|
||||
|
||||
right = QVBoxLayout()
|
||||
sheet_title = QLabel("Full sheet preview")
|
||||
sheet_title.setStyleSheet("font-weight: 600; font-size: 14px;")
|
||||
right.addWidget(sheet_title)
|
||||
|
||||
nav = QHBoxLayout()
|
||||
self.btn_prev_sheet = QPushButton("◀ Prev")
|
||||
self.btn_next_sheet = QPushButton("Next ▶")
|
||||
self.lbl_sheet_nav = QLabel("Sheet 1 / 1")
|
||||
self.lbl_sheet_nav.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
nav.addWidget(self.btn_prev_sheet)
|
||||
nav.addWidget(self.lbl_sheet_nav, stretch=1)
|
||||
nav.addWidget(self.btn_next_sheet)
|
||||
right.addLayout(nav)
|
||||
|
||||
right.addWidget(self.sheet_preview, stretch=1)
|
||||
right_wrap = QWidget()
|
||||
right_wrap.setMinimumWidth(300)
|
||||
right_wrap.setMaximumWidth(480)
|
||||
right_wrap.setLayout(right)
|
||||
self.right_wrap = right_wrap
|
||||
self.right_wrap.hide() # no preview until a template is selected
|
||||
|
||||
layout.addWidget(left_wrap, stretch=0)
|
||||
layout.addLayout(center, stretch=3)
|
||||
layout.addWidget(right_wrap, stretch=2)
|
||||
self.setCentralWidget(root)
|
||||
|
||||
def _build_welcome_panel(self) -> QWidget:
|
||||
panel = QWidget()
|
||||
panel.setObjectName("welcomePanel")
|
||||
# High-contrast block that stays readable in Windows dark mode
|
||||
panel.setStyleSheet(
|
||||
"""
|
||||
QWidget#welcomePanel {
|
||||
background-color: #0f172a;
|
||||
border: 2px solid #38bdf8;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QWidget#welcomePanel QLabel#welcomeTitle {
|
||||
color: #f8fafc;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
background: transparent;
|
||||
}
|
||||
QWidget#welcomePanel QLabel#welcomeBody {
|
||||
color: #e2e8f0;
|
||||
font-size: 14px;
|
||||
background: transparent;
|
||||
}
|
||||
QWidget#welcomePanel QPushButton {
|
||||
background-color: #38bdf8;
|
||||
color: #0f172a;
|
||||
font-weight: 700;
|
||||
font-size: 14px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 10px 18px;
|
||||
min-width: 240px;
|
||||
}
|
||||
QWidget#welcomePanel QPushButton:hover {
|
||||
background-color: #7dd3fc;
|
||||
}
|
||||
QWidget#welcomePanel QPushButton#secondaryBtn {
|
||||
background-color: #1e293b;
|
||||
color: #f8fafc;
|
||||
border: 1px solid #94a3b8;
|
||||
}
|
||||
QWidget#welcomePanel QPushButton#secondaryBtn:hover {
|
||||
background-color: #334155;
|
||||
}
|
||||
"""
|
||||
)
|
||||
lay = QVBoxLayout(panel)
|
||||
lay.setContentsMargins(36, 36, 36, 36)
|
||||
lay.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
lay.setSpacing(16)
|
||||
title = QLabel("Select a template")
|
||||
title.setObjectName("welcomeTitle")
|
||||
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
body = QLabel(
|
||||
"No Avery templates are built into this app.\n\n"
|
||||
"1. Download the official Word blank from Avery.com by product number\n"
|
||||
" (example: 60504), or\n"
|
||||
"2. Import a Word / JSON / PDF blank you already have.\n\n"
|
||||
"After you pick one, it is saved and will reopen next time."
|
||||
)
|
||||
body.setObjectName("welcomeBody")
|
||||
body.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
body.setWordWrap(True)
|
||||
lay.addWidget(title)
|
||||
lay.addWidget(body)
|
||||
|
||||
btn_dl = QPushButton("Download from Avery.com…")
|
||||
btn_dl.setMinimumHeight(40)
|
||||
btn_dl.clicked.connect(self.download_avery_template)
|
||||
btn_imp = QPushButton("Import template file…")
|
||||
btn_imp.setObjectName("secondaryBtn")
|
||||
btn_imp.setMinimumHeight(40)
|
||||
btn_imp.clicked.connect(self.load_template_file)
|
||||
lay.addWidget(btn_dl, alignment=Qt.AlignmentFlag.AlignCenter)
|
||||
lay.addWidget(btn_imp, alignment=Qt.AlignmentFlag.AlignCenter)
|
||||
return panel
|
||||
|
||||
def _show_welcome(self, show: bool) -> None:
|
||||
self.welcome.setVisible(show)
|
||||
self.canvas.setVisible(not show)
|
||||
self.right_wrap.setVisible(not show)
|
||||
if show:
|
||||
self.editor_title.setText("Select a template to begin")
|
||||
self.sheet_preview.setEnabled(not show)
|
||||
|
||||
def _build_menu(self) -> None:
|
||||
"""File / quick actions / template controls / Help — one menubar row."""
|
||||
mb = self.menuBar()
|
||||
|
||||
file_menu = mb.addMenu("&File")
|
||||
file_actions = [
|
||||
("New", QKeySequence.StandardKey.New, self.new_design),
|
||||
("Open…", QKeySequence.StandardKey.Open, self.open_design),
|
||||
("Save", QKeySequence.StandardKey.Save, self.save_design),
|
||||
("Save As…", QKeySequence.StandardKey.SaveAs, self.save_design_as),
|
||||
None,
|
||||
("Import", "Ctrl+I", self.import_document),
|
||||
None,
|
||||
("Download Avery Template…", None, self.download_avery_template),
|
||||
("Import Template File…", None, self.load_template_file),
|
||||
("Open Templates Folder", None, self.open_templates_folder),
|
||||
None,
|
||||
("Print…", QKeySequence.StandardKey.Print, self.print_document),
|
||||
("Print Preview…", None, self.print_preview),
|
||||
("Print via System PDF…", None, self.print_via_system),
|
||||
("Export PDF…", "Ctrl+E", self.export_pdf_dialog),
|
||||
("Export Alignment Guide…", None, self.export_guide_dialog),
|
||||
None,
|
||||
("Quit", QKeySequence.StandardKey.Quit, self.close),
|
||||
]
|
||||
for item in file_actions:
|
||||
if item is None:
|
||||
file_menu.addSeparator()
|
||||
continue
|
||||
text, shortcut, slot = item
|
||||
act = QAction(text, self)
|
||||
if shortcut:
|
||||
act.setShortcut(shortcut)
|
||||
act.triggered.connect(slot)
|
||||
file_menu.addAction(act)
|
||||
|
||||
for text, shortcut, slot in (
|
||||
("New", QKeySequence.StandardKey.New, self.new_design),
|
||||
("Import", "Ctrl+I", self.import_document),
|
||||
("Print", QKeySequence.StandardKey.Print, self.print_document),
|
||||
("Export PDF", "Ctrl+E", self.export_pdf_dialog),
|
||||
):
|
||||
act = QAction(text, self)
|
||||
# Shortcuts already on File menu; avoid duplicate QAction shortcut warnings
|
||||
act.triggered.connect(slot)
|
||||
mb.addAction(act)
|
||||
|
||||
template_wrap = QWidget()
|
||||
template_row = QHBoxLayout(template_wrap)
|
||||
template_row.setContentsMargins(8, 0, 4, 0)
|
||||
template_row.setSpacing(6)
|
||||
template_row.addWidget(QLabel("Template:"))
|
||||
self.cmb_template = QComboBox()
|
||||
self.cmb_template.setMinimumWidth(220)
|
||||
self.cmb_template.setToolTip(
|
||||
"Your installed templates only (AppData).\n"
|
||||
"Nothing is shipped — download or import first."
|
||||
)
|
||||
template_row.addWidget(self.cmb_template)
|
||||
btn_dl = QPushButton("Download…")
|
||||
btn_dl.setToolTip("Download official Word blank from avery.com")
|
||||
btn_dl.clicked.connect(self.download_avery_template)
|
||||
template_row.addWidget(btn_dl)
|
||||
btn_add = QPushButton("Import…")
|
||||
btn_add.setToolTip("Import a template file you already have")
|
||||
btn_add.clicked.connect(self.load_template_file)
|
||||
template_row.addWidget(btn_add)
|
||||
template_action = QWidgetAction(self)
|
||||
template_action.setDefaultWidget(template_wrap)
|
||||
mb.addAction(template_action)
|
||||
|
||||
help_menu = mb.addMenu("&Help")
|
||||
act_specs = QAction("Template Specs", self)
|
||||
act_specs.triggered.connect(self.show_template_specs)
|
||||
help_menu.addAction(act_specs)
|
||||
act_about = QAction("About", self)
|
||||
act_about.triggered.connect(self.show_about)
|
||||
help_menu.addAction(act_about)
|
||||
|
||||
def _wire(self) -> None:
|
||||
self.btn_import.clicked.connect(self.import_document)
|
||||
self.btn_text.clicked.connect(self.add_text)
|
||||
self.btn_image.clicked.connect(self.add_image)
|
||||
self.btn_rect.clicked.connect(self.add_rect)
|
||||
self.btn_delete.clicked.connect(self._delete_selected)
|
||||
self.btn_recenter.clicked.connect(self.recenter_selected)
|
||||
self.btn_text_color.clicked.connect(self.pick_text_color)
|
||||
self.btn_fill_color.clicked.connect(self.pick_fill_color)
|
||||
self.btn_bg.clicked.connect(self.pick_background)
|
||||
|
||||
self.txt_content.textChanged.connect(self.apply_text_props)
|
||||
self.spin_font.valueChanged.connect(self.apply_text_props)
|
||||
self.chk_bold.toggled.connect(self.apply_text_props)
|
||||
self.cmb_align.currentTextChanged.connect(self.apply_text_props)
|
||||
|
||||
for i, cb in enumerate(self.slot_checks):
|
||||
cb.toggled.connect(lambda checked, idx=i: self._set_slot_active(idx, checked))
|
||||
for i, btn in enumerate(self.slot_edit_buttons):
|
||||
btn.clicked.connect(lambda _checked=False, idx=i: self._set_editing_slot(idx))
|
||||
|
||||
self.spin_off_x.valueChanged.connect(self._set_offset_x)
|
||||
self.spin_off_y.valueChanged.connect(self._set_offset_y)
|
||||
|
||||
self.scene.selection_changed_element.connect(self._load_props)
|
||||
self.scene.design_changed.connect(self._on_design_changed)
|
||||
self.sheet_preview.slot_clicked.connect(self._on_preview_slot_clicked)
|
||||
self.btn_prev_sheet.clicked.connect(self._prev_sheet)
|
||||
self.btn_next_sheet.clicked.connect(self._next_sheet)
|
||||
self.cmb_template.currentIndexChanged.connect(self._on_template_combo_changed)
|
||||
|
||||
self._updating_props = False
|
||||
self._updating_slots = False
|
||||
self._updating_template_combo = False
|
||||
|
||||
def _refresh_template_combo(self, select_path: Path | None) -> None:
|
||||
self._updating_template_combo = True
|
||||
self.cmb_template.clear()
|
||||
self.cmb_template.addItem("Select a template…", "")
|
||||
files = list_installed_templates()
|
||||
select_idx = 0
|
||||
for i, path in enumerate(files):
|
||||
self.cmb_template.addItem(path.stem, str(path))
|
||||
if select_path and path.resolve() == Path(select_path).resolve():
|
||||
select_idx = i + 1
|
||||
elif (
|
||||
not select_path
|
||||
and self.template_ready
|
||||
and path.stem.lower() == (TEMPLATE.id or "").lower()
|
||||
):
|
||||
select_idx = i + 1
|
||||
self.cmb_template.setCurrentIndex(select_idx)
|
||||
self._updating_template_combo = False
|
||||
|
||||
def _on_template_combo_changed(self, index: int) -> None:
|
||||
if self._updating_template_combo or index < 0:
|
||||
return
|
||||
path_str = self.cmb_template.itemData(index)
|
||||
if not path_str:
|
||||
# User chose "Select a template…"
|
||||
set_active_template(UNSET_TEMPLATE)
|
||||
self.template_ready = False
|
||||
set_last_template_path(None)
|
||||
self.setWindowTitle("Avery Label Studio — Select a template")
|
||||
self._show_welcome(True)
|
||||
self.statusBar().showMessage(self._status_template_text())
|
||||
return
|
||||
path = Path(path_str)
|
||||
try:
|
||||
activate_template_file(path)
|
||||
assert_geometry()
|
||||
set_last_template_path(path)
|
||||
self._apply_loaded_template(f"Template {path.name}")
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "Template switch failed", str(exc))
|
||||
|
||||
def _sync_slot_ui(self) -> None:
|
||||
self._updating_slots = True
|
||||
for i, cb in enumerate(self.slot_checks):
|
||||
cb.setChecked(self.project.active_slots[i])
|
||||
local_slot = self.project.editing_index % LABELS_PER_SHEET
|
||||
for i, btn in enumerate(self.slot_edit_buttons):
|
||||
btn.setChecked(i == local_slot)
|
||||
self.spin_off_x.setValue(self.project.offset_x_in)
|
||||
self.spin_off_y.setValue(self.project.offset_y_in)
|
||||
sheet_no = self.project.editing_index // LABELS_PER_SHEET + 1
|
||||
global_no = self.project.editing_index + 1
|
||||
self.editor_title.setText(
|
||||
f"Edit label {global_no} · sheet {sheet_no}/{self.project.sheet_count} · "
|
||||
f'slot {local_slot + 1} ({TEMPLATE.label_width_in:.4f}")'
|
||||
)
|
||||
self.lbl_sheet_nav.setText(
|
||||
f"Sheet {self.project.preview_sheet + 1} / {self.project.sheet_count}"
|
||||
)
|
||||
self.btn_prev_sheet.setEnabled(self.project.preview_sheet > 0)
|
||||
self.btn_next_sheet.setEnabled(
|
||||
self.project.preview_sheet < self.project.sheet_count - 1
|
||||
)
|
||||
self._updating_slots = False
|
||||
|
||||
def _load_editing_slot_into_scene(self) -> None:
|
||||
self.project.preview_sheet = self.project.editing_index // LABELS_PER_SHEET
|
||||
self.scene.design = self.project.current
|
||||
self.scene.reload_from_design()
|
||||
self._sync_slot_ui()
|
||||
self._refresh_sheet_preview(immediate=True)
|
||||
|
||||
def _on_design_changed(self) -> None:
|
||||
self.project.set_current(self.scene.design)
|
||||
self._refresh_sheet_preview(immediate=False)
|
||||
|
||||
def _refresh_sheet_preview(self, immediate: bool = False) -> None:
|
||||
if immediate:
|
||||
self._preview_timer.stop()
|
||||
self._do_refresh_sheet_preview()
|
||||
else:
|
||||
self._preview_timer.start()
|
||||
|
||||
def _do_refresh_sheet_preview(self) -> None:
|
||||
self.sheet_preview.set_project(self.project)
|
||||
self.lbl_sheet_nav.setText(
|
||||
f"Sheet {self.project.preview_sheet + 1} / {self.project.sheet_count}"
|
||||
)
|
||||
self.btn_prev_sheet.setEnabled(self.project.preview_sheet > 0)
|
||||
self.btn_next_sheet.setEnabled(
|
||||
self.project.preview_sheet < self.project.sheet_count - 1
|
||||
)
|
||||
|
||||
def _set_editing_slot(self, index: int) -> None:
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
self.project.editing_index = self.project.global_index(
|
||||
self.project.preview_sheet, index
|
||||
)
|
||||
self._load_editing_slot_into_scene()
|
||||
|
||||
def _on_preview_slot_clicked(self, index: int) -> None:
|
||||
self._set_editing_slot(index)
|
||||
|
||||
def _prev_sheet(self) -> None:
|
||||
if self.project.preview_sheet <= 0:
|
||||
return
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
self.project.preview_sheet -= 1
|
||||
self.project.editing_index = self.project.global_index(self.project.preview_sheet, 0)
|
||||
self._load_editing_slot_into_scene()
|
||||
|
||||
def _next_sheet(self) -> None:
|
||||
if self.project.preview_sheet >= self.project.sheet_count - 1:
|
||||
return
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
self.project.preview_sheet += 1
|
||||
self.project.editing_index = self.project.global_index(self.project.preview_sheet, 0)
|
||||
self._load_editing_slot_into_scene()
|
||||
|
||||
def _set_slot_active(self, index: int, checked: bool) -> None:
|
||||
self.project.active_slots[index] = checked
|
||||
if not self._updating_slots:
|
||||
self.sheet_preview.update()
|
||||
|
||||
def _set_offset_x(self, value: float) -> None:
|
||||
self.project.offset_x_in = float(value)
|
||||
self.sheet_preview.update()
|
||||
|
||||
def _set_offset_y(self, value: float) -> None:
|
||||
self.project.offset_y_in = float(value)
|
||||
self.sheet_preview.update()
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
self.scene.remove_selected()
|
||||
|
||||
def recenter_selected(self) -> None:
|
||||
"""Center the selected element (or all artwork) on the label panel."""
|
||||
item = self.scene.selected_item()
|
||||
if item is not None:
|
||||
el = item.element
|
||||
el.x = (TEMPLATE.label_width_in - el.width) / 2
|
||||
el.y = (TEMPLATE.label_height_in - el.height) / 2
|
||||
item.refresh()
|
||||
self._on_design_changed()
|
||||
self.statusBar().showMessage("Recentered selected element")
|
||||
return
|
||||
|
||||
# Nothing selected — recenter every element on this label
|
||||
design = self.scene.design
|
||||
if not design.elements:
|
||||
QMessageBox.information(self, "Recenter", "Nothing to recenter on this label.")
|
||||
return
|
||||
for el in design.elements:
|
||||
el.x = (TEMPLATE.label_width_in - el.width) / 2
|
||||
el.y = (TEMPLATE.label_height_in - el.height) / 2
|
||||
self.scene.reload_from_design()
|
||||
self.statusBar().showMessage("Recentered all elements on this label")
|
||||
|
||||
def _load_props(self, element: LabelElement | None) -> None:
|
||||
self._updating_props = True
|
||||
enabled = element is not None and element.type == "text"
|
||||
self.txt_content.setEnabled(enabled)
|
||||
self.spin_font.setEnabled(enabled)
|
||||
self.chk_bold.setEnabled(enabled)
|
||||
self.cmb_align.setEnabled(enabled)
|
||||
self.btn_text_color.setEnabled(enabled)
|
||||
self.btn_fill_color.setEnabled(element is not None and element.type == "rect")
|
||||
if element and element.type == "text":
|
||||
self.txt_content.setPlainText(element.text)
|
||||
self.spin_font.setValue(int(element.font_size))
|
||||
self.chk_bold.setChecked(element.font_bold)
|
||||
self.cmb_align.setCurrentText(element.align)
|
||||
self._updating_props = False
|
||||
|
||||
def apply_text_props(self) -> None:
|
||||
if self._updating_props:
|
||||
return
|
||||
el = self.scene.selected_element()
|
||||
if not el or el.type != "text":
|
||||
return
|
||||
el.text = self.txt_content.toPlainText()
|
||||
el.font_size = float(self.spin_font.value())
|
||||
el.font_bold = self.chk_bold.isChecked()
|
||||
el.align = self.cmb_align.currentText() # type: ignore[assignment]
|
||||
item = self.scene.selected_item()
|
||||
if item:
|
||||
item.refresh()
|
||||
self._on_design_changed()
|
||||
|
||||
def pick_text_color(self) -> None:
|
||||
el = self.scene.selected_element()
|
||||
if not el or el.type != "text":
|
||||
return
|
||||
color = QColorDialog.getColor(QColor(el.color), self, "Text color")
|
||||
if color.isValid():
|
||||
el.color = color.name()
|
||||
item = self.scene.selected_item()
|
||||
if item:
|
||||
item.refresh()
|
||||
self._on_design_changed()
|
||||
|
||||
def pick_fill_color(self) -> None:
|
||||
el = self.scene.selected_element()
|
||||
if not el or el.type != "rect":
|
||||
return
|
||||
color = QColorDialog.getColor(QColor(el.fill), self, "Fill color")
|
||||
if color.isValid():
|
||||
el.fill = color.name()
|
||||
item = self.scene.selected_item()
|
||||
if item:
|
||||
item.refresh()
|
||||
self._on_design_changed()
|
||||
|
||||
def pick_background(self) -> None:
|
||||
color = QColorDialog.getColor(QColor(self.project.current.background), self, "Label background")
|
||||
if color.isValid():
|
||||
self.project.current.background = color.name()
|
||||
self.scene.reload_from_design()
|
||||
self._refresh_sheet_preview(immediate=True)
|
||||
|
||||
def add_text(self) -> None:
|
||||
self.scene.add_element(LabelElement.new_text())
|
||||
|
||||
def add_image(self) -> None:
|
||||
path, _ = QFileDialog.getOpenFileName(
|
||||
self,
|
||||
"Choose image",
|
||||
"",
|
||||
"Images (*.png *.jpg *.jpeg *.bmp *.gif *.webp)",
|
||||
)
|
||||
if path:
|
||||
self.scene.add_element(LabelElement.new_image(path))
|
||||
|
||||
def add_rect(self) -> None:
|
||||
self.scene.add_element(LabelElement.new_rect())
|
||||
|
||||
def import_document(self) -> None:
|
||||
if not self.template_ready:
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"Select a template",
|
||||
"Download or import an Avery template before importing artwork.",
|
||||
)
|
||||
self.download_avery_template()
|
||||
return
|
||||
dlg = ImportDocumentDialog(self.project.import_settings, self)
|
||||
if dlg.exec() != dlg.DialogCode.Accepted:
|
||||
return
|
||||
assert dlg.file_path is not None
|
||||
settings = dlg.result_settings()
|
||||
self.project.import_settings = settings
|
||||
try:
|
||||
labels, images, sheet_count = import_document_to_labels(
|
||||
dlg.file_path,
|
||||
settings,
|
||||
active_slots=self.project.active_slots,
|
||||
)
|
||||
self.project.set_labels(labels)
|
||||
self.project.name = dlg.file_path.stem
|
||||
self.project.editing_index = 0
|
||||
self.project.preview_sheet = 0
|
||||
self._load_editing_slot_into_scene()
|
||||
mode = settings.normalized_fill_mode()
|
||||
mode_text = (
|
||||
"one page → one label (extra Letter sheets auto-added)"
|
||||
if mode == "one_per_label"
|
||||
else "each page → full sheet of 4 copies"
|
||||
)
|
||||
self.statusBar().showMessage(
|
||||
f"Imported {dlg.file_path.name}: {len(images)} page(s) → "
|
||||
f"{len(labels)} label(s) on {sheet_count} sheet(s) · fit={settings.fit_mode}"
|
||||
)
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"Import complete",
|
||||
f"Loaded: {dlg.file_path.name}\n"
|
||||
f"Mode: {mode_text}\n"
|
||||
f"Fit: {settings.fit_mode}\n"
|
||||
f"PDF/Word pages used: {len(images)}\n"
|
||||
f"Labels created: {len(labels)}\n"
|
||||
f"Letter sheets: {sheet_count}\n\n"
|
||||
"Use Prev/Next on the right to browse sheets.\n"
|
||||
"Export PDF will include every sheet.",
|
||||
)
|
||||
except DocumentImportError as exc:
|
||||
QMessageBox.critical(self, "Import failed", str(exc))
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "Import failed", str(exc))
|
||||
|
||||
def new_design(self) -> None:
|
||||
self.project = SheetProject(name="My Avery 60504 Sheet")
|
||||
self.project_path = None
|
||||
self._load_editing_slot_into_scene()
|
||||
self.statusBar().showMessage("New sheet")
|
||||
|
||||
def open_design(self) -> None:
|
||||
path, _ = QFileDialog.getOpenFileName(self, "Open project", "", "Label Studio (*.json)")
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
self.project = SheetProject.load(path)
|
||||
self.project_path = Path(path)
|
||||
self._load_editing_slot_into_scene()
|
||||
self.statusBar().showMessage(f"Opened {path}")
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "Open failed", str(exc))
|
||||
|
||||
def save_design(self) -> None:
|
||||
if self.project_path is None:
|
||||
self.save_design_as()
|
||||
return
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
self.project.save(self.project_path)
|
||||
self.statusBar().showMessage(f"Saved {self.project_path}")
|
||||
|
||||
def save_design_as(self) -> None:
|
||||
path, _ = QFileDialog.getSaveFileName(
|
||||
self, "Save project", "avery-60504-sheet.json", "Label Studio (*.json)"
|
||||
)
|
||||
if not path:
|
||||
return
|
||||
self.project_path = Path(path)
|
||||
self.save_design()
|
||||
|
||||
def export_pdf_dialog(self) -> None:
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
path, _ = QFileDialog.getSaveFileName(
|
||||
self,
|
||||
"Export Avery PDF",
|
||||
"avery-60504-labels.pdf",
|
||||
"PDF (*.pdf)",
|
||||
)
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
export_pdf(self.project, path, draw_guides=False)
|
||||
self.statusBar().showMessage(
|
||||
f"Exported {path} ({self.project.sheet_count} sheet(s))"
|
||||
)
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"PDF exported",
|
||||
"Print at 100% scale (Actual size).\n"
|
||||
"Do not use Fit to page.\n\n"
|
||||
f"Labels: {self.project.label_count}\n"
|
||||
f"Letter sheets in PDF: {self.project.sheet_count}\n"
|
||||
f"Sheet offsets: X={self.project.offset_x_in:.3f}\" "
|
||||
f"Y={self.project.offset_y_in:.3f}\"\n"
|
||||
f"Saved:\n{path}",
|
||||
)
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "Export failed", str(exc))
|
||||
|
||||
def export_guide_dialog(self) -> None:
|
||||
path, _ = QFileDialog.getSaveFileName(
|
||||
self,
|
||||
f"Export {TEMPLATE.name} alignment guide",
|
||||
f"avery-{TEMPLATE.id}-alignment-guide.pdf",
|
||||
"PDF (*.pdf)",
|
||||
)
|
||||
if not path:
|
||||
return
|
||||
guide = SheetProject(name=f"{TEMPLATE.name} Alignment Guide")
|
||||
guide.active_slots = [False, False, False, False]
|
||||
guide.offset_x_in = self.project.offset_x_in
|
||||
guide.offset_y_in = self.project.offset_y_in
|
||||
try:
|
||||
export_pdf(guide, path, draw_guides=True)
|
||||
self.statusBar().showMessage(f"Exported alignment guide {path}")
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"Alignment guide exported",
|
||||
f"Print on plain Letter paper, then hold over a {TEMPLATE.name} sheet against a light.\n\n"
|
||||
f"Saved:\n{path}",
|
||||
)
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "Export failed", str(exc))
|
||||
|
||||
def print_document(self) -> None:
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
if print_project(self.project, self):
|
||||
self.statusBar().showMessage(
|
||||
f"Sent {self.project.sheet_count} sheet(s) to printer"
|
||||
)
|
||||
|
||||
def print_preview(self) -> None:
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
print_preview_project(self.project, self)
|
||||
|
||||
def print_via_system(self) -> None:
|
||||
self.scene.sync_all()
|
||||
self.project.set_current(self.scene.design)
|
||||
if print_via_system_pdf(self.project, self):
|
||||
self.statusBar().showMessage("Opened print PDF in system PDF app")
|
||||
|
||||
def _apply_loaded_template(self, note: str = "", installed_json: Path | None = None) -> None:
|
||||
self.template_ready = bool(TEMPLATE.id)
|
||||
self.setWindowTitle(
|
||||
f"Avery Label Studio — {TEMPLATE.name}"
|
||||
if self.template_ready
|
||||
else "Avery Label Studio — Select a template"
|
||||
)
|
||||
self.scene.resize_to_active_template()
|
||||
self.canvas.reset_zoom()
|
||||
self._show_welcome(not self.template_ready)
|
||||
self._refresh_sheet_preview(immediate=True)
|
||||
self._sync_slot_ui()
|
||||
if installed_json and installed_json.is_file():
|
||||
set_last_template_path(installed_json)
|
||||
self._refresh_template_combo(select_path=installed_json)
|
||||
msg = self._status_template_text()
|
||||
if note:
|
||||
msg = f"{note} · {msg}"
|
||||
self.statusBar().showMessage(msg)
|
||||
|
||||
def _restore_last_template(self) -> bool:
|
||||
path = get_last_template_path()
|
||||
if path is None:
|
||||
return False
|
||||
try:
|
||||
activate_template_file(path)
|
||||
assert_geometry()
|
||||
self._refresh_template_combo(select_path=path)
|
||||
self._apply_loaded_template(f"Restored {path.name}", installed_json=path)
|
||||
return True
|
||||
except Exception:
|
||||
set_last_template_path(None)
|
||||
return False
|
||||
|
||||
def download_avery_template(self) -> None:
|
||||
dlg = DownloadAveryTemplateDialog(self)
|
||||
if dlg.exec() != dlg.DialogCode.Accepted or dlg.downloaded_path is None:
|
||||
return
|
||||
try:
|
||||
activate_template_file(dlg.downloaded_path)
|
||||
assert_geometry()
|
||||
installed = user_templates_dir() / f"{TEMPLATE.id or 'template'}.json"
|
||||
candidate = user_templates_dir() / f"{TEMPLATE.id}.json"
|
||||
if candidate.is_file():
|
||||
installed = candidate
|
||||
self._apply_loaded_template(
|
||||
f"Downloaded {dlg.downloaded_path.name}",
|
||||
installed_json=installed if installed.is_file() else None,
|
||||
)
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"Template installed",
|
||||
"Downloaded Word blank from Avery.com and measured it.\n\n"
|
||||
f"Saved under:\n{user_templates_dir()}\n\n"
|
||||
+ "\n".join(TEMPLATE.summary_lines()),
|
||||
)
|
||||
except TemplateLoadError as exc:
|
||||
QMessageBox.critical(self, "Template install failed", str(exc) or repr(exc))
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(
|
||||
self,
|
||||
"Template install failed",
|
||||
f"{type(exc).__name__}: {exc or '(no details)'}",
|
||||
)
|
||||
|
||||
def load_template_file(self) -> None:
|
||||
start = str(user_templates_dir())
|
||||
path, _ = QFileDialog.getOpenFileName(
|
||||
self,
|
||||
"Import Avery template file",
|
||||
start,
|
||||
"Templates (*.json *.doc *.docx *.pdf);;JSON (*.json);;Word (*.doc *.docx);;PDF (*.pdf)",
|
||||
)
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
activate_template_file(path)
|
||||
assert_geometry()
|
||||
candidate = user_templates_dir() / f"{TEMPLATE.id}.json"
|
||||
self._apply_loaded_template(
|
||||
f"Imported {Path(path).name}",
|
||||
installed_json=candidate if candidate.is_file() else None,
|
||||
)
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"Template installed",
|
||||
"Template measured and saved to AppData:\n"
|
||||
f"{user_templates_dir()}\n\n"
|
||||
f"Source: {path}\n\n" + "\n".join(TEMPLATE.summary_lines()),
|
||||
)
|
||||
except TemplateLoadError as exc:
|
||||
QMessageBox.critical(self, "Template load failed", str(exc) or repr(exc))
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(
|
||||
self,
|
||||
"Template load failed",
|
||||
f"{type(exc).__name__}: {exc or '(no details)'}",
|
||||
)
|
||||
|
||||
def open_templates_folder(self) -> None:
|
||||
folder = ensure_templates_dir()
|
||||
os.startfile(str(folder)) # noqa: S606 — Windows explorer
|
||||
|
||||
def show_template_specs(self) -> None:
|
||||
if not self.template_ready:
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"No template",
|
||||
"Select or download a template first.",
|
||||
)
|
||||
return
|
||||
QMessageBox.information(
|
||||
self,
|
||||
f"{TEMPLATE.name} specs",
|
||||
"\n".join(TEMPLATE.summary_lines())
|
||||
+ f"\n\nSaved templates:\n{user_templates_dir()}",
|
||||
)
|
||||
|
||||
def show_about(self) -> None:
|
||||
details = "<br>".join(TEMPLATE.summary_lines()) if self.template_ready else "No template selected"
|
||||
QMessageBox.about(
|
||||
self,
|
||||
"About Avery Label Studio",
|
||||
"<h3>Avery Label Studio</h3>"
|
||||
"<p>Open-source desktop designer for Avery label templates.</p>"
|
||||
"<p>No templates are shipped. Download Word blanks from Avery.com "
|
||||
"by product number, or import your own files.</p>"
|
||||
f"<p>Templates folder:<br><code>{user_templates_dir()}</code></p>"
|
||||
f"<p style='font-family: Consolas, monospace; font-size: 11px;'>{details}</p>"
|
||||
"<p>MIT License · Not affiliated with Avery Products Corporation.</p>",
|
||||
)
|
||||
@@ -0,0 +1,342 @@
|
||||
"""Label / sheet document models (JSON-serializable)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
from .import_settings import ImportSettings
|
||||
from .template_60504 import TEMPLATE
|
||||
|
||||
ElementType = Literal["text", "image", "rect"]
|
||||
LABELS_PER_SHEET = TEMPLATE.labels_per_sheet
|
||||
|
||||
|
||||
@dataclass
|
||||
class LabelElement:
|
||||
id: str
|
||||
type: ElementType
|
||||
x: float # inches from label top-left
|
||||
y: float
|
||||
width: float
|
||||
height: float
|
||||
text: str = ""
|
||||
font_family: str = "Helvetica"
|
||||
font_size: float = 18.0
|
||||
font_bold: bool = False
|
||||
align: Literal["left", "center", "right"] = "left"
|
||||
color: str = "#000000"
|
||||
image_path: str = ""
|
||||
fill: str = "#ffffff"
|
||||
stroke: str = "#000000"
|
||||
stroke_width: float = 0.0
|
||||
|
||||
@staticmethod
|
||||
def new_text(
|
||||
x: float = 0.2,
|
||||
y: float = 0.2,
|
||||
width: float = 3.5,
|
||||
height: float = 0.5,
|
||||
text: str = "Label text",
|
||||
) -> LabelElement:
|
||||
return LabelElement(
|
||||
id=str(uuid.uuid4()),
|
||||
type="text",
|
||||
x=x,
|
||||
y=y,
|
||||
width=width,
|
||||
height=height,
|
||||
text=text,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def new_image(
|
||||
image_path: str,
|
||||
x: float = 0.4,
|
||||
y: float = 0.9,
|
||||
width: float = 3.1,
|
||||
height: float = 2.0,
|
||||
) -> LabelElement:
|
||||
return LabelElement(
|
||||
id=str(uuid.uuid4()),
|
||||
type="image",
|
||||
x=x,
|
||||
y=y,
|
||||
width=width,
|
||||
height=height,
|
||||
image_path=image_path,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def new_rect(
|
||||
x: float = 0.08,
|
||||
y: float = 0.08,
|
||||
width: float = 3.7775,
|
||||
height: float = 3.7775,
|
||||
fill: str = "#ffffff",
|
||||
stroke: str = "#333333",
|
||||
stroke_width: float = 2.0,
|
||||
) -> LabelElement:
|
||||
return LabelElement(
|
||||
id=str(uuid.uuid4()),
|
||||
type="rect",
|
||||
x=x,
|
||||
y=y,
|
||||
width=width,
|
||||
height=height,
|
||||
fill=fill,
|
||||
stroke=stroke,
|
||||
stroke_width=stroke_width,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LabelDesign:
|
||||
"""Content for one Avery 60504 label panel."""
|
||||
|
||||
name: str = "Untitled Label"
|
||||
background: str = "#ffffff"
|
||||
elements: list[LabelElement] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> LabelDesign:
|
||||
elements = [LabelElement(**el) for el in data.get("elements", [])]
|
||||
return cls(
|
||||
name=data.get("name", "Untitled Label"),
|
||||
background=data.get("background", "#ffffff"),
|
||||
elements=elements,
|
||||
)
|
||||
|
||||
def copy_shallow(self) -> LabelDesign:
|
||||
return LabelDesign.from_dict(self.to_dict())
|
||||
|
||||
@property
|
||||
def is_empty(self) -> bool:
|
||||
return not self.elements
|
||||
|
||||
|
||||
@dataclass
|
||||
class SheetProject:
|
||||
"""
|
||||
Avery 60504 project that can span many Letter sheets.
|
||||
|
||||
Labels are stored in order. Every 4 labels = one printed Letter page.
|
||||
Example: 10 imported PDF pages → 10 labels → 3 output sheets.
|
||||
"""
|
||||
|
||||
name: str = "My Avery 60504 Sheet"
|
||||
labels: list[LabelDesign] = field(
|
||||
default_factory=lambda: [LabelDesign(name=f"Label {i + 1}") for i in range(LABELS_PER_SHEET)]
|
||||
)
|
||||
# Which of the 4 physical slots on each sheet are allowed to print
|
||||
# (applied on every output page). Empty trailing labels on the last sheet stay blank.
|
||||
active_slots: list[bool] = field(default_factory=lambda: [True, True, True, True])
|
||||
offset_x_in: float = 0.0
|
||||
offset_y_in: float = 0.0
|
||||
import_settings: ImportSettings = field(default_factory=ImportSettings)
|
||||
# Global label index being edited
|
||||
editing_index: int = 0
|
||||
# Which Letter sheet the preview is showing (0-based)
|
||||
preview_sheet: int = 0
|
||||
|
||||
# --- compatibility alias used by older UI code ---
|
||||
@property
|
||||
def slots(self) -> list[LabelDesign]:
|
||||
"""Labels on the currently previewed sheet (always length 4)."""
|
||||
return self.labels_for_sheet(self.preview_sheet)
|
||||
|
||||
@slots.setter
|
||||
def slots(self, value: list[LabelDesign]) -> None:
|
||||
self.replace_sheet_labels(self.preview_sheet, value)
|
||||
|
||||
@property
|
||||
def editing_slot(self) -> int:
|
||||
return self.editing_index % LABELS_PER_SHEET
|
||||
|
||||
@editing_slot.setter
|
||||
def editing_slot(self, slot: int) -> None:
|
||||
sheet = self.editing_index // LABELS_PER_SHEET
|
||||
self.editing_index = sheet * LABELS_PER_SHEET + max(0, min(3, slot))
|
||||
self.preview_sheet = sheet
|
||||
self.ensure_capacity(self.editing_index + 1)
|
||||
|
||||
def ensure_capacity(self, count: int) -> None:
|
||||
"""Grow the label list so at least `count` labels exist (pad empty)."""
|
||||
while len(self.labels) < count:
|
||||
self.labels.append(LabelDesign(name=f"Label {len(self.labels) + 1}"))
|
||||
while len(self.active_slots) < LABELS_PER_SHEET:
|
||||
self.active_slots.append(True)
|
||||
self.active_slots = self.active_slots[:LABELS_PER_SHEET]
|
||||
if self.labels:
|
||||
self.editing_index = max(0, min(len(self.labels) - 1, self.editing_index))
|
||||
else:
|
||||
self.editing_index = 0
|
||||
self.preview_sheet = max(0, min(self.sheet_count - 1, self.preview_sheet))
|
||||
|
||||
def ensure_slots(self) -> None:
|
||||
"""Backward-compatible: ensure at least one full sheet exists."""
|
||||
self.ensure_capacity(LABELS_PER_SHEET)
|
||||
|
||||
@property
|
||||
def sheet_count(self) -> int:
|
||||
if not self.labels:
|
||||
return 1
|
||||
return max(1, math.ceil(len(self.labels) / LABELS_PER_SHEET))
|
||||
|
||||
@property
|
||||
def label_count(self) -> int:
|
||||
return len(self.labels)
|
||||
|
||||
def labels_for_sheet(self, sheet_index: int) -> list[LabelDesign]:
|
||||
"""Return exactly 4 designs for a sheet (padding empty if needed)."""
|
||||
start = sheet_index * LABELS_PER_SHEET
|
||||
self.ensure_capacity(start + LABELS_PER_SHEET)
|
||||
return self.labels[start : start + LABELS_PER_SHEET]
|
||||
|
||||
def replace_sheet_labels(self, sheet_index: int, designs: list[LabelDesign]) -> None:
|
||||
start = sheet_index * LABELS_PER_SHEET
|
||||
self.ensure_capacity(start + LABELS_PER_SHEET)
|
||||
for i in range(LABELS_PER_SHEET):
|
||||
if i < len(designs):
|
||||
self.labels[start + i] = designs[i]
|
||||
|
||||
def set_labels(self, designs: list[LabelDesign]) -> None:
|
||||
"""Replace all labels (e.g. after importing a multi-page PDF)."""
|
||||
self.labels = list(designs) if designs else [LabelDesign(name="Label 1")]
|
||||
# Pad final sheet to a full 4 so layout stays consistent while editing
|
||||
remainder = len(self.labels) % LABELS_PER_SHEET
|
||||
if remainder:
|
||||
for _ in range(LABELS_PER_SHEET - remainder):
|
||||
self.labels.append(LabelDesign(name=f"Label {len(self.labels) + 1}"))
|
||||
self.editing_index = 0
|
||||
self.preview_sheet = 0
|
||||
|
||||
@property
|
||||
def current(self) -> LabelDesign:
|
||||
self.ensure_capacity(self.editing_index + 1)
|
||||
return self.labels[self.editing_index]
|
||||
|
||||
def set_current(self, design: LabelDesign) -> None:
|
||||
self.ensure_capacity(self.editing_index + 1)
|
||||
self.labels[self.editing_index] = design
|
||||
|
||||
def set_all_slots_from(self, design: LabelDesign) -> None:
|
||||
"""Copy one design into every slot of sheet 0 (legacy helper)."""
|
||||
self.ensure_capacity(LABELS_PER_SHEET)
|
||||
for i in range(LABELS_PER_SHEET):
|
||||
self.labels[i] = design.copy_shallow()
|
||||
self.labels[i].name = f"{design.name} ({i + 1})"
|
||||
self.labels = self.labels[:LABELS_PER_SHEET]
|
||||
self.editing_index = 0
|
||||
self.preview_sheet = 0
|
||||
|
||||
def global_index(self, sheet_index: int, slot: int) -> int:
|
||||
return sheet_index * LABELS_PER_SHEET + slot
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
self.ensure_capacity(max(LABELS_PER_SHEET, len(self.labels)))
|
||||
return {
|
||||
"name": self.name,
|
||||
"labels": [s.to_dict() for s in self.labels],
|
||||
# Keep writing "slots" for the first sheet for older readers
|
||||
"slots": [s.to_dict() for s in self.labels_for_sheet(0)],
|
||||
"active_slots": list(self.active_slots),
|
||||
"offset_x_in": self.offset_x_in,
|
||||
"offset_y_in": self.offset_y_in,
|
||||
"import_settings": self.import_settings.to_dict(),
|
||||
"editing_index": self.editing_index,
|
||||
"preview_sheet": self.preview_sheet,
|
||||
"format": "avery_sheet_v3",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> SheetProject:
|
||||
fmt = data.get("format")
|
||||
if fmt in ("avery_sheet_v3",) or "labels" in data:
|
||||
labels = [LabelDesign.from_dict(s) for s in data.get("labels", [])]
|
||||
proj = cls(
|
||||
name=data.get("name", "My Avery 60504 Sheet"),
|
||||
labels=labels or [LabelDesign(name=f"Label {i + 1}") for i in range(4)],
|
||||
active_slots=list(data.get("active_slots", [True, True, True, True])),
|
||||
offset_x_in=float(data.get("offset_x_in", 0.0)),
|
||||
offset_y_in=float(data.get("offset_y_in", 0.0)),
|
||||
import_settings=ImportSettings.from_dict(data.get("import_settings", {})),
|
||||
editing_index=int(data.get("editing_index", 0)),
|
||||
preview_sheet=int(data.get("preview_sheet", 0)),
|
||||
)
|
||||
proj.ensure_capacity(len(proj.labels))
|
||||
return proj
|
||||
|
||||
if fmt == "avery_sheet_v2" or "slots" in data:
|
||||
slots = [LabelDesign.from_dict(s) for s in data.get("slots", [])]
|
||||
proj = cls(
|
||||
name=data.get("name", "My Avery 60504 Sheet"),
|
||||
labels=slots or [LabelDesign(name=f"Label {i + 1}") for i in range(4)],
|
||||
active_slots=list(data.get("active_slots", [True, True, True, True])),
|
||||
offset_x_in=float(data.get("offset_x_in", 0.0)),
|
||||
offset_y_in=float(data.get("offset_y_in", 0.0)),
|
||||
import_settings=ImportSettings.from_dict(data.get("import_settings", {})),
|
||||
editing_index=int(data.get("editing_slot", 0)),
|
||||
)
|
||||
proj.ensure_capacity(len(proj.labels))
|
||||
return proj
|
||||
|
||||
legacy = LabelDesign.from_dict(data)
|
||||
proj = cls(
|
||||
name=data.get("name", legacy.name),
|
||||
offset_x_in=float(data.get("offset_x_in", 0.0)),
|
||||
offset_y_in=float(data.get("offset_y_in", 0.0)),
|
||||
active_slots=list(data.get("active_slots", [True, True, True, True])),
|
||||
)
|
||||
proj.set_all_slots_from(legacy)
|
||||
return proj
|
||||
|
||||
def save(self, path: Path | str) -> None:
|
||||
"""
|
||||
Save project JSON and copy linked images into a sibling assets folder.
|
||||
|
||||
Artwork imports stay in temp until you save — then they live next to the project,
|
||||
not in AppData.
|
||||
"""
|
||||
import shutil
|
||||
import uuid as _uuid
|
||||
|
||||
path = Path(path)
|
||||
assets = path.with_name(f"{path.stem}_assets")
|
||||
assets.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for design in self.labels:
|
||||
for el in design.elements:
|
||||
if el.type != "image" or not el.image_path:
|
||||
continue
|
||||
src = Path(el.image_path)
|
||||
if not src.is_file():
|
||||
continue
|
||||
# Already inside this project's assets folder
|
||||
try:
|
||||
if src.resolve().parent.resolve() == assets.resolve():
|
||||
el.image_path = str(src)
|
||||
continue
|
||||
except OSError:
|
||||
pass
|
||||
dest_name = f"{_uuid.uuid4().hex[:10]}_{src.name}"
|
||||
dest = assets / dest_name
|
||||
try:
|
||||
shutil.copy2(src, dest)
|
||||
el.image_path = str(dest)
|
||||
except OSError:
|
||||
# Keep original path if copy fails
|
||||
pass
|
||||
|
||||
path.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: Path | str) -> SheetProject:
|
||||
return cls.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Export SheetProject / LabelDesign to print-ready Avery 60504 PDF (multi-page)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.lib.colors import Color, HexColor
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
from .models import LABELS_PER_SHEET, LabelDesign, LabelElement, SheetProject
|
||||
from .template_60504 import INCH, TEMPLATE
|
||||
|
||||
|
||||
def _color(hex_color: str) -> Color:
|
||||
try:
|
||||
return HexColor(hex_color)
|
||||
except Exception:
|
||||
return HexColor("#000000")
|
||||
|
||||
|
||||
def _font_name(element: LabelElement) -> str:
|
||||
if element.font_bold:
|
||||
return "Helvetica-Bold"
|
||||
return "Helvetica"
|
||||
|
||||
|
||||
def _draw_element(c: canvas.Canvas, element: LabelElement, origin_x: float, origin_y: float) -> None:
|
||||
x = origin_x + element.x * INCH
|
||||
y = origin_y + (TEMPLATE.label_height_in - element.y - element.height) * INCH
|
||||
w = element.width * INCH
|
||||
h = element.height * INCH
|
||||
|
||||
if element.type == "rect":
|
||||
c.setFillColor(_color(element.fill))
|
||||
c.setStrokeColor(_color(element.stroke))
|
||||
c.setLineWidth(element.stroke_width)
|
||||
c.rect(x, y, w, h, stroke=1 if element.stroke_width > 0 else 0, fill=1)
|
||||
return
|
||||
|
||||
if element.type == "image" and element.image_path:
|
||||
path = Path(element.image_path)
|
||||
if path.is_file():
|
||||
# Fill the element box exactly (contain/cover/stretch already set w/h).
|
||||
c.drawImage(
|
||||
ImageReader(str(path)),
|
||||
x,
|
||||
y,
|
||||
width=w,
|
||||
height=h,
|
||||
preserveAspectRatio=False,
|
||||
mask="auto",
|
||||
)
|
||||
return
|
||||
|
||||
if element.type == "text":
|
||||
c.setFillColor(_color(element.color))
|
||||
font = _font_name(element)
|
||||
size = element.font_size
|
||||
c.setFont(font, size)
|
||||
lines = (element.text or "").splitlines() or [""]
|
||||
line_height = size * 1.25
|
||||
text_top = y + h - size
|
||||
for i, line in enumerate(lines):
|
||||
ty = text_top - i * line_height
|
||||
if ty < y - size:
|
||||
break
|
||||
if element.align == "center":
|
||||
c.drawCentredString(x + w / 2, ty, line)
|
||||
elif element.align == "right":
|
||||
c.drawRightString(x + w, ty, line)
|
||||
else:
|
||||
c.drawString(x, ty, line)
|
||||
|
||||
|
||||
def _draw_label(
|
||||
c: canvas.Canvas,
|
||||
design: LabelDesign,
|
||||
slot: int,
|
||||
*,
|
||||
offset_x_in: float,
|
||||
offset_y_in: float,
|
||||
draw_guides: bool,
|
||||
) -> None:
|
||||
ox, oy = TEMPLATE.label_origin_pt(
|
||||
slot,
|
||||
offset_x_in=offset_x_in,
|
||||
offset_y_in=offset_y_in,
|
||||
)
|
||||
c.setFillColor(_color(design.background))
|
||||
c.rect(ox, oy, TEMPLATE.label_width_pt, TEMPLATE.label_height_pt, stroke=0, fill=1)
|
||||
|
||||
if draw_guides:
|
||||
c.setStrokeColor(HexColor("#bbbbbb"))
|
||||
c.setDash(3, 3)
|
||||
c.setLineWidth(0.5)
|
||||
c.rect(ox, oy, TEMPLATE.label_width_pt, TEMPLATE.label_height_pt, stroke=1, fill=0)
|
||||
c.setDash()
|
||||
|
||||
c.saveState()
|
||||
path = c.beginPath()
|
||||
path.rect(ox, oy, TEMPLATE.label_width_pt, TEMPLATE.label_height_pt)
|
||||
c.clipPath(path, stroke=0, fill=0)
|
||||
for element in design.elements:
|
||||
_draw_element(c, element, ox, oy)
|
||||
c.restoreState()
|
||||
|
||||
|
||||
def _draw_empty_guide(
|
||||
c: canvas.Canvas,
|
||||
slot: int,
|
||||
*,
|
||||
offset_x_in: float,
|
||||
offset_y_in: float,
|
||||
) -> None:
|
||||
ox, oy = TEMPLATE.label_origin_pt(
|
||||
slot,
|
||||
offset_x_in=offset_x_in,
|
||||
offset_y_in=offset_y_in,
|
||||
)
|
||||
c.setStrokeColor(HexColor("#cccccc"))
|
||||
c.setDash(2, 2)
|
||||
c.rect(ox, oy, TEMPLATE.label_width_pt, TEMPLATE.label_height_pt, stroke=1, fill=0)
|
||||
c.setDash()
|
||||
|
||||
|
||||
def export_pdf(
|
||||
project: SheetProject | LabelDesign,
|
||||
output_path: Path | str,
|
||||
*,
|
||||
draw_guides: bool = False,
|
||||
) -> Path:
|
||||
"""Write a multi-page US Letter PDF for Avery 60504 (4 labels per page)."""
|
||||
if isinstance(project, LabelDesign):
|
||||
sheet = SheetProject(name=project.name)
|
||||
sheet.set_all_slots_from(project)
|
||||
else:
|
||||
sheet = project
|
||||
sheet.ensure_capacity(max(LABELS_PER_SHEET, len(sheet.labels)))
|
||||
|
||||
output_path = Path(output_path)
|
||||
c = canvas.Canvas(
|
||||
str(output_path),
|
||||
pagesize=(TEMPLATE.page_width_pt, TEMPLATE.page_height_pt),
|
||||
)
|
||||
c.setTitle(f"{sheet.name} — Avery 60504")
|
||||
c.setAuthor("Avery Label Studio (Open Source)")
|
||||
|
||||
total_sheets = sheet.sheet_count
|
||||
for page_index in range(total_sheets):
|
||||
page_labels = sheet.labels_for_sheet(page_index)
|
||||
for slot in range(LABELS_PER_SHEET):
|
||||
active = slot < len(sheet.active_slots) and sheet.active_slots[slot]
|
||||
design = page_labels[slot]
|
||||
has_content = not design.is_empty
|
||||
if active and has_content:
|
||||
_draw_label(
|
||||
c,
|
||||
design,
|
||||
slot,
|
||||
offset_x_in=sheet.offset_x_in,
|
||||
offset_y_in=sheet.offset_y_in,
|
||||
draw_guides=draw_guides,
|
||||
)
|
||||
elif draw_guides or (active and not has_content and draw_guides):
|
||||
_draw_empty_guide(
|
||||
c,
|
||||
slot,
|
||||
offset_x_in=sheet.offset_x_in,
|
||||
offset_y_in=sheet.offset_y_in,
|
||||
)
|
||||
elif draw_guides and not active:
|
||||
_draw_empty_guide(
|
||||
c,
|
||||
slot,
|
||||
offset_x_in=sheet.offset_x_in,
|
||||
offset_y_in=sheet.offset_y_in,
|
||||
)
|
||||
c.showPage()
|
||||
|
||||
c.save()
|
||||
return output_path
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Persisted app preferences (last template, etc.)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .app_paths import user_data_dir
|
||||
|
||||
|
||||
def preferences_path() -> Path:
|
||||
return user_data_dir() / "settings.json"
|
||||
|
||||
|
||||
def load_preferences() -> dict[str, Any]:
|
||||
path = preferences_path()
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def save_preferences(data: dict[str, Any]) -> None:
|
||||
path = preferences_path()
|
||||
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def get_last_template_path() -> Path | None:
|
||||
raw = load_preferences().get("last_template_path")
|
||||
if not raw:
|
||||
return None
|
||||
path = Path(str(raw))
|
||||
return path if path.is_file() else None
|
||||
|
||||
|
||||
def set_last_template_path(path: Path | str | None) -> None:
|
||||
data = load_preferences()
|
||||
if path is None:
|
||||
data.pop("last_template_path", None)
|
||||
else:
|
||||
data["last_template_path"] = str(Path(path))
|
||||
save_preferences(data)
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Print Avery sheets via the system print dialog (actual size, honor user settings)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QMarginsF, QRectF, Qt
|
||||
from PySide6.QtGui import QImage, QPageLayout, QPageSize, QPainter
|
||||
from PySide6.QtPrintSupport import (
|
||||
QAbstractPrintDialog,
|
||||
QPrintDialog,
|
||||
QPrinter,
|
||||
QPrintPreviewDialog,
|
||||
)
|
||||
from PySide6.QtWidgets import QMessageBox, QWidget
|
||||
|
||||
from .models import SheetProject
|
||||
from .pdf_export import export_pdf
|
||||
from .template_60504 import TEMPLATE
|
||||
|
||||
# Render PDF pages at this DPI for the printer paint path (1:1 inches).
|
||||
_PRINT_DPI = 300.0
|
||||
|
||||
# Remember last printer so we do not silently switch devices.
|
||||
_last_printer_name: str | None = None
|
||||
|
||||
|
||||
def _project_to_temp_pdf(project: SheetProject) -> Path:
|
||||
tmp = Path(tempfile.gettempdir()) / "avery_label_studio_print.pdf"
|
||||
export_pdf(project, tmp, draw_guides=False)
|
||||
return tmp
|
||||
|
||||
|
||||
def _render_pdf_pages(pdf_path: Path, dpi: float = _PRINT_DPI) -> list[QImage]:
|
||||
try:
|
||||
import fitz
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("Printing requires pymupdf") from exc
|
||||
|
||||
images: list[QImage] = []
|
||||
doc = fitz.open(pdf_path)
|
||||
try:
|
||||
zoom = dpi / 72.0
|
||||
matrix = fitz.Matrix(zoom, zoom)
|
||||
for page in doc:
|
||||
pix = page.get_pixmap(matrix=matrix, alpha=False)
|
||||
fmt = QImage.Format.Format_RGB888
|
||||
img = QImage(pix.samples, pix.width, pix.height, pix.stride, fmt).copy()
|
||||
images.append(img)
|
||||
finally:
|
||||
doc.close()
|
||||
return images
|
||||
|
||||
|
||||
def _make_printer(doc_name: str) -> QPrinter:
|
||||
"""Create a printer with soft Letter defaults — never re-applied after the dialog."""
|
||||
global _last_printer_name
|
||||
printer = QPrinter(QPrinter.PrinterMode.HighResolution)
|
||||
if _last_printer_name:
|
||||
printer.setPrinterName(_last_printer_name)
|
||||
|
||||
# Soft defaults only. User Preferences / Properties in the dialog win after Accept.
|
||||
layout = QPageLayout(
|
||||
QPageSize(QPageSize.PageSizeId.Letter),
|
||||
QPageLayout.Orientation.Portrait,
|
||||
QMarginsF(0, 0, 0, 0),
|
||||
QPageLayout.Unit.Inch,
|
||||
)
|
||||
layout.setMode(QPageLayout.Mode.FullPageMode)
|
||||
printer.setPageLayout(layout)
|
||||
printer.setDocName(doc_name)
|
||||
printer.setFullPage(True)
|
||||
return printer
|
||||
|
||||
|
||||
def _remember_printer(printer: QPrinter) -> None:
|
||||
global _last_printer_name
|
||||
name = printer.printerName()
|
||||
if name:
|
||||
_last_printer_name = name
|
||||
|
||||
|
||||
def _configure_print_dialog(dialog: QPrintDialog) -> None:
|
||||
"""Expose every Qt-supported print option (native Windows dialog by default)."""
|
||||
opts = (
|
||||
QAbstractPrintDialog.PrintDialogOption.PrintToFile
|
||||
| QAbstractPrintDialog.PrintDialogOption.PrintPageRange
|
||||
| QAbstractPrintDialog.PrintDialogOption.PrintShowPageSize
|
||||
| QAbstractPrintDialog.PrintDialogOption.PrintCollateCopies
|
||||
| QAbstractPrintDialog.PrintDialogOption.PrintCurrentPage
|
||||
)
|
||||
dialog.setOptions(opts)
|
||||
|
||||
|
||||
def _paint_pages_on_printer(
|
||||
printer: QPrinter,
|
||||
images: list[QImage],
|
||||
source_dpi: float = _PRINT_DPI,
|
||||
) -> None:
|
||||
"""Paint Letter pages at actual physical size — do not fit/scale/center to override settings."""
|
||||
# Honor the page layout the user chose in the dialog (paper, orientation, full page).
|
||||
# Only ensure we paint the full sheet so Avery geometry is not inset twice.
|
||||
layout = printer.pageLayout()
|
||||
if layout.mode() != QPageLayout.Mode.FullPageMode:
|
||||
layout.setMode(QPageLayout.Mode.FullPageMode)
|
||||
printer.setPageLayout(layout)
|
||||
printer.setFullPage(True)
|
||||
|
||||
painter = QPainter(printer)
|
||||
try:
|
||||
dpi_x = float(printer.logicalDpiX()) or source_dpi
|
||||
dpi_y = float(printer.logicalDpiY()) or source_dpi
|
||||
page_rect = printer.pageRect(QPrinter.Unit.DevicePixel)
|
||||
|
||||
for i, image in enumerate(images):
|
||||
if i > 0:
|
||||
printer.newPage()
|
||||
|
||||
# Exact inches from render DPI → printer device pixels (100% / actual size).
|
||||
dest_w = image.width() * (dpi_x / source_dpi)
|
||||
dest_h = image.height() * (dpi_y / source_dpi)
|
||||
dest = QRectF(page_rect.left(), page_rect.top(), dest_w, dest_h)
|
||||
painter.drawImage(dest, image, image.rect())
|
||||
finally:
|
||||
painter.end()
|
||||
|
||||
|
||||
def print_project(project: SheetProject, parent: QWidget | None = None) -> bool:
|
||||
"""Show native print dialog and print all sheets at actual size. Returns True if sent."""
|
||||
try:
|
||||
pdf_path = _project_to_temp_pdf(project)
|
||||
images = _render_pdf_pages(pdf_path)
|
||||
except Exception as exc:
|
||||
if parent:
|
||||
QMessageBox.critical(parent, "Print failed", str(exc))
|
||||
return False
|
||||
|
||||
if not images:
|
||||
if parent:
|
||||
QMessageBox.warning(parent, "Print", "Nothing to print.")
|
||||
return False
|
||||
|
||||
printer = _make_printer(f"{project.name} — {TEMPLATE.name}")
|
||||
dialog = QPrintDialog(printer, parent)
|
||||
dialog.setWindowTitle(f"Print {TEMPLATE.name}")
|
||||
_configure_print_dialog(dialog)
|
||||
|
||||
if dialog.exec() != QPrintDialog.DialogCode.Accepted:
|
||||
return False
|
||||
|
||||
# Do not call setPageSize / setResolution / setPageLayout after Accept —
|
||||
# that is what overrides tray, duplex, scale, and media type from Preferences.
|
||||
_remember_printer(printer)
|
||||
|
||||
try:
|
||||
_paint_pages_on_printer(printer, images)
|
||||
except Exception as exc:
|
||||
if parent:
|
||||
QMessageBox.critical(parent, "Print failed", str(exc))
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def print_preview_project(project: SheetProject, parent: QWidget | None = None) -> bool:
|
||||
"""Show print preview; printing from preview also uses actual-size paint."""
|
||||
try:
|
||||
pdf_path = _project_to_temp_pdf(project)
|
||||
images = _render_pdf_pages(pdf_path)
|
||||
except Exception as exc:
|
||||
if parent:
|
||||
QMessageBox.critical(parent, "Print preview failed", str(exc))
|
||||
return False
|
||||
|
||||
printer = _make_printer(f"{project.name} — {TEMPLATE.name}")
|
||||
|
||||
def _paint(p: QPrinter) -> None:
|
||||
_remember_printer(p)
|
||||
_paint_pages_on_printer(p, images)
|
||||
|
||||
preview = QPrintPreviewDialog(printer, parent)
|
||||
preview.setWindowTitle(f"Print Preview — {TEMPLATE.name}")
|
||||
preview.paintRequested.connect(_paint)
|
||||
preview.exec()
|
||||
return True
|
||||
|
||||
|
||||
def print_via_system_pdf(project: SheetProject, parent: QWidget | None = None) -> bool:
|
||||
"""Open/print the PDF with Windows so the full printer driver UI is available.
|
||||
|
||||
Use this when the Qt dialog is missing tray, duplex, media type, or other
|
||||
driver-specific settings. Edge/Adobe/etc. show the complete Preferences sheet.
|
||||
"""
|
||||
try:
|
||||
pdf_path = _project_to_temp_pdf(project)
|
||||
except Exception as exc:
|
||||
if parent:
|
||||
QMessageBox.critical(parent, "Print failed", str(exc))
|
||||
return False
|
||||
|
||||
if parent:
|
||||
QMessageBox.information(
|
||||
parent,
|
||||
"System print",
|
||||
"Opening the print PDF in your default PDF app.\n\n"
|
||||
"Use that app’s Print dialog (Ctrl+P) for the full printer settings:\n"
|
||||
"tray, duplex, media type, quality, etc.\n\n"
|
||||
"Print at 100% / Actual size — do not Fit to page.",
|
||||
)
|
||||
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
os.startfile(pdf_path) # noqa: S606 — intentional user print helper
|
||||
else:
|
||||
subprocess.run(["xdg-open", str(pdf_path)], check=False)
|
||||
except OSError as exc:
|
||||
if parent:
|
||||
QMessageBox.critical(
|
||||
parent,
|
||||
"Print failed",
|
||||
f"Could not open PDF:\n{pdf_path}\n\n{exc}",
|
||||
)
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Full US Letter sheet preview showing all label slots (lightweight)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QRectF, Qt, Signal
|
||||
from PySide6.QtGui import QColor, QFont, QPainter, QPen, QPixmap
|
||||
from PySide6.QtWidgets import QWidget
|
||||
|
||||
from .models import LabelDesign, SheetProject
|
||||
from .template_60504 import TEMPLATE
|
||||
|
||||
# Keep preview cheap — full-res images were a major lag source
|
||||
SHEET_DPI = 36
|
||||
_THUMB_CACHE: dict[str, QPixmap] = {}
|
||||
_THUMB_CACHE_MAX = 64
|
||||
|
||||
|
||||
def _cached_thumb(path: str, w: int, h: int) -> QPixmap:
|
||||
key = f"{path}|{w}x{h}"
|
||||
hit = _THUMB_CACHE.get(key)
|
||||
if hit is not None and not hit.isNull():
|
||||
return hit
|
||||
src = QPixmap(path)
|
||||
if src.isNull():
|
||||
return QPixmap()
|
||||
# Fill element box (stretch/cover/contain already baked into element size)
|
||||
scaled = src.scaled(
|
||||
max(1, w),
|
||||
max(1, h),
|
||||
Qt.AspectRatioMode.IgnoreAspectRatio,
|
||||
Qt.TransformationMode.FastTransformation,
|
||||
)
|
||||
if len(_THUMB_CACHE) >= _THUMB_CACHE_MAX:
|
||||
_THUMB_CACHE.clear()
|
||||
_THUMB_CACHE[key] = scaled
|
||||
return scaled
|
||||
|
||||
|
||||
class SheetPreview(QWidget):
|
||||
"""Live preview of the full Letter page with label slots."""
|
||||
|
||||
slot_clicked = Signal(int)
|
||||
|
||||
def __init__(self, parent=None) -> None:
|
||||
super().__init__(parent)
|
||||
self.project: SheetProject | None = None
|
||||
self._slot_pixmaps: list[QPixmap] = [QPixmap() for _ in range(4)]
|
||||
self.setMinimumWidth(260)
|
||||
self.setMinimumHeight(320)
|
||||
self.setMouseTracking(True)
|
||||
self.setToolTip("Full sheet — click a slot to edit")
|
||||
|
||||
def set_project(self, project: SheetProject) -> None:
|
||||
self.project = project
|
||||
self.rebuild_slot_pixmaps()
|
||||
|
||||
def _header_text(self) -> str:
|
||||
if not self.project:
|
||||
return f"{TEMPLATE.name} · Letter sheet"
|
||||
total = self.project.sheet_count
|
||||
current = self.project.preview_sheet + 1
|
||||
labels = self.project.label_count
|
||||
return f"{TEMPLATE.name} · Sheet {current}/{total} · {labels} label(s)"
|
||||
|
||||
def rebuild_slot_pixmaps(self) -> None:
|
||||
if not self.project:
|
||||
self._slot_pixmaps = [QPixmap() for _ in range(4)]
|
||||
self.update()
|
||||
return
|
||||
sheet_labels = self.project.labels_for_sheet(self.project.preview_sheet)
|
||||
self._slot_pixmaps = [self._render_design(d) for d in sheet_labels]
|
||||
self.update()
|
||||
|
||||
def _render_design(self, design: LabelDesign) -> QPixmap:
|
||||
w = max(1, int(TEMPLATE.label_width_in * SHEET_DPI))
|
||||
h = max(1, int(TEMPLATE.label_height_in * SHEET_DPI))
|
||||
pix = QPixmap(w, h)
|
||||
pix.fill(QColor(design.background))
|
||||
painter = QPainter(pix)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, False)
|
||||
sx = w / TEMPLATE.label_width_in
|
||||
sy = h / TEMPLATE.label_height_in
|
||||
for el in design.elements:
|
||||
ex = el.x * sx
|
||||
ey = el.y * sy
|
||||
ew = max(1.0, el.width * sx)
|
||||
eh = max(1.0, el.height * sy)
|
||||
if el.type == "rect":
|
||||
painter.setBrush(QColor(el.fill))
|
||||
painter.setPen(QPen(QColor(el.stroke), max(1.0, el.stroke_width)))
|
||||
painter.drawRect(QRectF(ex, ey, ew, eh))
|
||||
elif el.type == "image" and el.image_path and Path(el.image_path).is_file():
|
||||
img = _cached_thumb(el.image_path, int(ew), int(eh))
|
||||
if not img.isNull():
|
||||
painter.drawPixmap(int(ex), int(ey), img)
|
||||
elif el.type == "text":
|
||||
painter.setPen(QColor(el.color))
|
||||
font = QFont("Arial", max(6, int(el.font_size * (sx / 96.0) * 0.85)))
|
||||
font.setBold(el.font_bold)
|
||||
painter.setFont(font)
|
||||
align = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
|
||||
if el.align == "center":
|
||||
align = Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop
|
||||
elif el.align == "right":
|
||||
align = Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop
|
||||
painter.drawText(QRectF(ex, ey, ew, eh), align, el.text)
|
||||
painter.end()
|
||||
return pix
|
||||
|
||||
def refresh(self) -> None:
|
||||
self.rebuild_slot_pixmaps()
|
||||
|
||||
def _page_rect(self) -> QRectF:
|
||||
pad = 12.0
|
||||
avail_w = max(1.0, self.width() - pad * 2)
|
||||
avail_h = max(1.0, self.height() - pad * 2 - 28)
|
||||
page_aspect = TEMPLATE.page_width_in / TEMPLATE.page_height_in
|
||||
widget_aspect = avail_w / avail_h
|
||||
if widget_aspect > page_aspect:
|
||||
h = avail_h
|
||||
w = h * page_aspect
|
||||
else:
|
||||
w = avail_w
|
||||
h = w / page_aspect
|
||||
x = (self.width() - w) / 2
|
||||
y = 20 + (avail_h - h) / 2
|
||||
return QRectF(x, y, w, h)
|
||||
|
||||
def _slot_rect(self, index: int, page: QRectF) -> QRectF:
|
||||
left_in, top_in = TEMPLATE.label_origin_in(index)
|
||||
if self.project:
|
||||
left_in += self.project.offset_x_in
|
||||
top_in += self.project.offset_y_in
|
||||
sx = page.width() / TEMPLATE.page_width_in
|
||||
sy = page.height() / TEMPLATE.page_height_in
|
||||
return QRectF(
|
||||
page.left() + left_in * sx,
|
||||
page.top() + top_in * sy,
|
||||
TEMPLATE.label_width_in * sx,
|
||||
TEMPLATE.label_height_in * sy,
|
||||
)
|
||||
|
||||
def _slot_at(self, pos) -> int | None:
|
||||
page = self._page_rect()
|
||||
for i in range(TEMPLATE.labels_per_sheet):
|
||||
if self._slot_rect(i, page).contains(pos):
|
||||
return i
|
||||
return None
|
||||
|
||||
def mousePressEvent(self, event) -> None:
|
||||
if event.button() == Qt.MouseButton.LeftButton:
|
||||
slot = self._slot_at(event.position())
|
||||
if slot is not None:
|
||||
self.slot_clicked.emit(slot)
|
||||
event.accept()
|
||||
return
|
||||
super().mousePressEvent(event)
|
||||
|
||||
def paintEvent(self, event) -> None:
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
painter.fillRect(self.rect(), QColor("#cbd5e1"))
|
||||
|
||||
page = self._page_rect()
|
||||
shadow = page.translated(3, 3)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(0, 0, 0, 40))
|
||||
painter.drawRoundedRect(shadow, 2, 2)
|
||||
|
||||
painter.setBrush(QColor("#f8fafc"))
|
||||
painter.setPen(QPen(QColor("#64748b"), 1.2))
|
||||
painter.drawRect(page)
|
||||
|
||||
painter.setPen(QColor("#334155"))
|
||||
font = QFont("Segoe UI", 9)
|
||||
font.setBold(True)
|
||||
painter.setFont(font)
|
||||
painter.drawText(
|
||||
QRectF(page.left(), max(0.0, page.top() - 18), page.width(), 16),
|
||||
Qt.AlignmentFlag.AlignCenter,
|
||||
self._header_text(),
|
||||
)
|
||||
|
||||
active = self.project.active_slots if self.project else [True, True, True, True]
|
||||
editing_slot = self.project.editing_slot if self.project else 0
|
||||
editing_on_this_sheet = (
|
||||
self.project is not None
|
||||
and (self.project.editing_index // 4) == self.project.preview_sheet
|
||||
)
|
||||
|
||||
sheet_labels = (
|
||||
self.project.labels_for_sheet(self.project.preview_sheet)
|
||||
if self.project
|
||||
else []
|
||||
)
|
||||
|
||||
for i in range(TEMPLATE.labels_per_sheet):
|
||||
rect = self._slot_rect(i, page)
|
||||
is_on = i < len(active) and active[i]
|
||||
pix = self._slot_pixmaps[i] if i < len(self._slot_pixmaps) else QPixmap()
|
||||
design = sheet_labels[i] if i < len(sheet_labels) else None
|
||||
empty = design is None or design.is_empty
|
||||
|
||||
if is_on and not pix.isNull() and not empty:
|
||||
painter.drawPixmap(rect.toRect(), pix)
|
||||
elif is_on and empty:
|
||||
painter.fillRect(rect, QColor("#f1f5f9"))
|
||||
painter.setPen(QColor("#94a3b8"))
|
||||
painter.setFont(QFont("Segoe UI", 8))
|
||||
painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, f"Slot {i + 1}\n(empty)")
|
||||
elif is_on:
|
||||
bg = design.background if design else "#ffffff"
|
||||
painter.fillRect(rect, QColor(bg))
|
||||
else:
|
||||
painter.fillRect(rect, QColor("#e2e8f0"))
|
||||
painter.setPen(QPen(QColor("#94a3b8"), 1.0, Qt.PenStyle.DashLine))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(rect)
|
||||
painter.setPen(QColor("#64748b"))
|
||||
painter.setFont(QFont("Segoe UI", 8))
|
||||
painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, f"Slot {i + 1}\n(skipped)")
|
||||
continue
|
||||
|
||||
is_editing = editing_on_this_sheet and i == editing_slot
|
||||
outline = QColor("#2563eb") if is_editing else QColor("#0f766e")
|
||||
width = 2.4 if is_editing else 1.4
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.setPen(QPen(outline, width))
|
||||
painter.drawRect(rect)
|
||||
|
||||
badge = QRectF(rect.left() + 4, rect.top() + 4, 18, 18)
|
||||
painter.setBrush(outline)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.drawRoundedRect(badge, 3, 3)
|
||||
painter.setPen(QColor("#ffffff"))
|
||||
badge_font = QFont("Segoe UI", 8)
|
||||
badge_font.setBold(True)
|
||||
painter.setFont(badge_font)
|
||||
painter.drawText(badge, Qt.AlignmentFlag.AlignCenter, str(i + 1))
|
||||
|
||||
painter.setPen(QColor("#475569"))
|
||||
painter.setFont(QFont("Segoe UI", 8))
|
||||
painter.drawText(
|
||||
QRectF(0, self.height() - 22, self.width(), 18),
|
||||
Qt.AlignmentFlag.AlignCenter,
|
||||
"Prev/Next sheet · Click a slot to edit",
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
"""Avery template definitions — geometry loaded from measured template files.
|
||||
|
||||
Default 60504 values were measured from the official Avery Word blank:
|
||||
TEMPLATES/Avery60504UltraDutyGHSLabelsLaser.doc (shape guides Rectangle 2–5).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
INCH = 72.0 # PDF points per inch
|
||||
TWIP = 1440.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LabelTemplate:
|
||||
"""Printable label-sheet geometry for one Avery (or compatible) product."""
|
||||
|
||||
id: str = "60504"
|
||||
name: str = "Avery 60504"
|
||||
source_file: str = ""
|
||||
source_url: str = "https://www.avery.com/templates/60504"
|
||||
product_group: str = "U-0651-01"
|
||||
marketed_size: str = '4" x 4"'
|
||||
print_to_edge: bool = False
|
||||
compatible: tuple[str, ...] = ("60524", "64659", "Presta 97200")
|
||||
|
||||
page_width_in: float = 8.5
|
||||
page_height_in: float = 11.0
|
||||
|
||||
# Measured from Avery60504UltraDutyGHSLabelsLaser.doc shape guides
|
||||
label_width_in: float = 3.9368057250976562
|
||||
label_height_in: float = 3.9368057250976562
|
||||
columns: int = 2
|
||||
rows: int = 2
|
||||
labels_per_sheet: int = 4
|
||||
|
||||
left_margin_in: float = 0.25069443384806317
|
||||
top_margin_in: float = 1.0013888676961262
|
||||
horizontal_gap_in: float = 0.125
|
||||
# IMPORTANT: vertical gap is ~1.126", NOT 0.125" (that was the layout bug)
|
||||
vertical_gap_in: float = 1.1263885137695005
|
||||
|
||||
@property
|
||||
def horizontal_pitch_in(self) -> float:
|
||||
return self.label_width_in + self.horizontal_gap_in
|
||||
|
||||
@property
|
||||
def vertical_pitch_in(self) -> float:
|
||||
return self.label_height_in + self.vertical_gap_in
|
||||
|
||||
@property
|
||||
def right_margin_in(self) -> float:
|
||||
return (
|
||||
self.page_width_in
|
||||
- self.left_margin_in
|
||||
- self.columns * self.label_width_in
|
||||
- (self.columns - 1) * self.horizontal_gap_in
|
||||
)
|
||||
|
||||
@property
|
||||
def bottom_margin_in(self) -> float:
|
||||
return (
|
||||
self.page_height_in
|
||||
- self.top_margin_in
|
||||
- self.rows * self.label_height_in
|
||||
- (self.rows - 1) * self.vertical_gap_in
|
||||
)
|
||||
|
||||
@property
|
||||
def page_width_pt(self) -> float:
|
||||
return self.page_width_in * INCH
|
||||
|
||||
@property
|
||||
def page_height_pt(self) -> float:
|
||||
return self.page_height_in * INCH
|
||||
|
||||
@property
|
||||
def label_width_pt(self) -> float:
|
||||
return self.label_width_in * INCH
|
||||
|
||||
@property
|
||||
def label_height_pt(self) -> float:
|
||||
return self.label_height_in * INCH
|
||||
|
||||
def label_origin_in(self, index: int) -> tuple[float, float]:
|
||||
if index < 0 or index >= self.labels_per_sheet:
|
||||
raise IndexError(f"Label index must be 0..{self.labels_per_sheet - 1}")
|
||||
col = index % self.columns
|
||||
row = index // self.columns
|
||||
left = self.left_margin_in + col * self.horizontal_pitch_in
|
||||
top = self.top_margin_in + row * self.vertical_pitch_in
|
||||
return left, top
|
||||
|
||||
def label_origin_pt(
|
||||
self,
|
||||
index: int,
|
||||
*,
|
||||
offset_x_in: float = 0.0,
|
||||
offset_y_in: float = 0.0,
|
||||
) -> tuple[float, float]:
|
||||
left_in, top_in = self.label_origin_in(index)
|
||||
left_in += offset_x_in
|
||||
top_in += offset_y_in
|
||||
x = left_in * INCH
|
||||
y = (self.page_height_in - top_in - self.label_height_in) * INCH
|
||||
return x, y
|
||||
|
||||
def summary_lines(self) -> list[str]:
|
||||
lines = [
|
||||
f"{self.name} ({self.marketed_size} marketed · {self.label_width_in:.4f}\" panel)",
|
||||
f"Page: {self.page_width_in}\" × {self.page_height_in}\" Letter",
|
||||
f"Labels: {self.columns}×{self.rows} = {self.labels_per_sheet}/sheet",
|
||||
f"Left/Top: {self.left_margin_in:.4f}\" / {self.top_margin_in:.4f}\"",
|
||||
f"Gap H/V: {self.horizontal_gap_in:.4f}\" / {self.vertical_gap_in:.4f}\"",
|
||||
f"Pitch H/V: {self.horizontal_pitch_in:.4f}\" / {self.vertical_pitch_in:.4f}\"",
|
||||
]
|
||||
if self.source_file:
|
||||
lines.append(f"Source file: {self.source_file}")
|
||||
if self.source_url:
|
||||
lines.append(f"URL: {self.source_url}")
|
||||
if self.compatible:
|
||||
lines.append(f"Compatible: {', '.join(self.compatible)}")
|
||||
return lines
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
d = asdict(self)
|
||||
d["compatible"] = list(self.compatible)
|
||||
return d
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> LabelTemplate:
|
||||
compat = data.get("compatible", ())
|
||||
if isinstance(compat, list):
|
||||
compat = tuple(compat)
|
||||
known = {f.name for f in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
|
||||
kwargs = {k: v for k, v in data.items() if k in known and k != "compatible"}
|
||||
return cls(compatible=compat, **kwargs)
|
||||
|
||||
def save_json(self, path: Path | str) -> None:
|
||||
Path(path).write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
|
||||
|
||||
@classmethod
|
||||
def load_json(cls, path: Path | str) -> LabelTemplate:
|
||||
return cls.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
# Placeholder until the user selects / downloads a template (not auto-activated)
|
||||
UNSET_TEMPLATE = LabelTemplate(
|
||||
id="",
|
||||
name="Select a template",
|
||||
source_file="",
|
||||
source_url="https://www.avery.com/templates",
|
||||
product_group="",
|
||||
marketed_size="",
|
||||
compatible=(),
|
||||
)
|
||||
|
||||
# Reference geometry measured from an Avery 60504 Word blank (used after user installs 60504)
|
||||
AVERY_60504 = LabelTemplate(
|
||||
id="60504",
|
||||
name="Avery 60504",
|
||||
source_file="",
|
||||
source_url="https://www.avery.com/templates/60504",
|
||||
product_group="U-0651-01",
|
||||
)
|
||||
|
||||
|
||||
class _ActiveTemplateProxy:
|
||||
"""
|
||||
Stable object imported as TEMPLATE everywhere.
|
||||
|
||||
`from module import TEMPLATE` keeps one reference; this proxy always
|
||||
forwards attribute access to the currently active LabelTemplate.
|
||||
"""
|
||||
|
||||
__slots__ = ("_current",)
|
||||
|
||||
def __init__(self, initial: LabelTemplate) -> None:
|
||||
object.__setattr__(self, "_current", initial)
|
||||
|
||||
def _set(self, template: LabelTemplate) -> LabelTemplate:
|
||||
object.__setattr__(self, "_current", template)
|
||||
return template
|
||||
|
||||
def _get(self) -> LabelTemplate:
|
||||
return object.__getattribute__(self, "_current")
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._get(), name)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return repr(self._get())
|
||||
|
||||
|
||||
# Mutable active template used by the rest of the app (proxy — do not rebind)
|
||||
TEMPLATE = _ActiveTemplateProxy(UNSET_TEMPLATE)
|
||||
|
||||
|
||||
def set_active_template(template: LabelTemplate) -> LabelTemplate:
|
||||
return TEMPLATE._set(template)
|
||||
|
||||
|
||||
def get_active_template() -> LabelTemplate:
|
||||
return TEMPLATE._get()
|
||||
|
||||
|
||||
def assert_geometry(template: LabelTemplate | None = None) -> None:
|
||||
"""Sanity-check that margins + labels + gaps fill the page (no hardcoded coords)."""
|
||||
t = template or get_active_template()
|
||||
if not t.id:
|
||||
return
|
||||
width = (
|
||||
t.left_margin_in
|
||||
+ t.columns * t.label_width_in
|
||||
+ (t.columns - 1) * t.horizontal_gap_in
|
||||
+ t.right_margin_in
|
||||
)
|
||||
height = (
|
||||
t.top_margin_in
|
||||
+ t.rows * t.label_height_in
|
||||
+ (t.rows - 1) * t.vertical_gap_in
|
||||
+ t.bottom_margin_in
|
||||
)
|
||||
if abs(width - t.page_width_in) >= 0.02:
|
||||
raise ValueError(
|
||||
f"Template width math does not match page width "
|
||||
f"({width:.4f}\" vs {t.page_width_in:.4f}\")."
|
||||
)
|
||||
if abs(height - t.page_height_in) >= 0.02:
|
||||
raise ValueError(
|
||||
f"Template height math does not match page height "
|
||||
f"({height:.4f}\" vs {t.page_height_in:.4f}\")."
|
||||
)
|
||||
if t.label_width_in <= 0 or t.label_height_in <= 0:
|
||||
raise ValueError("Template label size must be greater than zero.")
|
||||
if t.labels_per_sheet < 1:
|
||||
raise ValueError("Template must have at least one label per sheet.")
|
||||
@@ -0,0 +1,287 @@
|
||||
"""Load / measure / install Avery template files into AppData (user-owned only)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from .app_paths import user_templates_dir
|
||||
from .template_60504 import AVERY_60504, LabelTemplate, set_active_template
|
||||
|
||||
SUPPORTED_TEMPLATE_EXT = {".json", ".doc", ".docx", ".pdf"}
|
||||
|
||||
|
||||
class TemplateLoadError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def templates_dir() -> Path:
|
||||
"""User-writable installed templates (%LOCALAPPDATA%\\AveryLabelStudio\\templates)."""
|
||||
return user_templates_dir()
|
||||
|
||||
|
||||
def ensure_templates_dir() -> Path:
|
||||
path = user_templates_dir()
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def list_installed_templates(folder: Path | None = None) -> list[Path]:
|
||||
"""Installed templates for the dropdown — measured .json files only."""
|
||||
folder = folder or user_templates_dir()
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
return [
|
||||
p
|
||||
for p in sorted(folder.iterdir(), key=lambda p: p.name.lower())
|
||||
if p.is_file() and p.suffix.lower() == ".json"
|
||||
]
|
||||
|
||||
|
||||
def list_template_files(folder: Path | None = None) -> list[Path]:
|
||||
return list_installed_templates(folder)
|
||||
|
||||
|
||||
def load_template_json(path: Path) -> LabelTemplate:
|
||||
return LabelTemplate.load_json(path)
|
||||
|
||||
|
||||
def measure_word_template(path: Path) -> LabelTemplate:
|
||||
"""Measure label rectangles from Word shape guides (Avery blank templates)."""
|
||||
path = path.resolve()
|
||||
try:
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
except ImportError as exc:
|
||||
raise TemplateLoadError(
|
||||
"Measuring Word templates requires pywin32 and Microsoft Word.\n"
|
||||
"pip install pywin32"
|
||||
) from exc
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
word = None
|
||||
doc = None
|
||||
try:
|
||||
word = win32com.client.Dispatch("Word.Application")
|
||||
word.Visible = False
|
||||
word.DisplayAlerts = 0
|
||||
doc = word.Documents.Open(str(path), ReadOnly=True)
|
||||
ps = doc.PageSetup
|
||||
page_w = float(ps.PageWidth) / 72.0
|
||||
page_h = float(ps.PageHeight) / 72.0
|
||||
|
||||
rects: list[tuple[float, float, float, float]] = []
|
||||
for si in range(1, doc.Shapes.Count + 1):
|
||||
s = doc.Shapes(si)
|
||||
left = float(s.Left) / 72.0
|
||||
top = float(s.Top) / 72.0
|
||||
width = float(s.Width) / 72.0
|
||||
height = float(s.Height) / 72.0
|
||||
if width >= 0.5 and height >= 0.5:
|
||||
rects.append((left, top, width, height))
|
||||
|
||||
if len(rects) < 1:
|
||||
raise TemplateLoadError(
|
||||
"No label rectangle shapes found in the Word template.\n"
|
||||
"Avery blanks usually include Rectangle guides for each label."
|
||||
)
|
||||
|
||||
rects.sort(key=lambda r: (round(r[1], 3), round(r[0], 3)))
|
||||
xs = sorted({round(r[0], 4) for r in rects})
|
||||
ys = sorted({round(r[1], 4) for r in rects})
|
||||
left_margin = xs[0]
|
||||
top_margin = ys[0]
|
||||
label_w = rects[0][2]
|
||||
label_h = rects[0][3]
|
||||
h_gap = (xs[1] - xs[0] - label_w) if len(xs) >= 2 else 0.0
|
||||
v_gap = (ys[1] - ys[0] - label_h) if len(ys) >= 2 else 0.0
|
||||
columns = max(1, len(xs))
|
||||
rows = max(1, len(ys))
|
||||
|
||||
stem = path.stem
|
||||
digits = "".join(ch for ch in stem if ch.isdigit())
|
||||
tpl_id = digits[:8] if digits else stem[:32]
|
||||
if "60504" in stem:
|
||||
tpl_id = "60504"
|
||||
return LabelTemplate(
|
||||
id=tpl_id or "custom",
|
||||
name=f"Avery {tpl_id}" if tpl_id.isdigit() else stem,
|
||||
source_file=path.name,
|
||||
page_width_in=page_w,
|
||||
page_height_in=page_h,
|
||||
label_width_in=label_w,
|
||||
label_height_in=label_h,
|
||||
columns=columns,
|
||||
rows=rows,
|
||||
labels_per_sheet=columns * rows,
|
||||
left_margin_in=left_margin,
|
||||
top_margin_in=top_margin,
|
||||
horizontal_gap_in=max(0.0, h_gap),
|
||||
vertical_gap_in=max(0.0, v_gap),
|
||||
compatible=(),
|
||||
)
|
||||
except TemplateLoadError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise TemplateLoadError(f"Could not measure Word template:\n{exc}") from exc
|
||||
finally:
|
||||
if doc is not None:
|
||||
doc.Close(False)
|
||||
if word is not None:
|
||||
word.Quit()
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
|
||||
def measure_pdf_template(path: Path) -> LabelTemplate:
|
||||
"""
|
||||
Best-effort PDF rectangle detection.
|
||||
|
||||
Avery PDF blanks are unreliable (extra drawables). Prefer Word .doc.
|
||||
If the file looks like 60504 and detection is nonsense, use measured 60504.
|
||||
"""
|
||||
try:
|
||||
import fitz
|
||||
except ImportError as exc:
|
||||
raise TemplateLoadError("PDF templates need pymupdf") from exc
|
||||
|
||||
path = Path(path)
|
||||
is_60504 = "60504" in path.stem
|
||||
|
||||
def _fallback_60504() -> LabelTemplate:
|
||||
tpl = AVERY_60504
|
||||
return LabelTemplate(
|
||||
**{**tpl.to_dict(), "source_file": path.name, "compatible": tpl.compatible}
|
||||
)
|
||||
|
||||
doc = fitz.open(path)
|
||||
try:
|
||||
page = doc[0]
|
||||
page_w = page.rect.width / 72.0
|
||||
page_h = page.rect.height / 72.0
|
||||
drawings = page.get_drawings()
|
||||
rects: list[tuple[float, float, float, float]] = []
|
||||
for d in drawings:
|
||||
r = d.get("rect")
|
||||
if not r:
|
||||
continue
|
||||
w = abs(r.x1 - r.x0) / 72.0
|
||||
h = abs(r.y1 - r.y0) / 72.0
|
||||
# Near-square label-sized panels only
|
||||
if 2.5 <= w <= 5.0 and 2.5 <= h <= 5.0 and abs(w - h) < 0.35:
|
||||
rects.append((r.x0 / 72.0, r.y0 / 72.0, w, h))
|
||||
|
||||
# Deduplicate nearly-identical rects
|
||||
unique: list[tuple[float, float, float, float]] = []
|
||||
for r in sorted(rects, key=lambda x: (round(x[1], 2), round(x[0], 2))):
|
||||
if not unique or abs(r[0] - unique[-1][0]) > 0.05 or abs(r[1] - unique[-1][1]) > 0.05:
|
||||
unique.append(r)
|
||||
rects = unique
|
||||
|
||||
if len(rects) >= 2:
|
||||
rects.sort(key=lambda r: (round(r[1], 3), round(r[0], 3)))
|
||||
xs = sorted({round(r[0], 3) for r in rects})
|
||||
ys = sorted({round(r[1], 3) for r in rects})
|
||||
label_w = rects[0][2]
|
||||
label_h = rects[0][3]
|
||||
h_gap = (xs[1] - xs[0] - label_w) if len(xs) > 1 else 0.0
|
||||
v_gap = (ys[1] - ys[0] - label_h) if len(ys) > 1 else 0.0
|
||||
columns = max(1, len(xs))
|
||||
rows = max(1, len(ys))
|
||||
# Reject garbage grids (Avery PDF line art often yields this)
|
||||
if columns * rows > 8 or (is_60504 and (columns != 2 or rows != 2)):
|
||||
if is_60504:
|
||||
return _fallback_60504()
|
||||
raise TemplateLoadError(
|
||||
"PDF label detection looked unreliable.\n"
|
||||
"Please download/import the Microsoft Word (.doc) blank instead."
|
||||
)
|
||||
return LabelTemplate(
|
||||
id="60504" if is_60504 else path.stem[:32],
|
||||
name=f"Avery 60504" if is_60504 else path.stem,
|
||||
source_file=path.name,
|
||||
page_width_in=page_w,
|
||||
page_height_in=page_h,
|
||||
label_width_in=label_w,
|
||||
label_height_in=label_h,
|
||||
columns=columns,
|
||||
rows=rows,
|
||||
labels_per_sheet=columns * rows,
|
||||
left_margin_in=xs[0],
|
||||
top_margin_in=ys[0],
|
||||
horizontal_gap_in=max(0.0, h_gap),
|
||||
vertical_gap_in=max(0.0, v_gap),
|
||||
compatible=(),
|
||||
)
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
if is_60504:
|
||||
return _fallback_60504()
|
||||
raise TemplateLoadError(
|
||||
"Could not detect label rectangles in this PDF.\n"
|
||||
"Prefer Avery's Word blank template (.doc), or a measured .json template."
|
||||
)
|
||||
|
||||
|
||||
def load_template_file(path: Path | str) -> LabelTemplate:
|
||||
"""Load .json / measure .doc|.docx / probe .pdf and return a LabelTemplate."""
|
||||
path = Path(path)
|
||||
if not path.is_file():
|
||||
raise TemplateLoadError(f"File not found: {path}")
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".json":
|
||||
return load_template_json(path)
|
||||
if suffix in {".doc", ".docx"}:
|
||||
return measure_word_template(path)
|
||||
if suffix == ".pdf":
|
||||
return measure_pdf_template(path)
|
||||
raise TemplateLoadError(f"Unsupported template type: {suffix}")
|
||||
|
||||
|
||||
def _safe_stem(name: str) -> str:
|
||||
keep = "".join(c if c.isalnum() or c in "-_" else "_" for c in name)
|
||||
return keep[:48] or "template"
|
||||
|
||||
|
||||
def install_template_file(path: Path | str) -> tuple[LabelTemplate, Path]:
|
||||
"""
|
||||
Load/measure a template and save it permanently under AppData.
|
||||
|
||||
Returns (template, installed_json_path).
|
||||
"""
|
||||
path = Path(path).resolve()
|
||||
tpl = load_template_file(path)
|
||||
dest_dir = ensure_templates_dir()
|
||||
|
||||
stem = _safe_stem(tpl.id or path.stem)
|
||||
if "60504" in path.stem or tpl.id == "60504":
|
||||
stem = "60504"
|
||||
|
||||
if path.parent.resolve() != dest_dir.resolve():
|
||||
try:
|
||||
shutil.copy2(path, dest_dir / path.name)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
out_json = dest_dir / f"{stem}.json"
|
||||
data = tpl.to_dict()
|
||||
data["source_file"] = path.name
|
||||
installed = LabelTemplate.from_dict(data)
|
||||
installed.save_json(out_json)
|
||||
return installed, out_json
|
||||
|
||||
|
||||
def activate_template_file(path: Path | str) -> LabelTemplate:
|
||||
"""Install into AppData (if needed) and set as the active template."""
|
||||
path = Path(path)
|
||||
if path.suffix.lower() == ".json" and path.parent.resolve() == user_templates_dir().resolve():
|
||||
tpl = load_template_json(path)
|
||||
return set_active_template(tpl)
|
||||
tpl, _installed = install_template_file(path)
|
||||
return set_active_template(tpl)
|
||||
|
||||
|
||||
def activate_installed_json(path: Path | str) -> LabelTemplate:
|
||||
tpl = load_template_json(Path(path))
|
||||
return set_active_template(tpl)
|
||||
Reference in new issue
Block a user