holder + scad: SCAD source editor on /holder + new /scad universal renderer

Phase 2 — SCAD editor on /holder
================================
Some adjustments need more control than the parameter form gives
(e.g. tweaking the .scad logic itself). A collapsible CodeMirror-based
editor now slides up from the bottom of the viewport when you click
the "</> Source" button at the bottom-right.

- holder.html / holder.css: editor panel, toggle button, Reset and
  Close buttons. CodeMirror 5 loaded from cdnjs (single CSS + JS
  pair, clike mode for syntax highlighting since OpenSCAD is C-like).
- holder-app.js: lazy-initialises the editor on first show, fetches
  bundled source from /api/holder/source, tracks whether the editor
  content has been modified ("modified" tag in the panel title).
  When the editor is visible AND content differs from bundled,
  _doRender() switches from /api/holder/render -> /api/scad/render
  with {source, params}. Cell-count cap doesn't apply in that mode
  (the source may not even use the holder schema).

Phase 3 — Universal OpenSCAD playground at /scad
================================================
A standalone page for rendering arbitrary OpenSCAD. Paste code, click
Render (or Ctrl+Enter), see STL in the same Three.js viewer the
holder uses. Useful for prototyping new generators before wiring
them into a parameter form.

- New page: static/scad.html + scad.css + js/scad-app.js. Reuses
  holder-viewer.js (the Three.js scene module is generic enough).
- "Load example" populates a 6-hole rounded bracket so new users
  can verify the renderer works in two clicks.
- Same progress UI (elapsed timer + indeterminate bar + Cancel
  via AbortController) as /holder.
- Top nav now has Holder / Busbars / SCAD on every page.

Backend (shared by phase 2 & 3)
================================
- holder.py: split _run_openscad() out of render_stl(). New
  render_source(source, params=None) writes the source to a temp
  file and renders it; enforces MAX_SOURCE_BYTES (default 512 KB)
  and RENDER_TIMEOUT but skips the cell-count cap. New bundled_source()
  returns the hex_cell.scad text for editor pre-population.
- app.py: GET /api/holder/source returns the bundled .scad text.
  POST /api/scad/render takes {source, params?} and returns STL +
  X-Holder-Dimensions header. ValueError -> 400, RuntimeError -> 500.
  _stl_response() factored out so both render endpoints emit the same
  headers consistently.
This commit is contained in:
wenil
2026-05-25 12:52:18 +03:00
parent 5bba0e3c4a
commit 676d976937
9 changed files with 470 additions and 29 deletions
+48 -13
View File
@@ -338,30 +338,26 @@ def _parse_echo_dims(stderr_bytes: bytes) -> dict:
return out
def render_stl(params: dict) -> tuple[bytes, dict]:
"""Render the .scad with given parameter overrides.
MAX_SOURCE_BYTES = int(os.environ.get("OPENSCAD_MAX_SOURCE_BYTES", str(512 * 1024)))
Returns (stl_bytes, dimensions) where dimensions is a {name: float}
dict harvested from openscad ECHO output (pack/box/holder sizes).
"""
_check_cell_limit(params)
def _run_openscad(scad_path: Path, params: dict | None) -> tuple[bytes, dict]:
if not openscad_available():
raise RuntimeError(
f"`{OPENSCAD_BIN}` not found on PATH. Install OpenSCAD "
"(e.g. `apt install openscad` on Debian/Ubuntu)."
)
if not SCAD_FILE.is_file():
raise FileNotFoundError(f"SCAD source not found at {SCAD_FILE}")
clean = _filter_params(params)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "out.stl"
cmd = [OPENSCAD_BIN, "-o", str(out)]
if OPENSCAD_BACKEND:
cmd += ["--backend", OPENSCAD_BACKEND]
for k, v in clean.items():
cmd += ["-D", f"{k}={_to_scad_literal(v)}"]
cmd.append(str(SCAD_FILE))
# Only the bundled-schema render passes -D overrides; raw source
# may not know about those variable names.
if params is not None:
for k, v in _filter_params(params).items():
cmd += ["-D", f"{k}={_to_scad_literal(v)}"]
cmd.append(str(scad_path))
try:
r = subprocess.run(cmd, capture_output=True, timeout=RENDER_TIMEOUT)
except subprocess.TimeoutExpired:
@@ -372,3 +368,42 @@ def render_stl(params: dict) -> tuple[bytes, dict]:
if not out.exists() or out.stat().st_size == 0:
raise RuntimeError("openscad produced no STL (geometry empty?)")
return out.read_bytes(), _parse_echo_dims(r.stderr or b"")
def render_stl(params: dict) -> tuple[bytes, dict]:
"""Render the bundled hex_cell.scad with parameter overrides.
Enforces the holder cell-count cap (PARAMS-schema is assumed). For
rendering arbitrary user-supplied OpenSCAD source, use render_source.
"""
_check_cell_limit(params)
if not SCAD_FILE.is_file():
raise FileNotFoundError(f"SCAD source not found at {SCAD_FILE}")
return _run_openscad(SCAD_FILE, params)
def render_source(source: str, params: dict | None = None) -> tuple[bytes, dict]:
"""Render arbitrary user-supplied OpenSCAD source.
Source size is capped (MAX_SOURCE_BYTES). Cell-count limit does NOT
apply — the source defines its own variables. RENDER_TIMEOUT still
bounds runaway computation.
"""
if not isinstance(source, str) or not source.strip():
raise ValueError("Empty SCAD source.")
src_bytes = source.encode("utf-8", errors="replace")
if len(src_bytes) > MAX_SOURCE_BYTES:
raise ValueError(
f"SCAD source too large ({len(src_bytes)} > {MAX_SOURCE_BYTES} bytes)."
)
with tempfile.TemporaryDirectory() as tmp:
scad = Path(tmp) / "user.scad"
scad.write_bytes(src_bytes)
return _run_openscad(scad, params)
def bundled_source() -> str:
"""Read the bundled hex_cell.scad for editor pre-population."""
if not SCAD_FILE.is_file():
raise FileNotFoundError(f"SCAD source not found at {SCAD_FILE}")
return SCAD_FILE.read_text(encoding="utf-8", errors="replace")