vibe-sketcherDocumentation

Source code for vibesketcher.render.pages

"""Where a drawing falls on physical pages, and what does not fit (#163).

Page setup places the drawing; it never scales it. One bond is the style
preset's bond length in points on paper, exactly as in the cropped export.
The canvas origin sits at the top-left corner of the first page's content
area (inside the margins), or the drawing's extent is centred on the page
grid. A grid of ``columns`` x ``rows`` pages tiles the drawing content area by
content area, so page (row r, column c) shows the drawing region
[c w, (c + 1) w] x [r h, (r + 1) h] after that offset, w x h being one content
area. Pages are numbered in reading order: left to right, then top to bottom.

Object extents are those the export crops to
(:func:`vibesketcher.render.scene.scene_boxes`). An object outside the grid is
overflow and is reported, never shrunk; an object across an inner page edge
is reported as split.
"""

from __future__ import annotations

from typing import Any

from vibesketcher.document.model import Document, PageSetup
from vibesketcher.render import RenderRefused, drawing_boxes

#: Points per millimetre (1 pt = 1/72 inch, 1 inch = 25.4 mm).
PT_PER_MM = 72 / 25.4
_EPS = 1e-6  # mm: a box touching an edge is on that side of it


[docs] def page_layout( document: Document, setup: PageSetup | None = None, *, style: str | None = None, stereo_labels: bool = False, sequences: bool = False, math_text: bool = False, ) -> dict[str, Any]: """The pages, the objects on each, and every object split across or outside them. ``setup`` defaults to the document's ``style.page``; pass one to try a setup before storing it. The figure options are those of the export. """ setup = setup or document.style.page if setup is None: raise RenderRefused("the document has no page setup; set one first (style.page)") preset, boxes = drawing_boxes( document, style=style, stereo_labels=stereo_labels, sequences=sequences, math_text=math_text, ) width, height = setup.size_mm() top, right, bottom, left = setup.margins() cw, ch = width - left - right, height - top - bottom columns, rows = setup.columns, setup.rows mm = [(kind, name, tuple(v / PT_PER_MM for v in box)) for kind, name, box in boxes] x0 = min(b[2][0] for b in mm) y0 = min(b[2][1] for b in mm) x1 = max(b[2][2] for b in mm) y1 = max(b[2][3] for b in mm) # The drawing coordinate at the first content area's top-left corner. ox, oy = ( ((x0 + x1 - columns * cw) / 2, (y0 + y1 - rows * ch) / 2) if setup.center else (0.0, 0.0) ) pages: list[dict[str, Any]] = [ {"page": r * columns + c + 1, "row": r + 1, "column": c + 1, "objects": []} for r in range(rows) for c in range(columns) ] objects, overflow, split = [], [], [] for kind, name, (bx0, by0, bx1, by1) in mm: box = (bx0 - ox, by0 - oy, bx1 - ox, by1 - oy) label = f"{kind} {name}" on = [ page["page"] for page in pages if box[0] < page["column"] * cw - _EPS and box[2] > (page["column"] - 1) * cw + _EPS and box[1] < page["row"] * ch - _EPS and box[3] > (page["row"] - 1) * ch + _EPS ] for number in on: pages[number - 1]["objects"].append(label) entry = {"object": label, "kind": kind, "box_mm": _rounded(box), "pages": on} objects.append(entry) beyond = { "left": -box[0], "top": -box[1], "right": box[2] - columns * cw, "bottom": box[3] - rows * ch, } beyond = {side: round(v, 3) for side, v in beyond.items() if v > _EPS} if beyond: overflow.append({**entry, "beyond_mm": beyond}) if len(on) > 1: split.append(entry) for page in pages: page["empty"] = not page["objects"] placement = ( f"the drawing is centred on the {columns} x {rows} page grid" if setup.center else "the canvas origin is the top-left corner of page 1's content area" ) return { "setup": setup.model_dump(mode="json"), "page_mm": [width, height], "margins_mm": {"top": top, "right": right, "bottom": bottom, "left": left}, "content_mm": [round(cw, 3), round(ch, 3)], "grid": [columns, rows], "preset": preset.name, "bond_mm": round(preset.bond / PT_PER_MM, 4), "scale": 1.0, "offset_mm": [round(ox, 3), round(oy, 3)], "drawing_mm": _rounded((x0 - ox, y0 - oy, x1 - ox, y1 - oy)), "pages": pages, "objects": objects, "overflow": overflow, "split": split, "fits": not overflow, "assumptions": [ f"nothing is scaled: one bond is {preset.bond:g} pt " f"({preset.bond / PT_PER_MM:.3f} mm) of the {preset.name} style, as in the " "cropped export", placement, "boxes are in mm from the top-left corner of page 1's content area, x to the right " "and y downward; pages tile the drawing content area by content area, in reading " "order", "text is measured as generously as the cropped export measures it, so text close to " "an edge can be reported although it would fit", ], }
def _rounded(box: tuple[float, float, float, float]) -> list[float]: return [round(v, 3) for v in box]
[docs] def render_pages( document: Document, fmt: str, *, pages: bool, page: int | None, style: str | None, dpi: int, stereo_labels: bool, sequences: bool, math_text: bool, ) -> bytes: """Export a captured document at paper size, clipping without scaling. Called with a deep snapshot by ``render``. Render the scene once, then translate that same scene onto each page, including empty pages. """ import io import xml.etree.ElementTree as ET from vibesketcher.render import RenderUnavailable, render_svg from vibesketcher.render.fonts import NS, check_text from vibesketcher.render.publication import INSTALL, convert if pages and page is not None: raise RenderRefused("choose pages=True or page=N, not both") if pages and fmt != "pdf": raise RenderRefused("pages=True requires PDF; use page=N for SVG, PNG, EPS or EMF") if page is not None and fmt not in {"svg", "png", "eps", "emf"}: raise RenderRefused("page=N requires SVG, PNG, EPS or EMF; use pages=True for PDF") setup = document.style.page if setup is None: raise RenderRefused("the document has no page setup; set one first (style.page)") count = setup.columns * setup.rows if page is not None and (type(page) is not int or not 1 <= page <= count): raise RenderRefused(f"page must be an integer from 1 to {count}") # This also refuses fallback rows without canvas placement, like page_layout. _, boxes = drawing_boxes( document, style=style, stereo_labels=stereo_labels, sequences=sequences, math_text=math_text, ) svg = render_svg( document, style=style, stereo_labels=stereo_labels, sequences=sequences, math_text=math_text, ) check_text(svg) width, height = (v * PT_PER_MM for v in setup.size_mm()) top, right, bottom, left = (v * PT_PER_MM for v in setup.margins()) cw, ch = width - left - right, height - top - bottom # Use full-precision extents, never the rounded values in the layout report. ox, oy = (0.0, 0.0) if setup.center: ox = (min(b[2][0] for b in boxes) + max(b[2][2] for b in boxes) - setup.columns * cw) / 2 oy = (min(b[2][1] for b in boxes) + max(b[2][3] for b in boxes) - setup.rows * ch) / 2 clip = (left, top, cw, ch) def page_svg(number: int) -> bytes: root = ET.Element( f"{NS}svg", { "version": "1.1", "width": f"{width:.8f}pt", "height": f"{height:.8f}pt", "viewBox": f"0 0 {width:.8f} {height:.8f}", }, ) defs = ET.SubElement(root, f"{NS}defs") clipping = ET.SubElement( defs, f"{NS}clipPath", { "id": "vsk-page-content", "clipPathUnits": "userSpaceOnUse", }, ) ET.SubElement( clipping, f"{NS}rect", dict( zip( ("x", "y", "width", "height"), (f"{v:.8f}" for v in clip), strict=True, ) ), ) clipped = ET.SubElement(root, f"{NS}g", {"clip-path": "url(#vsk-page-content)"}) row, column = divmod(number - 1, setup.columns) translated = ET.SubElement( clipped, f"{NS}g", { "transform": f"translate({left - ox - column * cw:.8f},{top - oy - row * ch:.8f})", }, ) translated.extend(ET.fromstring(svg)) ET.register_namespace("", NS[1:-1]) return bytes(ET.tostring(root, encoding="utf-8", xml_declaration=True)) if page is not None: selected = page_svg(page) if fmt == "svg": return selected if fmt in {"eps", "emf"}: from vibesketcher.render.vector import emf, eps return eps(selected, clip=clip) if fmt == "eps" else emf(selected, clip=clip) return convert(selected, fmt, dpi=dpi) try: from pypdf import PdfWriter except ImportError as error: raise RenderUnavailable(f"Paged PDF export is unavailable. {INSTALL}") from error with PdfWriter() as writer: for number in range(1, count + 1): writer.append(io.BytesIO(convert(page_svg(number), "pdf"))) output = io.BytesIO() writer.write(output) return output.getvalue()