python/laymesh/bridge.py 1"""Use the LayMesh CLI with the same DSL as Rust and the browser.2 3Bare geometry defaults to mm (canvas unit); typography and line widths use pt.4Bindings substitute {{name}} only outside DSL strings, comments and LCSS.5Use save_source to preserve a layout and data for independent CLI rendering.6"""7 8from __future__ import annotations9 10import hashlib11import io12import json13import math14import os15import re16import shutil17import subprocess18import tempfile19import warnings20from contextvars import ContextVar21from dataclasses import dataclass, field22from pathlib import Path23from typing import Mapping24 25from ._runtime import bundled_command, development_command, override_command26from ._svg import SvgCompatibilityError, normalize_matplotlib_svg27 28 29_warning_state: ContextVar[tuple[bool, set[str]] | None] = ContextVar("laymesh_warning_state", default=None)30 31 32def _warn(message: str, *, stacklevel: int = 3) -> None:33 state = _warning_state.get()34 if state is not None:35 enabled, seen = state36 if not enabled or message in seen:37 return38 seen.add(message)39 warnings.warn(message, stacklevel=stacklevel)40 41 42def _warning_mode(value: bool | None) -> bool:43 if value is not None:44 if not isinstance(value, bool):45 raise LayMeshBridgeError("show_warnings 须为 None、True 或 False")46 return value47 mode = os.environ.get("LAYMESH_WARNINGS", "show")48 if mode not in ("show", "hide"):49 raise LayMeshBridgeError("LAYMESH_WARNINGS 须为 show 或 hide")50 return mode == "show"51 52 53class LayMeshBridgeError(RuntimeError):54 """A binding, asset, or CLI error with a message suitable for a Notebook."""55 56 57@dataclass(frozen=True)58class RenderResult:59 # A bare result in a Notebook should not print megabytes of SVG/base64.60 preview_svg: str = field(repr=False)61 output: Path | None62 saved_source: Path | None63 64 65@dataclass(frozen=True)66class _NotebookResult:67 preview_jpeg: bytes68 output: Path | None69 saved_source: Path | None70 71 72@dataclass(frozen=True)73class DocumentResult:74 """Document export with a native JPEG preview of one selected page."""75 preview_jpeg: bytes = field(repr=False)76 output: Path | None77 page: int78 79 def _repr_mimebundle_(self, include=None, exclude=None):80 from IPython.display import Image81 return Image(data=self.preview_jpeg, format="jpeg", retina=True)._repr_mimebundle_(include, exclude)82 83 84_NAME = re.compile(r"[A-Za-z_][A-Za-z_0-9]*\Z")85_GENERATED = "# Generated by LayMesh Jupyter; edit the Notebook cell instead.\n"86_FORMATS = {".svg", ".pdf", ".pptx", ".png", ".jpg", ".jpeg", ".tif", ".tiff", ".webp", ".bmp", ".gif", ".ico", ".pnm", ".pbm", ".pgm", ".ppm", ".pam", ".tga", ".html", ".zip"}87_RASTER_FORMATS = _FORMATS - {".svg", ".pdf", ".pptx", ".html", ".zip"}88 89 90def _command() -> list[str]:91 try:92 command = override_command() or bundled_command() or development_command()93 except RuntimeError as error:94 raise LayMeshBridgeError(str(error)) from error95 if command:96 return command97 installed = shutil.which("laymesh")98 if installed:99 return [installed]100 raise LayMeshBridgeError("找不到 LayMesh 原生 CLI;请运行 cargo build --release -p laymesh-cli,或设置 LAYMESH_CLI")101 102 103def _run(cli: list[str], args: list[str], base_dir: Path, source: Path | None = None) -> str:104 try:105 result = subprocess.run(106 [*cli, *args, "--warnings", "show" if _warning_state.get() is None or _warning_state.get()[0] else "hide"], cwd=base_dir, capture_output=True, text=True,107 encoding="utf-8", errors="replace", check=False,108 )109 except OSError as exc:110 raise LayMeshBridgeError(f"无法启动 LayMesh CLI:{exc}") from exc111 message = result.stderr.strip()112 if source is not None:113 message = message.replace(str(source), "<LayMesh cell>")114 if result.returncode:115 raise LayMeshBridgeError(message or result.stdout.strip() or f"LayMesh 退出状态 {result.returncode}")116 if message:117 for diagnostic in message.splitlines():118 _warn(diagnostic, stacklevel=3)119 return result.stdout120 121 122def _temporary_lay(base_dir: Path, source: str):123 handle = tempfile.NamedTemporaryFile(124 mode="w", encoding="utf-8", prefix=".laymesh-", suffix=".lay",125 dir=base_dir, delete=False,126 )127 try:128 handle.write(source)129 handle.close()130 return Path(handle.name)131 except Exception:132 handle.close()133 Path(handle.name).unlink(missing_ok=True)134 raise135 136 137def _figure_type():138 try:139 from matplotlib.figure import Figure140 except ImportError:141 return ()142 return Figure143 144 145def _numpy_scalar(value):146 try:147 import numpy as np148 except ImportError:149 return value150 return value.item() if isinstance(value, np.generic) else value151 152 153class _Bindings:154 def __init__(155 self, namespace: Mapping[str, object], cli: list[str], base_dir: Path,156 scratch: Path, plot_dpi: float, saved_source: Path | None,157 ) -> None:158 self.namespace = namespace159 self.cli = cli160 self.base_dir = base_dir161 self.scratch = scratch162 self.plot_dpi = plot_dpi163 self.saved_source = saved_source164 self.assets_dir = saved_source.with_suffix(".assets") if saved_source else None165 self.cache: dict[str, str] = {}166 167 def _asset(self, name: str, data: bytes, extension: str) -> str:168 if self.assets_dir:169 self.assets_dir.mkdir(exist_ok=True)170 filename = f"{name}-{hashlib.sha256(data).hexdigest()[:16]}{extension}"171 target = self.assets_dir / filename172 if not target.exists():173 target.write_bytes(data)174 return f"{self.assets_dir.name}/{filename}"175 target = self.scratch / f"{name}{extension}"176 target.write_bytes(data)177 return str(target)178 179 def _svg_accepted(self, svg: bytes, name: str) -> bool:180 candidate = self.scratch / f"{name}.svg"181 candidate.write_bytes(svg)182 probe = _temporary_lay(183 self.base_dir,184 f'page=canvas(size=(10 mm,10 mm))\nplot=image(src={json.dumps(str(candidate))})\npage.add(plot,size=(8 mm, auto),target=page.top_left)\n',185 )186 try:187 result = subprocess.run(188 [*self.cli, "validate", str(probe)], cwd=self.base_dir,189 capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,190 )191 if result.returncode == 0:192 return True193 if "E_SVG:" in result.stderr:194 return False195 raise LayMeshBridgeError(result.stderr.strip() or result.stdout.strip())196 except OSError as exc:197 raise LayMeshBridgeError(f"无法启动 LayMesh CLI:{exc}") from exc198 finally:199 probe.unlink(missing_ok=True)200 201 @staticmethod202 def _warn_plot_bounds(name: str, figure) -> None:203 # Both boxes use inches. Keep savefig's original bounds unchanged: this204 # check only explains clipping that an inline tight preview can hide.205 try:206 canvas = figure.canvas207 canvas.draw()208 content = figure.get_tightbbox(canvas.get_renderer())209 frame = figure.bbox_inches210 if content is None:211 return212 overhang = (213 ("left", frame.x0 - content.x0),214 ("bottom", frame.y0 - content.y0),215 ("right", content.x1 - frame.x1),216 ("top", content.y1 - frame.y1),217 )218 outside = [(side, float(amount)) for side, amount in overhang219 if math.isfinite(amount) and amount > 1 / 72]220 except Exception:221 # Some Matplotlib canvases have no renderer available here. Saving222 # the figure must still follow the existing path.223 return224 if outside:225 sides = ", ".join(f"{side} {amount * 25.4:.1f} mm" for side, amount in outside)226 _warn(227 f"W_PLOT_BOUNDS: Visible content in Matplotlib figure '{name}' extends beyond "228 f"the figure canvas ({sides}). Exporting with the original bounds may clip it, "229 "so the LayMesh output can differ from Jupyter's inline preview. "230 'Call fig.tight_layout() or create the figure with layout="constrained".',231 stacklevel=7,232 )233 234 def _figure(self, name: str, figure) -> str:235 import matplotlib as mpl236 237 self._warn_plot_bounds(name, figure)238 reason = "SVG 使用了当前 LayMesh 不支持的图形内容"239 try:240 settings = {"svg.fonttype": "path"}241 if mpl.rcParams["svg.hashsalt"] is None:242 # Random IDs make identical Figures miss the asset hash cache.243 settings["svg.hashsalt"] = "laymesh"244 with mpl.rc_context(settings):245 stream = io.StringIO()246 figure.savefig(stream, format="svg")247 svg = normalize_matplotlib_svg(stream.getvalue()).encode("utf-8")248 if self._svg_accepted(svg, name):249 return json.dumps(self._asset(name, svg, ".svg"), ensure_ascii=False)250 except SvgCompatibilityError as exc:251 reason = str(exc)252 _warn(253 f"Matplotlib 图 {name} 已改用 {self.plot_dpi:g} DPI PNG:{reason}",254 stacklevel=3,255 )256 stream = io.BytesIO()257 figure.savefig(stream, format="png", dpi=self.plot_dpi)258 return json.dumps(self._asset(name, stream.getvalue(), ".png"), ensure_ascii=False)259 260 def literal(self, name: str, line: int) -> str:261 if name in self.cache:262 return self.cache[name]263 if name not in self.namespace:264 raise LayMeshBridgeError(f"第 {line} 行引用了未定义的 Notebook 变量 {{{{{name}}}}}")265 value = _numpy_scalar(self.namespace[name])266 data_literal = self._data_literal(name, value, line)267 if data_literal is not None:268 literal = data_literal269 elif isinstance(value, Mapping):270 literal = self._dict_literal(name, value, line)271 elif isinstance(value, _figure_type()):272 literal = self._figure(name, value)273 elif isinstance(value, (str, Path)):274 literal = json.dumps(str(value), ensure_ascii=False)275 elif isinstance(value, bool):276 literal = "true" if value else "false"277 elif isinstance(value, (int, float)):278 try:279 finite = math.isfinite(value)280 except (OverflowError, ValueError):281 finite = False282 if not finite or isinstance(value, int) and abs(value) > 2**53 - 1:283 raise LayMeshBridgeError(f"第 {line} 行变量 {name} 必须是有限且可精确表示的数值")284 literal = repr(value)285 else:286 raise LayMeshBridgeError(287 f"第 {line} 行变量 {name} 类型不支持;支持标量、字典、数值数组、DataFrame 和 Matplotlib Figure"288 )289 self.cache[name] = literal290 return literal291 292 def _dict_literal(self, name: str, value: Mapping, line: int) -> str:293 """Serialize JSON containers to an asset, retaining mapping insertion order."""294 active: set[int] = set()295 296 def fail(path, reason):297 raise LayMeshBridgeError(f"第 {line} 行字典 {path}: {reason}")298 299 def normalize(item, path, depth=0):300 if depth > 100:301 fail(path, "嵌套超过 100 层")302 item = _numpy_scalar(item)303 if item is None or isinstance(item, (str, bool)):304 return item305 if isinstance(item, (int, float)):306 if isinstance(item, float) and math.isnan(item):307 return None308 try:309 finite = math.isfinite(item)310 except (OverflowError, ValueError):311 finite = False312 if not finite or isinstance(item, int) and abs(item) > 2**53 - 1:313 fail(path, "数值必须有限且能精确表示")314 return item315 is_numpy = type(item).__module__.split(".")[0] == "numpy"316 if not isinstance(item, (Mapping, list, tuple)) and not is_numpy:317 fail(path, f"不支持的类型 {type(item).__name__}")318 identity = id(item)319 if identity in active:320 fail(path, "循环引用")321 active.add(identity)322 try:323 if is_numpy:324 import numpy as np325 if not isinstance(item, np.ndarray) or item.ndim not in (1, 2):326 fail(path, "需要一维或二维 NumPy 数组")327 return normalize(item.tolist(), path, depth + 1)328 if isinstance(item, Mapping):329 result = {}330 for key, val in item.items():331 if not isinstance(key, str):332 fail(path, f"键 {key!r} 必须为字符串")333 result[key] = normalize(val, f"{path}[{key!r}]", depth + 1)334 return result335 return [normalize(val, f"{path}[{i}]", depth + 1) for i, val in enumerate(item)]336 finally:337 active.remove(identity)338 339 data = json.dumps(normalize(value, name), ensure_ascii=False, allow_nan=False,340 separators=(",", ":")).encode("utf-8")341 asset = self._asset(name, data, ".json")342 return f"dict(src={json.dumps(asset, ensure_ascii=False)})"343 344 def _data_literal(self, name: str, value, line: int) -> str | None:345 """Bind data as strict JSON assets, never as generated per-point DSL."""346 kind = "array"347 is_table = False348 module = type(value).__module__.split(".")[0]349 pandas = None350 if module == "pandas":351 import pandas352 if isinstance(value, pandas.DataFrame):353 if value.empty or not value.columns.is_unique or any(354 not isinstance(c, str) or not c for c in value.columns355 ):356 raise LayMeshBridgeError(f"第 {line} 行 {name} 需要非空 DataFrame 和唯一字符串列名")357 value = {column: value[column].tolist() for column in value.columns}358 kind, is_table = "table", True359 elif isinstance(value, pandas.Series):360 value = value.tolist()361 else:362 return None363 elif module == "numpy":364 import numpy as np365 if not isinstance(value, np.ndarray):366 return None367 if value.ndim not in (1, 2) or not value.size:368 raise LayMeshBridgeError(f"第 {line} 行 {name} 需要非空一维或二维数组")369 value = value.tolist()370 elif not isinstance(value, (list, tuple)):371 return None372 373 def scalar(item):374 if item is None or pandas is not None and item is pandas.NA:375 return None376 item = _numpy_scalar(item)377 if isinstance(item, bool):378 raise LayMeshBridgeError(f"第 {line} 行 {name} 的绘图数据不接受布尔值")379 if isinstance(item, (int, float)):380 if isinstance(item, float) and math.isnan(item):381 return None382 try:383 finite = math.isfinite(item)384 except OverflowError:385 finite = False386 if not finite or isinstance(item, int) and abs(item) > 2**53 - 1:387 raise LayMeshBridgeError(f"第 {line} 行 {name} 数据必须有限且可精确表示")388 return item389 if is_table and isinstance(item, str):390 return item391 raise LayMeshBridgeError(f"第 {line} 行 {name} 包含不支持的数据类型 {type(item).__name__}")392 393 if is_table:394 normalized = {column: [scalar(item) for item in items] for column, items in value.items()}395 else:396 if not value:397 raise LayMeshBridgeError(f"第 {line} 行 {name} 数组不能为空")398 if isinstance(value[0], (list, tuple)):399 width = len(value[0])400 if not width or any(not isinstance(row, (list, tuple)) or len(row) != width for row in value):401 raise LayMeshBridgeError(f"第 {line} 行 {name} 二维数组必须为非空矩形")402 normalized = [[scalar(item) for item in row] for row in value]403 else:404 normalized = [scalar(item) for item in value]405 data = json.dumps(normalized, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")406 asset = self._asset(name, data, ".json")407 return f"{kind}(src={json.dumps(asset, ensure_ascii=False)})"408 409 def expand(self, source: str) -> str:410 """Expand bindings only in DSL code, never in strings, comments or LCSS."""411 out: list[str] = []412 index = 0413 line = 1414 style_depth = 0415 while index < len(source):416 if not style_depth and source[index] == "#":417 end = source.find("\n", index)418 if end < 0:419 out.append(source[index:])420 break421 out.append(source[index:end])422 index = end423 continue424 match = re.match(r"(?:rf|fr|r|f)?([\"'])", source[index:], re.I)425 if match:426 quote = match.group(1)427 opening = index + len(match.group(0)) - 1428 delimiter = quote * 3 if source.startswith(quote * 3, opening) else quote429 end = opening + len(delimiter)430 while end < len(source):431 if source[end] == "\\":432 end += 2433 elif source.startswith(delimiter, end):434 end += len(delimiter)435 break436 else:437 end += 1438 literal = source[index:end]439 out.append(literal)440 line += literal.count("\n")441 index = end442 continue443 if source.startswith("/*", index):444 end = source.find("*/", index + 2)445 end = len(source) if end < 0 else end + 2446 value = source[index:end]447 line += value.count("\n")448 out.append(value)449 index = end450 continue451 if re.match(r"style\s*\{", source[index:]) and (index == 0 or not source[index-1].isalnum()):452 end = index + re.match(r"style\s*\{", source[index:]).end()453 value = source[index:end]454 out.append(value)455 line += value.count("\n")456 index = end457 style_depth = 1458 continue459 if style_depth:460 if source[index] == "{": style_depth += 1461 elif source[index] == "}": style_depth -= 1462 if not style_depth and source.startswith("{{", index):463 end = source.find("}}", index + 2)464 if end < 0:465 raise LayMeshBridgeError(f"第 {line} 行占位符缺少 }}}}")466 name = source[index + 2:end].strip()467 if not _NAME.fullmatch(name):468 raise LayMeshBridgeError(f"第 {line} 行只允许 {{{{变量名}}}},不能写 Python 表达式")469 out.append(self.literal(name, line))470 index = end + 2471 continue472 if source[index] == "\n":473 line += 1474 out.append(source[index])475 index += 1476 return "".join(out)477 478 479def _export_args(output: Path | None, options: Mapping[str, object]) -> list[str]:480 """Validate before staging assets; the native encoder validates the same options again."""481 explicit = {key: value for key, value in options.items() if value is not None}482 if not explicit:483 return []484 if output is None:485 raise LayMeshBridgeError("导出编码参数需要 output 文件")486 suffix = output.suffix.lower()487 jpeg = suffix in {".jpg", ".jpeg"}488 tiff = suffix in {".tif", ".tiff"}489 webp = suffix == ".webp"490 for key, value in explicit.items():491 if not key.startswith("html_"): continue492 valid = suffix in {".html", ".zip"}493 if key in {"html_editable", "html_embed_fonts"}: valid = valid and isinstance(value, bool)494 elif key == "html_image_compression": valid = valid and value in {"auto", "original", "lossless"}495 elif key == "html_image_quality": valid = valid and type(value) in {int, float} and math.isfinite(value) and 0 <= value <= 100496 else: valid = False497 if not valid: raise LayMeshBridgeError("无效的 HTML 参数:" + key)498 quality = explicit.get("quality")499 if quality is not None and (not (jpeg or webp) or isinstance(quality, bool) or not isinstance(quality, (int, float)) or not math.isfinite(quality) or not (1 if jpeg else 0) <= quality <= 100):500 raise LayMeshBridgeError("quality 仅用于 JPEG(1–100)或 WebP(0–100)")501 compression = explicit.get("compression")502 if compression is not None and compression not in ({"none", "lzw", "deflate", "packbits"} if tiff else {"fast", "default", "best"} if suffix == ".png" else set()):503 raise LayMeshBridgeError("compression:PNG 使用 fast/default/best;TIFF 使用 none/lzw/deflate/packbits")504 background = explicit.get("background")505 if background is not None and (suffix not in {".jpg", ".jpeg", ".gif", ".ppm", ".pgm", ".pbm"} or not isinstance(background, str) or not re.fullmatch(r"#[0-9a-fA-F]{6}", background)):506 raise LayMeshBridgeError("background 仅用于 JPEG/GIF/PPM/PGM/PBM,须为 #RRGGBB")507 for key in ("webp_lossless", "webp_method", "webp_alpha_quality", "webp_near_lossless"):508 if key not in explicit:509 continue510 value = explicit[key]511 if not webp or (key == "webp_lossless" and not isinstance(value, bool)) or (key != "webp_lossless" and (type(value) is not int or not 0 <= value <= (6 if key == "webp_method" else 100))):512 raise LayMeshBridgeError("webp_* 仅用于 WebP:lossless 为 bool,method 为 0–6,alpha_quality/near_lossless 为 0–100 整数")513 if explicit.get("webp_lossless") is False and "webp_near_lossless" in explicit:514 raise LayMeshBridgeError("webp_near_lossless 仅用于无损 WebP 模式")515 if explicit.get("webp_lossless", True) and explicit.get("webp_alpha_quality", 100) != 100:516 raise LayMeshBridgeError("降低 webp_alpha_quality 须选择有损 WebP 模式")517 for key, value in explicit.items():518 if not key.startswith("pdf_"):519 continue520 valid = suffix == ".pdf"521 if key == "pdf_image_compression": valid = valid and value in {"auto", "lossless", "jpeg"}522 elif key in {"pdf_downsample", "pdf_recompress_jpeg", "pdf_preserve_16bit", "pdf_preserve_alpha"}: valid = valid and isinstance(value, bool)523 elif key == "pdf_alpha_background": valid = valid and isinstance(value, str) and re.fullmatch(r"#[0-9a-fA-F]{6}", value) is not None524 elif key in {"pdf_jpeg_quality", "pdf_auto_palette_limit"}: valid = valid and type(value) is int and (1 if key == "pdf_jpeg_quality" else 0) <= value <= (100 if key == "pdf_jpeg_quality" else 16384)525 else: valid = valid and type(value) in {int, float} and math.isfinite(value) and 0 <= value <= 1526 if not valid: raise LayMeshBridgeError("无效的 PDF 参数:" + key)527 return [part for key, value in explicit.items() for part in ("--" + key.replace("_", "-"), str(value).lower() if isinstance(value, bool) else str(value))]528 529 530def _render_impl(531 source: str, *, namespace: Mapping[str, object], base_dir: Path,532 output: Path | str | None, dpi: float | None, plot_dpi: float,533 save_source: Path | str | None, original: Path | None,534 export_options: Mapping[str, object], config: Path | str | None = None,535 notebook_preview: bool = False,536 preview_dpi: float = 192, preview_quality: int = 95,537 preview_background: str = "#ffffff",538) -> RenderResult | _NotebookResult:539 base_dir = base_dir.resolve()540 if not base_dir.is_dir():541 raise LayMeshBridgeError(f"素材目录不存在:{base_dir}")542 if not math.isfinite(plot_dpi) or plot_dpi <= 0:543 raise LayMeshBridgeError("--plot-dpi 必须是正数")544 if dpi is not None and (not math.isfinite(dpi) or dpi <= 0 or dpi > 25400):545 raise LayMeshBridgeError("--dpi 必须为 0–25400 之间的正数")546 output_path = Path(output).resolve() if output is not None else None547 if output_path and output_path.suffix.lower() not in _FORMATS:548 raise LayMeshBridgeError("输出文件须为 SVG/PDF/PPTX/PNG/JPEG/TIFF/WebP/BMP/GIF/ICO/PNM/TGA")549 if dpi is not None and (not output_path or output_path.suffix.lower() not in (_RASTER_FORMATS | {".svg", ".pdf", ".pptx"})):550 raise LayMeshBridgeError("--dpi 需要位图、SVG、PDF 或 PPTX 导出路径")551 option_args = _export_args(output_path, export_options)552 if notebook_preview:553 if type(preview_dpi) not in {int, float} or not math.isfinite(preview_dpi) or not 0 < preview_dpi <= 25400:554 raise LayMeshBridgeError("--preview-dpi 必须为 0–25400 之间的正数")555 if type(preview_quality) is not int or not 1 <= preview_quality <= 100:556 raise LayMeshBridgeError("--preview-quality 必须为 1–100 的整数")557 if not isinstance(preview_background, str) or not re.fullmatch(r"#[0-9a-fA-F]{6}", preview_background):558 raise LayMeshBridgeError("--preview-background 须为 #RRGGBB")559 config_args = ["--config", str(Path(config).expanduser().resolve())] if config else []560 saved_path = (base_dir / save_source).resolve() if save_source else None561 if saved_path:562 if saved_path.suffix != ".lay" or saved_path.parent != base_dir:563 raise LayMeshBridgeError("--save-source 须是素材目录中的 .lay 文件")564 if saved_path.exists() and not saved_path.read_text(encoding="utf-8").startswith(_GENERATED):565 raise LayMeshBridgeError(f"不会覆盖非生成的布局文件:{saved_path}")566 cli = _command()567 with tempfile.TemporaryDirectory(prefix="laymesh-assets-") as scratch_name:568 binding = _Bindings(namespace, cli, base_dir, Path(scratch_name), plot_dpi, saved_path)569 expanded = binding.expand(source)570 file = original if original and expanded == source and not saved_path else _temporary_lay(base_dir, expanded)571 cleanup = file != original572 try:573 args = ["render", str(file)]574 if output_path:575 output_path.parent.mkdir(parents=True, exist_ok=True)576 args += ["-o", str(output_path)]577 if dpi is not None:578 args += ["--dpi", str(dpi)]579 args += option_args + config_args580 if notebook_preview:581 # Export and JPEG preview share one compiled Scene. Preview582 # settings are independent of export DPI, matte and PDF policy.583 preview_file = Path(scratch_name) / "preview.jpg"584 args += ["--preview-output", str(preview_file), "--preview-dpi", str(preview_dpi),585 "--preview-quality", str(preview_quality), "--preview-background", preview_background]586 if output_path or notebook_preview:587 _run(cli, args, base_dir, file if cleanup else None)588 if notebook_preview:589 preview = preview_file.read_bytes()590 elif output_path and output_path.suffix.lower() == ".svg":591 preview = output_path.read_text(encoding="utf-8")592 else:593 preview_file = Path(scratch_name) / "preview.svg"594 _run(cli, ["render", str(file), "-o", str(preview_file), *config_args], base_dir, file if cleanup else None)595 preview = preview_file.read_text(encoding="utf-8")596 if saved_path:597 staged = _temporary_lay(base_dir, _GENERATED + expanded)598 try:599 os.replace(staged, saved_path)600 finally:601 staged.unlink(missing_ok=True)602 result_type = _NotebookResult if notebook_preview else RenderResult603 return result_type(preview, output_path, saved_path)604 finally:605 if cleanup:606 file.unlink(missing_ok=True)607 608 609def _render(source: str, *, show_warnings: bool | None = None, **kwargs) -> RenderResult | _NotebookResult:610 token = _warning_state.set((_warning_mode(show_warnings), set()))611 try:612 return _render_impl(source, **kwargs)613 finally:614 _warning_state.reset(token)615 616 617def _read_layout(file: Path | str) -> tuple[Path, str]:618 file = Path(file).resolve()619 if file.suffix != ".lay" or not file.is_file():620 raise LayMeshBridgeError(f"布局文件不存在或不是 .lay:{file}")621 return file, file.read_text(encoding="utf-8")622 623 624def _render_notebook(625 *, source: str | None = None, file: Path | str | None = None,626 namespace: Mapping[str, object] | None = None,627 output: Path | str | None = None, dpi: float | None = None,628 plot_dpi: float = 300, save_source: Path | str | None = None,629 show_warnings: bool | None = None, config: Path | str | None = None,630 preview_dpi: float = 192, preview_quality: int = 95,631 preview_background: str = "#ffffff",632 page: int | None = None,633 **export_options,634) -> _NotebookResult:635 """Magic-only preview; the public SVG result and signatures stay compatible."""636 original = None637 base_dir = Path.cwd()638 if file is not None:639 if Path(file).suffix == ".laydoc":640 if save_source is not None:641 raise LayMeshBridgeError(".laydoc 请直接编辑编排与页面文件;不支持 --save-source")642 result = render_document(file, output=output, page=page, dpi=dpi, config=config,643 show_warnings=show_warnings, preview_dpi=preview_dpi,644 preview_quality=preview_quality, preview_background=preview_background,645 **export_options)646 return _NotebookResult(result.preview_jpeg, result.output, None)647 original, source = _read_layout(file)648 base_dir = original.parent649 if source is None:650 raise LayMeshBridgeError("Notebook 需要 .lay 源码或文件")651 if page is not None and (type(page) is not int or page != 1):652 raise LayMeshBridgeError("单页 .lay 的页码只能为 1")653 return _render(654 source, namespace=namespace or {}, base_dir=base_dir,655 output=output, dpi=dpi, plot_dpi=plot_dpi, config=config,656 save_source=save_source, original=original, show_warnings=show_warnings,657 export_options=export_options, notebook_preview=True,658 preview_dpi=preview_dpi, preview_quality=preview_quality, preview_background=preview_background,659 )660 661 662def render_document(663 file: Path | str, *, output: Path | str | None = None,664 page: int | None = None, preview_page: int = 1,665 dpi: float | None = None, config: Path | str | None = None,666 show_warnings: bool | None = None,667 preview_dpi: float = 192, preview_quality: int = 95,668 preview_background: str = "#ffffff", **export_options,669) -> DocumentResult:670 """Render .laydoc with the ordinary Lay DSL. PDF/PPTX exports all pages by671 default; page=N selects a single page. One native process also creates the672 JPEG preview, keeping export and preview settings independent.673 """674 file = Path(file).expanduser().resolve()675 if file.suffix != ".laydoc" or not file.is_file():676 raise LayMeshBridgeError(f"文档文件不存在或不是 .laydoc:{file}")677 for number in (page, preview_page):678 if number is not None and (type(number) is not int or number < 1):679 raise LayMeshBridgeError("页码需要从 1 开始的整数")680 selected = page if page is not None else preview_page681 if type(preview_dpi) not in {int, float} or not math.isfinite(preview_dpi) or not 0 < preview_dpi <= 25400:682 raise LayMeshBridgeError("preview_dpi 必须为 0–25400 之间的正数")683 if type(preview_quality) is not int or not 1 <= preview_quality <= 100:684 raise LayMeshBridgeError("preview_quality 必须为 1–100 的整数")685 if not isinstance(preview_background, str) or not re.fullmatch(r"#[0-9a-fA-F]{6}", preview_background):686 raise LayMeshBridgeError("preview_background 须为 #RRGGBB")687 output_path = Path(output).expanduser().resolve() if output is not None else None688 if output_path and output_path.suffix.lower() not in _FORMATS:689 raise LayMeshBridgeError("不支持的输出格式")690 if output_path and output_path.suffix.lower() not in {".pdf", ".pptx", ".html", ".zip"} and page is None:691 raise LayMeshBridgeError("此格式需要 page=N;完整文档支持 PDF/PPTX")692 if dpi is not None and (type(dpi) not in {int,float} or not math.isfinite(dpi) or not 0 < dpi <= 25400693 or output_path is None or output_path.suffix.lower() in {".svg", ".html", ".zip"}):694 raise LayMeshBridgeError("dpi 需要位图/PDF/PPTX 输出且为 0–25400 之间的正数")695 option_args = _export_args(output_path, export_options)696 token = _warning_state.set((_warning_mode(show_warnings), set()))697 try:698 with tempfile.TemporaryDirectory(prefix="laymesh-document-") as scratch:699 preview = Path(scratch) / "preview.jpg"700 args = ["render", str(file), "--preview-output", str(preview),701 "--preview-dpi", str(preview_dpi), "--preview-quality", str(preview_quality),702 "--preview-background", preview_background]703 if page is not None:704 args += ["--page", str(page)]705 else:706 args += ["--preview-page", str(selected)]707 if output_path:708 output_path.parent.mkdir(parents=True, exist_ok=True)709 args += ["-o", str(output_path)]710 if dpi is not None:711 args += ["--dpi", str(dpi)]712 if config is not None:713 args += ["--config", str(Path(config).expanduser().resolve())]714 _run(_command(), args + option_args, file.parent)715 return DocumentResult(preview.read_bytes(), output_path, selected)716 finally:717 _warning_state.reset(token)718 719 720def render_source(721 source: str, *, namespace: Mapping[str, object] | None = None,722 base_dir: Path | str | None = None, output: Path | str | None = None,723 dpi: float | None = None, plot_dpi: float = 300,724 save_source: Path | str | None = None, show_warnings: bool | None = None,725 quality: float | None = None, compression: str | None = None, background: str | None = None,726 webp_lossless: bool | None = None, webp_method: int | None = None,727 webp_alpha_quality: int | None = None, webp_near_lossless: int | None = None,728 pdf_image_compression: str | None = None,729 pdf_jpeg_quality: int | None = None,730 pdf_downsample: bool | None = None,731 pdf_preserve_16bit: bool | None = None,732 pdf_preserve_alpha: bool | None = None,733 pdf_alpha_background: str | None = None,734 pdf_recompress_jpeg: bool | None = None,735 pdf_auto_palette_limit: int | None = None,736 pdf_auto_flatness_threshold: float | None = None,737 html_editable: bool | None = None,738 html_embed_fonts: bool | None = None,739 html_image_compression: str | None = None,740 html_image_quality: float | None = None,741 config: Path | str | None = None,742) -> RenderResult:743 """Render inline .lay source with optional Notebook variable bindings."""744 return _render(745 source, namespace=namespace or {}, base_dir=Path(base_dir or Path.cwd()),746 output=output, dpi=dpi, plot_dpi=plot_dpi, config=config,747 save_source=save_source, original=None, show_warnings=show_warnings,748 export_options=dict(html_editable=html_editable, html_embed_fonts=html_embed_fonts, html_image_compression=html_image_compression, html_image_quality=html_image_quality, quality=quality, compression=compression, background=background,749 webp_lossless=webp_lossless, webp_method=webp_method,750 webp_alpha_quality=webp_alpha_quality, webp_near_lossless=webp_near_lossless,751 pdf_image_compression=pdf_image_compression, pdf_jpeg_quality=pdf_jpeg_quality, pdf_downsample=pdf_downsample, pdf_preserve_16bit=pdf_preserve_16bit, pdf_preserve_alpha=pdf_preserve_alpha, pdf_alpha_background=pdf_alpha_background, pdf_recompress_jpeg=pdf_recompress_jpeg, pdf_auto_palette_limit=pdf_auto_palette_limit, pdf_auto_flatness_threshold=pdf_auto_flatness_threshold),752 )753 754 755def render_file(756 file: Path | str, *, namespace: Mapping[str, object] | None = None,757 output: Path | str | None = None, dpi: float | None = None,758 plot_dpi: float = 300, save_source: Path | str | None = None, show_warnings: bool | None = None,759 quality: float | None = None, compression: str | None = None, background: str | None = None,760 webp_lossless: bool | None = None, webp_method: int | None = None,761 webp_alpha_quality: int | None = None, webp_near_lossless: int | None = None,762 pdf_image_compression: str | None = None,763 pdf_jpeg_quality: int | None = None,764 pdf_downsample: bool | None = None,765 pdf_preserve_16bit: bool | None = None,766 pdf_preserve_alpha: bool | None = None,767 pdf_alpha_background: str | None = None,768 pdf_recompress_jpeg: bool | None = None,769 pdf_auto_palette_limit: int | None = None,770 pdf_auto_flatness_threshold: float | None = None,771 html_editable: bool | None = None,772 html_embed_fonts: bool | None = None,773 html_image_compression: str | None = None,774 html_image_quality: float | None = None,775 config: Path | str | None = None,776) -> RenderResult:777 """Render an existing .lay file; its relative assets stay relative to it."""778 file, source = _read_layout(file)779 return _render(780 source, namespace=namespace or {},781 base_dir=file.parent, output=output, dpi=dpi, config=config,782 plot_dpi=plot_dpi, save_source=save_source, original=file, show_warnings=show_warnings,783 export_options=dict(html_editable=html_editable, html_embed_fonts=html_embed_fonts, html_image_compression=html_image_compression, html_image_quality=html_image_quality, quality=quality, compression=compression, background=background,784 webp_lossless=webp_lossless, webp_method=webp_method,785 webp_alpha_quality=webp_alpha_quality, webp_near_lossless=webp_near_lossless,786 pdf_image_compression=pdf_image_compression, pdf_jpeg_quality=pdf_jpeg_quality, pdf_downsample=pdf_downsample, pdf_preserve_16bit=pdf_preserve_16bit, pdf_preserve_alpha=pdf_preserve_alpha, pdf_alpha_background=pdf_alpha_background, pdf_recompress_jpeg=pdf_recompress_jpeg, pdf_auto_palette_limit=pdf_auto_palette_limit, pdf_auto_flatness_threshold=pdf_auto_flatness_threshold),787 )