diff --git a/backend/snapstudio_api/routes_creative.py b/backend/snapstudio_api/routes_creative.py index 35ca7fb4..2ad595f2 100644 --- a/backend/snapstudio_api/routes_creative.py +++ b/backend/snapstudio_api/routes_creative.py @@ -1,22 +1,25 @@ -"""Routes of the Creative track: inspect one local creative project (3MF) and say what Studio read. +"""Routes of the Creative track: inspect a local creative project (3MF), list the supported formats, +and write a prepared copy with a verification of what the copy kept. - POST /creative/inspect {path, format?} -> {origin, understood, passed_through, could_not_interpret, - missing, diagnostics, recipes, source, evidence, advisory} + POST /creative/inspect {path, format?} -> what Studio read (origin, facts, kept, not understood) + POST /creative/formats {} -> SUPPORTED_FORMATS: what each format reads and does not + POST /creative/prepare {path, format?, out_dir?} -> a NEW prepared file, member-by-member comparison with + the original, and a re-hash of the original -The handler opens the file for reading only. It never writes, renames or deletes anything, never -slices, never contacts a printer and makes no network request of its own (the local-path check is -best-effort, see snapstudio_core/localpath.py). `source` carries the SHA-256 of the -file before the readers ran and again afterwards, so the response itself shows the original is -unchanged. Recipes are simulated: `execution_supported` is False and nothing here runs them. An -unrecognised generator is reported as origin "unknown", never guessed. +Inspect opens the file for reading only. Prepare calls the existing Prepare service, which writes one new +file, never over or in place of the original, into `out_dir` (a local directory) or, when none is given, +into the `creative-prepared` folder of Studio's own data directory. Nothing slices, nothing contacts a +printer, and this module makes no network request of its own (the local-path check is best-effort, see +snapstudio_core/localpath.py). Recipes are simulated: `execution_supported` is False. An unrecognised or +ambiguous generator is reported as such and is never guessed, and Prepare refuses it with an explanation. """ from __future__ import annotations import hashlib import os -from snapstudio_core import localpath -from snapstudio_core.creative import container, readers +from snapstudio_core import localpath, paths +from snapstudio_core.creative import container, formats, generators, readers from . import ext_routes from . import request_validation as rv @@ -24,20 +27,35 @@ #: Same ceiling the 3MF reader enforces; a larger file is refused before it is read. MAX_FILE_BYTES = container.MAX_ARCHIVE_BYTES MAX_PATH_CHARS = 1024 +#: Longest list of names put into one comparison answer. +MAX_LISTED = 200 EVIDENCE = "fixture-tested; fixtures are hand-written to published shapes, not captures" ADVISORY = ("Advisory read of one project file. Studio does not slice, does not run recipes and " "does not change the file. What it could not interpret is listed, not guessed.") +PREPARE_ADVISORY = ("Advisory comparison by part name and content hash. A prepared copy is a new file; it is " + "checked here only for what it kept, changed, dropped and added, not for how it slices " + "or prints. Review it in Snapmaker Orca before slicing.") -#: format hint -> reader. "auto" picks by the keys the project settings contain. +#: format hint -> reader. "auto" picks by the markers or keys the project contains. _READERS = { + "ditherforge": generators.read_ditherforge, + "kromacut": generators.read_kromacut, + "sindricad": generators.read_sindricad, "forcaslicer": readers.read_forca, "lixnix": readers.read_lixnix, "fullspectrum": readers.read_fullspectrum, "imagemap": readers.read_imagemap, "lumina": readers.read_lumina, } -_FORMATS = ("auto",) + tuple(_READERS) +_FORMATS = ("auto",) + formats.KEYS +#: Key-identified formats: a chosen format whose published keys are all absent is the wrong shape. +_KEY_FORMATS = { + "forcaslicer": readers._FORCA_KEYS, + "lixnix": readers._LIX_KEYS, + "fullspectrum": readers._FULLSPECTRUM_KEYS, +} +_FORMAT_BY_KEY = {f["key"]: f for f in formats.SUPPORTED_FORMATS} _ERROR_TEXT = { "bad_zip": "That file is not a readable 3MF archive.", @@ -90,10 +108,10 @@ def _read_source(path: str) -> bytes: return blob -def _detect(settings: dict) -> list[str]: - """Formats whose published keys are present. Several can match; none means unknown.""" - keys = set(settings) - found = [] +def _detect(manifest: container.ThreeMFManifest) -> list[str]: + """Formats whose published keys or markers are present. Several can match; none means unknown.""" + keys = set(manifest.project_settings or {}) + found = list(generators.detect(manifest)) if keys & readers._FORCA_KEYS: found.append("forcaslicer") if keys & readers._LIX_KEYS: @@ -108,10 +126,47 @@ def _wrap(exc: container.ContainerError) -> rv.ValidationError: return rv.ValidationError(_ERROR_TEXT.get(code, "That file could not be read as a 3MF project.")) -@ext_routes.route("/creative/inspect") -def inspect(data: dict) -> tuple[int, dict]: - path = _path(data) - hint = _format(data) +def _seen_sentence(manifest: container.ThreeMFManifest) -> str: + app = "" + try: + app = generators._model_metadata(generators._xml(manifest.model_xml)).get("Application", "") + except container.ContainerError: + pass + keys = len(manifest.project_settings or {}) + text = f"a 3MF project with {len(manifest.members)} parts and {keys} project settings keys" + return text + (f", Application tag `{app[:60]}`" if app else ", no Application tag") + + +def _wrong_shape_message(key: str, manifest: container.ThreeMFManifest, expected: list[str]) -> str: + label = formats.LABELS[key] + return (f"That file does not carry what Studio reads for {label}. Studio looks for: " + f"{'; '.join(expected)}. This file is {_seen_sentence(manifest)}. " + "What to do: choose Detect from markers and settings, pick the format of the tool that wrote the file, " + "or open it in that tool. Studio does not guess a format.") + + +def _explain(origin: dict, manifest: container.ThreeMFManifest) -> dict | None: + """Plain explanation for an origin Studio could not decide: what was seen, what is not supported, what to do.""" + seen = _seen_sentence(manifest) + if origin["status"] == "unknown": + return {"kind": "unknown_origin", "seen": f"This file is {seen}.", + "not_supported": "None of the supported tools' markers or settings keys were found, so Studio " + "does not say which tool wrote it and does not read it as one of them.", + "what_to_do": ["If you know which tool wrote the file, choose its format from the list and inspect again. " + "Choosing a manual-only format (ImageMap or Lumina) prepares the file as a generic 3MF " + "with no shape check.", + "Otherwise the file is still listed part by part below, untouched."]} + if origin["status"] == "ambiguous": + names = " and ".join(formats.LABELS.get(c, c) for c in origin["candidates"]) + return {"kind": "ambiguous_origin", "seen": f"This file is {seen}.", + "not_supported": f"Markers of more than one tool are present ({names}), so Studio does not decide " + "which one wrote it.", + "what_to_do": ["Choose the format you know it came from and inspect again."]} + return None + + +def _inspect(path: str, hint: str): + """Shared by inspect and prepare. Returns (body, blob, manifest). Reads only.""" blob = _read_source(path) before = hashlib.sha256(blob).hexdigest() try: @@ -120,13 +175,17 @@ def inspect(data: dict) -> tuple[int, dict]: raise _wrap(exc) from None settings = manifest.project_settings or {} - names = [hint] if hint != "auto" else _detect(settings) + if hint in _KEY_FORMATS and not (set(settings) & _KEY_FORMATS[hint]): + raise rv.ValidationError(_wrong_shape_message(hint, manifest, list(_FORMAT_BY_KEY[hint]["identified_by"]))) + names = [hint] if hint != "auto" else _detect(manifest) projects = [] try: for name in names: projects.append(_READERS[name](blob)) except container.ContainerError as exc: raise _wrap(exc) from None + except generators.WrongShape as exc: + raise rv.ValidationError(_wrong_shape_message(exc.generator, manifest, exc.expected)) from None if not projects: # Unknown generator: container identity only. Every part is preserved, nothing is interpreted. @@ -139,6 +198,7 @@ def inspect(data: dict) -> tuple[int, dict]: diagnostics = ["generator_not_recognized"] recipes: list = [] slots = None + facts: dict = {} else: status = "detected" if len(projects) == 1 else "ambiguous" origin = {"generator": projects[0].source_format if len(projects) == 1 else "unknown", @@ -160,21 +220,214 @@ def inspect(data: dict) -> tuple[int, dict]: diagnostics = [d for p in projects for d in p.diagnostics] recipes = [r.to_dict() for p in projects for r in p.recipes] slots = next((p.physical_slots_needed for p in projects if p.recipes), None) + facts = {p.source_format: p.understood for p in projects if p.source_format in generators.GENERATORS} after = _read_source(path) after_hash = hashlib.sha256(after).hexdigest() - return 200, { + candidates = origin["candidates"] if origin["status"] != "unknown" else [] + body = { "origin": origin, "understood": list(understood), + "facts": facts, "passed_through": passed, "could_not_interpret": list(unknown), "missing": list(missing), "diagnostics": list(diagnostics), "recipes": recipes, "physical_slots_needed": slots, - "source": {"name": os.path.basename(path), "size_bytes": len(blob), - "sha256_before": before, "sha256_after": after_hash, - "unchanged": before == after_hash}, + "format_info": [_FORMAT_BY_KEY[c] for c in candidates if c in _FORMAT_BY_KEY], + "explanation": _explain(origin, manifest), + "source": {"name": os.path.basename(path), "size_bytes": len(blob), "sha256_before": before, + "sha256_after": after_hash, "unchanged": before == after_hash}, "evidence": EVIDENCE, "advisory": ADVISORY, } + return body, blob, manifest + + +@ext_routes.route("/creative/inspect") +def inspect(data: dict) -> tuple[int, dict]: + body, _blob, _manifest = _inspect(_path(data), _format(data)) + return 200, body + + +@ext_routes.route("/creative/formats") +def supported_formats(data: dict) -> tuple[int, dict]: + return 200, {"formats": [dict(f) for f in formats.SUPPORTED_FORMATS], "evidence": EVIDENCE, + "manual_only": list(formats.MANUAL_ONLY), + "note": "Support is listed per format. Studio does not infer support from the fact that a file is a ZIP."} + + +# -- prepare -------------------------------------------------------------------------------- + +DEFAULT_OUT_FOLDER = "creative-prepared" + + +def _out_dir(data: dict) -> tuple[str, str]: + """(directory, kind). A given directory must be an existing local one; otherwise Studio's own folder.""" + raw = data.get("out_dir") + if raw is None or raw == "": + target = os.path.join(paths.data_dir(), DEFAULT_OUT_FOLDER) + os.makedirs(target, exist_ok=True) + return target, "studio_default" + if not isinstance(raw, str) or len(raw) > MAX_PATH_CHARS or "\x00" in raw: + raise rv.ValidationError("Invalid 'out_dir'") + if localpath.is_network_or_device_path(raw) or not localpath.is_local_directory(raw): + raise rv.ValidationError("That output folder is not an existing local folder Studio can write to.") + return raw, "chosen" + + +def _refusal(kind: str, body: dict, explanation: dict) -> tuple[int, dict]: + return 200, {"prepared": False, "refusal": {"kind": kind, **explanation}, + "origin": body["origin"], "source": body["source"], "advisory": PREPARE_ADVISORY} + + +def _model_parts(parts: dict) -> list[bytes]: + names = ["3D/3dmodel.model"] + sorted(n for n in parts if n.startswith("3D/Objects/") and n.endswith(".model")) + return [parts[n] for n in names if n in parts] + + +def _paint_count(parts: dict) -> int | None: + """Painted triangles over the root model and the object part files; None when a part cannot be parsed.""" + total = 0 + try: + for blob in _model_parts(parts): + total += generators._mesh_stats(generators._xml(blob))["painted"] + except container.ContainerError: + return None + return total + + +def compare_members(original: container.ThreeMFManifest, exported: container.ThreeMFManifest) -> dict: + """Name-based comparison of two archives' non-directory members.""" + old = {m.name: m.sha256 for m in original.members} + new = {m.name: m.sha256 for m in exported.members} + return { + "preserved": sorted(n for n in old if n in new and old[n] == new[n]), + "modified": sorted(n for n in old if n in new and old[n] != new[n]), + "dropped": sorted(n for n in old if n not in new), + "added": sorted(n for n in new if n not in old), + } + + +def _settings_delta(original: dict | None, exported: dict | None) -> dict: + a, b = original or {}, exported or {} + removed = sorted(k for k in a if k not in b) + changed = sorted(k for k in a if k in b and a[k] != b[k]) + return {"removed_keys": removed[:MAX_LISTED], "removed_count": len(removed), + "changed_keys": changed[:MAX_LISTED], "changed_count": len(changed), + "added_key_count": sum(1 for k in b if k not in a)} + + +def _verify(original: container.ThreeMFManifest, out_path: str) -> dict: + """Open the exported archive and compare it with the original. Never raises on a bad export.""" + try: + blob = _read_source(out_path) + exported = container.read_3mf(blob) + except (rv.ValidationError, container.ContainerError) as exc: + return {"opens_as_zip": False, "problem": str(exc) if isinstance(exc, rv.ValidationError) + else _ERROR_TEXT.get(str(exc), "The exported file could not be read.")} + diff = compare_members(original, exported) + before, after = _paint_count(original.parts), _paint_count(exported.parts) + return { + "opens_as_zip": True, "size_bytes": len(blob), "sha256": hashlib.sha256(blob).hexdigest(), + "members": [{"name": m.name, "sha256": m.sha256} for m in exported.members], + "comparison": {k: v[:MAX_LISTED] for k, v in diff.items()}, + "counts": {k: len(v) for k, v in diff.items()}, + "settings": _settings_delta(original.project_settings, exported.project_settings), + "per_face_paint": {"original_triangles": before, "exported_triangles": after, + "kept": None if before is None or after is None else after >= before}, + } + + +def _loss_notes(verify: dict) -> list[str]: + notes = [] + counts = verify["counts"] + if counts["dropped"]: + notes.append(f"{counts['dropped']} part(s) of the original are not in the copy: " + + ", ".join(verify["comparison"]["dropped"][:6]) + ".") + if counts["modified"]: + notes.append(f"{counts['modified']} part(s) differ from the original: " + + ", ".join(verify["comparison"]["modified"][:6]) + ".") + paint = verify["per_face_paint"] + if paint["kept"] is False: + notes.append(f"Per-face paint: the original has {paint['original_triangles']} painted triangle(s), " + f"the copy has {paint['exported_triangles']}.") + if paint["kept"] is None: + notes.append("Per-face paint could not be counted in one of the two files.") + removed = verify["settings"]["removed_count"] + if removed: + notes.append(f"{removed} project setting(s) of the original are not in the copy.") + if not notes: + notes.append("By part name and content hash, nothing was dropped and nothing differs except the parts " + "listed as modified or added.") + return notes + + +def _summary_subset(result: dict) -> dict: + summary = result.get("settings_summary") or {} + pick = lambda key: [i if isinstance(i, (str, int, float)) else dict(i) for i in (summary.get(key) or [])][:MAX_LISTED] # noqa: E731 + return {"compat_changed": pick("compat_changed"), "mapped_to_u1": pick("mapped_to_u1"), + "could_not_carry": pick("could_not_carry"), "warnings": pick("warnings")} + + +@ext_routes.route("/creative/prepare") +def prepare(data: dict) -> tuple[int, dict]: + from snapstudio_core.errors import SnapStudioError + + from . import service + + path = _path(data) + hint = _format(data) + body, blob, manifest = _inspect(path, hint) + explanation = body["explanation"] + if explanation is not None: + return _refusal(explanation["kind"], body, { + "seen": explanation["seen"], + "not_supported": explanation["not_supported"] + " Nothing was prepared.", + "what_to_do": explanation["what_to_do"]}) + out_dir, out_kind = _out_dir(data) + original_sha = hashlib.sha256(blob).hexdigest() + try: + result = service.convert(path, out_dir, "preserve") + except SnapStudioError as exc: + problems = list(getattr(exc, "problems", [])) + return _refusal("prepare_refused", body, { + "seen": f"This file was read as {formats.LABELS.get(body['origin']['generator'], body['origin']['generator'])}.", + "not_supported": f"Studio's Prepare could not produce a copy it can vouch for. {exc}", + "what_to_do": ["Open the original in Snapmaker Orca to check it, or re-export it from the tool that wrote it.", + "Nothing was written and the original was not changed."], + "problems": problems[:20]}) + except ValueError as exc: + return _refusal("prepare_refused", body, { + "seen": "The file was read, but Prepare refused it.", "not_supported": str(exc), + "what_to_do": ["Nothing was written and the original was not changed."]}) + if result.get("blocked") or not result.get("output_path"): + return _refusal("prepare_blocked", body, { + "seen": "The file was read, but Prepare did not write a copy.", + "not_supported": " ".join(str(e) for e in result.get("errors") or []) or "Prepare wrote no file.", + "what_to_do": ["Nothing was written and the original was not changed."]}) + + out_path = result["output_path"] + verify = _verify(manifest, out_path) + after = hashlib.sha256(_read_source(path)).hexdigest() + same_place = os.path.dirname(os.path.abspath(out_path)) == os.path.dirname(os.path.abspath(path)) + return 200, { + "prepared": True, + "origin": body["origin"], + # File name and a generic label only: no directory path, not even a folder name, leaves this route. + "output": {"name": os.path.basename(out_path), "location": out_kind, + "location_label": ("Studio's creative-prepared folder" if out_kind == "studio_default" + else "the folder you chose"), + "in_source_folder": same_place}, + "prepare": {"mode": result.get("prepare_mode"), "validated_ok": bool(result.get("validated_ok")), + "errors": [str(e) for e in result.get("errors") or []][:MAX_LISTED], + **_summary_subset(result)}, + "verification": verify, + "loss_notes": _loss_notes(verify) if verify.get("opens_as_zip") else + ["The exported file could not be re-read, so nothing can be said about what it kept."], + "original": {"name": os.path.basename(path), "sha256_before": original_sha, "sha256_after": after, + "original_unchanged": original_sha == after}, + "source": body["source"], + "advisory": PREPARE_ADVISORY, + } diff --git a/backend/snapstudio_core/creative/container.py b/backend/snapstudio_core/creative/container.py index d9366582..14a2bdac 100644 --- a/backend/snapstudio_core/creative/container.py +++ b/backend/snapstudio_core/creative/container.py @@ -10,7 +10,7 @@ import posixpath import zipfile import zlib -from dataclasses import dataclass +from dataclasses import dataclass, field from xml.etree import ElementTree CORE_NS = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" @@ -38,6 +38,9 @@ class ThreeMFManifest: passed_through: tuple[MemberDigest, ...] model_xml: bytes project_settings: dict | None + #: Member bytes already read under the container limits; lets format readers look inside + #: named parts without opening the archive a second time. Never serialized. + parts: dict = field(default_factory=dict, repr=False, compare=False) def to_dict(self) -> dict: """Serialize member identity only; original archive payloads stay untouched.""" @@ -130,4 +133,4 @@ def read_3mf(data: bytes) -> ThreeMFManifest: understood.append("Metadata/project_settings.config") records = tuple(MemberDigest(n, hashlib.sha256(blobs[n]).hexdigest()) for n in sorted(blobs)) passed = tuple(rec for rec in records if rec.name not in understood) - return ThreeMFManifest(records, tuple(understood), passed, model, settings) + return ThreeMFManifest(records, tuple(understood), passed, model, settings, blobs) diff --git a/backend/snapstudio_core/creative/formats.py b/backend/snapstudio_core/creative/formats.py new file mode 100644 index 00000000..b409b2f8 --- /dev/null +++ b/backend/snapstudio_core/creative/formats.py @@ -0,0 +1,71 @@ +"""The explicit list of input formats the Creative inspector supports, and what each one reads. + +This table is the contract returned by `POST /creative/formats` and mirrored in +docs/internal/CREATIVE_COMPAT.md. Support is never inferred from generic ZIP inspection: a format is +listed only with the carrier, the documented markers or keys, what is established and what is not. +""" +from __future__ import annotations + +from . import generators, readers + +EVIDENCE = "fixture-tested" +_CARRIER = "3MF (ZIP) with 3D/3dmodel.model in the 3MF core namespace" + +SUPPORTED_FORMATS: tuple[dict, ...] = ( + {"key": "ditherforge", "label": "DitherForge", "carrier": _CARRIER, "selection": "automatic", + "identified_by": list(generators.MARKERS["ditherforge"]), + "reads": ["application tag and variant", "object part files", "triangle and painted-triangle counts", + "paint extruders used (documented 1-2 character paint_color values)", + "object names and extruders from model_settings.config", + "filament_colour, filament_type, printer_settings_id, print_settings_id"], + "kept_untouched": ["every other part and settings key, by name and SHA-256"], + "not_read": ["geometry beyond counts", "longer paint_color strings (split-triangle encoding)", + "settings JSON and collection TXT written beside the 3MF"], + "prepare_limits": ["Prepare works on the Bambu-path export (Application tag BambuStudio-+ditherforge-).", + "The generic-path export writes part id 1 under a component with objectid 2 or more. Studio's " + "structure check does not accept that, so such a file is inspect-only: Prepare refuses it and " + "writes nothing."], + "upstream": "rtwfroody/ditherforge (MIT) 4d3552a434e8084d9b5fe573959a3493325be29f"}, + {"key": "kromacut", "label": "Kromacut", "carrier": _CARRIER, "selection": "automatic", + "identified_by": list(generators.MARKERS["kromacut"]), + "reads": ["layer height and first layer height metadata", "colour layer object count and assembly object", + "parts and their extruders from model_settings.config", "base material colours", + "filament_colour, layer_height, initial_layer_print_height"], + "kept_untouched": ["Metadata/kromacut.config and every other part, by name and SHA-256"], + "not_read": ["the payload of Metadata/kromacut.config", "mesh geometry", + "optional custom metadata files"], + "upstream": "vycdev/Kromacut (AGPL-3.0, format only) 94874755426ee7f33b3684a5544e7fab0e2e73f7"}, + {"key": "sindricad", "label": "SindriCAD", "carrier": _CARRIER, "selection": "automatic", + "identified_by": list(generators.MARKERS["sindricad"]), + "reads": ["named bodies with palette slot (pindex) and extruder", "palette base materials", + "per-face paint (documented 1-2 character paint_color values)", + "filament_colour and filament_type"], + "kept_untouched": ["every other part and settings key, by name and SHA-256"], + "not_read": ["mesh geometry beyond counts", "longer paint_color strings"], + "upstream": "MakerViking/sindricad (AGPL-3.0, format only) 8b2e9dc4f82fba58b39c206c993534c487cc1eab"}, + {"key": "forcaslicer", "label": "FOrcaSlicer", "carrier": _CARRIER, "selection": "automatic", + "identified_by": ["published fos_*, mms_* and color_patch_* keys in project_settings.config"], + "reads": sorted(readers._FORCA_KEYS), "kept_untouched": ["all other keys and parts"], + "not_read": ["unknown fos_* keys", "plain nozzle_diameter as a physical value"], "upstream": None}, + {"key": "lixnix", "label": "LixNix Full Multi-Nozzle", "carrier": _CARRIER, "selection": "automatic", + "identified_by": sorted(readers._LIX_KEYS), "reads": sorted(readers._LIX_KEYS), + "kept_untouched": ["all other keys and parts"], "not_read": ["effective heights", "unpublished variants"], + "upstream": None}, + {"key": "fullspectrum", "label": "FullSpectrum 0.9.12", "carrier": _CARRIER, "selection": "automatic", + "identified_by": sorted(readers._FULLSPECTRUM_KEYS), "reads": ["mixed_filament_definitions rows (simulated recipes)"], + "kept_untouched": ["all other keys and parts"], + "not_read": ["ratios", "pattern semantics", "execution", "the draft vnext schema"], "upstream": None}, + {"key": "imagemap", "label": "OrcaSlicer ImageMap", "carrier": _CARRIER, "selection": "manual only", + "identified_by": [], "reads": ["3MF artifact identity (size, SHA-256, member list)"], + "kept_untouched": ["every part, by name and SHA-256"], + "not_read": ["the zone shape: the exact serialized carrier is not established, so no zone claim is made"], + "upstream": None}, + {"key": "lumina", "label": "Lumina Layers", "carrier": _CARRIER, "selection": "manual only", + "identified_by": [], "reads": ["3MF artifact identity (size, SHA-256, member list)"], + "kept_untouched": ["every part, by name and SHA-256"], + "not_read": ["generation provenance", "session behaviour", "file-ID lifetime"], "upstream": None}, +) + +KEYS = tuple(f["key"] for f in SUPPORTED_FORMATS) +MANUAL_ONLY = tuple(f["key"] for f in SUPPORTED_FORMATS if f["selection"] == "manual only") +LABELS = {f["key"]: f["label"] for f in SUPPORTED_FORMATS} diff --git a/backend/snapstudio_core/creative/generators.py b/backend/snapstudio_core/creative/generators.py new file mode 100644 index 00000000..34710f3a --- /dev/null +++ b/backend/snapstudio_core/creative/generators.py @@ -0,0 +1,305 @@ +"""Readers for 3MF projects written by DitherForge, Kromacut and SindriCAD. + +Each reader is built only from the output shape its upstream exporter source documents (commits +and paths are listed in tests/fixtures/creative/PROVENANCE.md and docs/internal/CREATIVE_COMPAT.md). +Kromacut and SindriCAD are AGPL-3.0: only the output FORMAT (member names, element and attribute +names, JSON keys) was learned from them; no code, comment or sample was copied. + +A generator is identified from its documented markers, never from "it is a ZIP". When markers of +more than one generator are present the caller reports the origin as ambiguous. Anything beyond the +named facts is passed through by name and SHA-256 or listed as could-not-interpret. +""" +from __future__ import annotations + +from typing import Any +from xml.etree import ElementTree + +from .container import CORE_NS, ContainerError, ThreeMFManifest, read_3mf +from .readers import CreativeProject, _digest_obj + +_C = f"{{{CORE_NS}}}" +_P = "{http://schemas.microsoft.com/3dmanufacturing/production/2015/06}" +_M = "{http://schemas.microsoft.com/3dmanufacturing/material/2015/02}" + +GENERATORS = ("ditherforge", "kromacut", "sindricad") +SETTINGS_PART = "Metadata/project_settings.config" +MODEL_SETTINGS_PART = "Metadata/model_settings.config" +KROMACUT_CONFIG_PART = "Metadata/kromacut.config" +_KROMACUT_NS = b'xmlns:Kromacut="https://github.com/vycdev/Kromacut"' + +#: Parts each generator is documented to write. Absent ones are reported as missing, not guessed. +_EXPECTED_PARTS = { + "ditherforge": (MODEL_SETTINGS_PART, SETTINGS_PART), + "kromacut": (MODEL_SETTINGS_PART, KROMACUT_CONFIG_PART, SETTINGS_PART), + "sindricad": (MODEL_SETTINGS_PART, SETTINGS_PART), +} +#: Metadata keys of model_settings.config each exporter writes. Others are listed as not interpreted. +_KNOWN_MODEL_SETTINGS_KEYS = { + "ditherforge": {"name", "extruder", "face_count", "source_file", "subtype"}, + "kromacut": {"name", "extruder", "plater_id", "plater_name", "locked", "object_id", "instance_id"}, + "sindricad": {"name", "extruder"}, +} +#: project_settings.config keys each reader names. Every other key is passed through by digest. +_KNOWN_SETTINGS_KEYS = { + "ditherforge": ("filament_colour", "filament_type", "printer_settings_id", "print_settings_id"), + "kromacut": ("filament_colour", "layer_height", "initial_layer_print_height"), + "sindricad": ("filament_colour", "filament_type"), +} + +MARKERS = { + "ditherforge": ("model metadata Application starting `ditherforge-` or containing `+ditherforge-`",), + "kromacut": ("model metadata Application `Kromacut_Print`", "model namespace `xmlns:Kromacut`", + f"archive member `{KROMACUT_CONFIG_PART}`"), + "sindricad": ("model metadata Application `SindriCAD`",), +} + + +class WrongShape(ValueError): + """The file does not carry the documented markers of the format that was asked for.""" + + def __init__(self, generator: str, seen: list[str]): + super().__init__(generator) + self.generator = generator + self.expected = list(MARKERS[generator]) + self.seen = seen + + +def _xml(blob: bytes) -> ElementTree.Element: + upper = blob.upper() + if b" dict[str, str]: + return {el.get("name", ""): (el.text or "") for el in root if el.tag == f"{_C}metadata"} + + +def markers_present(manifest: ThreeMFManifest) -> dict[str, list[str]]: + """generator -> markers that matched. Pure inspection of the already-read container.""" + root = _xml(manifest.model_xml) + meta = _model_metadata(root) + app = meta.get("Application", "") + found: dict[str, list[str]] = {} + if app.startswith("ditherforge-") or "+ditherforge-" in app: + found["ditherforge"] = [MARKERS["ditherforge"][0]] + kro = [] + if app == "Kromacut_Print": + kro.append(MARKERS["kromacut"][0]) + if _KROMACUT_NS in manifest.model_xml: + kro.append(MARKERS["kromacut"][1]) + if KROMACUT_CONFIG_PART in manifest.parts: + kro.append(MARKERS["kromacut"][2]) + if kro: + found["kromacut"] = kro + if app == "SindriCAD": + found["sindricad"] = [MARKERS["sindricad"][0]] + return found + + +def detect(manifest: ThreeMFManifest) -> list[str]: + return sorted(markers_present(manifest)) + + +def _decode_paint(value: str) -> int | None: + """1-based extruder for a documented 1-2 character `paint_color`, else None (not decoded).""" + if value == "4": + return 1 + if value == "8": + return 2 + if len(value) == 2 and value.endswith("C") and value[0] in "0123456789ABCDEF": + return int(value[0], 16) + 3 + return None + + +def _mesh_stats(root: ElementTree.Element) -> dict[str, Any]: + triangles = painted = 0 + values: dict[str, int] = {} + for tri in root.iter(f"{_C}triangle"): + triangles += 1 + value = tri.get("paint_color") or "" + if value: + painted += 1 + values[value] = values.get(value, 0) + 1 + return {"triangles": triangles, "painted": painted, "values": values} + + +def _objects(root: ElementTree.Element) -> list[dict[str, Any]]: + out = [] + for obj in root.iter(f"{_C}object"): + comps = [{"objectid": c.get("objectid"), "path": c.get(f"{_P}path")} + for c in obj.iter(f"{_C}component")] + out.append({"id": obj.get("id"), "name": obj.get("name"), "pid": obj.get("pid"), + "pindex": obj.get("pindex"), "has_mesh": obj.find(f"{_C}mesh") is not None, + "components": comps}) + return out + + +def _metadata_rows(el: ElementTree.Element) -> dict[str, str]: + return {m.get("key", ""): m.get("value", "") for m in el.findall("metadata") if m.get("key")} + + +def _model_settings(blob: bytes) -> tuple[list[dict[str, Any]], set[str]]: + """Objects (and their parts) with name and extruder, plus every metadata key seen.""" + root = _xml(blob) + if root.tag != "config": + raise ContainerError("bad_xml") + keys: set[str] = set() + objects = [] + for obj in root.findall("object"): + rows = _metadata_rows(obj) + keys |= set(rows) + parts = [] + for part in obj.findall("part"): + prow = _metadata_rows(part) + keys |= set(prow) + parts.append({"id": part.get("id"), "name": prow.get("name"), "extruder": _int(prow.get("extruder"))}) + objects.append({"id": obj.get("id"), "name": rows.get("name"), "extruder": _int(rows.get("extruder")), + "parts": parts}) + for plate in root.findall("plate"): + keys |= set(_metadata_rows(plate)) + for inst in plate.findall("model_instance"): + keys |= set(_metadata_rows(inst)) + return objects, keys + + +def _int(value: Any) -> int | None: + try: + return int(str(value)) + except (TypeError, ValueError): + return None + + +def _palette(root: ElementTree.Element) -> list[dict[str, str]]: + bases = [b for b in root.iter() if b.tag in (f"{_C}base", f"{_M}base")] + return [{"name": b.get("name", ""), "colour": b.get("displaycolor", "")} for b in bases] + + +def _str_list(value: Any) -> list[str] | None: + return [x for x in value] if isinstance(value, list) and all(isinstance(x, str) for x in value) else None + + +def _build(generator: str, data: bytes) -> CreativeProject: + manifest = read_3mf(data) + markers = markers_present(manifest) + if generator not in markers: + raise WrongShape(generator, sorted(manifest.parts)) + root = _xml(manifest.model_xml) + meta = _model_metadata(root) + settings = manifest.project_settings or {} + facts: dict[str, Any] = {"application": meta.get("Application", ""), "markers_matched": markers[generator]} + unknown: list[str] = [] + diagnostics: list[str] = [] + other = sorted(g for g in markers if g != generator) + if other: + diagnostics.append("markers_of_other_generators_present:" + ",".join(other)) + + # -- geometry facts: main model plus every object part file (DitherForge keeps meshes there) + models = [("3D/3dmodel.model", root)] + for name in sorted(manifest.parts): + if name.startswith("3D/Objects/") and name.endswith(".model"): + try: + models.append((name, _xml(manifest.parts[name]))) + except ContainerError: + diagnostics.append(f"object_model_unreadable:{name}") + stats = {"triangles": 0, "painted": 0, "values": {}} + for _, tree in models: + part = _mesh_stats(tree) + stats["triangles"] += part["triangles"] + stats["painted"] += part["painted"] + for key, count in part["values"].items(): + stats["values"][key] = stats["values"].get(key, 0) + count + objects = _objects(root) + mesh_objects = [o for o in objects if o["has_mesh"]] + decoded = {k: _decode_paint(k) for k in stats["values"]} + undecoded = sorted(k for k, v in decoded.items() if v is None) + slots_used = sorted({v for v in decoded.values() if v is not None}) + + # -- model_settings.config + ms_objects: list[dict[str, Any]] = [] + if MODEL_SETTINGS_PART in manifest.parts: + try: + ms_objects, ms_keys = _model_settings(manifest.parts[MODEL_SETTINGS_PART]) + for key in sorted(ms_keys - _KNOWN_MODEL_SETTINGS_KEYS[generator]): + unknown.append(f"{MODEL_SETTINGS_PART} metadata key {key}") + except ContainerError: + diagnostics.append("model_settings_unreadable") + missing = [p for p in _EXPECTED_PARTS[generator] if p not in manifest.parts] + + if generator == "ditherforge": + app = facts["application"] + facts["variant"] = "bambu_project" if app.startswith("BambuStudio-") else "generic" + facts["designer"] = meta.get("Designer", "") + facts["build_item_count"] = len(list(root.iter(f"{_C}item"))) + facts["object_part_files"] = [n for n, _ in models[1:]] + facts["triangle_count"] = stats["triangles"] + facts["per_face_paint"] = stats["painted"] > 0 + facts["painted_triangle_count"] = stats["painted"] + facts["paint_extruders_used"] = slots_used + facts["objects"] = [{"name": o["name"], "extruder": o["extruder"]} for o in ms_objects] + elif generator == "kromacut": + facts["layer_object_count"] = len(mesh_objects) + facts["assembly_present"] = any(o["components"] for o in objects) + for key, fact in (("slic3rpe:layer_height", "layer_height"), + ("slic3rpe:first_layer_height", "first_layer_height"), + ("Kromacut:SmoothMeshingStrength", "smooth_meshing_strength")): + if key in meta: + facts[fact] = meta[key] + parts = [part for o in ms_objects for part in o["parts"]] + facts["parts"] = [{"name": p["name"], "extruder": p["extruder"]} for p in parts] + facts["palette"] = _palette(root) + facts["per_face_paint"] = stats["painted"] > 0 + if KROMACUT_CONFIG_PART in manifest.parts: + unknown.append(f"{KROMACUT_CONFIG_PART} payload (format not documented in the exporter output)") + else: # sindricad + bodies = [] + for o in mesh_objects: + ext = next((m["extruder"] for m in ms_objects if m["id"] == o["id"]), None) + slot = _int(o["pindex"]) + bodies.append({"name": o["name"], "palette_slot": slot, "extruder": ext}) + if ext is not None and slot is not None and ext != slot + 1: + diagnostics.append(f"extruder_disagrees_with_palette_slot:{o['name']}") + facts["body_count"] = len(mesh_objects) + facts["bodies"] = bodies + facts["palette"] = _palette(root) + facts["per_face_paint"] = stats["painted"] > 0 + facts["painted_triangle_count"] = stats["painted"] + facts["paint_extruders_used"] = slots_used + if undecoded: + unknown.append("paint_color values not decoded: " + ", ".join(undecoded[:8])) + + known_keys = _KNOWN_SETTINGS_KEYS[generator] + understood: dict[str, Any] = dict(facts) + for key in known_keys: + if key in settings: + value = settings[key] + if key in ("filament_colour", "filament_type"): + value = _str_list(value) + if value is None: + unknown.append(f"{key} (not a list of strings)") + continue + understood[key] = value + passed = tuple({"name": m.name, "sha256": m.sha256} for m in manifest.passed_through) + passed += tuple({"name": k, "sha256": _digest_obj({k: v})["sha256"]} + for k, v in sorted(settings.items()) if k not in understood) + project = CreativeProject(generator, _digest_obj(settings), understood, passed, tuple(unknown), + tuple(missing), tuple(diagnostics)) + return project + + +def read_ditherforge(data: bytes) -> CreativeProject: + """DitherForge 3MF: Application `ditherforge-` (generic) or `BambuStudio-+ditherforge-`.""" + return _build("ditherforge", data) + + +def read_kromacut(data: bytes) -> CreativeProject: + """Kromacut 3MF: Application `Kromacut_Print`, `xmlns:Kromacut`, or `Metadata/kromacut.config`.""" + return _build("kromacut", data) + + +def read_sindricad(data: bytes) -> CreativeProject: + """SindriCAD 3MF: Application `SindriCAD`; bodies with `pindex` and extruder rows.""" + return _build("sindricad", data) diff --git a/backend/snapstudio_core/multipart.py b/backend/snapstudio_core/multipart.py index cadeb1de..31aa43b2 100644 --- a/backend/snapstudio_core/multipart.py +++ b/backend/snapstudio_core/multipart.py @@ -455,6 +455,81 @@ def _parts_by_object(settings_xml: str) -> dict: _OBJECT_TAG = re.compile(r']") +_TRIANGLE_START = re.compile(r" container +_COMPONENT_TAG = re.compile(r"]*>") +_PATH_ATTR = re.compile(r'\bp:path="([^"]*)"') +_OBJECTID_ATTR = re.compile(r'\bobjectid="(\d+)"') + + +def _component_refs(block: str) -> list[tuple]: + """(p:path or None, objectid or None) for each component tag, whatever order its attributes come in.""" + refs = [] + for tag in _COMPONENT_TAG.findall(block): + path = _PATH_ATTR.search(tag) + object_id = _OBJECTID_ATTR.search(tag) + refs.append((path.group(1) if path else None, object_id.group(1) if object_id else None)) + return refs + + +def _scan_objects(body: str, where: str) -> tuple[dict, list[str]]: + """Every `` in one model part, read the same way for the root model and a p:path file. + + One linear pass with str.find: regexes over a many-megabyte mesh (a lazy `.*?`, or a search + per object from the top of the file) made the Doctor several times slower. Returns + ({id: {type, mesh, geometry, valid}}, problems). An object that is not closed, or that holds + another object, is `valid` False: it earns no geometry and cannot satisfy a reference, because + whatever lies inside it belongs to something else. A repeated id keeps its first definition. + """ + if "", "", body, flags=re.S) + objects: dict[str, dict] = {} + problems: list[str] = [] + pos = 0 + visited = 0 + truncated = False + while True: + start = body.find('", start) + if tag_end < 0: + problems.append(f"an object tag in {where} is not closed") + truncated = True + break + pos = tag_end + tag = _OBJECT_TAG.match(body, start, tag_end) + if not tag: + problems.append(f"an object in {where} has an id that is not a number") + continue + object_id = tag.group(1) + if object_id in objects: + problems.append(f"object {object_id} is defined more than once in {where}") + continue + kind = _TYPE_ATTR.search(body, start, tag_end) + entry = {"type": kind.group(1) if kind else None, "mesh": False, "geometry": False, "valid": True} + objects[object_id] = entry + if body[tag_end - 1] == "/": # self-closing: no body, no geometry + continue + end = body.find("", tag_end) + if end < 0: + problems.append(f"object {object_id} in {where} is not closed") + entry["valid"] = False + continue + if _NESTED_OBJECT.search(body, tag_end, end): + # 3MF Core does not nest objects; a mesh found inside one belongs to the inner object + problems.append(f"object {object_id} in {where} contains another object") + entry["valid"] = False + continue + entry["mesh"] = body.find("= 0 + entry["geometry"] = _TRIANGLE_START.search(body, tag_end, end) is not None + pos = end + if not truncated and len(_NESTED_OBJECT.findall(body)) > visited: + # an object opened some other way (another attribute first, single quotes) is never scanned, + # so nothing would check it: refuse rather than let it pass unread + problems.append(f"{where} has an object tag the scan cannot read (`id` must be the first attribute, double-quoted)") + return objects, problems def _object_label(body: str) -> str: @@ -513,11 +588,12 @@ def validate_archive(tm) -> dict: lose the file. """ problems: list[str] = [] - mesh_types: dict[str, str] = {} def read(name: str) -> str: try: - return tm.read_part(name).decode("utf-8", "ignore") if tm.has_part(name) else "" + text = tm.read_part(name).decode("utf-8", "ignore") if tm.has_part(name) else "" + # comments are not structure: no reader below may see a commented-out tag + return re.sub(r"", "", text, flags=re.S) if "{obj(1)}' + result = multipart.validate_archive(build({A: commented}, [(A, 1)])) + assert result["ok"] is True, result["problems"] + + +def test_a_comment_in_the_root_model_does_not_refuse_a_valid_root_mesh(): + archive = build({A: model(obj(1))}, [(None, 2), (A, 1)], root_objects=[ + f' {MESH}'], parts=[(2, "normal_part"), (1, "normal_part")]) + assert multipart.validate_archive(archive)["ok"] is True + + +# -- the p:path scan now has the nested / unclosed handling the root scan has --------------------------------- + +def test_an_object_nested_in_a_file_object_is_not_credited_to_the_outer_object(): + nested = model(f'{MESH}') + result = multipart.validate_archive(build({A: nested}, [(A, 1)])) + assert result["ok"] is False + assert any("object 1 in /3D/Objects/a.model contains another object" in p for p in result["problems"]) + assert any("no file defines" in p and "'1'" in p for p in result["problems"]) + + +def test_an_unclosed_file_object_is_refused_not_ignored(): + unclosed = f'{MESH}' + result = multipart.validate_archive(build({A: unclosed}, [(A, 1)])) + assert result["ok"] is False + assert any("object 1 in /3D/Objects/a.model is not closed" in p for p in result["problems"]) + assert any("no file defines" in p for p in result["problems"]) + + +def test_an_unclosed_file_object_does_not_borrow_the_next_objects_geometry(): + """Object 1 has no mesh and no close tag; object 2's closing tag must not make it look like geometry.""" + xml = f'{MESH}' + result = multipart.validate_archive(build({A: xml}, [(A, 1)])) + assert result["ok"] is False + assert any("contains another object" in p for p in result["problems"]) + + +def test_an_empty_triangles_container_in_a_file_is_not_geometry(): + result = multipart.validate_archive(build({A: model(obj(1, body=EMPTY_MESH))}, [(A, 1)])) + assert result["ok"] is False + assert any("object 1 in /3D/Objects/a.model carries no geometry" in p for p in result["problems"]) + + +def test_an_empty_triangles_container_in_the_root_is_not_geometry(): + archive = build({A: model(obj(1))}, [(None, 2), (A, 1)], root_objects=[obj(2, body=EMPTY_MESH)], + parts=[(2, "normal_part"), (1, "normal_part")]) + assert any("object 2 in the root model carries no geometry" in p for p in problems_of(archive)) + + +def test_a_self_closing_file_object_carries_no_geometry(): + result = multipart.validate_archive(build({A: model('')}, [(A, 1)])) + assert result["ok"] is False + assert any("object 1 in /3D/Objects/a.model carries no geometry" in p for p in result["problems"]) + + +# -- ids: duplicates, cross-file reuse, missing references ---------------------------------------------------- + +def test_a_duplicate_id_inside_one_file_is_refused(): + result = multipart.validate_archive(build({A: model(obj(1), obj(1))}, [(A, 1)])) + assert result["ok"] is False + assert any("object 1 is defined more than once in /3D/Objects/a.model" in p for p in result["problems"]) + + +def test_a_duplicate_id_in_the_root_model_is_refused(): + archive = build({A: model(obj(1))}, [(None, 2), (A, 1)], root_objects=[obj(2), obj(2)], + parts=[(2, "normal_part"), (1, "normal_part")]) + assert any("object 2 is defined more than once in the root model" in p for p in problems_of(archive)) + + +def test_a_reference_resolves_in_its_own_file_not_in_another_file_with_that_id(): + """Component names file A object 2, which only file B defines: it is missing, not satisfied by B.""" + archive = build({A: model(obj(1)), B: model(obj(2))}, [(A, 2), (B, 2)]) + result = multipart.validate_archive(archive) + assert result["ok"] is False + assert any("no file defines" in p and "'2'" in p for p in result["problems"]) + + +def test_a_pathed_reference_is_not_satisfied_by_a_root_object_with_that_id(): + archive = build({A: model(obj(5))}, [(A, 1)], root_objects=[obj(1)]) + assert any("no file defines" in p and "'1'" in p for p in problems_of(archive)) + + +def test_a_missing_file_object_is_reported_when_the_file_exists_but_lacks_the_id(): + assert any("no file defines" in p and "'7'" in p + for p in problems_of(build({A: model(obj(1))}, [(A, 7)]))) + + +def test_type_is_checked_against_the_named_file_object_when_another_file_reuses_the_id(): + """Both files define object 1; the one the component names is typed 'other' under a normal_part.""" + archive = build({A: model(obj(1, "other")), B: model(obj(1, "model"))}, [(A, 1)]) + assert any("is a normal_part and the geometry under it is typed 'other'" in p for p in problems_of(archive)) + + +def test_type_in_an_unreferenced_file_does_not_cause_a_false_mismatch(): + archive = build({A: model(obj(1, "model")), B: model(obj(1, "other"))}, [(A, 1)]) + assert multipart.validate_archive(archive)["ok"] is True + + +def test_two_files_that_disagree_on_an_ids_type_in_one_assembly_are_refused(): + archive = build({A: model(obj(1, "model")), B: model(obj(1, "other"))}, [(A, 1), (B, 1)], + parts=[(1, "normal_part"), (1, "normal_part")]) + assert any("several files that disagree" in p for p in problems_of(archive)) + + +def test_two_files_that_agree_on_an_ids_type_in_one_assembly_stay_valid(): + archive = build({A: model(obj(1)), B: model(obj(1))}, [(A, 1), (B, 1)], + parts=[(1, "normal_part"), (1, "normal_part")]) + assert multipart.validate_archive(archive)["ok"] is True + + +# -- malformed objects and components ------------------------------------------------------------------------ + +def test_a_non_numeric_object_id_in_a_file_is_refused(): + xml = model(f'{MESH}', obj(1)) + assert any("has an id that is not a number" in p for p in problems_of(build({A: xml}, [(A, 1)]))) + + +def test_a_truncated_object_tag_is_refused(): + xml = f'{obj(1)}", f'', 1) + archive.parts["3D/3dmodel.model"] = root.encode() + assert any("has no object id" in p for p in problems_of(archive)) + + +def test_component_attribute_order_does_not_matter(): + archive = build({A: model(obj(1))}, [(A, 1)]) + root = archive.parts["3D/3dmodel.model"].decode().replace( + f'', f'') + archive.parts["3D/3dmodel.model"] = root.encode() + assert multipart.validate_archive(archive)["ok"] is True + + +def test_an_unclosed_root_mesh_object_is_refused(): + archive = build({A: model(obj(1))}, [(None, 2), (A, 1)], parts=[(2, "normal_part"), (1, "normal_part")], + root_objects=[f'{MESH}']) + # no closing tag: the next belongs to the assembly, so object 2 holds another object + assert any("object 2 in the root model" in p for p in problems_of(archive)) + + +# -- same-id root/file assembly stays refused (Sol R5-F1) ------------------------------------------------------ + +def test_one_assembly_still_may_not_mix_root_and_file_components_with_the_same_id(): + archive = build({A: model(obj(1, "other"))}, [(A, 1), (None, 1)], root_objects=[obj(1, "model")], + parts=[(1, "normal_part"), (1, "normal_part")]) + assert any("referenced both from the root model and from a file" in p for p in problems_of(archive)) + + +# -- Sol R7-F1 / R7-F2 --------------------------------------------------------------------------------------- + +def test_a_commented_out_component_in_the_root_model_does_not_refuse_a_valid_archive(): + archive = build({A: model(obj(1))}, [(A, 1)]) + root = archive.parts["3D/3dmodel.model"].decode().replace( + "", '', 1) + archive.parts["3D/3dmodel.model"] = root.encode() + assert multipart.validate_archive(archive)["ok"] is True + + +def test_a_commented_out_assembly_is_not_read_as_structure(): + archive = build({A: model(obj(1))}, [(A, 1)]) + root = archive.parts["3D/3dmodel.model"].decode().replace( + "", + '', 1) + archive.parts["3D/3dmodel.model"] = root.encode() + assert multipart.validate_archive(archive)["ok"] is True + + +def test_an_omitted_object_type_equals_an_explicit_model_across_files(): + untyped = f'{MESH}' + archive = build({A: model(untyped), B: model(obj(1, "model"))}, [(A, 1), (B, 1)], + parts=[(1, "normal_part"), (1, "normal_part")]) + assert multipart.validate_archive(archive)["ok"] is True + + +def test_an_omitted_object_type_still_disagrees_with_an_explicit_other_across_files(): + untyped = f'{MESH}' + archive = build({A: model(untyped), B: model(obj(1, "other"))}, [(A, 1), (B, 1)], + parts=[(1, "normal_part"), (1, "normal_part")]) + assert any("several files that disagree" in p for p in problems_of(archive)) + + +def test_an_object_written_with_id_not_first_is_refused_not_skipped(): + """Opus O-R7-F1: an unreadable object spelling must not hide a nested object from the scan.""" + xml = model(f'{MESH}') + result = multipart.validate_archive(build({A: xml}, [(A, 9)])) + assert result["ok"] is False + assert any("object tag the scan cannot read" in p for p in result["problems"]) diff --git a/desktop/src/components/creative/CreativeFormatChooser.tsx b/desktop/src/components/creative/CreativeFormatChooser.tsx new file mode 100644 index 00000000..0644ac9a --- /dev/null +++ b/desktop/src/components/creative/CreativeFormatChooser.tsx @@ -0,0 +1,53 @@ +import { CREATIVE_FORMATS, GENERATOR_LABEL, type CreativeFormat, type CreativeFormatInfo } from "@/lib/creativeApi"; + +const field = "h-9 rounded-md border border-border bg-card px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-primary/50"; + +/** Format choice. When detection could not decide, the person picks one and is told plainly what is read for it. */ +export default function CreativeFormatChooser({ value, onChange, formats, needsChoice }: { + value: CreativeFormat; + onChange: (f: CreativeFormat) => void; + formats: CreativeFormatInfo[]; + needsChoice: boolean; +}) { + const info = formats.find((f) => f.key === value); + return ( +
+
+ + {needsChoice && value === "auto" && ( +

Studio could not decide the tool. Choose the format you know this file came from, then inspect again.

+ )} +
+ {info && ( +
+

{info.label}: {info.selection === "manual only" ? "read only when you choose it" : "identified automatically only when its markers are present in the file"}.

+

Carrier: {info.carrier}.

+
+
+

Studio reads

+
    {info.reads.map((r) =>
  • {r}
  • )}
+
+
+

Studio does not read

+
    {info.not_read.map((r) =>
  • {r}
  • )}
+
+
+ {info.prepare_limits && info.prepare_limits.length > 0 && ( +
+

Prepare limits

+
    {info.prepare_limits.map((r) =>
  • {r}
  • )}
+
+ )} + {info.identified_by.length === 0 && ( +

This format leaves no identifying marker in the file, so Studio cannot confirm the file really came from this tool.

+ )} +
+ )} + {value === "auto" && !needsChoice && ( +

Studio does not guess the tool: when the markers and settings do not identify it, the origin is reported as unknown.

+ )} +
+ ); +} diff --git a/desktop/src/components/creative/CreativePreparePanel.tsx b/desktop/src/components/creative/CreativePreparePanel.tsx new file mode 100644 index 00000000..edcfa844 --- /dev/null +++ b/desktop/src/components/creative/CreativePreparePanel.tsx @@ -0,0 +1,84 @@ +import type { ReactNode } from "react"; +import { comparisonBuckets, settingsTotals, type CreativePrepareResponse, type CreativeVerification } from "@/lib/creativeApi"; + +function Box({ title, note, children }: { title: string; note?: string; children: ReactNode }) { + return ( +
+

{title}

+ {note &&

{note}

} + {children} +
+ ); +} + +/** Members kept, changed, dropped and added between the original and the new copy, by part name and content hash. */ +export function ExportVerification({ verification, lossNotes }: { verification: CreativeVerification; lossNotes: string[] }) { + if (!verification.opens_as_zip) { + return

The exported file could not be re-read: {verification.problem ?? "unknown problem"}. Nothing can be said about what it kept.

; + } + const paint = verification.per_face_paint; + return ( + +
+ {comparisonBuckets(verification).map((b) => ( +
+

{b.title} ({b.total})

+

{b.note}

+ {b.truncated &&

showing {b.items.length} of {b.total}

} + {b.items.length === 0 + ?

None.

+ :
    {b.items.map((i) =>
  • {i}
  • )}
} +
+ ))} +
+ {paint && paint.original_triangles !== null && paint.exported_triangles !== null && ( +

Per-face paint: {paint.original_triangles} painted triangle(s) in the original, {paint.exported_triangles} in the copy.

+ )} + {verification.settings && (() => { + const t = settingsTotals(verification.settings); + return

Project settings: {t.removed} removed, {t.changed} changed, {t.added} added.

; + })()} +
    {lossNotes.map((n) =>
  • {n}
  • )}
+
+ ); +} + +/** Result of "Prepare a U1 copy": either an explanation of why nothing was written, or the verified new file. */ +export default function CreativePreparePanel({ result }: { result: CreativePrepareResponse }) { + if (!result.prepared) { + const r = result.refusal; + return ( +
+

No copy was written

+

What Studio saw. {r.seen}

+

What is not supported. {r.not_supported}

+
What to do. +
    {r.what_to_do.map((w) =>
  • {w}
  • )}
+
+ {r.problems && r.problems.length > 0 && ( +

What the check found

+
    {r.problems.map((p) =>
  • {p}
  • )}
+
+ )} +

{result.advisory}

+
+ ); + } + const unchanged = result.original.original_unchanged; + return ( +
+ +

Copy: {result.output.name}

+

Saved in: {result.output.location_label}.{result.output.in_source_folder ? " This is the same folder as the original, because you chose it." : " It is not next to the original."}

+

Review it in Snapmaker Orca before slicing. Studio does not slice.

+
+ +
+

{unchanged + ? "Original unchanged: its fingerprint is identical before and after Prepare." + : "The original's fingerprint differs between the two reads. Something outside Studio changed the file while it was being prepared."}

+

{result.original.name}. before {result.original.sha256_before.slice(0, 16)}, after {result.original.sha256_after.slice(0, 16)}

+
+
+ ); +} diff --git a/desktop/src/components/creative/CreativeReportView.tsx b/desktop/src/components/creative/CreativeReportView.tsx index 8ed1d3f5..af726c34 100644 --- a/desktop/src/components/creative/CreativeReportView.tsx +++ b/desktop/src/components/creative/CreativeReportView.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from "react"; -import { originSentence, type CreativeInspectResponse } from "@/lib/creativeApi"; +import { factLines, GENERATOR_LABEL, originSentence, type CreativeInspectResponse } from "@/lib/creativeApi"; function Section({ title, note, children }: { title: string; note: string; children: ReactNode }) { return ( @@ -19,6 +19,7 @@ function NameList({ items, empty }: { items: string[]; empty: string }) { /** What Studio read from one project file: understood, kept untouched, could not interpret. Advisory only. */ export default function CreativeReportView({ report }: { report: CreativeInspectResponse }) { const { source } = report; + const facts = Object.values(report.facts ?? {}).flatMap((f) => factLines(f)); return (
@@ -26,6 +27,34 @@ export default function CreativeReportView({ report }: { report: CreativeInspect

{report.advisory}

Evidence: fixture-tested. The readers are tested against hand-written files shaped like the published formats, not against captured projects.

+ {report.explanation && ( +
+

{report.explanation.kind === "ambiguous_origin" ? "Studio cannot tell which tool wrote this" : "Studio does not recognise this file's tool"}

+

What Studio saw. {report.explanation.seen}

+

What is not supported. {report.explanation.not_supported}

+
What to do. +
    {report.explanation.what_to_do.map((w) =>
  • {w}
  • )}
+
+
+ )} + {facts.length > 0 && ( +
+ {Object.entries(report.facts ?? {}).map(([gen, f]) => ( +
+ {Object.keys(report.facts ?? {}).length > 1 &&

{GENERATOR_LABEL[gen] ?? gen}

} +
    {factLines(f).map((l) =>
  • {l}
  • )}
+
+ ))} +
+ )} + {(report.format_info ?? []).map((info) => ( +
+
+

Read

+

Not read

+
+
+ ))}
diff --git a/desktop/src/components/creative/CreativeView.tsx b/desktop/src/components/creative/CreativeView.tsx index ed9d3737..1b16e828 100644 --- a/desktop/src/components/creative/CreativeView.tsx +++ b/desktop/src/components/creative/CreativeView.tsx @@ -2,26 +2,35 @@ import { useEffect, useRef, useState } from "react"; import { Palette } from "lucide-react"; import { Button } from "@/components/ui/button"; import { PageHeader } from "@/components/ui/layout"; -import { CREATIVE_FORMATS, inspectCreative, type CreativeFormat, type CreativeInspectResponse } from "@/lib/creativeApi"; +import { + fetchCreativeFormats, inspectCreative, prepareCreative, + type CreativeFormat, type CreativeFormatInfo, type CreativeInspectResponse, type CreativePrepareResponse, +} from "@/lib/creativeApi"; +import CreativeFormatChooser from "./CreativeFormatChooser"; +import CreativePreparePanel from "./CreativePreparePanel"; import CreativeReportView from "./CreativeReportView"; -/** Inspect one local creative project file. The path is sent to the local Studio service only, which - * opens the file for reading, never writes it, and never slices or contacts a printer. */ -export default function CreativeView() { +/** Inspect one local creative project file, then optionally write a prepared copy. The path is sent to the local + * Studio service only. Inspecting never writes anything; Prepare writes one new file and never the original. */ +export default function CreativeView({ initialFormats = [] }: { initialFormats?: CreativeFormatInfo[] }) { const [path, setPath] = useState(""); const [format, setFormat] = useState("auto"); + const [outDir, setOutDir] = useState(""); + const [formats, setFormats] = useState(initialFormats); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [report, setReport] = useState(null); + const [prepared, setPrepared] = useState(null); const alive = useRef(true); useEffect(() => { alive.current = true; + fetchCreativeFormats().then((r) => { if (alive.current) setFormats(r.formats); }).catch(() => undefined); return () => { alive.current = false; }; }, []); const run = async () => { // A failed inspection must not leave the previous file's report under the new path. - setBusy(true); setError(null); setReport(null); + setBusy(true); setError(null); setReport(null); setPrepared(null); try { const res = await inspectCreative(path, format); if (alive.current) setReport(res); @@ -32,21 +41,43 @@ export default function CreativeView() { } }; + const prepare = async () => { + setBusy(true); setError(null); setPrepared(null); + try { + const res = await prepareCreative(path, format, outDir); + if (alive.current) setPrepared(res); + } catch (e) { + if (alive.current) setError(e instanceof Error ? e.message : "Prepare failed."); + } finally { + if (alive.current) setBusy(false); + } + }; + const field = "h-9 rounded-md border border-border bg-card px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-primary/50"; + const undecided = report !== null && (report.origin.status === "unknown" || report.origin.status === "ambiguous"); return (
- +
setPath(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !busy && path.trim() !== "") void run(); }} /> -
-

Studio does not guess the generator: when the settings do not identify it, the origin is reported as unknown.

+ {error &&

{error}

} {report && } + {report && ( +
+

Prepare a U1 copy

+

Writes a new file with Studio's Prepare and never touches the original. The copy is then compared with the original part by part. Studio refuses a file whose tool it cannot identify.

+
+ setOutDir(e.target.value)} /> + +
+
+ )} + {prepared && }
); } diff --git a/desktop/src/components/creative/creative.test.tsx b/desktop/src/components/creative/creative.test.tsx index 955c3ed3..707d2cc2 100644 --- a/desktop/src/components/creative/creative.test.tsx +++ b/desktop/src/components/creative/creative.test.tsx @@ -2,9 +2,11 @@ import { describe, expect, it } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import CreativeReportView from "./CreativeReportView"; import CreativeView from "./CreativeView"; +import CreativeFormatChooser from "./CreativeFormatChooser"; +import CreativePreparePanel, { ExportVerification } from "./CreativePreparePanel"; import creativeRoute from "@/routes/ext/creative.route"; import creativeMeta from "@/routes/ext/creative.meta"; -import type { CreativeInspectResponse } from "@/lib/creativeApi"; +import type { CreativeFormatInfo, CreativeInspectResponse, CreativePrepareResponse } from "@/lib/creativeApi"; const HASH = "a".repeat(64); @@ -85,7 +87,161 @@ describe("creative view", () => { it("renders the path input, format choice and a disabled inspect button", () => { const html = renderToStaticMarkup(); expect(html).toContain("Project file path"); - expect(html).toContain("Detect from settings"); + expect(html).toContain("Detect from markers and settings"); expect(html).toMatch(/]*disabled[^>]*>Inspect project/); }); + + it("offers every supported tool in the format list, including the three new readers", () => { + const html = renderToStaticMarkup(); + for (const label of ["DitherForge", "Kromacut", "SindriCAD", "OrcaSlicer ImageMap", "Lumina Layers"]) expect(html).toContain(label); + }); +}); + +const FORMAT: CreativeFormatInfo = { + key: "imagemap", label: "OrcaSlicer ImageMap", carrier: "3MF (ZIP) with 3D/3dmodel.model", selection: "manual only", + identified_by: [], reads: ["3MF artifact identity (size, SHA-256, member list)"], kept_untouched: ["every part"], + not_read: ["the zone shape: not established"], upstream: null, +}; + +describe("format chooser", () => { + it("says plainly what is and is not read for a manual-only format", () => { + const html = renderToStaticMarkup( undefined} formats={[FORMAT]} needsChoice={false} />); + expect(html).toContain("read only when you choose it"); + expect(html).toContain("Studio reads"); + expect(html).toContain("3MF artifact identity"); + expect(html).toContain("Studio does not read"); + expect(html).toContain("the zone shape: not established"); + expect(html).toContain("cannot confirm the file really came from this tool"); + }); + + it("words automatic identification as conditional on markers being present", () => { + const html = renderToStaticMarkup( undefined} formats={[{ ...FORMAT, key: "sindricad", label: "SindriCAD", selection: "automatic", identified_by: ["model metadata Application `SindriCAD`"] }]} needsChoice={false} />); + expect(html).toContain("identified automatically only when its markers are present in the file"); + expect(html).not.toContain("detected automatically"); + expect(html).not.toContain("Prepare limits"); + }); + + it("states a format's Prepare limits when the engine lists them", () => { + const html = renderToStaticMarkup( undefined} formats={[{ ...FORMAT, key: "ditherforge", label: "DitherForge", selection: "automatic", prepare_limits: ["The generic-path export is inspect-only."] }]} needsChoice={false} />); + expect(html).toContain("Prepare limits"); + expect(html).toContain("The generic-path export is inspect-only."); + }); + + it("asks for a choice when detection could not decide, and not otherwise", () => { + const ask = renderToStaticMarkup( undefined} formats={[]} needsChoice />); + expect(ask).toContain("Studio could not decide the tool"); + const quiet = renderToStaticMarkup( undefined} formats={[]} needsChoice={false} />); + expect(quiet).not.toContain("Studio could not decide the tool"); + expect(quiet).toContain("does not guess the tool"); + }); +}); + +describe("inspection of the new tools", () => { + it("shows facts read from a SindriCAD file and its read and not-read lists", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("Looks like SindriCAD"); + expect(html).toContain("Body count: 2"); + expect(html).toContain("Bodies: Plate (extruder 1), Lid (extruder 2)"); + expect(html).toContain("Per-face paint: 2 painted triangle(s)"); + expect(html).toContain("SindriCAD: what is and is not read"); + expect(html).toContain("mesh geometry beyond counts"); + }); + + it("explains an undecided origin: what was seen, what is not supported, what to do", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("does not recognise this file's tool"); + expect(html).toContain("What Studio saw."); + expect(html).toContain("What is not supported."); + expect(html).toContain("What to do."); + expect(html).toContain("Choose the format you know it came from."); + }); +}); + +const BASE_SOURCE = { name: "x.3mf", size_bytes: 1, sha256_before: HASH, sha256_after: HASH, unchanged: true }; + +describe("prepare panel", () => { + const done: CreativePrepareResponse = { + prepared: true, origin: { generator: "sindricad", status: "detected", candidates: ["sindricad"] }, + output: { name: "x_SnapmakerU1.3mf", location: "studio_default", location_label: "Studio's creative-prepared folder", in_source_folder: false }, + prepare: { mode: "preserve", validated_ok: true, errors: [], compat_changed: [], mapped_to_u1: [], could_not_carry: [], warnings: [] }, + verification: { opens_as_zip: true, members: [{ name: "a", sha256: HASH }, { name: "b", sha256: HASH }], + comparison: { preserved: ["3D/3dmodel.model"], modified: ["Metadata/project_settings.config"], dropped: ["Metadata/gone.bin"], added: ["Metadata/new.bin"] }, + settings: { removed_keys: [], changed_keys: ["layer_height"], added_key_count: 64 }, + per_face_paint: { original_triangles: 2, exported_triangles: 2, kept: true } }, + loss_notes: ["1 part(s) of the original are not in the copy: Metadata/gone.bin."], + original: { name: "x.3mf", sha256_before: HASH, sha256_after: HASH, original_unchanged: true }, + source: BASE_SOURCE, advisory: "Advisory comparison by part name and content hash.", + }; + + it("shows the four export buckets, paint count, loss notes and the unchanged original", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("Kept identical (1)"); + expect(html).toContain("Changed (1)"); + expect(html).toContain("Dropped (1)"); + expect(html).toContain("Added (1)"); + expect(html).toContain("Metadata/gone.bin"); + expect(html).toContain("2 painted triangle(s) in the original, 2 in the copy"); + expect(html).toContain("Project settings: 0 removed, 1 changed, 64 added"); + expect(html).toContain("It is not next to the original."); + expect(html).toContain("Original unchanged"); + expect(html).toContain("Review it in Snapmaker Orca before slicing"); + }); + + it("headings use the engine totals and say 'showing N of M' when a name list is capped", () => { + const names = Array.from({ length: 200 }, (_, i) => `Metadata/p${i}.bin`); + const html = renderToStaticMarkup(); + expect(html).toContain("Kept identical (250)"); + expect(html).toContain("showing 200 of 250"); + expect(html).not.toContain("showing 0 of"); + expect(html).toContain("Project settings: 300 removed, 0 changed, 2 added"); + }); + + it("names the saved location with a label only, never a folder path", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("Saved in: the folder you chose."); + expect(html).not.toMatch(/[A-Za-z]:\\|\/Users\/|\/home\//); + }); + + it("does not claim the original is unchanged when its fingerprint moved", () => { + const html = renderToStaticMarkup(); + expect(html).not.toContain("Original unchanged"); + expect(html).toContain("differs between the two reads"); + }); + + it("says when the exported file could not be re-read", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("could not be re-read"); + expect(html).toContain("not a readable 3MF archive"); + }); + + it("explains a refusal and says nothing was written", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("No copy was written"); + expect(html).toContain("This file was read as Kromacut."); + expect(html).toContain("can vouch for"); + expect(html).toContain("What the check found"); + expect(html).toContain("reference an object that no file defines"); + }); + + it("uses no readiness or guarantee wording in prepare copy", () => { + const all = (renderToStaticMarkup() + renderToStaticMarkup() + + renderToStaticMarkup( undefined} formats={[]} needsChoice />)).toLowerCase(); + for (const banned of ["ready", "coming soon", "guarantee", "100%", "print success", "printer doctor"]) expect(all).not.toContain(banned); + }); }); diff --git a/desktop/src/lib/creativeApi.test.ts b/desktop/src/lib/creativeApi.test.ts index 94938a0d..ca3de6be 100644 --- a/desktop/src/lib/creativeApi.test.ts +++ b/desktop/src/lib/creativeApi.test.ts @@ -1,5 +1,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { buildInspectBody, inspectCreative, originSentence } from "./creativeApi"; +import { + buildInspectBody, buildPrepareBody, comparisonBuckets, factLines, fetchCreativeFormats, inspectCreative, + originSentence, prepareCreative, settingsTotals, +} from "./creativeApi"; vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn().mockResolvedValue({ port: 4321, token: "test-token" }) })); const originalFetch = globalThis.fetch; @@ -36,7 +39,55 @@ describe("creative API client", () => { it("keeps an unknown origin unknown and an ambiguous one undecided", () => { expect(originSentence({ generator: "unknown", status: "unknown", candidates: [] })).toContain("Origin unknown"); expect(originSentence({ generator: "unknown", status: "ambiguous", candidates: ["forcaslicer", "lixnix"] })) - .toBe("Origin not decided: the settings match FOrcaSlicer and LixNix Full Multi-Nozzle."); + .toBe("Origin not decided: the file's markers or settings match FOrcaSlicer and LixNix Full Multi-Nozzle."); expect(originSentence({ generator: "fullspectrum", status: "detected", candidates: ["fullspectrum"] })).toContain("Looks like FullSpectrum"); + expect(originSentence({ generator: "sindricad", status: "detected", candidates: ["sindricad"] })).toContain("Looks like SindriCAD"); + }); + + it("builds the prepare body with an output folder only when one was typed", () => { + expect(buildPrepareBody("a.3mf")).toEqual({ path: "a.3mf" }); + expect(buildPrepareBody(" a.3mf ", "sindricad", ' "D:\\out" ')).toEqual({ path: "a.3mf", format: "sindricad", out_dir: "D:\\out" }); + expect(() => buildPrepareBody("", "auto", "x")).toThrow("Enter the path"); + }); + + it("posts to /creative/prepare and /creative/formats", async () => { + const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(JSON.stringify({ prepared: false, formats: [] }), { + status: 200, headers: { "Content-Type": "application/json" } }))); + globalThis.fetch = fetchMock; + await prepareCreative("a.3mf", "kromacut"); + await fetchCreativeFormats(); + expect(fetchMock).toHaveBeenNthCalledWith(1, "http://127.0.0.1:4321/creative/prepare", expect.objectContaining({ + method: "POST", body: JSON.stringify({ path: "a.3mf", format: "kromacut" }) })); + expect(fetchMock).toHaveBeenNthCalledWith(2, "http://127.0.0.1:4321/creative/formats", expect.objectContaining({ method: "POST", body: "{}" })); + }); + + it("turns reader facts into plain lines and skips facts that are absent", () => { + const lines = factLines({ application: "SindriCAD", body_count: 2, painted_triangle_count: 0, + bodies: [{ name: "Plate", extruder: 1 }], filament_colour: ["#FF0000", "#0000FF"], paint_extruders_used: [] }); + expect(lines).toContain("Written by (Application tag): SindriCAD"); + expect(lines).toContain("Body count: 2"); + expect(lines).toContain("Per-face paint: none found"); + expect(lines).toContain("Bodies: Plate (extruder 1)"); + expect(lines).toContain("Filament colours: #FF0000, #0000FF"); + expect(lines.some((l) => l.startsWith("Extruders used by paint"))).toBe(false); + expect(factLines(undefined)).toEqual([]); + }); + + it("orders the comparison buckets kept, changed, dropped, added", () => { + const buckets = comparisonBuckets({ opens_as_zip: true, comparison: { preserved: ["a"], modified: ["b"], dropped: ["c"], added: ["d"] } }); + expect(buckets.map((b) => `${b.key}:${b.items.join("")}`)).toEqual(["preserved:a", "modified:b", "dropped:c", "added:d"]); + expect(buckets.every((b) => b.total === 1 && !b.truncated)).toBe(true); + }); + + it("uses the engine totals for the bucket headings and flags a capped list", () => { + const buckets = comparisonBuckets({ opens_as_zip: true, comparison: { preserved: ["a", "b"], modified: [], dropped: [], added: [] }, + counts: { preserved: 250, modified: 0, dropped: 0, added: 0 } }); + expect(buckets[0]).toMatchObject({ total: 250, truncated: true }); + expect(buckets[1]).toMatchObject({ total: 0, truncated: false }); + }); + + it("settings totals come from the counts, not from the bounded key lists", () => { + expect(settingsTotals({ removed_keys: ["a"], removed_count: 9, changed_keys: [], changed_count: 4, added_key_count: 2 })).toEqual({ removed: 9, changed: 4, added: 2 }); + expect(settingsTotals({ removed_keys: ["a"], changed_keys: ["b", "c"], added_key_count: 0 })).toEqual({ removed: 1, changed: 2, added: 0 }); }); }); diff --git a/desktop/src/lib/creativeApi.ts b/desktop/src/lib/creativeApi.ts index 12cccbb4..6394cf7e 100644 --- a/desktop/src/lib/creativeApi.ts +++ b/desktop/src/lib/creativeApi.ts @@ -19,21 +19,84 @@ export interface CreativeOrigin { candidates: string[]; } +/** What one supported format reads and does not read. Mirrors SUPPORTED_FORMATS in the engine. */ +export interface CreativeFormatInfo { + key: string; + label: string; + carrier: string; + selection: "automatic" | "manual only"; + identified_by: string[]; + reads: string[]; + kept_untouched: string[]; + not_read: string[]; + /** Why Prepare may refuse files of this format, when it does. Absent when there is nothing to say. */ + prepare_limits?: string[]; + upstream: string | null; +} + +export interface CreativeExplanation { + kind: "unknown_origin" | "ambiguous_origin"; + seen: string; + not_supported: string; + what_to_do: string[]; +} + +export interface CreativeSourceInfo { name: string; size_bytes: number; sha256_before: string; sha256_after: string; unchanged: boolean } + export interface CreativeInspectResponse { origin: CreativeOrigin; understood: string[]; + facts?: Record>; passed_through: CreativeNamedPart[]; could_not_interpret: string[]; missing: string[]; diagnostics: string[]; recipes: CreativeRecipe[]; physical_slots_needed: number | null; - source: { name: string; size_bytes: number; sha256_before: string; sha256_after: string; unchanged: boolean }; + format_info?: CreativeFormatInfo[]; + explanation?: CreativeExplanation | null; + source: CreativeSourceInfo; evidence: string; advisory: string; } -export const CREATIVE_FORMATS = ["auto", "forcaslicer", "lixnix", "fullspectrum", "imagemap", "lumina"] as const; +export interface CreativeComparison { preserved: string[]; modified: string[]; dropped: string[]; added: string[] } + +export interface CreativeVerification { + opens_as_zip: boolean; + problem?: string; + size_bytes?: number; + sha256?: string; + members?: CreativeNamedPart[]; + comparison?: CreativeComparison; + counts?: Record; + settings?: { removed_keys: string[]; removed_count?: number; changed_keys: string[]; changed_count?: number; added_key_count: number }; + per_face_paint?: { original_triangles: number | null; exported_triangles: number | null; kept: boolean | null }; +} + +export interface CreativePrepareDone { + prepared: true; + origin: CreativeOrigin; + output: { name: string; location: "studio_default" | "chosen"; location_label: string; in_source_folder: boolean }; + prepare: { mode: string; validated_ok: boolean; errors: string[]; compat_changed: unknown[]; mapped_to_u1: unknown[]; could_not_carry: unknown[]; warnings: unknown[] }; + verification: CreativeVerification; + loss_notes: string[]; + original: { name: string; sha256_before: string; sha256_after: string; original_unchanged: boolean }; + source: CreativeSourceInfo; + advisory: string; +} + +export interface CreativePrepareRefused { + prepared: false; + refusal: { kind: string; seen: string; not_supported: string; what_to_do: string[]; problems?: string[] }; + origin: CreativeOrigin; + source: CreativeSourceInfo; + advisory: string; +} + +export type CreativePrepareResponse = CreativePrepareDone | CreativePrepareRefused; + +export const CREATIVE_FORMATS = ["auto", "ditherforge", "kromacut", "sindricad", "forcaslicer", "lixnix", "fullspectrum", "imagemap", "lumina"] as const; export type CreativeFormat = (typeof CREATIVE_FORMATS)[number]; /** The request body for one inspection. A blank path is a sentence for the person, not a request. */ @@ -48,7 +111,28 @@ export function inspectCreative(path: string, format: CreativeFormat = "auto"): return callExt("/creative/inspect", buildInspectBody(path, format), "Creative project inspection"); } -const GENERATOR_LABEL: Record = { +/** The format list from the engine: what each format reads and does not. */ +export function fetchCreativeFormats(): Promise<{ formats: CreativeFormatInfo[]; manual_only: string[]; note: string }> { + return callExt("/creative/formats", {}, "Creative formats"); +} + +/** The request body for one Prepare. The output folder is sent only when the person typed one. */ +export function buildPrepareBody(path: string, format: CreativeFormat = "auto", outDir = ""): { path: string; format?: CreativeFormat; out_dir?: string } { + const body: { path: string; format?: CreativeFormat; out_dir?: string } = buildInspectBody(path, format); + const folder = outDir.trim().replace(/^"(.*)"$/, "$1"); + if (folder !== "") body.out_dir = folder; + return body; +} + +/** Write a new prepared copy through the local service and compare it with the original. */ +export function prepareCreative(path: string, format: CreativeFormat = "auto", outDir = ""): Promise { + return callExt("/creative/prepare", buildPrepareBody(path, format, outDir), "Prepare a U1 copy"); +} + +export const GENERATOR_LABEL: Record = { + ditherforge: "DitherForge", + kromacut: "Kromacut", + sindricad: "SindriCAD", forcaslicer: "FOrcaSlicer", lixnix: "LixNix Full Multi-Nozzle", fullspectrum: "FullSpectrum", @@ -60,9 +144,84 @@ const GENERATOR_LABEL: Record = { export function originSentence(origin: CreativeOrigin): string { if (origin.status === "ambiguous") { const names = origin.candidates.map((c) => GENERATOR_LABEL[c] ?? c).join(" and "); - return `Origin not decided: the settings match ${names}.`; + return `Origin not decided: the file's markers or settings match ${names}.`; } if (origin.generator === "unknown") return "Origin unknown: Studio does not recognise the generator of this project."; const name = GENERATOR_LABEL[origin.generator] ?? origin.generator; - return origin.status === "chosen" ? `Read as ${name} (your choice).` : `Looks like ${name}, from the settings it contains.`; + return origin.status === "chosen" ? `Read as ${name} (your choice).` : `Looks like ${name}, from the markers or settings it contains.`; +} + +function colours(value: unknown): string { + return Array.isArray(value) ? value.map((c) => (typeof c === "string" ? c : "?")).join(", ") : ""; +} + +function named(items: unknown, key: string): string { + if (!Array.isArray(items)) return ""; + return items.map((i) => { + const row = i as Record; + return `${String(row.name ?? "unnamed")} (${key} ${String(row[key] ?? "unknown")})`; + }).join(", "); +} + +/** Plain lines for the facts a reader proved from the file. A fact that is absent produces no line. */ +export function factLines(facts: Record | undefined): string[] { + if (!facts) return []; + const out: string[] = []; + const add = (label: string, value: unknown) => { + if (value === undefined || value === null || value === "") return; + out.push(`${label}: ${String(value)}`); + }; + add("Written by (Application tag)", facts.application); + add("Variant", facts.variant === "bambu_project" ? "Bambu-style project tag" : facts.variant); + add("Objects in the build", facts.build_item_count); + add("Body count", facts.body_count); + add("Colour layer objects", facts.layer_object_count); + if (facts.assembly_present === true) out.push("Layers are grouped in one assembly object"); + add("Layer height (mm)", facts.layer_height); + add("First layer height (mm)", facts.first_layer_height); + add("Triangles", facts.triangle_count); + if (typeof facts.painted_triangle_count === "number") { + out.push(facts.painted_triangle_count > 0 + ? `Per-face paint: ${facts.painted_triangle_count} painted triangle(s)` + : "Per-face paint: none found"); + } + if (Array.isArray(facts.paint_extruders_used) && facts.paint_extruders_used.length > 0) { + add("Extruders used by paint", facts.paint_extruders_used.join(", ")); + } + add("Objects", named(facts.objects, "extruder")); + add("Bodies", named(facts.bodies, "extruder")); + add("Parts", named(facts.parts, "extruder")); + const palette = Array.isArray(facts.palette) ? facts.palette.map((p) => `${String((p as Record).name)} ${String((p as Record).colour)}`).join(", ") : ""; + add("Base materials", palette); + add("Filament colours", colours(facts.filament_colour)); + add("Filament types", colours(facts.filament_type)); + add("Printer settings id", facts.printer_settings_id); + return out; +} + +export interface CreativeBucket { key: keyof CreativeComparison; title: string; note: string; items: string[]; total: number; truncated: boolean } + +/** + * The four buckets of the export comparison, in the order a person reads them. `total` is the engine's + * own count (verification.counts) and falls back to the listed names only when the engine sent none; + * `truncated` is true when the name list is shorter than the total. + */ +export function comparisonBuckets(v: CreativeVerification): CreativeBucket[] { + const c = v.comparison; + const bucket = (key: keyof CreativeComparison, title: string, note: string): CreativeBucket => { + const items = c?.[key] ?? []; + const total = v.counts?.[key] ?? items.length; + return { key, title, note, items, total, truncated: total > items.length }; + }; + return [ + bucket("preserved", "Kept identical", "Same part name and same content fingerprint as the original."), + bucket("modified", "Changed", "Same part name, different content."), + bucket("dropped", "Dropped", "In the original, not in the copy."), + bucket("added", "Added", "In the copy, not in the original."), + ]; +} + +/** Project-settings totals from the engine's counts; the key lists are bounded and may be shorter. */ +export function settingsTotals(s: NonNullable): { removed: number; changed: number; added: number } { + return { removed: s.removed_count ?? s.removed_keys.length, changed: s.changed_count ?? s.changed_keys.length, added: s.added_key_count }; } diff --git a/docs/internal/CREATIVE_COMPAT.md b/docs/internal/CREATIVE_COMPAT.md index 54c70868..b2058e4a 100644 --- a/docs/internal/CREATIVE_COMPAT.md +++ b/docs/internal/CREATIVE_COMPAT.md @@ -12,9 +12,9 @@ Evidence level: `fixture-tested`. Fixtures are hand-written to published shapes, | FullSpectrum 0.9.12 | `mixed_filament_definitions` compact rows; pair IDs and documented `g` gradient IDs become foundation `VirtualRecipe` project-slot references; `u` is used as the recipe identity when present | Other config keys and all unrecognized row detail | Ratios, pattern semantics, rendering, color and execution are unknown. Recipes always report `simulated=True` and `execution_supported=False`. `physical_slots_needed` counts distinct referenced project slots, while `source_component_ids` preserves their 1-based source IDs; these do not assert physical filament inventory. The draft vnext schema is not read. | | OrcaSlicer ImageMap | 3MF container artifact identity only | All project settings and unknown archive members by name and digest | ImageMap's exact serialized 3MF carrier and zone shape remain unestablished in the research; the reader reports that shape as unknown and makes no zone compatibility claim. | | Lumina Layers output | 3MF artifact identity: byte size, SHA-256 and optional opaque file ID | Project settings and unknown archive members by name and digest | Generation provenance, session behavior and file-ID lifetime are unknown. No API is called. | -| DitherForge | No reader in this slice | Not applicable | Research describes 3MF output with per-face painting and split objects, plus settings JSON and collection TXT. Shape-specific parsing is deferred to slice 2. | -| Kromacut | No reader in this slice | Not applicable | Research describes 3MF per-object extruder mapping, layer and first-layer heights, generic material metadata, and optional custom metadata files. Shape-specific parsing is deferred to slice 2. | -| SindriCAD | No reader in this slice | Not applicable | Research describes named bodies, color-slot assignment, per-face paint, base materials, Orca extruder configuration and per-triangle `pindex`. Shape-specific parsing is deferred to slice 2. | +| DitherForge | Application tag and variant, build item count, object part files, triangle and painted-triangle counts, paint extruders (documented 1-2 character `paint_color`), object names and extruders from `model_settings.config`, `filament_colour`, `filament_type`, `printer_settings_id`, `print_settings_id` | Every other member and settings key, by name and SHA-256 | Longer `paint_color` strings, geometry beyond counts, settings JSON and collection TXT (written beside the 3MF, not inside it). Reader: `creative/generators.py`, evidence `fixture-tested`, upstream commit in PROVENANCE.md. | +| Kromacut | Application `Kromacut_Print`, layer and first-layer height metadata, colour layer object count, assembly object, parts with extruders, base materials, `filament_colour`, `layer_height`, `initial_layer_print_height` | Every other member, including `Metadata/kromacut.config` | The `kromacut.config` payload and mesh geometry are not interpreted. Format learned from AGPL source; no code copied. Evidence `fixture-tested`. | +| SindriCAD | Application `SindriCAD`, body count, body names with palette slot (`pindex`) and 1-based extruder, palette base materials, per-face paint, `filament_colour`, `filament_type` | Every other member and settings key | Longer `paint_color` strings and geometry beyond counts. A body whose extruder disagrees with its palette slot is flagged. Format learned from AGPL source; no code copied. Evidence `fixture-tested`. | ## Evidence references @@ -23,7 +23,7 @@ Evidence level: `fixture-tested`. Fixtures are hand-written to published shapes, - FullSpectrum: inspected v0.9.12 source and packaging notes describe `Metadata/project_settings.config`, the `mixed_filament_definitions` key and compact row tokens. `doc/fullspectrum-3mf-packaging.md` lines 74-76 and 162-211. Research entry `xipit-fullspectrum-ui` identifies the exact release and explicitly separates the draft vnext schema. - ImageMap: inspected `src/libslic3r/TextureMapping.hpp` lines 55-145, 187-238, 538-548, 948-976 and 1034-1110, and README lines 50-103. Research reports that the exact 3MF carrier still needs tracing. - Lumina: inspected `api/routers/converter.py` lines 192-268, 469, 609, 730 and 832. Research records `/api/files/{file_id}` retrieval, but this reader only hashes a supplied artifact. -- DitherForge: `internal/export3mf/export3mf.go` lines 15-107 and `internal/export3mf/printers.go` lines 18-65. +- DitherForge: the reader is based on `internal/export3mf/export3mf.go` and `internal/export3mf/bambu.go` (commit 4d3552a, see PROVENANCE.md). Earlier research notes also cited `export3mf.go` lines 15-107 and `internal/export3mf/printers.go` lines 18-65; `printers.go` exists upstream but was not re-read for the reader and the reader does not depend on it. - Kromacut: `src/lib/export3mf.ts` lines 8-21, 147-160, 259-281, 331-335 and 734-771. - SindriCAD: `sidecar/project3mf.py` lines 1-23, 130-158 and 203-306. @@ -33,9 +33,45 @@ The contract tests create small in-memory ZIPs through a checked-in helper. They Evidence level: `fixture-tested`. Only synthetic archives have been inspected; no project captured from a real generator has been read. -- `POST /creative/inspect {path, format?}` (`backend/snapstudio_api/routes_creative.py`). The handler opens one local file for reading only: it must exist, be a regular file and be under the 128 MiB archive cap, otherwise the request is refused with 400 before any parsing. Non-archives, archives with no 3D model part and every container limit error also return 400 with a plain sentence. Nothing is written, renamed or deleted, no slicer or printer is contacted and the handler makes no network request. UNC, device and link-to-share paths are refused before opening; that check is best-effort (see `localpath.py`), not a sandbox. -- Generator detection (`format` omitted or `auto`) uses only the published keys each reader knows. One match is reported as `detected`, a `format` hint as `chosen`, several matches as `ambiguous` (origin not decided, candidates listed) and none as `unknown`. An unknown generator still gets the container identity: every archive member and every settings key is listed as passed through by name and SHA-256. +- `POST /creative/inspect {path, format?}` (`backend/snapstudio_api/routes_creative.py`). The handler opens one local file for reading only: it must exist, be a regular file and be under the 128 MiB archive cap, otherwise the request is refused with 400 before any parsing. Non-archives, archives with no 3D model part and every container limit error also return 400 with a plain sentence. Nothing is written, renamed or deleted, no slicer or printer is contacted and the handler makes no network request of its own. UNC, device and link-to-share paths are refused before opening; that check is best-effort (see `snapstudio_core/localpath.py`), not a sandbox. +- Generator detection (`format` omitted or `auto`): superseded by the journey slice below. In slice 2 it used only the published settings keys; it now also uses the application tag and file markers of DitherForge, Kromacut and SindriCAD, and never decides from "it is a ZIP". One match is reported as `detected`, a `format` hint as `chosen`, several matches as `ambiguous` (origin not decided, candidates listed) and none as `unknown`. An unknown generator still gets the container identity: every archive member and every settings key is listed as passed through by name and SHA-256. - The response carries `understood`, `passed_through`, `could_not_interpret` (unknown keys), `missing` (expected keys that were absent), `diagnostics`, simulated `recipes` (`simulated=True`, `execution_supported=False`), `physical_slots_needed`, and `source` with the file name only (never the full path), size, `sha256_before`, `sha256_after` and `unchanged`. The file is hashed from the bytes read and again by re-reading it after the readers ran. - Desktop: route `/creative` ("Creative import", group Studio+) in `desktop/src/routes/ext/creative.{meta.ts,route.tsx}`; view in `desktop/src/components/creative/`; client in `desktop/src/lib/creativeApi.ts`. The page takes a typed file path (no file picker in this slice) and shows origin, understood, kept untouched, could not interpret, simulated recipes and the unchanged-original line. - Screenshots in `docs/internal/screens/creative/` come from `capture.mjs`: real engine process, vite dev UI, headless Edge, synthetic archives with relative file names. -- Limits: ImageMap and Lumina are only reachable by the explicit `format` choice because their archives carry no settings keys that identify them. DitherForge, Kromacut and SindriCAD have no reader and are not offered. The files are inspected one at a time; there is no batch or folder scan. +- Limits: ImageMap and Lumina are only reachable by the explicit `format` choice because their archives carry no settings keys that identify them. (Slice-2 statement that DitherForge, Kromacut and SindriCAD have no reader is superseded: the journey slice adds readers for all three.) The files are inspected one at a time; there is no batch or folder scan. + +## Journey slice: supported formats, prepare and export verification + +Evidence level: `fixture-tested`. Upstream sources were read for FORMAT only (owner/repo, commit, path in `backend/tests/fixtures/creative/PROVENANCE.md`): DitherForge (MIT) `rtwfroody/ditherforge` 4d3552a, Kromacut (AGPL-3.0) `vycdev/Kromacut` 9487475, SindriCAD (AGPL-3.0) `MakerViking/sindricad` 8b2e9dc. ImageMap and Lumina were not re-read; they stay manual-only with identity-only reading. Every fixture is generated by `zip_factory.py` and is synthetic. + +### Supported formats (`POST /creative/formats {}`; table `SUPPORTED_FORMATS` in `creative/formats.py`) + +| Format | Selection | Identified by | Not read | +| --- | --- | --- | --- | +| DitherForge | automatic | Application `ditherforge-` or `+ditherforge-` | long paint strings, geometry, sidecar JSON/TXT | +| Kromacut | automatic | Application `Kromacut_Print`, `xmlns:Kromacut`, or `Metadata/kromacut.config` | kromacut.config payload, geometry | +| SindriCAD | automatic | Application `SindriCAD` | long paint strings, geometry | +| FOrcaSlicer, LixNix, FullSpectrum | automatic | published settings keys (see above) | see reader table | +| OrcaSlicer ImageMap, Lumina Layers | manual only | nothing: no identifying marker | zone shape; provenance | + +Markers of several tools in one file give origin `ambiguous`; a chosen format with the wrong shape is refused with a 400 listing what was expected, what the file has, and what to do. + +### `POST /creative/prepare {path, format?, out_dir?}` + +Re-inspects, refuses unknown or ambiguous input with an explanation (HTTP 200, `prepared: false`, `refusal`), then calls `service.convert(path, out_dir, "preserve")` and verifies the result: the export is re-opened, members listed with SHA-256, compared by name with the original (kept identical / changed / dropped / added), project-settings keys removed/changed/added, painted-triangle counts before and after, and the original is re-hashed (`original_unchanged`). `out_dir` must be an existing local folder (UNC and device paths refused). With no `out_dir` the copy goes to `creative-prepared` inside Studio's data directory, NOT next to the original (the service's own default is next to the source, which this route deliberately does not use). The route does not call `service.record_conversion`, but `service.convert` itself still writes its Prepare fix-ledger entry in Studio's data directory, so a successful Prepare leaves that ledger entry there. The response names the output file and a generic location label only ("Studio's creative-prepared folder" or "the folder you chose"); no directory path is returned. + +Measured behaviour of the existing Prepare on synthetic files (preserve mode): + +| Tool shape | Result | +| --- | --- | +| SindriCAD | Copy written. Model, `model_settings.config`, other members kept identical; `project_settings.config` rewritten (settings keys all kept, 64 added); painted triangles 2 of 2. | +| FullSpectrum-keyed / plain 3MF (ImageMap or Lumina chosen) | Copy written. Unknown members kept identical; `project_settings.config` rewritten, no keys removed. | +| DitherForge, Bambu path (`BambuStudio-+ditherforge-`) | Copy written. Geometry, object file, relationships and `model_settings.config` kept identical; `project_settings.config` rewritten; `Metadata/plate_1.json` dropped (Prepare removes `Metadata/plate_*.json` as a stale slice cache, `orca_import.SLICE_CACHE_*`); painted triangles 3 of 3. | +| DitherForge, generic path (`ditherforge-`) | REFUSED by Prepare's structure check, and this is what the exporter really writes: `export3mf.go` gives each part object id 2+i (also for a single mesh: id 2), the component and inner object use that id, and `buildModelSettingsParts` writes `` for every object. Studio reports "part ids ['1'] do not match its component ids ['2']". The check is unchanged and has no producer exemption; such a file is inspect-only and the format table says so (`prepare_limits`). Whether Orca loads that shape is not established here. | +| Kromacut | Copy written (fixed in this slice). The exporter writes colour layers as mesh objects in the root model and an assembly object whose components carry no `p:path`; that is valid 3MF Core. `multipart.validate_archive` looked for mesh objects only in `p:path` files and reported "reference an object that no file defines"; it now also counts mesh objects the root model defines (a component without `p:path` needs a root mesh object; one with `p:path` needs that id in the file it names, resolved by (file, id) and never pooled across files; the root model and every `p:path` file are scanned the same way, so an object that contains another object, an object with no closing tag, a repeated id inside one model part, a non-numeric id and a component with no `objectid` are each refused; an empty `` container is not geometry in the root or in a file, and tag text inside an XML comment is ignored; root and file object types are kept in separate id namespaces; one assembly that references the same id both from the root model and from a file is refused, and so is one that references it from several files that disagree on its type, because a part record cannot say which it describes). Model, `model_settings.config` and `kromacut.config` kept identical; `project_settings.config` rewritten; no per-triangle paint (colour is by material pid/pindex). | + +The Kromacut refusal was a Studio validator defect and is fixed; the DitherForge generic-path refusal is the validator correctly declining a shape it cannot vouch for. Both rows are from synthetic files built from the exporter source, not from captured exports. The earlier carried gaps in the `p:path` file scan (nested and unclosed objects, an empty `` container, ids pooled across files) are closed by the shared scan `multipart._scan_objects`, covered by `tests/test_multipart_validator_files.py` (synthetic archives only). A file that repeats an id, or two files in one assembly that give the same id different types, is now refused where it was silently accepted. Tag matching still starts from the literal ` { localStorage.setItem("theme", "dark"); }); const page = await ctx.newPage(); page.on("pageerror", (e) => console.log("PAGEERROR", e.message)); @@ -81,9 +86,45 @@ const inspect = async (file, shot, waitText) => { await page.screenshot({ path: join(out, shot), fullPage: true }); console.log(shot, "->", (await page.locator("main, body").first().innerText()).split("\n").slice(0, 40).join(" | ")); }; +const prepare = async (shot, waitText) => { + await page.getByRole("button", { name: "Prepare a U1 copy" }).click(); + await page.getByText(waitText).first().waitFor({ timeout: 30000 }); + await sleep(300); + await page.screenshot({ path: join(out, shot), fullPage: true }); + console.log(shot, "->", (await page.locator("main, body").first().innerText()).split("\n").slice(0, 60).join(" | ")); +}; await inspect("sample-fullspectrum.3mf", "fullspectrum-recipes.png", "Original unchanged"); await inspect("sample-forca.3mf", "forca-expected-and-unknown.png", "Original unchanged"); await inspect("sample-other.3mf", "unknown-origin.png", "Origin unknown"); +// New in the journey slice: three more tools, the format chooser, refusals and the prepare result. +await inspect("sample-kromacut.3mf", "kromacut-inspection.png", "Looks like Kromacut"); +await prepare("kromacut-prepare-result.png", "Export verification"); +// DitherForge: the Bambu-path export is prepared; the generic-path export (sample above) is refused with the reason. +await inspect("sample-ditherforge-bambu.3mf", "ditherforge-bambu-inspection.png", "Looks like DitherForge"); +await prepare("ditherforge-bambu-prepare-result.png", "Export verification"); +await inspect("sample-ditherforge.3mf", "ditherforge-inspection.png", "Looks like DitherForge"); +await page.getByLabel("Project format").selectOption("ditherforge"); +await sleep(300); +await prepare("ditherforge-generic-prepare-refused.png", "No copy was written"); +await page.getByLabel("Project format").selectOption("auto"); +await inspect("sample-sindricad.3mf", "sindricad-inspection.png", "Looks like SindriCAD"); +await prepare("sindricad-prepare-result.png", "Export verification"); +await inspect("sample-ambiguous.3mf", "format-chooser-ambiguous.png", "Origin not decided"); +await page.getByLabel("Project format").selectOption("sindricad"); +await sleep(300); +await page.screenshot({ path: join(out, "format-chooser-choice.png"), fullPage: true }); +await page.getByLabel("Project format").selectOption("auto"); +// A chosen format with the wrong shape: Kromacut on a plain 3MF gives the actionable refusal text. +await page.getByLabel("Project format").selectOption("kromacut"); +await inspect("sample-other.3mf", "unsupported-explanation.png", "does not carry what Studio reads"); +await page.getByLabel("Project format").selectOption("auto"); +// The failed inspection cleared the report; re-run it (no screenshot) so Prepare is offered again. +await page.getByRole("button", { name: "Inspect project" }).click(); +await page.getByText("Origin unknown").first().waitFor({ timeout: 15000 }); +await prepare("unknown-prepare-refused.png", "No copy was written"); +await page.getByLabel("Project format").selectOption("imagemap"); +await sleep(300); +await page.screenshot({ path: join(out, "format-chooser-manual-only.png"), fullPage: true }); await browser.close(); cleanup(); process.exit(0); diff --git a/docs/internal/screens/creative/ditherforge-bambu-inspection.png b/docs/internal/screens/creative/ditherforge-bambu-inspection.png new file mode 100644 index 00000000..3da8315f Binary files /dev/null and b/docs/internal/screens/creative/ditherforge-bambu-inspection.png differ diff --git a/docs/internal/screens/creative/ditherforge-bambu-prepare-result.png b/docs/internal/screens/creative/ditherforge-bambu-prepare-result.png new file mode 100644 index 00000000..4aecfadd Binary files /dev/null and b/docs/internal/screens/creative/ditherforge-bambu-prepare-result.png differ diff --git a/docs/internal/screens/creative/ditherforge-generic-prepare-refused.png b/docs/internal/screens/creative/ditherforge-generic-prepare-refused.png new file mode 100644 index 00000000..343b1e6f Binary files /dev/null and b/docs/internal/screens/creative/ditherforge-generic-prepare-refused.png differ diff --git a/docs/internal/screens/creative/ditherforge-inspection.png b/docs/internal/screens/creative/ditherforge-inspection.png new file mode 100644 index 00000000..70b91ea6 Binary files /dev/null and b/docs/internal/screens/creative/ditherforge-inspection.png differ diff --git a/docs/internal/screens/creative/forca-expected-and-unknown.png b/docs/internal/screens/creative/forca-expected-and-unknown.png index fc6b4a5e..3e78c448 100644 Binary files a/docs/internal/screens/creative/forca-expected-and-unknown.png and b/docs/internal/screens/creative/forca-expected-and-unknown.png differ diff --git a/docs/internal/screens/creative/format-chooser-ambiguous.png b/docs/internal/screens/creative/format-chooser-ambiguous.png new file mode 100644 index 00000000..01f5fb53 Binary files /dev/null and b/docs/internal/screens/creative/format-chooser-ambiguous.png differ diff --git a/docs/internal/screens/creative/format-chooser-choice.png b/docs/internal/screens/creative/format-chooser-choice.png new file mode 100644 index 00000000..b446033b Binary files /dev/null and b/docs/internal/screens/creative/format-chooser-choice.png differ diff --git a/docs/internal/screens/creative/format-chooser-manual-only.png b/docs/internal/screens/creative/format-chooser-manual-only.png new file mode 100644 index 00000000..56641097 Binary files /dev/null and b/docs/internal/screens/creative/format-chooser-manual-only.png differ diff --git a/docs/internal/screens/creative/fullspectrum-recipes.png b/docs/internal/screens/creative/fullspectrum-recipes.png index 145c8508..ae08e3f8 100644 Binary files a/docs/internal/screens/creative/fullspectrum-recipes.png and b/docs/internal/screens/creative/fullspectrum-recipes.png differ diff --git a/docs/internal/screens/creative/kromacut-inspection.png b/docs/internal/screens/creative/kromacut-inspection.png new file mode 100644 index 00000000..11d96ae1 Binary files /dev/null and b/docs/internal/screens/creative/kromacut-inspection.png differ diff --git a/docs/internal/screens/creative/kromacut-prepare-result.png b/docs/internal/screens/creative/kromacut-prepare-result.png new file mode 100644 index 00000000..5b22c4f0 Binary files /dev/null and b/docs/internal/screens/creative/kromacut-prepare-result.png differ diff --git a/docs/internal/screens/creative/sindricad-inspection.png b/docs/internal/screens/creative/sindricad-inspection.png new file mode 100644 index 00000000..04e78b03 Binary files /dev/null and b/docs/internal/screens/creative/sindricad-inspection.png differ diff --git a/docs/internal/screens/creative/sindricad-prepare-result.png b/docs/internal/screens/creative/sindricad-prepare-result.png new file mode 100644 index 00000000..d60db69f Binary files /dev/null and b/docs/internal/screens/creative/sindricad-prepare-result.png differ diff --git a/docs/internal/screens/creative/unknown-origin.png b/docs/internal/screens/creative/unknown-origin.png index 139c67a0..b943113f 100644 Binary files a/docs/internal/screens/creative/unknown-origin.png and b/docs/internal/screens/creative/unknown-origin.png differ diff --git a/docs/internal/screens/creative/unknown-prepare-refused.png b/docs/internal/screens/creative/unknown-prepare-refused.png new file mode 100644 index 00000000..9fe9a049 Binary files /dev/null and b/docs/internal/screens/creative/unknown-prepare-refused.png differ diff --git a/docs/internal/screens/creative/unsupported-explanation.png b/docs/internal/screens/creative/unsupported-explanation.png new file mode 100644 index 00000000..1a5ae79d Binary files /dev/null and b/docs/internal/screens/creative/unsupported-explanation.png differ