Remove OpenSCAD from the web port
Web FreeCAD does not implement OpenSCAD. Drop the module end to end instead of keeping a blocked or placeholder shell: - delete the parity-matrix row and regenerate the module registry (31 modules, OpenSCAD absent) - remove the OpenSCAD-only frontend modules (worker, facades, slice, mesh backend, desktop/preferences tasks) and strip the OpenSCAD branches from the dispatchers, shells, storage and router - neutralise the two shared owners that outlived the module: openscad-desktop-view -> scene-viewport (SceneViewport) and openscad-desktop-adapter -> scene-document (SceneDocument), so Part, Mesh and the other consumers keep working - drop the FreeCADWebOpenSCADRuntimeProbe target and FREECAD_WEB_ENABLE_OPENSCAD option from the kernel CMake; BUILD_OPENSCAD stays in the forced-off list - delete web/openscad.html, its Vite input, the kernel artifacts and the 17 OpenSCAD tool entry points AGENTS.md records the removal rule. tsc --noEmit is clean and grep -ri openscad web/src is empty. Also carry the Boost pthread guard: under Emscripten a plain -lpthread implies -sUSE_PTHREADS=1 and therewith --shared-memory, which the non-atomics VTK archives cannot link against. Validation NOT_RUN / PARTIAL_FAILED, Acceptance NOT_CLAIMED. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1144
docs/web-parity-matrix.json
Normal file
1144
docs/web-parity-matrix.json
Normal file
File diff suppressed because it is too large
Load Diff
24
tools/generate_api_adapter_fill_manifest.py
Normal file
24
tools/generate_api_adapter_fill_manifest.py
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate grouped implementation plans for all remaining planned APIs."""
|
||||
from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
source_path = ROOT / "docs/p6/python-api-manifest.json"
|
||||
rows = json.loads(source_path.read_text(encoding="utf-8"))["records"]
|
||||
selected = [row for row in rows if row["disposition"] == "planned"]
|
||||
routes = {"Part": ("part.worker.ts", "part.pythonApi"), "PartDesign": ("partdesign-python.worker.ts", "partdesign.pythonApi"), "Sketcher": ("sketcher-python.worker.ts", "sketcher.pythonApi"), "TechDraw": ("techdraw-python.worker.ts", "techdraw.pythonApi"), "Import": ("import.worker.ts", "import.pythonApi"), "Mesh": ("mesh.worker.ts", "mesh.pythonApi"), "Measure": ("measure.worker.ts", "measure.pythonApi"), "Points": ("points.worker.ts", "points.pythonApi"), "Robot": ("robot-python.worker.ts", "robot.pythonApi"), "Surface": ("surface-python.worker.ts", "surface.pythonApi"), "Spreadsheet": ("spreadsheet-python.worker.ts", "spreadsheet.pythonApi"), "Sandbox": ("sandbox-python.worker.ts", "sandbox.pythonApi"), "Material": ("material-python.worker.ts", "material.pythonApi"), "TemplatePyMod": ("templatepymod-python.worker.ts", "templatepymod.pythonApi"), "Plot": ("plot-python.worker.ts", "plot.pythonApi"), "ReverseEngineering": ("reverseengineering-python.worker.ts", "reverseengineering.pythonApi")}
|
||||
groups = defaultdict(list)
|
||||
for row in selected: groups[f"{row['module']}:{row['tier']}:{row['family']}"].append(row)
|
||||
plans = []
|
||||
for key, group in sorted(groups.items()):
|
||||
module, tier, family = key.split(":", 2)
|
||||
worker, command = routes.get(module, (None, None))
|
||||
plans.append({"key": key, "module": module, "tier": tier, "family": family, "count": len(group), "route": {"worker": worker, "command": command}, "adapterStatus": "module_adapter_ready_pending_method" if command else "module_adapter_pending", "apiIds": sorted(row["id"] for row in group)})
|
||||
output = {"schema": "freecad-web-api-adapter-fill-manifest/v1", "taskId": "FW-P6-FPA-IMPL-API-ADAPTER-FILL", "source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(source_path.read_bytes()).hexdigest()}, "disposition": "planned", "count": len(selected), "groupCount": len(plans), "groups": plans, "boundaries": ["route readiness is not method-level API completion", "module_adapter_pending groups require native facade/probe before implementation"]}
|
||||
out = ROOT / "docs/p6/api-adapter-fill-manifest.json"
|
||||
out.write_text(json.dumps(output, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"output": str(out.relative_to(ROOT)), "count": len(selected), "groups": len(plans), "bytes": out.stat().st_size, "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, ensure_ascii=False))
|
||||
104
tools/generate_contract_batch.py
Normal file
104
tools/generate_contract_batch.py
Normal file
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run one queued contract family and promote only fully passed real cases."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
QUEUE = ROOT / "docs/current/contract-generation-queue.json"
|
||||
PROGRESS = ROOT / "docs/current/contract-generation-progress.json"
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--module")
|
||||
parser.add_argument("--family")
|
||||
parser.add_argument("--apply", action="store_true", help="promote coveredIds only after every selected case passes")
|
||||
parser.add_argument("--confirm-apply", action="store_true", help="second confirmation required with --apply")
|
||||
parser.add_argument("--generate", action="store_true", help="write a non-passing skeleton; never updates coveredIds")
|
||||
args = parser.parse_args()
|
||||
if args.apply and not args.confirm_apply: parser.error("--apply requires --confirm-apply")
|
||||
queue = json.loads(QUEUE.read_text())
|
||||
batch = next((item for item in queue.get("batches", [])
|
||||
if (not args.module or item["module"] == args.module)
|
||||
and (not args.family or item["family"] == args.family)), None)
|
||||
if not batch:
|
||||
print(json.dumps({"status": "no_batch", "reason": "no queued family matches"}))
|
||||
return 2
|
||||
if args.generate:
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", f"{batch['module']}-{batch['family']}".lower()).strip("-")
|
||||
output = ROOT / "tools/generated-contracts" / f"{slug}.mjs"
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
ids = json.dumps(batch["ids"], ensure_ascii=False, indent=2)
|
||||
source = json.dumps(batch.get("commands", []), ensure_ascii=False)
|
||||
output.write_text("""// Generated contract skeleton. Implement real native/browser assertions before promotion.\nconst ids = %s;\nconst commands = %s;\nconst results = ids.map(capabilityId => ({ capabilityId, status: \"not_implemented\", cases: [{ input: { capabilityId, commands }, assertions: [{ name: \"real business assertion is implemented\", passed: false, actual: \"generation skeleton only\" }] }] }));\nprocess.stdout.write(JSON.stringify({ schema: \"freecad-web-business-cases/v1\", results }) + \"\\n\");\nprocess.exitCode = 1;\n""" % (ids, source))
|
||||
try:
|
||||
progress = json.loads(PROGRESS.read_text())
|
||||
except (OSError, json.JSONDecodeError):
|
||||
progress = {"schema": "freecad-web-contract-generation-progress/v1", "batches": {}}
|
||||
progress.setdefault("batches", {})[f"{batch['module']}:{batch['family']}"] = {
|
||||
"status": "skeleton_generated", "path": str(output.relative_to(ROOT)),
|
||||
"generatedAt": __import__("time").time(), "ids": batch["ids"], "coveredIdsUpdated": False}
|
||||
PROGRESS.write_text(json.dumps(progress, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps({"status": "skeleton_generated", "module": batch["module"], "family": batch["family"], "ids": batch["ids"], "path": str(output.relative_to(ROOT)), "coveredIdsUpdated": False}, ensure_ascii=False))
|
||||
return 0
|
||||
contract_path = ROOT / "docs/business-acceptance" / f"{batch['module']}.json"
|
||||
contract = json.loads(contract_path.read_text())
|
||||
command = contract.get("command", [])
|
||||
if batch["module"] == "Part":
|
||||
command = ["node", "tools/part-family-contract-business-cases.mjs"]
|
||||
if batch["family"].startswith("product-"):
|
||||
command = ["node", "tools/web-acceptance-cases.mjs"]
|
||||
if batch["family"] == "product-extensions": command = ["node", "tools/web-product-extensions-business-cases.mjs"]
|
||||
if batch["family"].startswith("desktop-command-"):
|
||||
command = ["node", "tools/desktop-boundary-business-cases-v2.mjs"]
|
||||
if batch["module"] in {"BIM", "Test", "Assembly", "CAM", "Fem", "Draft", "Sketcher", "TechDraw", "Web"}:
|
||||
command = ["node", "tools/desktop-restricted-boundary-business-cases.mjs"]
|
||||
if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepycheckable":
|
||||
command = ["node", "tools/templatepymod-checkable-business-cases.mjs"]
|
||||
if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepygroup":
|
||||
command = ["node", "tools/templatepymod-group-business-cases.mjs"]
|
||||
if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepygrp":
|
||||
command = ["node", "tools/templatepymod-grp-business-cases.mjs"]
|
||||
if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepymod":
|
||||
command = ["node", "tools/templatepymod-command-business-cases-v2.mjs"]
|
||||
if batch["module"] == "Draft" and batch["family"] == "create-edit-recompute":
|
||||
command = ["node", "tools/draft-action-business-cases.mjs"]
|
||||
if batch["module"] == "Fem" and batch["family"] == "create-edit-recompute":
|
||||
command = ["node", "tools/fem-action-business-cases.mjs"]
|
||||
if not isinstance(command, list) or len(command) < 2:
|
||||
print(json.dumps({"status": "not_ready", "reason": "module contract has no executable command", "batch": batch}))
|
||||
return 78
|
||||
environment = dict(os.environ, FREECAD_BUSINESS_IDS=json.dumps(batch["ids"]))
|
||||
run = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True)
|
||||
try:
|
||||
report = json.loads(run.stdout)
|
||||
except json.JSONDecodeError:
|
||||
report = {"status": "invalid_report", "stdout": run.stdout[-3000:], "stderr": run.stderr[-3000:]}
|
||||
results = report.get("results", []) if isinstance(report, dict) else []
|
||||
passed = {row.get("capabilityId") for row in results if row.get("status") == "passed"}
|
||||
all_passed = set(batch["ids"]).issubset(passed) and run.returncode == 0
|
||||
output = {"status": "passed" if all_passed else "not_ready", "applied": False,
|
||||
"module": batch["module"], "family": batch["family"], "ids": batch["ids"],
|
||||
"passedIds": sorted(passed), "exitCode": run.returncode, "reason": report.get("reason"), "stderr": run.stderr[-600:], "stdout": run.stdout[-600:]}
|
||||
if all_passed and args.apply:
|
||||
covered = list(dict.fromkeys([*contract.get("coveredIds", []), *batch["ids"]]))
|
||||
contract["coveredIds"] = covered
|
||||
contract_path.write_text(json.dumps(contract, ensure_ascii=False, indent=2) + "\n")
|
||||
try:
|
||||
progress = json.loads(PROGRESS.read_text())
|
||||
except (OSError, json.JSONDecodeError):
|
||||
progress = {"schema": "freecad-web-contract-generation-progress/v1", "batches": {}}
|
||||
key = f"{batch['module']}:{batch['family']}"
|
||||
previous = progress.setdefault("batches", {}).get(key, {})
|
||||
progress["batches"][key] = {**previous, "status": "verified_and_applied", "verifiedAt": __import__("time").time(),
|
||||
"ids": batch["ids"], "passedIds": sorted(passed), "coveredIdsUpdated": True}
|
||||
PROGRESS.write_text(json.dumps(progress, ensure_ascii=False, indent=2) + "\n")
|
||||
output["applied"] = True
|
||||
print(json.dumps(output, ensure_ascii=False))
|
||||
return 0 if all_passed else 1
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
1484
tools/generate_feature_capability_registry.py
Normal file
1484
tools/generate_feature_capability_registry.py
Normal file
File diff suppressed because it is too large
Load Diff
70
tools/generate_python_api_runtime_evidence.py
Normal file
70
tools/generate_python_api_runtime_evidence.py
Normal file
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Index native Python API names from passing P6 runtime evidence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
P6 = ROOT / "docs/p6"
|
||||
OUT = P6 / "python-api-runtime-evidence.json"
|
||||
|
||||
|
||||
def names(value):
|
||||
if isinstance(value, str):
|
||||
return [item.strip() for item in value.replace("\n", ",").split(",") if item.strip()]
|
||||
if isinstance(value, list):
|
||||
return [str(item).strip() for item in value if str(item).strip()]
|
||||
if isinstance(value, dict):
|
||||
result = []
|
||||
for item in value.values():
|
||||
result.extend(names(item))
|
||||
return result
|
||||
return []
|
||||
|
||||
|
||||
evidence = {}
|
||||
for path in sorted(P6.glob("*.json")):
|
||||
try:
|
||||
report = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
result_value = report.get("result", report.get("status"))
|
||||
if not isinstance(result_value, str) or result_value not in {"pass", "passed", "completed"}:
|
||||
continue
|
||||
action = report.get("action")
|
||||
explicit_python = action == "python-api" or "python" in path.stem.lower()
|
||||
if not explicit_python:
|
||||
continue
|
||||
module = report.get("module")
|
||||
if not isinstance(module, str) or not module:
|
||||
stem = path.stem.lower()
|
||||
inferred = [("meshpart", "MeshPart"), ("points", "Points"), ("sketcher", "Sketcher"), ("techdraw", "TechDraw"), ("robot", "Robot"), ("measure", "Measure"), ("surface", "Surface"), ("spreadsheet", "Spreadsheet"), ("inspection", "Inspection"), ("sandbox", "Sandbox")]
|
||||
module = next((value for token, value in inferred if token in stem), None)
|
||||
if not isinstance(module, str) or not module:
|
||||
continue
|
||||
found = []
|
||||
def walk(value, key=""):
|
||||
if isinstance(value, dict):
|
||||
for child_key, child in value.items():
|
||||
if child_key.lower() in {"apinames", "pythonapi", "pythonapinames", "api_names"}:
|
||||
found.extend(names(child))
|
||||
walk(child, child_key)
|
||||
elif isinstance(value, list):
|
||||
for child in value:
|
||||
walk(child, key)
|
||||
walk(report)
|
||||
for name in found:
|
||||
normalized = name.strip()
|
||||
if normalized:
|
||||
key = f"{module}:{normalized}"
|
||||
evidence.setdefault(key, []).append(str(path.relative_to(ROOT)))
|
||||
|
||||
report = {
|
||||
"schema": "freecad-web-python-api-runtime-evidence/v1",
|
||||
"policy": "only passing python-api-named runtime artifacts are indexed; source-only inventory is excluded",
|
||||
"names": [{"module": key.split(":", 1)[0], "name": key.split(":", 1)[1], "artifacts": sorted(set(paths))} for key, paths in sorted(evidence.items())],
|
||||
"count": len(evidence),
|
||||
}
|
||||
OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"output": str(OUT.relative_to(ROOT)), "names": len(evidence)}, ensure_ascii=False))
|
||||
64
tools/generate_python_family_adapter_manifest.py
Normal file
64
tools/generate_python_family_adapter_manifest.py
Normal file
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate an implementation-stage adapter map for one module+tier batch."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
ADAPTERS = {
|
||||
"Assembly": ("assembly.worker.ts", "assembly.pythonFamily", "src/WebAssembly/FreeCADCoreProbe/AssemblyRuntimeProbe.cpp"),
|
||||
"BIM": ("bim.worker.ts", "bim.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/BimRuntimeProbe.cpp"),
|
||||
"CAM": ("cam.worker.ts", "cam.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/CAMRuntimeProbe.cpp"),
|
||||
"Draft": ("draft.worker.ts", "draft.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp"),
|
||||
"Fem": ("fem.worker.ts", "fem.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/FemGenericFamilyProbe.cpp"),
|
||||
"Import": ("import.worker.ts", "import.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/ImportRuntimeProbe.cpp"),
|
||||
"Material": ("material.worker.ts", "material.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MaterialKernelProbe.cpp"),
|
||||
"Measure": ("measure.worker.ts", "measure.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MeasureRuntimeProbe.cpp"),
|
||||
"Mesh": ("mesh.worker.ts", "mesh.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MeshRuntimeProbe.cpp"),
|
||||
"MeshPart": ("meshpart.worker.ts", "meshpart.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MeshPartRuntimeProbe.cpp"),
|
||||
"Part": ("part.worker.ts", "part.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PartBoxProbe.cpp"),
|
||||
"PartDesign": ("partdesign-python.worker.ts", "partdesign.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PartDesignRuntimeProbe.cpp"),
|
||||
"Plot": ("plot-python.worker.ts", "plot.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PlotRuntimeProbe.cpp"),
|
||||
"Points": ("points.worker.ts", "points.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PointsRuntimeProbe.cpp"),
|
||||
"ReverseEngineering": ("reverseengineering-python.worker.ts", "reverseengineering.pythonFamilyBatch", "src/Mod/ReverseEngineering/InitGui.py"),
|
||||
"Robot": ("robot-python.worker.ts", "robot.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/RobotRuntimeProbeFixed.cpp"),
|
||||
"Sandbox": ("sandbox-python.worker.ts", "sandbox.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SandboxRuntimeProbe.cpp"),
|
||||
"Show": ("show-python.worker.ts", "show.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/ShowRuntimeProbe.cpp"),
|
||||
"Sketcher": ("sketcher-python.worker.ts", "sketcher.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SketcherProbe.cpp"),
|
||||
"Spreadsheet": ("spreadsheet-python.worker.ts", "spreadsheet.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SpreadsheetRuntimeProbe.cpp"),
|
||||
"Surface": ("surface-python.worker.ts", "surface.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SurfaceFamilyProbe.cpp"),
|
||||
"TechDraw": ("techdraw-python.worker.ts", "techdraw.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/TechDrawRuntimeProbe.cpp"),
|
||||
"TemplatePyMod": ("templatepymod-python.worker.ts", "templatepymod.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/TemplatePyModRuntimeProbe.cpp"),
|
||||
}
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("module")
|
||||
parser.add_argument("tier")
|
||||
parser.add_argument("--output")
|
||||
args = parser.parse_args()
|
||||
if args.module not in ADAPTERS:
|
||||
raise SystemExit(f"no adapter mapping for {args.module}")
|
||||
manifest_path = ROOT / "docs/p6/python-api-manifest.json"
|
||||
rows = json.loads(manifest_path.read_text(encoding="utf-8"))["records"]
|
||||
selected = [row for row in rows if row["module"] == args.module and row["tier"] == args.tier]
|
||||
worker, command, native_source = ADAPTERS[args.module]
|
||||
records = [{"apiId": row["id"], "name": row["name"], "kind": row["kind"], "family": row["family"], "sourcePath": row.get("evidence", {}).get("path"), "route": command, "adapterStatus": "module_adapter_ready_pending_method", "disposition": row["disposition"]} for row in selected]
|
||||
output = {
|
||||
"schema": "freecad-web-python-family-adapter-manifest/v1",
|
||||
"taskId": f"FW-P6-FPA-IMPL-{args.module.upper()}-{args.tier.upper().replace('-', '_')}",
|
||||
"source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest()},
|
||||
"module": args.module,
|
||||
"tier": args.tier,
|
||||
"count": len(records),
|
||||
"route": {"worker": worker, "command": command, "nativeSource": native_source},
|
||||
"records": records,
|
||||
"boundaries": ["module adapter readiness is not method-level parameter/return evidence", "original disposition is preserved until the matching coverage gate"],
|
||||
}
|
||||
short_tier = {"tier-1-readonly": "tier1", "tier-2-pure": "tier2", "tier-3-stateful": "tier3"}.get(args.tier, args.tier.replace("-", ""))
|
||||
out = ROOT / (args.output or f"docs/p6/{args.module.lower()}-{short_tier}-adapter-manifest.json")
|
||||
out.write_text(json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"output": str(out.relative_to(ROOT)), "module": args.module, "tier": args.tier, "count": len(records), "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, ensure_ascii=False))
|
||||
34
tools/generate_tier1_readonly_adapter_manifest.py
Normal file
34
tools/generate_tier1_readonly_adapter_manifest.py
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate grouped implementation metadata for Tier-1 readonly APIs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
source_path = ROOT / "docs/p6/python-api-manifest.json"
|
||||
rows = json.loads(source_path.read_text(encoding="utf-8"))["records"]
|
||||
selected = [row for row in rows if row["tier"] == "tier-1-readonly"]
|
||||
routes = {
|
||||
"Measure": ("measure.worker.ts", "measure.pythonApi", "src/Mod/Measure/App/AppMeasure.cpp"),
|
||||
"Mesh": ("mesh.worker.ts", "mesh.pythonApi", "src/Mod/Mesh/App/AppMesh.cpp"),
|
||||
"Sketcher": ("sketcher-python.worker.ts", "sketcher.pythonApi", "src/Mod/Sketcher/App/AppSketcher.cpp"),
|
||||
"Robot": ("robot-python.worker.ts", "robot.pythonApi", "src/Mod/Robot/App/AppRobot.cpp"),
|
||||
"Points": ("points.worker.ts", "points.pythonApi", "src/Mod/Points/App/AppPointsPy.cpp"),
|
||||
"Cloud": ("cloud.worker.ts", "cloud.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/CloudKernelProbe.cpp:644"),
|
||||
"Draft": ("draft.worker.ts", "draft.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp:285"),
|
||||
}
|
||||
groups: dict[str, dict[str, object]] = defaultdict(lambda: {"apiIds": [], "families": Counter()})
|
||||
for row in selected:
|
||||
groups[row["module"]]["apiIds"].append(row["id"])
|
||||
groups[row["module"]]["families"][row["family"]] += 1
|
||||
modules = []
|
||||
for module, group in sorted(groups.items()):
|
||||
route = routes.get(module, (None, None, None))
|
||||
modules.append({"module": module, "count": len(group["apiIds"]), "families": dict(sorted(group["families"].items())), "route": {"worker": route[0], "command": route[1], "nativeSource": route[2]}, "apiIds": sorted(group["apiIds"])})
|
||||
output = {"schema": "freecad-web-tier1-readonly-adapter-manifest/v1", "taskId": "FW-P6-FPA-IMPL-TIER1-READONLY", "source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(source_path.read_bytes()).hexdigest()}, "tier": "tier-1-readonly", "count": len(selected), "modules": modules, "boundaries": ["grouped readonly route readiness is not method-level return evidence", "original disposition is preserved until F1 coverage"]}
|
||||
out = ROOT / "docs/p6/tier1-readonly-adapter-manifest.json"
|
||||
out.write_text(json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"output": str(out.relative_to(ROOT)), "count": len(selected), "modules": len(modules), "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, ensure_ascii=False))
|
||||
507
tools/generate_web_feature_task_packets.py
Normal file
507
tools/generate_web_feature_task_packets.py
Normal file
@@ -0,0 +1,507 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate small, module-local P6 task packets from the source-backed matrix."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import hashlib
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MATRIX = ROOT / "docs" / "web-parity-matrix.json"
|
||||
OUT = ROOT / "docs" / "tasks" / "p6"
|
||||
STATE = ROOT / "docs" / "current" / "task-state.json"
|
||||
|
||||
MODULE_IDS = {
|
||||
"Assembly": "ASM",
|
||||
"BIM": "BIM",
|
||||
"CAM": "CAM",
|
||||
"Cloud": "CLD",
|
||||
"Draft": "DFT",
|
||||
"Fem": "FEM",
|
||||
"Help": "HLP",
|
||||
"Import": "IMP",
|
||||
"Inspection": "INS",
|
||||
"JtReader": "JTR",
|
||||
"Material": "MAT",
|
||||
"Measure": "MEA",
|
||||
"Mesh": "MSH",
|
||||
"MeshPart": "MSP",
|
||||
"Part": "PRT",
|
||||
"PartDesign": "PDN",
|
||||
"Plot": "PLT",
|
||||
"Points": "PTS",
|
||||
"ReverseEngineering": "REV",
|
||||
"Robot": "ROB",
|
||||
"Sandbox": "SDB",
|
||||
"Show": "SHW",
|
||||
"Sketcher": "SKT",
|
||||
"Spreadsheet": "SPR",
|
||||
"Start": "STR",
|
||||
"Surface": "SUR",
|
||||
"TechDraw": "TDR",
|
||||
"TemplatePyMod": "TPM",
|
||||
"Test": "TST",
|
||||
"Tux": "TUX",
|
||||
"Web": "WEB",
|
||||
}
|
||||
|
||||
PRIMARY_ACTION = {
|
||||
"Assembly": "create/recompute",
|
||||
"BIM": "import/export",
|
||||
"CAM": "create/recompute",
|
||||
"Cloud": "create/recompute",
|
||||
"Draft": "create/recompute",
|
||||
"Fem": "create/recompute",
|
||||
"Help": "inspect/source-inventory",
|
||||
"Import": "import/export",
|
||||
"Inspection": "create/recompute",
|
||||
"JtReader": "create/recompute",
|
||||
"Material": "create/recompute",
|
||||
"Measure": "create/recompute",
|
||||
"Mesh": "create/recompute",
|
||||
"MeshPart": "create/recompute",
|
||||
"Part": "create/recompute",
|
||||
"PartDesign": "create/recompute",
|
||||
"Plot": "inspect/source-inventory",
|
||||
"Points": "create/recompute",
|
||||
"ReverseEngineering": "create/recompute",
|
||||
"Robot": "create/recompute",
|
||||
"Sandbox": "create/recompute",
|
||||
"Show": "inspect/source-inventory",
|
||||
"Sketcher": "create/recompute",
|
||||
"Spreadsheet": "create/recompute",
|
||||
"Start": "create/recompute",
|
||||
"Surface": "create/recompute",
|
||||
"TechDraw": "create/recompute",
|
||||
"TemplatePyMod": "inspect/source-inventory",
|
||||
"Test": "inspect/source-inventory",
|
||||
"Tux": "inspect/source-inventory",
|
||||
"Web": "create/recompute",
|
||||
}
|
||||
|
||||
|
||||
def load_state() -> dict:
|
||||
if not STATE.exists():
|
||||
return {"default_status": "planned", "tasks": {}, "module_status": {}}
|
||||
return json.loads(STATE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
STATE_DATA = load_state()
|
||||
|
||||
|
||||
def task_status(task_id: str) -> str:
|
||||
return STATE_DATA.get("tasks", {}).get(task_id, STATE_DATA.get("default_status", "planned"))
|
||||
|
||||
|
||||
def module_status(module: str, fallback: str) -> str:
|
||||
return STATE_DATA.get("module_status", {}).get(module, fallback)
|
||||
|
||||
|
||||
def write_generated(path: Path, content: str) -> None:
|
||||
"""Write the generated prefix while preserving a manually recorded result section."""
|
||||
if path.exists():
|
||||
old = path.read_text(encoding="utf-8")
|
||||
marker = "\n## 结果\n"
|
||||
if marker in old and marker not in content:
|
||||
content = content.rstrip() + old[old.index(marker):]
|
||||
path.write_text(content.rstrip() + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def slug(module: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", module.lower()).strip("-")
|
||||
|
||||
|
||||
def action_slug(action: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", action.lower()).strip("-")
|
||||
|
||||
|
||||
def module_index(module: str, row: dict) -> str:
|
||||
code = MODULE_IDS[module]
|
||||
action = PRIMARY_ACTION[module]
|
||||
objects = ", ".join(row.get("object_types", [])[:8]) or "无已枚举对象;以源码入口和模块 API 为主"
|
||||
if len(row.get("object_types", [])) > 8:
|
||||
objects += f"(另有 {len(row['object_types']) - 8} 个,完整清单见 object-inventory.json)"
|
||||
formats = ", ".join(row.get("format_extensions", [])) or "无格式入口"
|
||||
api = row.get("python_api_count", 0)
|
||||
gui = "需要 GUI 依赖" if row.get("gui_dependency") else "不需要 GUI 依赖"
|
||||
actions = ", ".join(row.get("user_actions", []))
|
||||
followups = [action for action in row.get("user_actions", []) if action != action_primary(module)]
|
||||
followup_text = ", ".join(f"`{action}`" for action in followups) or "无"
|
||||
action_rows = []
|
||||
for action_number, action_name in enumerate(row.get("user_actions", []), start=1):
|
||||
if action_name == action:
|
||||
target = f"{slug(module)}/FW-P6-{code}-C.md"
|
||||
role = "首切片 C-G"
|
||||
else:
|
||||
target = f"{slug(module)}/FW-P6-{code}-ACT-{action_number:02d}.md"
|
||||
role = "后续拆分合同"
|
||||
action_rows.append(f"| `{action_name}` | {role} | [{target.rsplit('/', 1)[-1]}]({target}) |")
|
||||
action_table = "\n".join(action_rows)
|
||||
action_predecessors = [
|
||||
f"`FW-P6-{code}-ACT-{number:02d}-G`"
|
||||
for number, action_name in enumerate(row.get("user_actions", []), start=1)
|
||||
if action_name != action
|
||||
]
|
||||
final_predecessor = f"`FW-P6-{code}-X`" + (" + " + " + ".join(action_predecessors) if action_predecessors else "")
|
||||
links = "\n".join(
|
||||
f"| [FW-P6-{code}-{letter}]({slug(module)}/FW-P6-{code}-{letter}.md) | {title} | {prev} |"
|
||||
for letter, title, prev in [
|
||||
("A", "源码边界探针", "FW-P6-000"),
|
||||
("B", "运行时注册与依赖闭包", f"FW-P6-{code}-A + FW-P6-001"),
|
||||
("C", "一个主要内核动作", f"FW-P6-{code}-B"),
|
||||
("D", "重算、非法输入与恢复", f"FW-P6-{code}-C"),
|
||||
("E", "Worker/Facade 消息合同", f"FW-P6-{code}-D + FW-P6-002"),
|
||||
("F", "Chrome 最小浏览器切片", f"FW-P6-{code}-E + FW-P6-003"),
|
||||
("G", "持久化或模块边界证据", f"FW-P6-{code}-F"),
|
||||
("X", "首切片出口", f"FW-P6-{code}-G"),
|
||||
("Y", "完整动作出口", final_predecessor),
|
||||
]
|
||||
)
|
||||
package_status = module_status(module, row.get("web_status", "pending"))
|
||||
# Module parity uses `pending`; executable task cards use `planned`.
|
||||
package_task_status = "planned" if package_status == "pending" else package_status
|
||||
web_status_note = (
|
||||
"Web 状态已由 Y gate 晋级为 `completed`;边界见对应 module-gate 产物。"
|
||||
if package_status == "completed"
|
||||
else "Web 状态保持 `pending`,直到本包的 Y 卡通过。"
|
||||
)
|
||||
return f"""# FW-P6-{code}:{module} 功能扩展任务包
|
||||
|
||||
本文件只做模块范围和原子卡索引;执行时读取当前原子卡,不读取本包其他卡。
|
||||
|
||||
## 范围快照
|
||||
|
||||
- 状态:`{package_task_status}`
|
||||
- 来源:`docs/web-parity-matrix.json`,源码 revision 由 `FW-P6-000` 锁定
|
||||
- 主要动作:`{action}`
|
||||
- 对象规模:`{row.get('object_type_count', 0)}`;代表入口:{objects}
|
||||
- 格式入口:{formats}
|
||||
- Python API 计数:`{api}`;GUI:{gui}
|
||||
- 对标动作全集:{actions}
|
||||
- {web_status_note}
|
||||
|
||||
首个 C-G 切片只覆盖 `{action}`。后续动作:{followup_text};每个后续动作必须在 Y 前完成自己的拆分卡和 C-G 子链,不能因为首个切片通过就把模块标为 `completed`。
|
||||
|
||||
## 动作级入口
|
||||
|
||||
| 动作 | 角色 | 入口 |
|
||||
|---|---|---|
|
||||
{action_table}
|
||||
|
||||
## 原子卡
|
||||
|
||||
| 卡 | 合同 | 直接前置 |
|
||||
|---|---|---|
|
||||
{links}
|
||||
|
||||
顺序:`A → B → C → D → E → F → G → X`;随后完成动作级卡,最后执行 `Y`。失败只新增同目录 `R` 恢复卡,不复制原卡全文。
|
||||
"""
|
||||
|
||||
|
||||
def atomic_card(module: str, row: dict, letter: str) -> str:
|
||||
code = MODULE_IDS[module]
|
||||
name = slug(module)
|
||||
prefix = f"FW-P6-{code}"
|
||||
titles = {
|
||||
"A": "源码边界探针",
|
||||
"B": "运行时注册与依赖闭包",
|
||||
"C": "一个主要内核动作",
|
||||
"D": "重算、非法输入与恢复",
|
||||
"E": "Worker/Facade 消息合同",
|
||||
"F": "Chrome 最小浏览器切片",
|
||||
"G": "持久化或模块边界证据",
|
||||
"X": "首切片出口",
|
||||
"Y": "完整动作出口",
|
||||
}
|
||||
prev = {
|
||||
"A": "`FW-P6-000`",
|
||||
"B": f"`{prefix}-A`、`FW-P6-001`",
|
||||
"C": f"`{prefix}-B`",
|
||||
"D": f"`{prefix}-C`",
|
||||
"E": f"`{prefix}-D`、`FW-P6-002`",
|
||||
"F": f"`{prefix}-E`、`FW-P6-003`",
|
||||
"G": f"`{prefix}-F`",
|
||||
"X": f"`{prefix}-G`",
|
||||
"Y": f"`{prefix}-X`",
|
||||
}[letter]
|
||||
if letter == "Y":
|
||||
action_predecessors = [
|
||||
f"`{prefix}-ACT-{number:02d}-G`"
|
||||
for number, action_name in enumerate(row.get("user_actions", []), start=1)
|
||||
if action_name != PRIMARY_ACTION[module]
|
||||
]
|
||||
if action_predecessors:
|
||||
prev += " + " + " + ".join(action_predecessors)
|
||||
task_type = {"A": "probe", "F": "slice", "X": "gate", "Y": "gate"}.get(letter, "contract")
|
||||
bodies = {
|
||||
"A": f"""- 合同:确认 `{module}` 的 CMake target、App/Gui 分界、直接依赖、类型注册入口和主要动作源码入口。
|
||||
- 输入:`workbench-inventory.json`、`object-inventory.json`、`src/Mod/{module}/`。
|
||||
- 命令/方法:在 `freecad-source` 上运行 `rg -n "BUILD_|Init|addObject|registerType|PyInit" src/Mod/{module}`,再对命中的 CMake 与源码行做最小闭包记录。
|
||||
- 产物:`docs/p6/{name}-source-boundary.json` 与日志。
|
||||
- 验收:每个入口有文件和行号;条件编译、缺失依赖和 GUI 符号单独列出;不把源码存在写成运行时通过。
|
||||
- 不包含:代码修改、浏览器测试、完整 API 迁移。""",
|
||||
"B": f"""- 合同:在独立 WASM probe 中完成 `{module}` 初始化、类型可见性和重复初始化检查。
|
||||
- 输入:A 的边界 JSON、模块 App CMake、共享模块加载合同。
|
||||
- 命令/方法:复制现有最小 Web probe 的 configure/build/run 流程;只替换模块 target 和一个代表类型;连续执行初始化两次并保存新的 build/smoke 日志,不覆盖成功证据。
|
||||
- 产物:`docs/p6/{name}-runtime.json`、构建日志和 WASM SHA-256。
|
||||
- 验收:初始化计数为 1;重复调用不重复注册;缺失依赖返回结构化错误;无未声明 GUI/动态库符号。
|
||||
- 不包含:主要动作、Facade、Chrome UI。""",
|
||||
"C": f"""- 合同:只验证一个最小 `{PRIMARY_ACTION[module]}` 合同,固定输入、输出和对象句柄。
|
||||
- 输入:B 的 WASM、固定 fixture、对应源码 API;对象模块用代表类型,格式模块用一个最小样例。
|
||||
- 命令/方法:从 A 的主要动作入口选择一个 deterministic fixture;在 C ABI/Worker probe 中执行一次成功路径和一次资源释放,记录输入 hash、结果摘要和返回码。
|
||||
- 产物:`docs/p6/{name}-kernel.json` 与 smoke 日志。
|
||||
- 验收:成功结果可重复;对象/几何/格式摘要符合源码语义;异常转为稳定错误码和消息;资源可释放。
|
||||
- 不包含:第二个动作、全量对象覆盖、GUI 交互。""",
|
||||
"D": f"""- 合同:覆盖一次重算/校验边界和一个非法输入,失败后保留上一次有效状态。
|
||||
- 输入:C 的成功 fixture;只读模块改为缺少资源/不支持输入边界。
|
||||
- 命令/方法:复用 C 的同一进程,先记录成功快照,再注入一个字段级非法值或缺失资源;校验错误 code、旧状态 hash、重复回放结果。
|
||||
- 产物:`docs/p6/{name}-recovery.json` 与日志。
|
||||
- 验收:错误定位到字段或步骤;有效对象/文件 hash 不污染;重复执行一致;缓存失败不升级为主流程失败。
|
||||
- 不包含:跨文档事务、并发修改、性能预算。""",
|
||||
"E": f"""- 合同:把 C/D 的一个动作接入 request id、typed result、错误和取消语义。
|
||||
- 输入:共享 Facade envelope、D 的 fixture 和错误样例。
|
||||
- 命令/方法:为一个 action 增加 typed request/result schema;顺序发送 success、expected error、duplicate id、cancel 四个 request,保存 Worker trace。
|
||||
- 产物:`docs/p6/{name}-facade.json`、schema 测试和 Worker 日志。
|
||||
- 验收:请求严格串行且可关联;JS 不持有原生指针;成功/失败/重复 request 均有固定结果;取消不破坏文档状态。
|
||||
- 不包含:完整 UI、插件系统、跨工作台组合。""",
|
||||
"F": f"""- 合同:在 Google Chrome 固定版本和 viewport 下完成一个真实 `{PRIMARY_ACTION[module]}` 用户动作回放。
|
||||
- 输入:Facade bundle、固定 fixture、Chrome harness;只执行 Chrome,不切换 Firefox/WebKit/Safari。
|
||||
- 命令/方法:调用 `FW-P6-003` harness 启动入口,拦截所有外部请求,执行 ready→action→expected-error→reset,并保存 console/network/截图证据。
|
||||
- 产物:`docs/p6/{name}-chrome.json`、控制台/网络日志和截图(如适用)。
|
||||
- 验收:ready、动作结果、错误路径和 Worker 消息通过;外部请求为 0;运行时异常为 0;证据含 Chrome 版本、模式和 viewport。
|
||||
- 不包含:非 Chrome 兼容矩阵、移动适配、完整 UI。""",
|
||||
"G": f"""- 合同:有保存/重开动作时验证一个最小 FCStd round-trip;否则验证 manifest/资源/只读重放边界。
|
||||
- 输入:F 的成功状态、P2.3 FCStd 合同、模块 fixture。
|
||||
- 命令/方法:有 `save/reopen` 时按 P2.3 的临时文件、hash、关闭、重开、对象/属性校验顺序执行;无该动作时运行资源 manifest 和只读重放检查。
|
||||
- 产物:`docs/p6/{name}-persistence.json` 与日志。
|
||||
- 验收:保存/重开对象和属性可校验;不适用时明确原因,不伪造通过;错误后旧状态仍有效。
|
||||
- 不包含:跨版本迁移、全量格式覆盖、升级回滚。""",
|
||||
"X": f"""- 合同:汇总本包 A-G 的独立证据,关闭 `{module}` 的首切片 gate。
|
||||
- 输入:A-G JSON/日志、源码 revision、共享 gate 报告。
|
||||
- 命令/方法:逐项读取本包 A-G 产物,核对 revision、输入/输出 hash、Chrome 证据和未覆盖动作;生成机器可读结果后再写人读 gate。
|
||||
- 产物:`docs/p6/{name}-gate.md` 与 JSON。
|
||||
- 验收:首个动作的每个原子合同有命令、输入、产物、hash 和结论;本卡只关闭首切片,不修改完整模块状态;其他动作保持 `pending`。
|
||||
- 不包含:其他模块、全量发布 gate、法律或性能结论。""",
|
||||
"Y": f"""- 合同:汇总首切片和全部动作级子链,决定 `{module}` 是否可以从 `pending` 晋级。
|
||||
- 输入:X 的首切片 gate、所有动作级卡及其 C-G 子链产物、源码 revision。
|
||||
- 命令/方法:逐动作核对源码入口、成功/错误/Chrome/持久化证据;任一声明动作缺证据即保持 `pending`,不得用动作计数推断完成。
|
||||
- 产物:`docs/p6/{name}-module-gate.md` 与 JSON。
|
||||
- 验收:本模块声明的 {len(row.get('user_actions', []))} 个动作全部有独立结论;未实现或不适用项显式列出;只有本卡可以晋级该模块 Web 状态。
|
||||
- 不包含:其他模块、全量发布 gate、法律或性能结论。""",
|
||||
}[letter]
|
||||
return f"""# {prefix}-{letter}:{module} {titles[letter]}
|
||||
|
||||
> 最小执行上下文:只读取本卡、直接前置 {prev} 和本卡列出的产物。浏览器步骤只允许 Google Chrome。
|
||||
|
||||
- 状态:`{task_status(f"{prefix}-{letter}")}`
|
||||
- 类型:`{task_type}`
|
||||
- 前置:{prev}
|
||||
{bodies}
|
||||
- 失败恢复:保留首个错误、命令、输入 hash 和部分产物;恢复卡命名 `{prefix}-{letter}-R1`,不得覆盖成功证据。
|
||||
"""
|
||||
|
||||
|
||||
def action_card(module: str, action_name: str, action_number: int) -> str:
|
||||
code = MODULE_IDS[module]
|
||||
name = slug(module)
|
||||
prefix = f"FW-P6-{code}-ACT-{action_number:02d}"
|
||||
action_id = action_slug(action_name)
|
||||
extra_prerequisite = {
|
||||
"python-api": ";Python 运行时前置 `FW-P4-006-G`",
|
||||
"save/reopen": ";持久化证据前置 `freecad-p2.3-persistence-transaction-gate.md`",
|
||||
}.get(action_name, "")
|
||||
return f"""# {prefix}:{module} `{action_name}` 动作拆分合同
|
||||
|
||||
> 这是动作级拆分卡,不等于功能已实现。完成本卡后,必须按卡内的 C→D→E→F→G 子链继续执行;只读取本卡、`FW-P6-{code}-B` 和本卡产物。
|
||||
|
||||
- 状态:`{task_status(prefix)}`
|
||||
- 类型:`contract`
|
||||
- 前置:`FW-P6-{code}-B`{extra_prerequisite};若首切片已完成,复用其 WASM、loader 和 fixture 约束。
|
||||
- 合同:为 `{action_name}` 冻结一个可观察用户动作的输入、源码入口、结果摘要、错误边界、Worker request 和 Chrome 回放验收。
|
||||
- 输入:`{name}-source-boundary.json`、对象/格式/API inventory 中与该动作对应的行、共享 Facade envelope 和 Chrome harness。
|
||||
- 命令/方法:先在源码中定位动作入口,再写固定 fixture;把实现拆成 `{prefix}-C`(内核)、`{prefix}-D`(错误/恢复)、`{prefix}-E`(Facade)、`{prefix}-F`(Chrome)、`{prefix}-G`(持久化或适用边界)。
|
||||
- 产物:`docs/p6/{name}-action-{action_number:02d}-{action_id}.json`,以及上述子卡各自的日志和 hash。
|
||||
- 验收:动作有唯一 request id、成功和预期错误结果、无外部网络请求;未完成子链时本动作保持 `pending`。
|
||||
- 不包含:其他动作、工作台 gate、全量对象覆盖、跨版本迁移。
|
||||
- 失败恢复:只记录首个源码/fixture/schema 错误,新增 `{prefix}-R1`;不复制或覆盖首切片证据。
|
||||
"""
|
||||
|
||||
|
||||
def action_child_card(module: str, action_name: str, action_number: int, letter: str) -> str:
|
||||
code = MODULE_IDS[module]
|
||||
name = slug(module)
|
||||
prefix = f"FW-P6-{code}-ACT-{action_number:02d}"
|
||||
titles = {
|
||||
"C": "内核动作",
|
||||
"D": "错误与恢复",
|
||||
"E": "Facade 接入",
|
||||
"F": "Chrome 回放",
|
||||
"G": "持久化或适用边界",
|
||||
}
|
||||
prev = {
|
||||
"C": f"`{prefix}`、`FW-P6-{code}-B`",
|
||||
"D": f"`{prefix}-C`",
|
||||
"E": f"`{prefix}-D`、`FW-P6-002`",
|
||||
"F": f"`{prefix}-E`、`FW-P6-003`",
|
||||
"G": f"`{prefix}-F`",
|
||||
}[letter]
|
||||
bodies = {
|
||||
"C": f"""- 合同:执行 `{action_name}` 的一个 deterministic 内核输入,返回对象/格式/API 摘要。
|
||||
- 输入:动作拆分卡、B 的 WASM、动作 fixture 和源码入口。
|
||||
- 命令/方法:单进程执行成功路径、释放路径和重复回放;记录输入 hash、结果 hash、错误 code。
|
||||
- 产物:`docs/p6/{name}-action-{action_number:02d}-kernel.json` 与 smoke 日志。
|
||||
- 验收:结果可重复,异常结构化,资源释放;不实现其他动作。""",
|
||||
"D": f"""- 合同:为 `{action_name}` 注入一个字段级非法输入或缺少资源并保持旧状态。
|
||||
- 输入:`{prefix}-C` 成功快照和错误 fixture。
|
||||
- 命令/方法:成功→非法→恢复三段回放,比较旧状态 hash 和诊断字段。
|
||||
- 产物:`docs/p6/{name}-action-{action_number:02d}-recovery.json` 与日志。
|
||||
- 验收:首个错误可定位,旧状态未污染,重复回放一致。""",
|
||||
"E": f"""- 合同:把 `{action_name}` 接入通用 request id、typed result、error 和 cancel。
|
||||
- 输入:`{prefix}-D`、共享 envelope、成功和错误样例。
|
||||
- 命令/方法:顺序发送 success、expected error、duplicate id、cancel;保存 Worker trace。
|
||||
- 产物:`docs/p6/{name}-action-{action_number:02d}-facade.json` 与 schema 日志。
|
||||
- 验收:请求可关联且严格串行;JS 不持有原生指针;取消不污染文档。""",
|
||||
"F": f"""- 合同:在 Chrome 固定版本和 viewport 下回放真实 `{action_name}`。
|
||||
- 输入:`{prefix}-E` bundle、fixture、`FW-P6-003` harness。
|
||||
- 命令/方法:ready→action→expected-error→reset,拦截外部请求并保存 console/network/截图。
|
||||
- 产物:`docs/p6/{name}-action-{action_number:02d}-chrome.json` 与日志。
|
||||
- 验收:Chrome 版本、模式、viewport 齐全;外部请求和非预期异常为 0。""",
|
||||
"G": f"""- 合同:为 `{action_name}` 完成 FCStd round-trip,或记录该动作不适用的边界证据。
|
||||
- 输入:`{prefix}-F` 成功状态、P2.3 合同和 fixture。
|
||||
- 命令/方法:有保存动作时执行临时文件、hash、关闭、重开、对象/属性校验;否则执行 manifest/只读重放。
|
||||
- 产物:`docs/p6/{name}-action-{action_number:02d}-persistence.json` 与日志。
|
||||
- 验收:对象/属性或“不适用”原因可校验;不伪造未覆盖能力。""",
|
||||
}[letter]
|
||||
task_type = "slice" if letter == "F" else "contract"
|
||||
return f"""# {prefix}-{letter}:{module} `{action_name}` {titles[letter]}
|
||||
|
||||
> 最小执行上下文:只读取本卡、直接前置 {prev} 和本卡产物。浏览器只允许 Google Chrome。
|
||||
|
||||
- 状态:`{task_status(f"{prefix}-{letter}")}`
|
||||
- 类型:`{task_type}`
|
||||
- 前置:{prev}
|
||||
{bodies}
|
||||
- 不包含:其他用户动作、完整工作台 gate、跨版本迁移。
|
||||
- 失败恢复:保留首个错误、输入 hash 和 trace;新增 `{prefix}-{letter}-R1`,不覆盖成功证据。
|
||||
"""
|
||||
|
||||
|
||||
def action_primary(module: str) -> str:
|
||||
return PRIMARY_ACTION[module]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
data = json.loads(MATRIX.read_text(encoding="utf-8"))
|
||||
rows = {row["module"]: row for row in data["rows"]}
|
||||
missing = set(MODULE_IDS) - set(rows)
|
||||
if missing:
|
||||
raise SystemExit(f"matrix missing modules: {sorted(missing)}")
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
index = [
|
||||
"# P6 功能扩展任务索引",
|
||||
"",
|
||||
"> P3 gate 已完成的是源码盘点,不是 32 个工作台的 Web 实现。P6 按工作台建立独立任务包;每个包内部再拆为 A-G、X 首切片和 Y 完整出口。",
|
||||
"> 当前 32 个模块声明了 115 个用户动作;每个包先做一个首切片,其他动作必须继续拆独立合同,不能用首切片冒充完整对标。",
|
||||
"> 状态由 `docs/current/task-state.json` 统一维护;本索引和卡片是生成投影。",
|
||||
"> 机器可读文件清单和数量校验见 [`manifest.json`](manifest.json)。",
|
||||
"> 矩阵更新后依次运行生成器、`sync_web_task_state.py` 和 `validate_web_context.py`;不要手改生成结构。",
|
||||
"",
|
||||
"## 共享前置",
|
||||
"",
|
||||
"| 编号 | 合同 | 产物 |",
|
||||
"|---|---|---|",
|
||||
"| [FW-P6-000](../FW-P6-000.md) | 锁定源码、矩阵、构建和 Chrome 环境 | `docs/p6/baseline.json` |",
|
||||
"| [FW-P6-001](../FW-P6-001.md) | 模块初始化、类型注册和依赖错误 | `docs/p6/module-loader.json` |",
|
||||
"| [FW-P6-002](../FW-P6-002.md) | Worker/Facade 通用消息 envelope | `docs/p6/facade-envelope.json` |",
|
||||
"| [FW-P6-003](../FW-P6-003.md) | Chrome 回放 harness 和证据格式 | `docs/p6/chrome-harness.json` |",
|
||||
"",
|
||||
"## 工作台任务包",
|
||||
"",
|
||||
"| 包 | 模块 | 模块状态 | 首个动作 | 全部动作 | 对象 | 格式 | Python API | 直接前置 |",
|
||||
"|---|---|---|---|---|---:|---|---:|---|",
|
||||
]
|
||||
for module in MODULE_IDS:
|
||||
row = rows[module]
|
||||
code = MODULE_IDS[module]
|
||||
index.append(
|
||||
f"| [FW-P6-{code}](FW-P6-{slug(module)}.md) | `{module}` | "
|
||||
f"`{module_status(module, row.get('web_status', 'pending'))}` | `{PRIMARY_ACTION[module]}` | "
|
||||
f"{', '.join(row['user_actions'])} | {row['object_type_count']} | "
|
||||
f"{', '.join('`'+x+'`' for x in row['format_extensions']) or '-'} | "
|
||||
f"{row['python_api_count']} | `FW-P6-000`, `001`, `002`, `003` |"
|
||||
)
|
||||
index += [
|
||||
"",
|
||||
"## 原子步骤语义",
|
||||
"",
|
||||
"| 步骤 | 单一合同 | 不读取的内容 |",
|
||||
"|---|---|---|",
|
||||
"| A | 源码边界探针 | 其他模块实现、浏览器日志 |",
|
||||
"| B | WASM 初始化和类型注册 | 主要动作、UI |",
|
||||
"| C | 一个主要内核动作 | 第二个动作、全量对象 |",
|
||||
"| D | 重算/非法输入/恢复 | 并发和性能 |",
|
||||
"| E | Worker/Facade 消息 | 完整 UI 和插件 |",
|
||||
"| F | Chrome 用户动作 | 非 Chrome 浏览器 |",
|
||||
"| G | FCStd round-trip 或适用边界 | 跨版本迁移 |",
|
||||
"| X | 首切片 gate | 其他模块和发布 gate |",
|
||||
"| Y | 完整动作 gate | 其他模块和发布 gate |",
|
||||
"",
|
||||
"失败恢复卡使用同一包内的 `R` 后缀,例如 `FW-P6-PRT-C-R1`;恢复卡只记录首个错误、最小修复和重放命令,不复制原卡全文。",
|
||||
]
|
||||
write_generated(OUT / "INDEX.md", "\n".join(index))
|
||||
for module, row in rows.items():
|
||||
module_slug = slug(module)
|
||||
write_generated(OUT / f"FW-P6-{module_slug}.md", module_index(module, row))
|
||||
module_dir = OUT / module_slug
|
||||
module_dir.mkdir(parents=True, exist_ok=True)
|
||||
for letter in "ABCDEFGXY":
|
||||
write_generated(
|
||||
module_dir / f"FW-P6-{MODULE_IDS[module]}-{letter}.md",
|
||||
atomic_card(module, row, letter),
|
||||
)
|
||||
for action_number, action_name in enumerate(row.get("user_actions", []), start=1):
|
||||
if action_name == PRIMARY_ACTION[module]:
|
||||
continue
|
||||
write_generated(
|
||||
module_dir / f"FW-P6-{MODULE_IDS[module]}-ACT-{action_number:02d}.md",
|
||||
action_card(module, action_name, action_number),
|
||||
)
|
||||
for letter in "CDEFG":
|
||||
write_generated(
|
||||
module_dir / f"FW-P6-{MODULE_IDS[module]}-ACT-{action_number:02d}-{letter}.md",
|
||||
action_child_card(module, action_name, action_number, letter),
|
||||
)
|
||||
files = sorted(str(path.relative_to(ROOT)) for path in OUT.rglob("*.md"))
|
||||
manifest = {
|
||||
"schema": "freecad-web-p6-task-packet-manifest/v1",
|
||||
"source_matrix": str(MATRIX.relative_to(ROOT)),
|
||||
"source_matrix_sha256": hashlib.sha256(MATRIX.read_bytes()).hexdigest(),
|
||||
"module_count": len(rows),
|
||||
"declared_action_count": sum(len(row.get("user_actions", [])) for row in rows.values()),
|
||||
"module_index_count": len(rows),
|
||||
"atomic_card_count": len(rows) * 9,
|
||||
"action_split_card_count": sum(
|
||||
len([action for action in row.get("user_actions", []) if action != PRIMARY_ACTION[module]])
|
||||
for module, row in rows.items()
|
||||
),
|
||||
"action_child_card_count": sum(
|
||||
5 * len([action for action in row.get("user_actions", []) if action != PRIMARY_ACTION[module]])
|
||||
for module, row in rows.items()
|
||||
),
|
||||
"markdown_file_count": len(files),
|
||||
"files": files,
|
||||
"shared_prerequisites": [
|
||||
"docs/tasks/FW-P6-000.md",
|
||||
"docs/tasks/FW-P6-001.md",
|
||||
"docs/tasks/FW-P6-002.md",
|
||||
"docs/tasks/FW-P6-003.md",
|
||||
],
|
||||
}
|
||||
(OUT / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
319
tools/inventory_desktop_ui_parity.py
Normal file
319
tools/inventory_desktop_ui_parity.py
Normal file
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inventory desktop UI surfaces and group Web parity work by shared owners.
|
||||
|
||||
This is a source inventory, not a validation or acceptance check. It records
|
||||
the existing desktop GUI anchors, Web mounted surfaces, policy gap counts and
|
||||
the native build targets that can own a package. The output is deliberately
|
||||
separate from module-batch-manifest.json, whose status and selection belong to
|
||||
the outer scheduler planner.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from policy_io import atomic_write
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DOCS = ROOT / "docs/current"
|
||||
SOURCE = ROOT / "freecad-source/src/Mod"
|
||||
WEB = ROOT / "web/src"
|
||||
POLICY = DOCS / "execution-policy.json"
|
||||
OUT_JSON = DOCS / "desktop-ui-parity-inventory.json"
|
||||
OUT_MD = DOCS / "DESKTOP_UI_PARITY_PACKAGE_PLAN_20260922.md"
|
||||
|
||||
MODULES = [
|
||||
"Part", "PartDesign", "Sketcher", "Spreadsheet", "TechDraw", "Surface",
|
||||
"Draft", "Mesh", "MeshPart", "BIM", "Fem", "CAM", "Assembly", "Measure",
|
||||
"Material", "Points", "Robot", "ReverseEngineering", "Inspection",
|
||||
"Import", "Cloud", "JtReader", "Start", "Help", "Plot", "Show", "Sandbox",
|
||||
"TemplatePyMod", "Test", "Tux", "Web",
|
||||
]
|
||||
|
||||
TARGET_RE = re.compile(r"FreeCADWeb[A-Za-z0-9_]+Probe")
|
||||
COMMAND_RE = re.compile(r"\b(?:Cmd|Command)[A-Za-z0-9_]+")
|
||||
|
||||
|
||||
def read(path: Path) -> str:
|
||||
try:
|
||||
return path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def files(directory: Path, suffix: str | None = None) -> list[str]:
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
values = [str(p.relative_to(ROOT)) for p in directory.rglob("*") if p.is_file()]
|
||||
if suffix:
|
||||
values = [value for value in values if value.endswith(suffix)]
|
||||
return sorted(values)
|
||||
|
||||
|
||||
def web_files(module: str) -> list[str]:
|
||||
aliases = {
|
||||
"PartDesign": "partdesign-", "TechDraw": "techdraw-", "MeshPart": "meshpart-",
|
||||
"ReverseEngineering": "reverseengineering-",
|
||||
"TemplatePyMod": "templatepymod-",
|
||||
}
|
||||
prefix = aliases.get(module, module.lower() + "-")
|
||||
return sorted(str(path.relative_to(ROOT)) for path in WEB.glob(f"{prefix}*") if path.is_file())
|
||||
|
||||
|
||||
def command_source(module: str) -> list[str]:
|
||||
return desktop_sources(module)["commandSources"]
|
||||
|
||||
|
||||
def desktop_sources(module: str) -> dict:
|
||||
# Python workbenches put panels/commands outside Gui; Web also owns the
|
||||
# application-wide C++ GUI. A missing Gui directory is not missing UI.
|
||||
roots = [SOURCE / module]
|
||||
if module == "Web":
|
||||
roots.append(ROOT / "freecad-source/src/Gui")
|
||||
paths = sorted({name for root in roots for name in files(root)
|
||||
if Path(name).suffix in {".cpp", ".h", ".py", ".ui"}
|
||||
and not any(part.lower() in {"tests", "test", "resources", "__pycache__"}
|
||||
for part in Path(name).parts[5:-1])})
|
||||
# Designer UI files intentionally include Resources/panels/preferences.
|
||||
ui_files = sorted({name for root in roots for name in files(root, ".ui")})
|
||||
commands, workbenches, panels, properties, preferences = [], [], [], [], []
|
||||
for name in paths:
|
||||
path = Path(name)
|
||||
lower = path.name.lower()
|
||||
if path.suffix == ".py":
|
||||
text = read(ROOT / name)
|
||||
if re.search(r"\b(?:addCommand|addWorkbench|appendMenu|appendToolbar|appendContextMenu)\s*\(", text):
|
||||
commands.append(name)
|
||||
if lower == "initgui.py" or re.search(r"\b(?:appendMenu|appendToolbar)\s*\(", text):
|
||||
workbenches.append(name)
|
||||
if "task" in lower or "panel" in lower or re.search(r"\b(?:showDialog|QDialog)\s*\(", text):
|
||||
panels.append(name)
|
||||
if "viewprovider" in lower or "property" in lower:
|
||||
properties.append(name)
|
||||
if "pref" in lower or re.search(r"\baddPreferencePage\s*\(", text):
|
||||
preferences.append(name)
|
||||
elif path.suffix in {".cpp", ".h"} and ("Gui" in path.parts or module == "Web"):
|
||||
if lower.startswith("command") or lower.endswith("workbench.cpp"):
|
||||
commands.append(name)
|
||||
if lower.endswith("workbench.cpp"):
|
||||
workbenches.append(name)
|
||||
if lower.startswith(("task", "dlg")) or "dialog" in lower:
|
||||
panels.append(name)
|
||||
if lower.startswith(("property", "viewprovider")):
|
||||
properties.append(name)
|
||||
if "settings" in lower or "pref" in lower:
|
||||
preferences.append(name)
|
||||
return {"sourceRoots": [str(root.relative_to(ROOT)) for root in roots if root.is_dir()],
|
||||
"commandSources": commands, "workbenchSources": workbenches,
|
||||
"taskAndDialogUi": ui_files, "taskAndDialogSources": panels,
|
||||
"propertyAndViewSources": properties, "preferenceSources": preferences}
|
||||
|
||||
|
||||
def native_targets(module: str, cmake_text: str) -> list[str]:
|
||||
if module == "Web":
|
||||
return sorted(set(TARGET_RE.findall(cmake_text)) & {
|
||||
"FreeCADWebWebRuntimeProbe", "FreeCADWebDocumentProbe", "FreeCADWebWorkbenchCommandProbe"})
|
||||
if module == "Part":
|
||||
return sorted(name for name in set(TARGET_RE.findall(cmake_text))
|
||||
if re.fullmatch(r"FreeCADWeb(?:Part(?:Box|DesktopCommand|GeometryFamily|Io)|Document)Probe", name))
|
||||
aliases = {"Fem": "Fem", "PartDesign": "PartDesign",
|
||||
"MeshPart": "MeshPart", "TechDraw": "TechDraw", "ReverseEngineering": "ReverseEngineering",
|
||||
"Assembly": "Assembly"}
|
||||
needle = aliases.get(module, module)
|
||||
return sorted({name for name in TARGET_RE.findall(cmake_text) if needle.lower() in name.lower()})
|
||||
|
||||
|
||||
def package_for(module: str) -> str:
|
||||
if module in {"Part", "PartDesign", "Sketcher"}:
|
||||
return "ui-primary-modeling-workspace"
|
||||
if module in {"Spreadsheet", "TechDraw"}:
|
||||
return "ui-document-editors-output"
|
||||
if module in {"Mesh", "MeshPart", "Surface", "Draft"}:
|
||||
return "ui-geometry-workbench-tasks"
|
||||
if module in {"BIM", "Fem", "CAM", "Assembly"}:
|
||||
return "ui-domain-workbench-tasks"
|
||||
if module in {"Material", "Measure", "Points", "Robot", "ReverseEngineering", "Inspection"}:
|
||||
return "ui-analysis-and-inspection-tasks"
|
||||
return "ui-shell-preferences-and-utility"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
cmake = read(ROOT / "freecad-source/src/WebAssembly/FreeCADCoreProbe/CMakeLists.txt")
|
||||
try:
|
||||
policy = json.loads(POLICY.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
policy = {}
|
||||
gaps = policy.get("confirmedGapRepairs", []) if isinstance(policy, dict) else []
|
||||
gap_counts: dict[str, dict[str, int]] = {}
|
||||
for row in gaps:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
module = str(row.get("module") or "")
|
||||
if not module:
|
||||
continue
|
||||
status = str(row.get("status") or "open")
|
||||
gap_counts.setdefault(module, {})[status] = gap_counts.setdefault(module, {}).get(status, 0) + 1
|
||||
|
||||
shared_sources = [
|
||||
"web/src/project-shell.tsx", "web/src/workbench-shell.tsx",
|
||||
"web/src/desktop-command-dispatcher.ts", "web/src/persistent-toolbar-workspace.tsx",
|
||||
"web/src/web-desktop-adapter.ts", "web/src/css.ts",
|
||||
]
|
||||
inventory = []
|
||||
for module in MODULES:
|
||||
gui = SOURCE / module / "Gui"
|
||||
desktop = desktop_sources(module)
|
||||
ui_files = desktop["taskAndDialogUi"]
|
||||
command_files = desktop["commandSources"]
|
||||
command_text = "\n".join(read(ROOT / path) for path in command_files)
|
||||
web_owned = web_files(module)
|
||||
task_files = [path for path in web_owned if path.endswith("-task.tsx") or path.endswith("-task.ts")]
|
||||
adapter_files = [path for path in web_owned if "adapter" in Path(path).name or "facade" in Path(path).name]
|
||||
imports = []
|
||||
for host in ("web/src/project-shell.tsx", "web/src/workbench-shell.tsx", "web/src/partdesign-workspace-component.tsx"):
|
||||
for line, text in enumerate(read(ROOT / host).splitlines(), 1):
|
||||
if "import" in text and any(Path(name).stem in text for name in web_owned if name.endswith(".tsx")):
|
||||
imports.append({"path": host, "line": line, "source": text.strip()})
|
||||
inventory.append({
|
||||
"module": module,
|
||||
"package": package_for(module),
|
||||
"desktop": {
|
||||
**desktop,
|
||||
"guiDirectory": str(gui.relative_to(ROOT)),
|
||||
"guiDirectoryExists": gui.is_dir(),
|
||||
"commandSymbolCount": len(set(COMMAND_RE.findall(command_text))),
|
||||
"countMeaning": "Source search symbols only; not command coverage or completion",
|
||||
},
|
||||
"web": {
|
||||
"ownedFiles": web_owned,
|
||||
"taskPanels": task_files,
|
||||
"adaptersAndFacades": adapter_files,
|
||||
"candidateSharedShells": [path for path in shared_sources if (ROOT / path).is_file()],
|
||||
"componentImportAnchors": imports,
|
||||
"importMeaning": "Imports locate code; imports do not prove mounted or usable routes",
|
||||
},
|
||||
"nativeBuildTargets": native_targets(module, cmake),
|
||||
"gapStatusCounts": gap_counts.get(module, {}),
|
||||
"uiCoverage": {area: "source_indexed_not_compared" for area in (
|
||||
"menus", "toolbars_buttons", "tasks_control_panels", "properties",
|
||||
"dialogs_preferences", "context_menus", "status_feedback", "shortcuts_focus_styles")},
|
||||
"retainedGapKeys": [row.get("key") for row in gaps if row.get("module") == module],
|
||||
"registration": {
|
||||
"sourceGapLedger": "docs/current/execution-policy.json:confirmedGapRepairs[]",
|
||||
"discoveryRecords": "docs/current/operator-gap-discovery/run-*.json",
|
||||
"implementationRecord": "docs/current/operator-gap-<key>-implementation.json or README.md",
|
||||
"statusRule": "implemented_unvalidated; validation remains disabled",
|
||||
},
|
||||
})
|
||||
|
||||
packages = [
|
||||
{
|
||||
"id": "ui-shell-preferences-and-utility",
|
||||
"modules": [m["module"] for m in inventory if m["package"] == "ui-shell-preferences-and-utility"],
|
||||
"sharedFrontendOwners": ["project-shell.tsx", "workbench-shell.tsx", "persistent-toolbar-workspace.tsx", "web-desktop-adapter.ts"],
|
||||
"nativeTargets": ["FreeCADWebDocumentProbe", "FreeCADWebWorkbenchCommandProbe"],
|
||||
"surfaceScope": ["application menus", "workbench selector", "toolbar layout", "status/error feedback", "preferences/dialog host", "context menu host"],
|
||||
"buildScope": "frontend Vite bundle once; native target only when shared owner or command registry changes",
|
||||
},
|
||||
{
|
||||
"id": "ui-primary-modeling-workspace",
|
||||
"modules": ["Part", "PartDesign", "Sketcher"],
|
||||
"sharedFrontendOwners": ["project-shell.tsx", "partdesign-workspace-component.tsx", "workbench-shell.tsx", "desktop-command-dispatcher.ts"],
|
||||
"nativeTargets": ["FreeCADWebDocumentProbe", "FreeCADWebPartBoxProbe", "FreeCADWebPartDesignRuntimeProbe", "FreeCADWebSketcherProbe", "FreeCADWebPartDesktopCommandProbe"],
|
||||
"surfaceScope": ["modeling menus/toolbars", "shared task panels", "tree/property pages", "selection and viewport handoff", "accept/cancel/history"],
|
||||
"buildScope": "group changed native owners by configured tree; one -j8 build per affected tree, then one frontend build",
|
||||
},
|
||||
{
|
||||
"id": "ui-document-editors-output",
|
||||
"modules": ["Spreadsheet", "TechDraw"],
|
||||
"sharedFrontendOwners": ["spreadsheet-sheet-editor.tsx", "project-shell.tsx", "workbench-shell.tsx", "web-print-adapter.ts"],
|
||||
"nativeTargets": ["FreeCADWebSpreadsheetRuntimeProbe", "FreeCADWebTechDrawRuntimeProbe", "FreeCADWebDocumentProbe"],
|
||||
"surfaceScope": ["sheet/page menus", "table/page task panels", "cell/page property dialogs", "print/export/preview", "context actions"],
|
||||
"buildScope": "reuse current retained owners; build only changed Spreadsheet/TechDraw targets and one frontend bundle",
|
||||
},
|
||||
{
|
||||
"id": "ui-geometry-workbench-tasks",
|
||||
"modules": ["Mesh", "MeshPart", "Surface", "Draft"],
|
||||
"sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"],
|
||||
"nativeTargets": ["FreeCADWebMeshRuntimeProbe", "FreeCADWebMeshPartRuntimeProbe", "FreeCADWebSurfaceRuntimeProbe", "FreeCADWebDraftRuntimeProbe"],
|
||||
"surfaceScope": ["workbench menus/toolbars", "geometry task dialogs", "property editors", "selection filters", "preview/apply/cancel feedback"],
|
||||
"buildScope": "one target build per changed native owner; shared Web route and frontend build once",
|
||||
},
|
||||
{
|
||||
"id": "ui-domain-workbench-tasks",
|
||||
"modules": ["BIM", "Fem", "CAM", "Assembly"],
|
||||
"sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"],
|
||||
"nativeTargets": ["FreeCADWebBimRuntimeProbe", "FreeCADWebFemGenericFamilyProbe", "FreeCADWebCAMProbe", "FreeCADWebAssemblyProbe", "FreeCADWebAssemblyKernelProbe"],
|
||||
"surfaceScope": ["domain menus/toolbars", "task panels", "property/preferences dialogs", "context menus", "job/progress/status feedback"],
|
||||
"buildScope": "group native changes by actual configured owner target; no unrelated module rebuild",
|
||||
},
|
||||
{
|
||||
"id": "ui-analysis-and-inspection-tasks",
|
||||
"modules": ["Material", "Measure", "Points", "Robot", "ReverseEngineering", "Inspection"],
|
||||
"sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"],
|
||||
"nativeTargets": ["FreeCADWebMaterialRuntimeProbe", "FreeCADWebMeasureRuntimeProbe", "FreeCADWebPointsRuntimeProbe", "FreeCADWebRobotRuntimeProbe", "FreeCADWebReverseEngineeringRuntimeProbe", "FreeCADWebInspectionRuntimeProbe"],
|
||||
"surfaceScope": ["command menus", "selection/property dialogs", "task panels", "result/status presentation", "cancel/recovery semantics"],
|
||||
"buildScope": "shared frontend bundle; build only native targets whose source owner changed",
|
||||
},
|
||||
]
|
||||
result = {
|
||||
"schema": "freecad-web-desktop-ui-parity-inventory/v1",
|
||||
"generatedAt": datetime.now(timezone.utc).isoformat(),
|
||||
"mode": "source-inventory-no-validation",
|
||||
"coverageMeaning": "Source index only. Eight UI surfaces per module remain explicitly unassessed by this index. Reuse keyed implementation records; do not re-open completed work solely for missing comparisons.",
|
||||
"buildTargetMeaning": "Candidate targets only, never a build list. Resolve changed file consumers and published build trees in web/tools/sync-assets.mjs before necessary native -j8 builds.",
|
||||
"objective": "Desktop UI parity packages grouped by shared workbench owners and native build targets",
|
||||
"registration": {
|
||||
"policy": "docs/current/execution-policy.json",
|
||||
"confirmedGapKey": "operator-gap-<concrete-ui-gap>",
|
||||
"packageRecord": "docs/current/desktop-ui-parity-package-records.json",
|
||||
"implementationStatus": "implemented_unvalidated",
|
||||
},
|
||||
"sharedFrontendOwners": shared_sources,
|
||||
"packages": packages,
|
||||
"modules": inventory,
|
||||
}
|
||||
atomic_write(OUT_JSON, result)
|
||||
|
||||
lines = [
|
||||
"# 桌面 UI 对标包计划(2026-09-22)",
|
||||
"",
|
||||
"本文件是源码盘点和分包基线,不是验证报告。调度器继续保持单一实例;`module-batch-manifest.json` 的状态、选择和批次 ID 仍由外层规划器维护。",
|
||||
"主线:桌面 FreeCAD UI → Web FreeCAD UI 完全功能与样式对标。覆盖 C++ GUI、Python InitGui/命令/任务面板、Designer .ui 和应用公共 GUI。文件存在、import、命令符号和构建成功均不代表入口已挂载或整模块已对标。",
|
||||
"每模块保留菜单、工具栏按钮、任务/控制面板、属性页、对话框/偏好、右键菜单、状态反馈、快捷键/焦点/样式八类覆盖状态;未比较项不自动制造缺口,只沿具体源码路由查缺。六个大类是索引目录,实际实施包仍按共享文档所有者/适配器/构建目标聚合。",
|
||||
"",
|
||||
"## 统一路由骨架",
|
||||
"",
|
||||
"每个包都沿用:桌面 `Workbench.cpp/Command.cpp` 注册 → Web `project-shell.tsx` 或 `workbench-shell.tsx` 菜单/工具栏 → React 任务面板、属性页或对话框 → `DesktopCommandDispatcher` 与模块 adapter/facade → 原生 Document owner/WASM → 树、视口、状态栏和历史反馈。",
|
||||
"",
|
||||
"共享前端所有者:`project-shell.tsx`、`workbench-shell.tsx`、`persistent-toolbar-workspace.tsx`、`desktop-command-dispatcher.ts`、`web-desktop-adapter.ts`。",
|
||||
"",
|
||||
"## 分包",
|
||||
"",
|
||||
]
|
||||
for package in packages:
|
||||
lines.extend([
|
||||
f"### `{package['id']}`",
|
||||
f"模块:{', '.join(package['modules'])}",
|
||||
f"构建目标:{', '.join(package['nativeTargets'])}",
|
||||
f"对标面:{ '、'.join(package['surfaceScope']) }。",
|
||||
f"接续规则:{package['buildScope']}。",
|
||||
"",
|
||||
])
|
||||
lines.extend([
|
||||
"## 缺口登记方式",
|
||||
"",
|
||||
"具体缺口仍登记在 `docs/current/execution-policy.json` 的 `confirmedGapRepairs[]`,每条必须有桌面源码锚点、Web 路由入口、原生 owner、对标范围、具体剩余限制和实现记录。多个同一工作台/构建目标的缺口使用同一个 `functionalPackage`,在一个回合集中修改;不要为单个按钮单独创建包。",
|
||||
"",
|
||||
"状态只使用 `open`、`implemented_unvalidated` 或真实阻塞状态;不运行测试、烟测、浏览器检查、截图、验收或独立类型检查。必要构建仅使用受影响目标和原生 `-j8`,前端使用现有 Vite 配置。",
|
||||
"",
|
||||
"详细机器可读盘点见 [`desktop-ui-parity-inventory.json`](desktop-ui-parity-inventory.json)。包状态见 [`desktop-ui-parity-package-records.json`](desktop-ui-parity-package-records.json)。",
|
||||
])
|
||||
OUT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"inventory": str(OUT_JSON.relative_to(ROOT)), "plan": str(OUT_MD.relative_to(ROOT)), "modules": len(inventory), "packages": len(packages)}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
100
tools/module-support-combined-business-cases.mjs
Normal file
100
tools/module-support-combined-business-cases.mjs
Normal file
@@ -0,0 +1,100 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = process.cwd();
|
||||
const ids = JSON.parse(process.env.FREECAD_BUSINESS_IDS || '[]');
|
||||
const groups = new Map();
|
||||
const add = (script, selected) => {
|
||||
if (!selected.length) return;
|
||||
const output = execFileSync(process.execPath, [`tools/${script}`], {
|
||||
cwd: root,
|
||||
env: { ...process.env, FREECAD_BUSINESS_IDS: JSON.stringify(selected) },
|
||||
encoding: 'utf8',
|
||||
});
|
||||
const report = JSON.parse(output);
|
||||
for (const result of report.results || []) groups.set(result.capabilityId, result);
|
||||
}
|
||||
const support = {
|
||||
Assembly: new Set(['Assembly:assembly.inspectPythonApi', 'Assembly:assembly.inspectSourceInventory', 'Assembly:assembly.nativeTypeProbe', 'Assembly:assembly.pythonFamily']),
|
||||
BIM: new Set(['BIM:bim.inspectPythonApi', 'BIM:bim.inspectSourceInventory', 'BIM:bim.nativeProbe', 'BIM:bim.pythonFamily', 'BIM:bim.pythonFamilyBatch']),
|
||||
Mesh: new Set(['Mesh:mesh.inspectSourceInventory', 'Mesh:mesh.pythonApi', 'Mesh:mesh.pythonFamilyBatch']),
|
||||
Points: new Set(['Points:points.inspectSource', 'Points:points.pythonApi', 'Points:points.pythonFamilyBatch']),
|
||||
TemplatePyMod: new Set(['TemplatePyMod:templatepymod.inspectSourceInventory', 'TemplatePyMod:templatepymod.pythonApi', 'TemplatePyMod:templatepymod.pythonFamilyBatch']),
|
||||
Cloud: new Set(['Cloud:cloud.inspectSourceInventory', 'Cloud:cloud.inspectPythonApi', 'Cloud:cloud.pythonFamilyBatch']),
|
||||
Start: new Set(['Start:start.inspectSourceInventory', 'Start:start.pythonApi']),
|
||||
CAM: new Set(['CAM:cam.inspectPythonApi', 'CAM:cam.inspectSourceInventory', 'CAM:cam.pythonFamilyBatch']),
|
||||
Help: new Set(['Help:help.inspectSourceInventory', 'Help:help.pythonApi']),
|
||||
Plot: new Set(['Plot:plot.pythonApi', 'Plot:plot.pythonFamilyBatch']),
|
||||
Robot: new Set(['Robot:robot.inspectSourceInventory', 'Robot:robot.pythonApi', 'Robot:robot.pythonFamilyBatch']),
|
||||
Sandbox: new Set(['Sandbox:sandbox.inspectSourceInventory', 'Sandbox:sandbox.pythonApi', 'Sandbox:sandbox.pythonFamilyBatch']),
|
||||
Inspection: new Set(['Inspection:inspection.createRecompute', 'Inspection:inspection.inspectPythonApi', 'Inspection:inspection.inspectSourceInventory', 'Inspection:inspection.pythonFamilyBatch', 'Inspection:inspection.saveReopen']),
|
||||
Material: new Set(['Material:material.inspectSourceInventory', 'Material:material.pythonApi', 'Material:material.pythonFamilyBatch']),
|
||||
};
|
||||
const moduleOf = id => id.split(':', 1)[0];
|
||||
for (const module of Object.keys(support)) {
|
||||
const selected = ids.filter(id => support[module].has(id));
|
||||
const scripts = {
|
||||
Assembly: 'assembly-business-cases.mjs', BIM: 'bim-supporting-business-cases.mjs',
|
||||
Mesh: 'mesh-supporting-business-cases.mjs',
|
||||
Points: 'points-supporting-business-cases.mjs', TemplatePyMod: 'templatepymod-supporting-business-cases.mjs',
|
||||
Cloud: 'cloud-supporting-business-cases.mjs', Start: 'start-supporting-business-cases.mjs', CAM: 'cam-supporting-business-cases.mjs', Help: 'help-supporting-business-cases.mjs', Inspection: 'inspection-supporting-business-cases.mjs', Material: 'material-supporting-business-cases.mjs', Plot: 'plot-supporting-business-cases.mjs', Robot: 'robot-supporting-business-cases.mjs', Sandbox: 'sandbox-supporting-business-cases.mjs',
|
||||
};
|
||||
add(scripts[module], selected);
|
||||
}
|
||||
const aliasId = 'Start:Start:desktop:Start_Start';
|
||||
const rest = ids.filter(id => !groups.has(id) && id !== aliasId);
|
||||
const restBy = new Map();
|
||||
for (const id of rest) {
|
||||
const module = moduleOf(id);
|
||||
if (!restBy.has(module)) restBy.set(module, []);
|
||||
restBy.get(module).push(id);
|
||||
}
|
||||
for (const [module, selected] of restBy) {
|
||||
if (module === 'Fem' && selected.includes('Fem:fem.action')) {
|
||||
add('fem-action-business-cases.mjs', selected.filter(id => id === 'Fem:fem.action'));
|
||||
const remainingFem = selected.filter(id => id !== 'Fem:fem.action');
|
||||
if (!remainingFem.length) continue;
|
||||
selected.splice(0, selected.length, ...remainingFem);
|
||||
}
|
||||
if (module === 'Fem') {
|
||||
add('fem-business-cases.mjs', selected);
|
||||
continue;
|
||||
}
|
||||
let script;
|
||||
if (module === 'Assembly') script = selected.includes('Assembly:desktop:Separator') ? 'assembly-desktop-separator-v2.mjs' : 'assembly-business-cases.mjs';
|
||||
else if (module === 'BIM') script = 'bim-create-edit-business-cases.mjs';
|
||||
else if (module === 'Mesh') script = 'mesh-desktop-command-business-cases.mjs';
|
||||
else if (module === 'Points') script = selected.some(id => ['Points:points.createRecompute', 'Points:points.saveReopen', 'Points:points.desktopBatch', 'Points:desktop:Points_Merge', 'Points:desktop:Points_Structure', 'business-format:Points:export:.obj', 'business-format:Points:import:.ply', 'Points:desktop:Points_Import', 'Points:desktop:Points_Export'].includes(id)) ? 'points-business-cases.mjs' : 'points-document-business-cases.mjs';
|
||||
else if (module === 'TemplatePyMod') script = 'templatepymod-checkable-business-cases.mjs';
|
||||
else if (module === 'Cloud') script = selected.includes('Cloud:cloud.restore') ? 'cloud-restore-business-cases-v2.mjs' : 'cloud-save-business-cases.mjs';
|
||||
else if (module === 'Draft') script = selected.includes('Draft:draft.action') ? 'draft-action-business-cases.mjs' : 'draft-business-cases.mjs';
|
||||
else if (module === 'JtReader') script = 'jtreader-business-cases.mjs';
|
||||
else if (module === 'Start') script = 'start-business-cases.mjs';
|
||||
else if (module === 'CAM') script = 'cam-business-cases.mjs';
|
||||
else if (module === 'Material') script = 'material-business-cases.mjs';
|
||||
else if (module === 'Robot') script = 'robot-business-cases.mjs';
|
||||
else if (module === 'Sandbox') script = 'sandbox-business-cases.mjs';
|
||||
else if (module === 'Fem') script = selected.includes('Fem:fem.action') ? 'fem-action-business-cases.mjs' : 'fem-desktop-command-business-cases.mjs';
|
||||
else { continue; }
|
||||
add(script, selected);
|
||||
}
|
||||
// The duplicated Start requirement is an alias of the canonical matrix ID.
|
||||
if (ids.includes('Start:Start:desktop:Start_Start')) {
|
||||
const matrix = JSON.parse(fs.readFileSync(path.join(root, 'docs/p6/workbench-command-matrix.json'), 'utf8'));
|
||||
const find = value => {
|
||||
if (value && typeof value === 'object') {
|
||||
if (value.id === 'Start:desktop:Start_Start') return value;
|
||||
for (const child of Object.values(value)) { const found = find(child); if (found) return found; }
|
||||
}
|
||||
};
|
||||
const actual = find(matrix);
|
||||
groups.set('Start:Start:desktop:Start_Start', {
|
||||
capabilityId: 'Start:Start:desktop:Start_Start', status: actual?.disposition === 'restricted' ? 'passed' : 'failed',
|
||||
cases: [{ input: { evidence: 'docs/p6/workbench-command-matrix.json', canonicalId: 'Start:desktop:Start_Start' }, actual,
|
||||
assertions: [{ name: 'Start alias resolves to the canonical restricted command boundary', passed: actual?.disposition === 'restricted' }] }],
|
||||
});
|
||||
}
|
||||
const results = ids.map(id => groups.get(id) || { capabilityId: id, status: 'failed', cases: [], error: 'no route for selected business ID' });
|
||||
process.stdout.write(JSON.stringify({ schema: 'freecad-web-business-cases/v1', results }) + '\n');
|
||||
process.exitCode = results.length === ids.length && results.every(result => result.status === 'passed') ? 0 : 1;
|
||||
372
tools/part-circle-vertex-picking-business-cases.mjs
Normal file
372
tools/part-circle-vertex-picking-business-cases.mjs
Normal file
@@ -0,0 +1,372 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { playwright } from './part-primitive-business-cases.mjs';
|
||||
import { checkEdgeLocation } from './part-edge-location-business-cases.mjs';
|
||||
import { checkPrimitiveExpressions } from './part-primitive-expression-business-cases.mjs';
|
||||
|
||||
export const runPrimitiveExpressionCases = ids => runCircleVertexPickingCases(ids, true);
|
||||
|
||||
export async function runCircleVertexPickingCases(ids, expressionsOnly = false) {
|
||||
const capabilityId = 'Part:desktop:Part_Primitives';
|
||||
if (!ids.includes(capabilityId)) return [];
|
||||
const directory = path.resolve('docs/current/part-circle-vertex-picking-business', new Date().toISOString().replace(/[:.]/g, '-'));
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const result = { capabilityId, status: 'failed', cases: [], stages: [], evidenceFiles: {},
|
||||
remaining: [],
|
||||
deferredCases: ['runCircleThreePointCases', 'runCylinderSkewCases', 'runLegacyPrimitiveTaskCases', 'runAdditionalPrimitiveCases',
|
||||
'runWedgePrimitiveCases', 'runHelixSpiralCases', 'runPrimitivePlacementCases', 'runPrimitiveContainerCases'] };
|
||||
const stage = name => { result.stages.push({ name, at: new Date().toISOString() }); process.stderr.write(`Circle vertex picking: ${name}\n`); };
|
||||
const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
|
||||
const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
|
||||
const points = [[-10, 0, 0], [0, 0, 10], [10, 0, 0]];
|
||||
let browser;
|
||||
try {
|
||||
for (const file of ['tools/part-circle-vertex-picking-business-cases.mjs', 'tools/part-primitive-business-cases.mjs',
|
||||
'tools/part-edge-location-business-cases.mjs',
|
||||
'tools/part-primitive-expression-business-cases.mjs',
|
||||
'web/src/part-primitives-task.tsx', 'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts',
|
||||
'web/src/scene-viewport.tsx', 'web/src/workbench-shell.tsx',
|
||||
'freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp',
|
||||
...['js', 'wasm', 'worker.js'].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
|
||||
result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
stage('browser-native-load-enter');
|
||||
browser = await playwright().chromium.launch({ headless: process.env.HEADLESS !== "0", executablePath: process.env.FREECAD_CHROME ?? '/usr/bin/google-chrome',
|
||||
args: ['--no-sandbox', '--disable-dev-shm-usage'] });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const errors = []; page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? 'http://127.0.0.1:5180'}/workbench.html?module=Part&command=Part_Primitives&document=CirclePick`);
|
||||
const panel = page.locator('section[aria-label="Part primitives"]');
|
||||
const click = async name => {
|
||||
name = ({ 'Create primitive': 'Create', 'Apply primitive': 'OK' })[name] ?? name;
|
||||
await page.evaluate(() => { window.circlePickBefore = window.__freecadWorkbenchState?.response; });
|
||||
await panel.getByRole('button', { name, exact: true }).click();
|
||||
if (['New document', 'Primitives undo', 'Primitives redo'].includes(name))
|
||||
await panel.getByRole('button', { name: 'Read primitives document', exact: true }).click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response && window.__freecadWorkbenchState.response !== window.circlePickBefore);
|
||||
const reply = await page.evaluate(() => window.__freecadWorkbenchState.response);
|
||||
assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result;
|
||||
};
|
||||
await panel.getByLabel('Primitives document', { exact: true }).fill('CirclePick');
|
||||
await click('New document'); stage('browser-native-load-complete');
|
||||
stage('browser-primitive-expressions-enter');
|
||||
await checkPrimitiveExpressions({ page, panel, click, record, persist: expressionsOnly });
|
||||
stage('browser-primitive-expressions-complete');
|
||||
if (expressionsOnly) result.deferredCases.push('runCircleVertexPickingCases');
|
||||
if (!expressionsOnly) {
|
||||
stage('browser-edge-location-enter');
|
||||
await checkEdgeLocation({ page, panel, click, record, result, directory });
|
||||
stage('browser-edge-location-complete');
|
||||
for (let i = 0; i < points.length; ++i) {
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Vertex');
|
||||
await panel.getByLabel('Primitive object', { exact: true }).fill(`Point${i + 1}`);
|
||||
for (let axis = 0; axis < 3; ++axis)
|
||||
await panel.getByLabel(`Primitive ${['X', 'Y', 'Z'][axis]}`, { exact: true }).fill(String(points[i][axis]));
|
||||
const state = await click('Create');
|
||||
assert.deepEqual(state.objects.find(o => o.name === `Point${i + 1}`).primitivePoint, points[i]);
|
||||
}
|
||||
const before = await click('Read primitives document');
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle');
|
||||
await panel.getByLabel('Primitive object', { exact: true }).fill('PickedArc');
|
||||
await panel.getByLabel('Circle definition', { exact: true }).selectOption('points');
|
||||
const canvas = panel.locator('[aria-label="Primitives geometry"] canvas');
|
||||
// Project fixture vertices using the viewport's initial camera solely to locate mouse clicks.
|
||||
const pick = async (index, point) => {
|
||||
const button = panel.getByRole('button', { name: `Pick circle point ${index + 1} from a vertex`, exact: true });
|
||||
await button.click(); assert.equal(await button.getAttribute('aria-pressed'), 'true');
|
||||
await canvas.scrollIntoViewIfNeeded();
|
||||
const size = await canvas.boundingBox();
|
||||
const position = await page.evaluate(async ({ point, width, height }) => {
|
||||
const THREE = await import('/node_modules/three/build/three.module.js');
|
||||
const center = new THREE.Vector3(0, 0, 5), radius = Math.hypot(20, 0, 10);
|
||||
const camera = new THREE.PerspectiveCamera(45, width / height, radius / 10000, radius * 100);
|
||||
camera.up.set(0, 0, 1);
|
||||
camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7));
|
||||
camera.lookAt(center); camera.updateMatrixWorld();
|
||||
const projected = new THREE.Vector3(...point).project(camera);
|
||||
return [(projected.x + 1) * width / 2, (1 - projected.y) * height / 2];
|
||||
}, { point, width: size.width, height: size.height });
|
||||
await canvas.click({ position: { x: position[0], y: position[1] } });
|
||||
await page.waitForFunction(({ index, point }) => point.every((value, axis) =>
|
||||
Number(document.querySelector(`[aria-label="Circle point ${index + 1} ${['X', 'Y', 'Z'][axis]}"]`).value) === value), { index, point });
|
||||
assert.equal(await button.getAttribute('aria-pressed'), 'false');
|
||||
assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Circle');
|
||||
assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'PickedArc');
|
||||
};
|
||||
for (let index = 0; index < 3; ++index) await pick(index, points[index]);
|
||||
assert.deepEqual(await click('Read primitives document'), before);
|
||||
const created = await click('Create');
|
||||
const check = state => {
|
||||
const arc = state.objects.find(o => o.name === 'PickedArc');
|
||||
assert.equal(arc?.type, 'Part::Circle'); assert.equal(arc.topology.valid, true);
|
||||
assert.equal(arc.topology.Edge, 1); near(arc.parameters.Radius, 10);
|
||||
near(arc.parameters.Angle2 - arc.parameters.Angle1, 180);
|
||||
const line = arc.lines[0];
|
||||
line[0].forEach((value, axis) => near(value, points[0][axis]));
|
||||
line.at(-1).forEach((value, axis) => near(value, points[2][axis]));
|
||||
assert.ok(line.some(point => Math.abs(point[2] - 10) < 0.1));
|
||||
assert.deepEqual(state.objects.filter(o => o.name !== 'PickedArc'), before.objects);
|
||||
return arc;
|
||||
};
|
||||
check(created); assert.equal(created.undoCount, before.undoCount + 1);
|
||||
assert.deepEqual((await click('Primitives undo')).objects, before.objects);
|
||||
check(await click('Primitives redo'));
|
||||
record({ points, route: 'mounted viewport pointer events' }, { arc: check(created), undoCount: created.undoCount },
|
||||
'Three native vertices are picked without changing object/type or document; OCCT creates the oriented arc with expected radius/endpoints and atomic undo/redo');
|
||||
await panel.getByRole('button', { name: 'Pick circle point 1 from a vertex', exact: true }).click();
|
||||
const cancelled = await click('Cancel'); check(cancelled); assert.equal(cancelled.undoCount, created.undoCount);
|
||||
assert.equal(await panel.getByRole('button', { name: 'Pick circle point 1 from a vertex', exact: true }).getAttribute('aria-pressed'), 'false');
|
||||
await panel.getByRole('button', { name: 'Save primitives document', exact: true }).click();
|
||||
await panel.getByLabel('Saved primitives file').waitFor();
|
||||
const bytes = await page.evaluate(async () => {
|
||||
const { readDocumentFile } = await import('/src/storage.ts');
|
||||
return Array.from(new Uint8Array(await readDocumentFile('Primitives-CirclePick.FCStd')));
|
||||
});
|
||||
assert.ok(bytes.length > 0); await page.reload();
|
||||
await panel.getByLabel('Primitives document', { exact: true }).fill('CirclePick');
|
||||
await panel.getByLabel('Primitives FCStd file', { exact: true }).setInputFiles({ name: 'picked.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) });
|
||||
await panel.locator('[data-primitive-object="PickedArc"]').waitFor();
|
||||
check(await click('Read primitives document'));
|
||||
for (const [label, viewport] of [['desktop', { width: 1440, height: 1000 }], ['mobile', { width: 390, height: 844 }]]) {
|
||||
await page.setViewportSize(viewport);
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle');
|
||||
await panel.getByLabel('Primitive object', { exact: true }).fill('PickedArc');
|
||||
await panel.getByLabel('Circle definition', { exact: true }).selectOption('points');
|
||||
if (label === 'mobile') await pick(1, points[1]);
|
||||
const bounds = await panel.evaluate(node => ({ width: node.clientWidth, scroll: node.scrollWidth }));
|
||||
assert.ok(bounds.scroll <= bounds.width + 1);
|
||||
const png = await canvas.screenshot({ path: path.join(directory, `${label}-canvas.png`) });
|
||||
const colors = await page.evaluate(async encoded => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${encoded}`; await image.decode();
|
||||
const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
|
||||
const context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
|
||||
const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data, values = new Set();
|
||||
for (let index = 0; index < pixels.length; index += 4) values.add(`${pixels[index]},${pixels[index + 1]},${pixels[index + 2]}`);
|
||||
return values.size;
|
||||
}, png.toString('base64'));
|
||||
assert.ok(colors > 1, `Blank ${label} canvas`);
|
||||
const screenshot = path.join(directory, `${label}.png`); await page.screenshot({ path: screenshot, fullPage: true });
|
||||
result.evidenceFiles[screenshot] = createHash('sha256').update(fs.readFileSync(screenshot)).digest('hex');
|
||||
}
|
||||
record({ cancel: true, opfs: true, mobilePick: true }, { bytes: bytes.length },
|
||||
'Cancel disarms vertex picking without native mutation; OPFS FCStd reload retains geometry, and desktop/mobile canvases render with mobile vertex picking');
|
||||
stage('browser-surface-picking-enter');
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await panel.getByLabel('Primitives document', { exact: true }).fill('SurfacePick');
|
||||
await click('New document');
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Plane');
|
||||
await panel.getByLabel('Primitive Length', { exact: true }).fill('20');
|
||||
await panel.getByLabel('Primitive Width', { exact: true }).fill('20');
|
||||
await click('Create');
|
||||
const planeState = await click('Read primitives document');
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle');
|
||||
await panel.getByLabel('Primitive object', { exact: true }).fill('SurfaceArc');
|
||||
await panel.getByLabel('Circle definition', { exact: true }).selectOption('points');
|
||||
const surfacePoints = [[5, 10, 0], [10, 15, 0], [15, 10, 0]], picked = [];
|
||||
for (let index = 0; index < 3; ++index) {
|
||||
if (index === 1) await page.setViewportSize({ width: 390, height: 844 });
|
||||
if (index === 2) await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
const button = panel.getByRole('button', { name: `Pick circle point ${index + 1} on geometry`, exact: true });
|
||||
await button.click();
|
||||
await canvas.scrollIntoViewIfNeeded();
|
||||
const size = await canvas.boundingBox();
|
||||
const position = await page.evaluate(async ({ point, width, height }) => {
|
||||
const THREE = await import('/node_modules/three/build/three.module.js');
|
||||
const center = new THREE.Vector3(10, 10, 0), radius = Math.hypot(20, 20);
|
||||
const camera = new THREE.PerspectiveCamera(45, width / height, radius / 10000, radius * 100);
|
||||
camera.up.set(0, 0, 1);
|
||||
camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7));
|
||||
camera.lookAt(center); camera.updateMatrixWorld();
|
||||
const projected = new THREE.Vector3(...point).project(camera);
|
||||
return [(projected.x + 1) * width / 2, (1 - projected.y) * height / 2];
|
||||
}, { point: surfacePoints[index], width: size.width, height: size.height });
|
||||
await canvas.click({ position: { x: position[0], y: position[1] } });
|
||||
await page.waitForFunction(index => document.querySelector(`[aria-label="Pick circle point ${index + 1} on geometry"]`)
|
||||
?.getAttribute('aria-pressed') === 'false', index);
|
||||
const point = await Promise.all(['X', 'Y', 'Z'].map(async axis => Number(await panel.getByLabel(`Circle point ${index + 1} ${axis}`, { exact: true }).inputValue())));
|
||||
point.forEach((value, axis) => assert.ok(Math.abs(value - surfacePoints[index][axis]) < 0.1, JSON.stringify({ point, expected: surfacePoints[index] })));
|
||||
picked.push(point);
|
||||
assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'SurfaceArc');
|
||||
assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Circle');
|
||||
}
|
||||
assert.deepEqual(await click('Read primitives document'), planeState);
|
||||
const surfaceState = await click('Create');
|
||||
const surfaceArc = surfaceState.objects.find(o => o.name === 'SurfaceArc');
|
||||
assert.equal(surfaceArc.type, 'Part::Circle'); assert.equal(surfaceArc.topology.valid, true);
|
||||
assert.equal(surfaceArc.topology.Edge, 1); assert.ok(Math.abs(surfaceArc.parameters.Radius - 5) < 0.1);
|
||||
surfaceArc.lines[0][0].forEach((value, axis) => near(value, picked[0][axis]));
|
||||
surfaceArc.lines[0].at(-1).forEach((value, axis) => near(value, picked[2][axis]));
|
||||
assert.ok(surfaceArc.lines[0].some(point => Math.hypot(...point.map((value, axis) => value - picked[1][axis])) < 0.1));
|
||||
assert.equal(surfaceState.undoCount, planeState.undoCount + 1);
|
||||
assert.deepEqual((await click('Primitives undo')).objects, planeState.objects);
|
||||
assert.deepEqual((await click('Primitives redo')).objects, surfaceState.objects);
|
||||
const surfaceScreenshot = path.join(directory, 'surface-picking.png');
|
||||
await canvas.screenshot({ path: surfaceScreenshot });
|
||||
result.evidenceFiles[surfaceScreenshot] = createHash('sha256').update(fs.readFileSync(surfaceScreenshot)).digest('hex');
|
||||
record({ surfacePoints, route: 'mounted desktop/mobile surface pointer events' }, { picked, arc: surfaceArc },
|
||||
'Surface picks preserve the draft object and document; native OCCT creates an arc through the picked positions with analytic radius and atomic undo/redo');
|
||||
stage('browser-subelement-vertices-enter');
|
||||
await panel.getByLabel('Primitives document', { exact: true }).fill('SubelementPick');
|
||||
await click('New document');
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Plane');
|
||||
for (const field of ['Length', 'Width']) await panel.getByLabel(`Primitive ${field}`, { exact: true }).fill('20');
|
||||
await panel.getByLabel('Primitive position Z', { exact: true }).fill('4');
|
||||
await panel.getByLabel('Primitive axis X', { exact: true }).fill('1');
|
||||
await panel.getByLabel('Primitive axis Z', { exact: true }).fill('0');
|
||||
await panel.getByLabel('Primitive rotation angle', { exact: true }).fill('90');
|
||||
await click('Create');
|
||||
const vertexState = await click('Read primitives document');
|
||||
const plane = vertexState.objects.find(o => o.name === 'Plane');
|
||||
assert.equal(plane.topology.Vertex, 4); assert.equal(plane.vertices.length, 4);
|
||||
const corners = [[0, 0, 4], [20, 0, 4], [20, 0, 24], [0, 0, 24]];
|
||||
for (const corner of corners) assert.ok(plane.vertices.some(point => point.every((value, axis) => Math.abs(value - corner[axis]) < 1e-6)));
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle');
|
||||
await panel.getByLabel('Primitive object', { exact: true }).fill('CornerArc');
|
||||
await panel.getByLabel('Circle definition', { exact: true }).selectOption('points');
|
||||
const clickWorld = async (point, offset = 0) => {
|
||||
await canvas.scrollIntoViewIfNeeded(); const size = await canvas.boundingBox();
|
||||
const position = await page.evaluate(async ({ point, width, height }) => {
|
||||
const THREE = await import('/node_modules/three/build/three.module.js');
|
||||
const center = new THREE.Vector3(10, 0, 14), radius = Math.hypot(20, 20);
|
||||
const camera = new THREE.PerspectiveCamera(45, width / height, radius / 10000, radius * 100);
|
||||
camera.up.set(0, 0, 1);
|
||||
camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7));
|
||||
camera.lookAt(center); camera.updateMatrixWorld();
|
||||
const p = new THREE.Vector3(...point).project(camera);
|
||||
return [(p.x + 1) * width / 2, (1 - p.y) * height / 2];
|
||||
}, { point, width: size.width, height: size.height });
|
||||
await canvas.click({ position: { x: position[0] + offset, y: position[1] } });
|
||||
};
|
||||
for (let index = 0; index < 3; ++index) {
|
||||
await page.setViewportSize(index === 1 ? { width: 390, height: 844 } : { width: 1440, height: 1000 });
|
||||
const button = panel.getByRole('button', { name: `Pick circle point ${index + 1} from a vertex`, exact: true });
|
||||
await button.click();
|
||||
const beforePoint = await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Circle point ${index + 1} ${axis}`, { exact: true }).inputValue()));
|
||||
await clickWorld([10, 0, 14]);
|
||||
assert.equal(await button.getAttribute('aria-pressed'), 'true');
|
||||
assert.deepEqual(await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Circle point ${index + 1} ${axis}`, { exact: true }).inputValue())), beforePoint);
|
||||
await clickWorld(corners[index], 3);
|
||||
await page.waitForFunction(index => document.querySelector(`[aria-label="Pick circle point ${index + 1} from a vertex"]`)
|
||||
?.getAttribute('aria-pressed') === 'false', index);
|
||||
for (const [axis, label] of ['X', 'Y', 'Z'].entries()) near(Number(await panel.getByLabel(`Circle point ${index + 1} ${label}`, { exact: true }).inputValue()), corners[index][axis]);
|
||||
assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'CornerArc');
|
||||
assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Circle');
|
||||
}
|
||||
assert.deepEqual(await click('Read primitives document'), vertexState);
|
||||
const cornerState = await click('Create');
|
||||
const cornerArc = cornerState.objects.find(o => o.name === 'CornerArc');
|
||||
assert.equal(cornerArc.topology.valid, true); assert.equal(cornerArc.topology.Edge, 1);
|
||||
near(cornerArc.parameters.Radius, Math.sqrt(200)); near(cornerArc.parameters.Angle2 - cornerArc.parameters.Angle1, 180);
|
||||
cornerArc.lines[0][0].forEach((value, axis) => near(value, corners[0][axis]));
|
||||
cornerArc.lines[0].at(-1).forEach((value, axis) => near(value, corners[2][axis]));
|
||||
assert.equal(cornerState.undoCount, vertexState.undoCount + 1);
|
||||
assert.deepEqual((await click('Primitives undo')).objects, vertexState.objects);
|
||||
assert.deepEqual((await click('Primitives redo')).objects, cornerState.objects);
|
||||
const vertexScreenshot = path.join(directory, 'subelement-vertices.png');
|
||||
await canvas.screenshot({ path: vertexScreenshot });
|
||||
result.evidenceFiles[vertexScreenshot] = createHash('sha256').update(fs.readFileSync(vertexScreenshot)).digest('hex');
|
||||
record({ corners, placement: plane.primitivePlacement, pixelOffset: 3 }, { vertices: plane.vertices, arc: cornerArc },
|
||||
'Desktop/mobile clicks snap to exact transformed OCCT subelement vertices; face interiors cannot satisfy the vertex gate; native arc geometry and atomic history are preserved');
|
||||
stage('browser-subelement-vertices-complete');
|
||||
stage('browser-location-picking-enter');
|
||||
assert.deepEqual((await click('Primitives undo')).objects, vertexState.objects);
|
||||
const locationBaseline = await click('Read primitives document');
|
||||
await panel.getByLabel('Primitive type', { exact: true }).selectOption('Box');
|
||||
await panel.getByLabel('Primitive object', { exact: true }).fill('LocatedBox');
|
||||
for (const [field, value] of [['Length', 2], ['Width', 3], ['Height', 4]])
|
||||
await panel.getByLabel(`Primitive ${field}`, { exact: true }).fill(String(value));
|
||||
await panel.getByRole('button', { name: 'Reset primitive placement', exact: true }).click();
|
||||
await panel.getByLabel('Primitive rotation angle', { exact: true }).fill('90');
|
||||
const locationButton = panel.getByRole('button', { name: 'Pick primitive location', exact: true });
|
||||
const placementFields = async key => Promise.all(['X', 'Y', 'Z'].map(async axis =>
|
||||
Number(await panel.getByLabel(`Primitive ${key} ${axis}`, { exact: true }).inputValue())));
|
||||
await locationButton.click();
|
||||
let location;
|
||||
for (const [label, viewport, target] of [
|
||||
['desktop', { width: 1440, height: 1000 }, [5, 0, 10]],
|
||||
['mobile', { width: 390, height: 844 }, [15, 0, 20]],
|
||||
]) {
|
||||
await page.setViewportSize(viewport);
|
||||
await clickWorld(target);
|
||||
location = await placementFields('position');
|
||||
location.forEach((value, axis) => assert.ok(Math.abs(value - target[axis]) < 0.15));
|
||||
(await placementFields('axis')).forEach((value, axis) => near(value, [0, -1, 0][axis]));
|
||||
assert.equal(await panel.getByLabel('Primitive rotation angle', { exact: true }).inputValue(), '90');
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'true');
|
||||
assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'LocatedBox');
|
||||
assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Box');
|
||||
await canvas.click({ position: { x: 5, y: 5 } });
|
||||
assert.deepEqual(await placementFields('position'), location);
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'true');
|
||||
assert.deepEqual(await click('Read primitives document'), locationBaseline);
|
||||
const screenshot = path.join(directory, `location-${label}.png`);
|
||||
await page.screenshot({ path: screenshot, fullPage: true });
|
||||
result.evidenceFiles[screenshot] = createHash('sha256').update(fs.readFileSync(screenshot)).digest('hex');
|
||||
}
|
||||
for (const [viewport, corner] of [
|
||||
[{ width: 1440, height: 1000 }, corners[0]],
|
||||
[{ width: 390, height: 844 }, corners[2]],
|
||||
]) {
|
||||
await page.setViewportSize(viewport);
|
||||
for (const [axis, value] of [['X', 1], ['Y', 0], ['Z', 0]])
|
||||
await panel.getByLabel(`Primitive axis ${axis}`, { exact: true }).fill(String(value));
|
||||
await clickWorld(corner, 3);
|
||||
location = await placementFields('position');
|
||||
location.forEach((value, axis) => near(value, corner[axis]));
|
||||
(await placementFields('axis')).forEach((value, axis) => near(value, [0, -1, 0][axis]));
|
||||
assert.equal(await panel.getByLabel('Primitive rotation angle', { exact: true }).inputValue(), '90');
|
||||
assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'LocatedBox');
|
||||
assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Box');
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'true');
|
||||
assert.deepEqual(await click('Read primitives document'), locationBaseline);
|
||||
}
|
||||
record({ corners: [corners[0], corners[2]], pixelOffset: 3 }, { location, axis: await placementFields('axis') },
|
||||
'Desktop/mobile location picks snap to transformed native vertices and replace a stale draft axis with the rotated plane normal without changing draft identity, angle, native objects or history');
|
||||
await canvas.click({ button: 'right', position: { x: 5, y: 5 } });
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'false');
|
||||
assert.deepEqual(await placementFields('position'), location);
|
||||
await locationButton.click(); await page.keyboard.press('Escape');
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'false');
|
||||
await locationButton.click(); await locationButton.click();
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'false');
|
||||
await locationButton.click();
|
||||
assert.deepEqual(await click('Cancel'), locationBaseline);
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'false');
|
||||
assert.deepEqual(await placementFields('position'), [0, 0, 0]);
|
||||
// Cancel resets dimensions, so restore the independent analytic fixture.
|
||||
for (const [field, value] of [['Length', 2], ['Width', 3], ['Height', 4]])
|
||||
await panel.getByLabel(`Primitive ${field}`, { exact: true }).fill(String(value));
|
||||
await panel.getByLabel('Primitive rotation angle', { exact: true }).fill('90');
|
||||
await locationButton.click(); await clickWorld([15, 0, 20]);
|
||||
await clickWorld(corners[2], 3);
|
||||
location = await placementFields('position');
|
||||
const locatedState = await click('Create');
|
||||
const locatedBox = locatedState.objects.find(item => item.name === 'LocatedBox');
|
||||
assert.equal(await locationButton.getAttribute('aria-pressed'), 'false');
|
||||
assert.equal(locatedBox.type, 'Part::Box'); assert.equal(locatedBox.topology.valid, true);
|
||||
near(locatedBox.volume, 24);
|
||||
locatedBox.primitivePlacement.position.forEach((value, axis) => near(value, location[axis]));
|
||||
locatedBox.primitivePlacement.axis.forEach((value, axis) => near(value, [0, -1, 0][axis]));
|
||||
near(locatedBox.primitivePlacement.angle, 90);
|
||||
for (const [axis, offsets] of [[0, [-4, 0]], [1, [0, 3]], [2, [0, 2]]]) {
|
||||
near(Math.min(...locatedBox.vertices.map(point => point[axis])), location[axis] + offsets[0]);
|
||||
near(Math.max(...locatedBox.vertices.map(point => point[axis])), location[axis] + offsets[1]);
|
||||
}
|
||||
assert.deepEqual(locatedState.objects.filter(item => item.name !== 'LocatedBox'), locationBaseline.objects);
|
||||
assert.equal(locatedState.undoCount, locationBaseline.undoCount + 1);
|
||||
assert.deepEqual((await click('Primitives undo')).objects, locationBaseline.objects);
|
||||
assert.deepEqual((await click('Primitives redo')).objects, locatedState.objects);
|
||||
record({ targets: [[5, 0, 10], [15, 0, 20], corners[2]], angle: 90, dimensions: [2, 3, 4] }, { location, box: locatedBox },
|
||||
'Surface and planar vertex location picking copy world position and normal; misses and cancellation preserve native state; create at the native vertex yields analytic rotated OCCT vertices and atomic history');
|
||||
stage('browser-location-picking-complete');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
stage('browser-complete'); result.status = 'passed';
|
||||
} catch (error) { result.error = { code: 'circle_vertex_picking_failed', message: error.stack || String(error) }; }
|
||||
finally {
|
||||
if (browser) await browser.close(); stage('browser-cleanup-complete');
|
||||
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
|
||||
}
|
||||
return [result];
|
||||
}
|
||||
50
tools/part-desktop-alias-cases.mjs
Normal file
50
tools/part-desktop-alias-cases.mjs
Normal file
@@ -0,0 +1,50 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import { registerHooks } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import ts from "../web/node_modules/typescript/lib/typescript.js";
|
||||
|
||||
const hooks = registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
if (specifier.endsWith("?worker&url"))
|
||||
return { url: `data:text/javascript,export default ${JSON.stringify(specifier)}`, shortCircuit: true };
|
||||
if (specifier.startsWith(".") && specifier.endsWith(".js") && context.parentURL?.includes("/web/src/"))
|
||||
return next(specifier.slice(0, -3) + ".ts", context);
|
||||
return next(specifier, context);
|
||||
},
|
||||
load(url, context, next) {
|
||||
if (url.endsWith(".ts")) return { format: "module", shortCircuit: true,
|
||||
source: ts.transpileModule(fs.readFileSync(fileURLToPath(url), "utf8"), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
|
||||
}).outputText };
|
||||
return next(url, context);
|
||||
},
|
||||
});
|
||||
const { DesktopCommandDispatcher } = await import("../web/src/desktop-command-dispatcher.ts");
|
||||
const index = JSON.parse(fs.readFileSync("web/public/api/desktop-command-routes.json", "utf8"));
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => index });
|
||||
const calls = [];
|
||||
const dispatcher = new DesktopCommandDispatcher({ request: async (...args) => {
|
||||
calls.push(args);
|
||||
return { kind: "error", requestId: "native-boundary", error: { code: "test_boundary" } };
|
||||
} });
|
||||
for (const command of ["Part_CheckGeometry", "Part_Builder"]) {
|
||||
const record = { id: `Part:desktop:${command}`, module: "Part", command };
|
||||
for (const args of [{}, { activeTask: true }, { selection: [{ documentId: "Other", object: "Box" }] }]) {
|
||||
const response = await dispatcher.execute(record, args, "Current");
|
||||
assert.equal(response.kind, "error");
|
||||
assert.equal(response.error.code, "invalid_request");
|
||||
}
|
||||
assert.equal(calls.length, command === "Part_Builder" ? 1 : 0);
|
||||
const args = command === "Part_CheckGeometry"
|
||||
? { selection: [{ documentId: "Current", object: "Box" }] }
|
||||
: { points: [[0, 0, 0], [1, 0, 0], [0, 1, 0]] };
|
||||
await dispatcher.execute(record, args, "Current");
|
||||
const [module, route, payload, document] = calls.at(-1);
|
||||
assert.equal(module, "Part");
|
||||
assert.equal(route, "part.pythonFamilyBatch");
|
||||
assert.equal(document, "Current");
|
||||
assert.equal(payload.records[0].apiId, `Part:desktop:${command}`);
|
||||
}
|
||||
console.log("PASS: six invalid alias requests rejected before Worker dispatch; two valid requests preserve canonical Part routing. No native business acceptance claimed.");
|
||||
hooks.deregister();
|
||||
300
tools/part-projection-business-cases.mjs
Normal file
300
tools/part-projection-business-cases.mjs
Normal file
@@ -0,0 +1,300 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { loadWasmProbe } from './wasm-probe-runtime.mjs';
|
||||
import { playwright } from './part-primitive-business-cases.mjs';
|
||||
|
||||
export const projectionId = 'Part:desktop:Part_ProjectionOnSurface';
|
||||
export { runLinkedProjectionCases as runProjectionCases } from './part-linked-projection-business-cases.mjs';
|
||||
export async function runLegacyProjectionCases(ids) {
|
||||
if (!ids.includes(projectionId)) return [];
|
||||
const directory = path.resolve('docs/current/part-projection-business', new Date().toISOString().replace(/[:.]/g, '-'));
|
||||
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'part-projection-business-'));
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const result = { capabilityId: projectionId, status: 'failed', cases: [], stages: [], evidenceFiles: {} };
|
||||
const stage = name => { result.stages.push({ name, at: new Date().toISOString() }); process.stderr.write(`Projection: ${name}\n`); };
|
||||
const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
|
||||
const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
|
||||
let kernel, browser;
|
||||
try {
|
||||
for (const file of ['tools/part-projection-business-cases.mjs', 'web/src/part-projection-task.tsx',
|
||||
'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts', 'web/src/workbench-shell.tsx', 'web/src/scene-viewport.tsx',
|
||||
'freecad-source/src/WebAssembly/FreeCADCoreProbe/PartProjectionDocument.h',
|
||||
'freecad-source/src/Mod/Part/App/FeatureProjectOnSurface.cpp', 'freecad-source/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp',
|
||||
...['js', 'wasm', 'worker.js'].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
|
||||
result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
stage('adapter-compile-enter');
|
||||
execFileSync(path.resolve('web/node_modules/.bin/tsc'), ['--target', 'ES2022', '--module', 'ESNext', '--moduleResolution', 'Bundler',
|
||||
'--strict', '--skipLibCheck', '--jsx', 'preserve', '--outDir', temporary, 'web/node_modules/vite/client.d.ts', 'web/src/part-desktop-adapter.ts', 'web/src/part-view-facade.ts'], { stdio: 'pipe' });
|
||||
const facade = await import(pathToFileURL(path.join(temporary, 'part-document-facade.js')));
|
||||
const adapter = await import(pathToFileURL(path.join(temporary, 'part-desktop-adapter.js')));
|
||||
const { FacadeSerialQueue } = await import(pathToFileURL(path.join(temporary, 'facade-envelope.js')));
|
||||
stage('native-load-enter');
|
||||
({ kernel } = await loadWasmProbe(process.env.FREECAD_PART_DOCUMENT_BUSINESS_BUILD ?? 'web/public/kernel', 'FreeCADWebDocumentProbe'));
|
||||
stage('native-load-complete');
|
||||
const queue = new FacadeSerialQueue(); let sequence = 0;
|
||||
const router = { request: (_module, command, payload) => {
|
||||
assert.equal(command, facade.PART_DOCUMENT_COMMAND);
|
||||
return facade.dispatchPartDocument(queue, facade.createPartDocumentRequest(`projection-${++sequence}`, payload), kernel);
|
||||
} };
|
||||
const document = 'ProjectionBusiness';
|
||||
const request = (action, args = {}, owner = document) => router.request('Part', facade.PART_DOCUMENT_COMMAND, {
|
||||
schema: facade.PART_DOCUMENT_SCHEMA, module: 'Part', document: owner, action, builderInfo: true, includeMesh: true, ...args });
|
||||
const call = async (action, args = {}, owner = document) => {
|
||||
const reply = await request(action, args, owner); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result;
|
||||
};
|
||||
const python = source => {
|
||||
const reply = JSON.parse(kernel.ccall('fc_web_dispatch_json', 'string', ['string'], [JSON.stringify({ cmd: 'part.documentViewCommand', args: {
|
||||
owner: 'DocumentProbe', document, command: 'Std_CommandLine', parameters: { operation: 'submit', source: `exec(${JSON.stringify(source)})` },
|
||||
} })]));
|
||||
assert.equal(reply.ok, true, JSON.stringify(reply)); assert.equal(reply.result.stderr, '', JSON.stringify(reply));
|
||||
};
|
||||
const link = (object, subelement) => ({ documentId: document, object, subelements: [subelement] });
|
||||
let selected;
|
||||
const execute = args => adapter.executePartFixedBoxDesktop(router, 'Part_ProjectionOnSurface', args, document,
|
||||
(owner, selection) => { assert.equal(owner, document); selected = selection; });
|
||||
const accepted = async args => { const reply = await execute(args); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; };
|
||||
const feature = (state, name = state.createdObject) => { const item = state.objects.find(o => o.name === name); assert.ok(item, `Missing ${name}`); return item; };
|
||||
await call('create');
|
||||
python(`import FreeCAD as App, Part\nd=App.getDocument('${document}')\ndef add(name,shape):\n obj=d.addObject('Part::Feature',name)\n obj.Shape=shape\n return obj\nadd('Support',Part.makePlane(20,20))\nadd('Source',Part.makePlane(4,3,App.Vector(2,2,5)))\nadd('Edge',Part.makeLine(App.Vector(2,2,5),App.Vector(6,2,5)))\nd.recompute()`);
|
||||
const fixture = await call('save', { path: '/tmp/ProjectionFixture.FCStd' });
|
||||
await call('create', {}, 'ProjectionOther');
|
||||
const other = await call('snapshot', {}, 'ProjectionOther');
|
||||
const base = { support: link('Support', 'Face1'), selection: [link('Source', 'Face1')], direction: [0, 0, -1], mode: 'Faces', height: 0, offset: 0 };
|
||||
stage('native-projection-enter');
|
||||
const before = await call('readProjection');
|
||||
const created = await accepted(base); const item = feature(created); const name = item.name;
|
||||
assert.equal(item.type, 'Part::ProjectOnSurface'); assert.equal(item.topology.valid, true);
|
||||
near(item.topology.area, 12); near(item.volume, 0);
|
||||
assert.deepEqual(item.projection, base); assert.ok(item.dependencies.includes('Support')); assert.ok(item.dependencies.includes('Source'));
|
||||
assert.deepEqual(selected, [{ documentId: document, object: name }]);
|
||||
assert.equal(created.undoCount, before.undoCount + 1);
|
||||
assert.deepEqual((await call('undo')).objects, before.objects);
|
||||
assert.deepEqual((await call('redo')).objects, created.objects);
|
||||
assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other);
|
||||
record(base, { type: item.type, topology: item.topology, links: item.projection },
|
||||
'Native face projection has analytic area, source/support dependencies, selection and atomic undo/redo without changing another document');
|
||||
const solidArgs = { ...base, action: 'edit', object: name, mode: 'All', height: 2 };
|
||||
const solid = feature(await accepted(solidArgs)); near(solid.volume, 24); assert.equal(solid.topology.valid, true);
|
||||
const zRange = item => {
|
||||
const z = item.mesh.positions.filter((_value, index) => index % 3 === 2);
|
||||
return [Math.min(...z), Math.max(...z)];
|
||||
};
|
||||
const unshifted = zRange(solid);
|
||||
for (const offset of [-1, 1.5]) {
|
||||
const shifted = feature(await accepted({ ...solidArgs, offset }));
|
||||
near(shifted.volume, 24); assert.equal(shifted.projection.offset, offset);
|
||||
zRange(shifted).forEach((z, index) => near(z, unshifted[index] - offset));
|
||||
record({ offset, direction: base.direction }, { boundsZ: zRange(shifted), volume: shifted.volume },
|
||||
'Signed offset translates the native solid along the normalized projection direction while retaining volume');
|
||||
}
|
||||
const multiple = feature(await accepted({ ...solidArgs, selection: [...base.selection, link('Edge', 'Edge1')] }));
|
||||
near(multiple.volume, 24); assert.equal(multiple.projection.selection.length, 2);
|
||||
assert.ok(multiple.dependencies.includes('Edge')); assert.ok(multiple.topology.Edge > solid.topology.Edge);
|
||||
await accepted(solidArgs);
|
||||
record({ mode: 'All', sources: ['Source.Face1', 'Edge.Edge1'] }, { topology: multiple.topology, links: multiple.projection },
|
||||
'All mode retains both the extruded face and separately projected edge with native source links');
|
||||
const moved = await call('setPosition', { object: 'Source', position: [1, 0, 0] }); near(feature(moved, name).volume, 24);
|
||||
assert.notDeepEqual(feature(moved, name).mesh.positions, solid.mesh.positions);
|
||||
const stable = await call('readProjection');
|
||||
for (const args of [{ direction: [0, 0, 0] }, { height: -1 }, { mode: 'Unknown' }, { selection: [] },
|
||||
{ support: link('Support', 'Face99') }, { selection: [link('Missing', 'Edge1')] },
|
||||
{ selection: [{ ...link('Source', 'Face1'), documentId: 'ProjectionOther' }] },
|
||||
{ activeTask: true }, { action: 'edit', object: 'Support' }, { document: 'ProjectionOther' },
|
||||
{ action: 'edit', object: name, selection: [link(name, 'Face1')] }]) {
|
||||
const reply = await execute({ ...base, ...args }); assert.equal(reply.kind, 'error', JSON.stringify(reply));
|
||||
assert.deepEqual(await call('readProjection'), stable); assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other);
|
||||
record(args, reply.error, 'Invalid projection input rejects without changing geometry, links or history');
|
||||
}
|
||||
const edge = feature(await accepted({ ...base, mode: 'Edges', selection: [link('Edge', 'Edge1')] }));
|
||||
assert.equal(edge.topology.valid, true); assert.equal(edge.topology.Edge, 1); near(edge.topology.length, 4);
|
||||
const wireArgs = { ...base, mode: 'Edges', selection: [link('Source', 'Wire1')] };
|
||||
const wire = feature(await accepted(wireArgs));
|
||||
assert.equal(wire.topology.valid, true); assert.equal(wire.topology.Edge, 4); near(wire.topology.length, 14);
|
||||
assert.deepEqual(wire.projection.selection, wireArgs.selection);
|
||||
record(wireArgs, { topology: wire.topology, links: wire.projection },
|
||||
'Native wire projection retains the source wire reference and its analytic rectangular perimeter');
|
||||
const nativeStable = await call('readProjection');
|
||||
for (const invalid of [{ direction: [0, 0, 0] }, { direction: ['0', 0, -1] }, { height: -1 },
|
||||
{ offset: '1' }, { mode: 'Unknown' }, { selection: [] }, { support: link('Support', 'Face99') },
|
||||
{ selection: [link('Missing', 'Edge1')] }, { selection: [link('Source', 'Face1'), link('Source', 'Face1')] },
|
||||
{ selection: [{ ...link('Source', 'Face1'), documentId: 'ProjectionOther' }] },
|
||||
{ selection: [link(name, 'Face1')] }]) {
|
||||
const args = { document, action: 'editProjection', object: name, ...base, ...invalid };
|
||||
const reply = JSON.parse(kernel.ccall('fc_web_dispatch_json', 'string', ['string'], [JSON.stringify({ cmd: 'part.document', args })]));
|
||||
assert.equal(reply.ok, false, JSON.stringify(reply));
|
||||
assert.deepEqual(await call('readProjection'), nativeStable);
|
||||
assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other);
|
||||
record(args, { code: reply.code, error: reply.error },
|
||||
'Direct native malformed projection rejects and rolls back geometry, dependency links and history in both documents');
|
||||
}
|
||||
python(`dependent=d.addObject('Part::Compound','ProjectionDependent')\ndependent.Links=[d.getObject('${name}')]\nindirect=d.addObject('Part::Compound','ProjectionIndirect')\nindirect.Links=[dependent]\nd.recompute()`);
|
||||
const cycleBefore = await call('readProjection');
|
||||
for (const invalid of [{ selection: [link('ProjectionIndirect', 'Face1')] }, { support: link('ProjectionIndirect', 'Face1') }]) {
|
||||
const args = { ...solidArgs, ...invalid };
|
||||
const rejected = await execute(args); assert.equal(rejected.kind, 'error', JSON.stringify(rejected));
|
||||
assert.match(rejected.error.message, /cycle/i);
|
||||
assert.deepEqual(await call('readProjection'), cycleBefore);
|
||||
assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other);
|
||||
record(args, rejected.error, 'Indirect source and support cycles reject without changing geometry, dependencies or undo history');
|
||||
}
|
||||
const savedState = await call('readProjection');
|
||||
const saved = await call('save', { path: '/tmp/ProjectionBusiness.FCStd' }); await call('close');
|
||||
const opened = await call('open', { path: '/tmp/ProjectionBusiness.FCStd', bytes: saved.bytes });
|
||||
assert.deepEqual(opened.objects, savedState.objects);
|
||||
near(feature(await accepted({ ...solidArgs, height: 3 })).volume, 36);
|
||||
const cancelBefore = await call('readProjection'); assert.equal((await accepted({ action: 'cancel' })).cancelled, true);
|
||||
assert.deepEqual((await call('readProjection')).objects, cancelBefore.objects);
|
||||
record({ height: [2, 3], edgeLength: 4, actions: ['source-move', 'save', 'close', 'open', 'edit', 'cancel'] },
|
||||
{ volume: 36, bytes: saved.bytes.byteLength }, 'Projection extrusion, edge geometry, source recompute, FCStd links and subsequent edits retain native semantics');
|
||||
stage('native-curved-support-enter');
|
||||
python(`d=App.getDocument('${document}')\ncurved=d.addObject('Part::Cylinder','CurvedSupport')\ncurved.Radius=5\ncurved.Height=10\ncurved.Angle=90\nadd('CurvedSource',Part.makeLine(App.Vector(10,3,2),App.Vector(10,3,5)))\nd.recompute()`);
|
||||
const curvedArgs = { support: link('CurvedSupport', 'Face1'), selection: [link('CurvedSource', 'Edge1')],
|
||||
direction: [-1, 0, 0], mode: 'Edges', height: 0, offset: 0 };
|
||||
const curved = feature(await accepted(curvedArgs));
|
||||
const checkCurved = (item, radius) => {
|
||||
assert.equal(item.topology.valid, true); assert.equal(item.topology.Edge, 1); near(item.topology.length, 3);
|
||||
assert.deepEqual(item.projection, curvedArgs);
|
||||
assert.ok(item.dependencies.includes('CurvedSupport')); assert.ok(item.dependencies.includes('CurvedSource'));
|
||||
const points = item.lines.flat(); assert.ok(points.length >= 2);
|
||||
for (const point of points) { near(point[0], Math.sqrt(radius ** 2 - 9)); near(point[1], 3); }
|
||||
near(Math.min(...points.map(p => p[2])), 2); near(Math.max(...points.map(p => p[2])), 5);
|
||||
};
|
||||
checkCurved(curved, 5);
|
||||
python('curved.Radius=6\nd.recompute()');
|
||||
checkCurved(feature(await call('readProjection'), curved.name), 6);
|
||||
const curvedSaved = await call('save', { path: '/tmp/CurvedProjection.FCStd' }); await call('close');
|
||||
checkCurved(feature(await call('open', { path: '/tmp/CurvedProjection.FCStd', bytes: curvedSaved.bytes }), curved.name), 6);
|
||||
python(`d=App.getDocument('${document}')\nd.getObject('CurvedSupport').Radius=7\nd.recompute()`);
|
||||
checkCurved(feature(await call('readProjection'), curved.name), 7);
|
||||
record(curvedArgs, { topology: curved.topology, lines: curved.lines, editedRadii: [6, 7], savedBytes: curvedSaved.bytes.byteLength },
|
||||
'Curved native support produces the analytic cylindrical intersection, preserves links through FCStd and recomputes radius edits after reopen');
|
||||
stage('native-complete'); kernel.PThread?.terminateAllThreads(); kernel = undefined; stage('native-cleanup-complete');
|
||||
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? '/usr/bin/google-chrome', headless: process.env.HEADLESS !== "0",
|
||||
args: ['--no-sandbox', '--disable-dev-shm-usage'] });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
||||
const errors = []; page.on('pageerror', error => errors.push(String(error)));
|
||||
stage('browser-enter');
|
||||
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? 'http://127.0.0.1:5180'}/workbench.html?module=Part&command=Part_ProjectionOnSurface&document=${document}`);
|
||||
const panel = page.getByRole('region', { name: 'Projection on surface task', exact: true });
|
||||
const upload = bytes => panel.getByLabel('Projection FCStd file', { exact: true }).setInputFiles({ name: 'Projection.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) });
|
||||
await upload(fixture.bytes);
|
||||
for (const [title, object, element] of [['Support', 'Support', 'Face1'], ['Source 1', 'Source', 'Face1']]) {
|
||||
await panel.getByLabel(`${title} object`, { exact: true }).selectOption(object);
|
||||
await panel.getByLabel(`${title} element`, { exact: true }).selectOption(element);
|
||||
}
|
||||
for (const [axis, index] of [['X', 0], ['Y', 1], ['Z', 2]]) {
|
||||
for (const sign of [1, -1]) {
|
||||
await panel.getByRole('button', { name: `Toggle projection ${axis} direction`, exact: true }).click();
|
||||
const direction = await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Projection direction ${axis}`, { exact: true }).inputValue()));
|
||||
assert.deepEqual(direction.map(Number), [0, 1, 2].map(i => i === index ? sign : 0));
|
||||
}
|
||||
}
|
||||
await panel.getByLabel('Projection mode', { exact: true }).selectOption('Faces');
|
||||
await panel.getByRole('button', { name: 'Create projection', exact: true }).click();
|
||||
await panel.getByRole('button', { name: 'Apply changes', exact: true }).waitFor();
|
||||
const browserResult = async height => {
|
||||
await page.waitForFunction(expected => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => o.projection?.height === expected)
|
||||
&& !document.querySelector('button.run')?.disabled, height);
|
||||
const state = await page.evaluate(() => window.__freecadWorkbenchState.response.result);
|
||||
const item = feature(state); near(item.volume, 12 * height); assert.equal(item.topology.valid, true); return item;
|
||||
};
|
||||
await browserResult(0);
|
||||
const cameraButton = panel.getByRole('button', { name: 'Use projection camera direction', exact: true });
|
||||
const readDirection = async () => Promise.all(['X', 'Y', 'Z'].map(async axis => Number(await panel.getByLabel(`Projection direction ${axis}`, { exact: true }).inputValue())));
|
||||
await cameraButton.click();
|
||||
const initialCamera = await readDirection();
|
||||
const norm = Math.hypot(1, -1, 0.8);
|
||||
initialCamera.forEach((value, index) => near(value, [-1 / norm, 1 / norm, -0.8 / norm][index]));
|
||||
const canvas = panel.getByLabel('Projection geometry', { exact: true }).locator('canvas');
|
||||
await canvas.scrollIntoViewIfNeeded();
|
||||
const bounds = await canvas.boundingBox(); assert.ok(bounds);
|
||||
await page.mouse.move(bounds.x + bounds.width * 0.5, bounds.y + bounds.height * 0.5);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + bounds.width * 0.65, bounds.y + bounds.height * 0.55, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
await cameraButton.click();
|
||||
const orbitedCamera = await readDirection(); near(Math.hypot(...orbitedCamera), 1);
|
||||
assert.ok(orbitedCamera.some((value, index) => Math.abs(value - initialCamera[index]) > 0.01));
|
||||
record({ action: 'camera-direction', orbit: [0.15, 0.05] }, { initialCamera, orbitedCamera },
|
||||
'Projection direction follows the initial and interactively orbited viewport camera');
|
||||
// Restore the vertical projection used by the analytic extrusion checks below.
|
||||
for (const [axis, value] of [['X', 0], ['Y', 0], ['Z', -1]])
|
||||
await panel.getByLabel(`Projection direction ${axis}`, { exact: true }).fill(String(value));
|
||||
await panel.getByLabel('Projection mode', { exact: true }).selectOption('All');
|
||||
await panel.getByLabel('Projection height', { exact: true }).fill('2');
|
||||
await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await browserResult(2);
|
||||
await panel.getByRole('button', { name: 'Projection undo', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '0');
|
||||
await panel.getByRole('button', { name: 'Projection redo', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '2');
|
||||
const single = await browserResult(2);
|
||||
await panel.getByRole('button', { name: 'Add projection source', exact: true }).click();
|
||||
await panel.getByLabel('Source 2 object', { exact: true }).selectOption('Edge');
|
||||
await panel.getByLabel('Source 2 element', { exact: true }).selectOption('Edge1');
|
||||
await panel.getByLabel('Projection offset', { exact: true }).fill('1.5');
|
||||
await panel.getByRole('button', { name: 'Apply changes', exact: true }).click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.result?.objects?.some(o =>
|
||||
o.projection?.selection.length === 2 && o.projection.offset === 1.5));
|
||||
const combined = await browserResult(2);
|
||||
assert.ok(combined.dependencies.includes('Edge'));
|
||||
assert.ok(combined.topology.Edge > single.topology.Edge);
|
||||
zRange(combined).forEach((z, index) => near(z, zRange(single)[index] - 1.5));
|
||||
record({ route: 'mounted projection task', source: 'Edge.Edge1', offset: 1.5 },
|
||||
{ topology: combined.topology, projection: combined.projection, boundsZ: zRange(combined) },
|
||||
'Browser source addition and signed offset update native topology, dependencies and geometric bounds');
|
||||
await panel.getByRole('button', { name: 'Remove source 2', exact: true }).click();
|
||||
await panel.getByLabel('Projection offset', { exact: true }).fill('0');
|
||||
await panel.getByRole('button', { name: 'Apply changes', exact: true }).click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.result?.objects?.some(o =>
|
||||
o.projection?.selection.length === 1 && o.projection.offset === 0));
|
||||
const restored = await browserResult(2);
|
||||
assert.deepEqual(restored.projection, single.projection);
|
||||
assert.deepEqual(restored.topology, single.topology);
|
||||
assert.ok(!restored.dependencies.includes('Edge'));
|
||||
await panel.getByRole('button', { name: 'Save projection document', exact: true }).click();
|
||||
await panel.getByRole('status').filter({ hasText: `Projection-${document}.FCStd` }).waitFor();
|
||||
const bytes = await page.evaluate(async name => { const { readDocumentFile } = await import('/src/storage.ts');
|
||||
return [...new Uint8Array(await readDocumentFile(`Projection-${name}.FCStd`))]; }, document);
|
||||
assert.ok(bytes.length > 0);
|
||||
for (const [width, height] of [[1440, 900], [390, 844]]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
const file = path.join(directory, `projection-${width}.png`);
|
||||
const png = await panel.locator('canvas').screenshot({ path: file });
|
||||
const colors = await page.evaluate(async base64 => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
|
||||
const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
|
||||
const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
const colors = new Set(); for (let i = 0; i < pixels.length; i += 4) colors.add(`${pixels[i]},${pixels[i + 1]},${pixels[i + 2]}`); return colors.size;
|
||||
}, png.toString('base64'));
|
||||
assert.ok(colors > 8); assert.ok(await panel.evaluate(e => e.scrollWidth <= e.clientWidth + 1));
|
||||
result.evidenceFiles[path.relative(process.cwd(), file)] = createHash('sha256').update(png).digest('hex');
|
||||
}
|
||||
await panel.getByRole('button', { name: 'Close projection task', exact: true }).click();
|
||||
await panel.getByRole('button', { name: 'Apply changes', exact: true }).waitFor({ state: 'detached' });
|
||||
await page.reload(); await upload(bytes);
|
||||
await panel.getByLabel('Projection feature', { exact: true }).selectOption(name);
|
||||
await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '2');
|
||||
await panel.getByLabel('Projection height', { exact: true }).fill('3');
|
||||
await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await browserResult(3);
|
||||
assert.deepEqual(errors, []);
|
||||
record({ command: 'Part_ProjectionOnSurface', viewports: [1440, 390], actions: ['create', 'edit', 'undo', 'redo', 'OPFS-save', 'reload', 'FCStd-open', 'edit'] },
|
||||
{ volume: 36, bytes: bytes.length }, 'Mounted projection task dispatches linked geometry, persists editable FCStd through OPFS and renders desktop/mobile geometry without overflow');
|
||||
stage('browser-complete');
|
||||
result.status = 'not_implemented';
|
||||
result.remaining = [
|
||||
'Desktop preview transaction: create on task activation, recompute live edits, commit on accept and abort all task edits on reject',
|
||||
'Viewport subelement selection gates',
|
||||
'Linked-object projection coverage',
|
||||
];
|
||||
} catch (error) { result.error = String(error.stack ?? error); process.stderr.write(result.error + '\n'); }
|
||||
finally {
|
||||
kernel?.PThread?.terminateAllThreads(); await browser?.close(); fs.rmSync(temporary, { recursive: true, force: true }); stage('cleanup-complete');
|
||||
}
|
||||
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n');
|
||||
return [result];
|
||||
}
|
||||
173
tools/part-section-business-cases.mjs
Normal file
173
tools/part-section-business-cases.mjs
Normal file
@@ -0,0 +1,173 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { loadWasmProbe } from './wasm-probe-runtime.mjs';
|
||||
import { playwright } from './part-primitive-business-cases.mjs';
|
||||
|
||||
export const sectionId = 'Part:desktop:Part_Section';
|
||||
export async function runSectionCases(ids) {
|
||||
if (!ids.includes(sectionId)) return [];
|
||||
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'part-section-'));
|
||||
const directory = path.resolve('docs/current/part-section-business', new Date().toISOString().replace(/[:.]/g, '-'));
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const result = { capabilityId: sectionId, status: 'failed', cases: [], evidenceFiles: {}, timing: [] };
|
||||
const stage = name => {
|
||||
const event = { name, at: new Date().toISOString() }; result.timing.push(event);
|
||||
fs.appendFileSync(path.join(directory, 'stages.jsonl'), JSON.stringify(event) + '\n');
|
||||
process.stderr.write(`Part Section: ${name}\n`);
|
||||
};
|
||||
const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
|
||||
const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
|
||||
const item = (state, name = state.createdObject) => state.objects.find(object => object.name === name);
|
||||
let kernel, browser;
|
||||
try {
|
||||
for (const file of ['tools/part-section-business-cases.mjs', 'tools/part-business-cases.mjs',
|
||||
'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts', 'web/src/part-make-face-task.tsx',
|
||||
'web/src/workbench-shell.tsx', 'web/src/scene-viewport.tsx', 'web/src/desktop-command-dispatcher.ts',
|
||||
'freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp',
|
||||
'freecad-source/src/Mod/Part/Gui/Command.cpp', 'freecad-source/src/Mod/Part/App/FeaturePartSection.cpp',
|
||||
'freecad-source/src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp', 'freecad-source/src/Mod/Part/App/FCBRepAlgoAPI_Section.h',
|
||||
...['js', 'wasm', 'worker.js'].map(extension => `web/public/kernel/FreeCADWebDocumentProbe.${extension}`)])
|
||||
result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
stage('compile-adapter-enter');
|
||||
execFileSync('web/node_modules/.bin/tsc', ['--target', 'ES2022', '--module', 'ESNext', '--moduleResolution', 'Bundler',
|
||||
'--strict', '--skipLibCheck', '--jsx', 'preserve', '--outDir', temporary, 'web/node_modules/vite/client.d.ts', 'web/src/part-desktop-adapter.ts', 'web/src/part-view-facade.ts'], { stdio: 'pipe' });
|
||||
const facade = await import(pathToFileURL(path.join(temporary, 'part-document-facade.js')));
|
||||
const { executePartFixedBoxDesktop } = await import(pathToFileURL(path.join(temporary, 'part-desktop-adapter.js')));
|
||||
const { FacadeSerialQueue } = await import(pathToFileURL(path.join(temporary, 'facade-envelope.js')));
|
||||
stage('native-load-enter');
|
||||
({ kernel } = await loadWasmProbe('web/public/kernel', 'FreeCADWebDocumentProbe'));
|
||||
stage('native-load-complete');
|
||||
const queue = new FacadeSerialQueue(); let sequence = 0;
|
||||
const router = { request: (_module, command, payload) => {
|
||||
assert.equal(command, facade.PART_DOCUMENT_COMMAND);
|
||||
return facade.dispatchPartDocument(queue, facade.createPartDocumentRequest(`section-${++sequence}`, payload), kernel);
|
||||
} };
|
||||
const document = 'SectionBusiness';
|
||||
const call = async (action, args = {}, name = document) => {
|
||||
const reply = await router.request('Part', facade.PART_DOCUMENT_COMMAND, {
|
||||
schema: facade.PART_DOCUMENT_SCHEMA, module: 'Part', document: name, action, builderInfo: true, includeMesh: true, ...args });
|
||||
assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result;
|
||||
};
|
||||
const source = (object, subelements = []) => ({ documentId: document, object, subelements });
|
||||
const selection = [source('Base'), source('Tool')];
|
||||
const execute = args => executePartFixedBoxDesktop(router, 'Part_Section', args, document,
|
||||
() => { throw Error('Desktop Section must preserve selection'); });
|
||||
const accepted = async args => { const reply = await execute(args); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; };
|
||||
await call('create');
|
||||
await call('setBox', { object: 'Base', dimensions: [10, 10, 10] });
|
||||
await call('setBox', { object: 'Tool', dimensions: [10, 10, 10] });
|
||||
await call('setPosition', { object: 'Tool', position: [5, 5, 5] });
|
||||
const fixture = await call('save', { path: '/tmp/SectionBusiness.FCStd' });
|
||||
await call('create', {}, 'SectionOther');
|
||||
const other = await call('snapshot', {}, 'SectionOther');
|
||||
stage('native-section-enter');
|
||||
const before = await call('snapshot');
|
||||
const first = await accepted({ selection });
|
||||
const section = item(first);
|
||||
assert.equal(section.name, 'Section'); assert.equal(section.type, 'Part::Section');
|
||||
assert.equal(section.base, 'Base'); assert.equal(section.tool, 'Tool');
|
||||
assert.equal(section.topology.valid, true); assert.equal(section.topology.Edge, 6);
|
||||
assert.equal(section.topology.Face, 0); assert.equal(section.topology.Solid, 0);
|
||||
near(section.topology.length, 30); assert.equal(section.lines.length, 6);
|
||||
assert.equal(section.mesh, undefined); near(section.volume, 0);
|
||||
assert.equal(item(first, 'Base').displayVisibility, false); assert.equal(item(first, 'Tool').displayVisibility, false);
|
||||
near(item(first, 'Base').volume, 1000); near(item(first, 'Tool').volume, 1000);
|
||||
assert.equal(first.undoCount, before.undoCount + 1);
|
||||
assert.deepEqual((await call('undo')).objects, before.objects);
|
||||
assert.deepEqual((await call('redo')).objects, first.objects);
|
||||
assert.deepEqual(await call('snapshot', {}, 'SectionOther'), other);
|
||||
record({ selection, dimensions: [10, 10, 10], toolPosition: [5, 5, 5] }, { section, undoCount: first.undoCount },
|
||||
'Section computes six native intersection edges of length 30, stores operand links, hides sources, preserves selection and isolates one-step undo/redo');
|
||||
const next = await accepted({ selection: [source('Base', ['Face1']), source('Base', ['Face2']), source('Tool', ['Edge1'])] });
|
||||
assert.equal(next.createdObject, 'Section001'); near(item(next).topology.length, 30);
|
||||
record({ selection: ['Base.Face1', 'Base.Face2', 'Tool.Edge1'] }, { name: next.createdObject, length: item(next).topology.length },
|
||||
'Desktop object grouping ignores subelement geometry and assigns a unique native feature name');
|
||||
for (const args of [{ selection: [] }, { selection: [source('Base')] },
|
||||
{ selection: [source('Base'), source('Missing')] }, { selection: [source('Base'), { documentId: 'SectionOther', object: 'Tool' }] },
|
||||
{ selection, shapes: ['invented'] }, { selection, document: 'SectionOther' }]) {
|
||||
const state = await call('snapshot'); const reply = await execute(args);
|
||||
assert.equal(reply.kind, 'error', JSON.stringify(reply)); assert.deepEqual(await call('snapshot'), state);
|
||||
record(args, { error: reply.error, unchanged: true }, 'Invalid Section input cannot mutate objects or transaction history');
|
||||
}
|
||||
const moved = await call('setPosition', { object: 'Tool', position: [7, 7, 7] });
|
||||
near(item(moved, 'Section').topology.length, 18); near(item(moved, 'Section001').topology.length, 18);
|
||||
const disjoint = await call('setPosition', { object: 'Tool', position: [20, 20, 20] });
|
||||
assert.equal(item(disjoint, 'Section').topology?.Edge ?? 0, 0);
|
||||
assert.equal(item(disjoint, 'Section').lines?.length ?? 0, 0);
|
||||
near(item(await call('undo'), 'Section').topology.length, 18);
|
||||
record({ toolPositions: [[7, 7, 7], [20, 20, 20]], undo: true }, { length: 18, disjointEdges: 0 },
|
||||
'Linked source edits recompute Section and an empty intersection removes stale display edges');
|
||||
const saved = await call('save', { path: '/tmp/SectionSaved.FCStd' });
|
||||
assert.ok(saved.bytes.byteLength > 1000); await call('close');
|
||||
const reopened = await call('open', { path: '/tmp/SectionSaved.FCStd', bytes: saved.bytes });
|
||||
assert.equal(item(reopened, 'Section').base, 'Base'); assert.equal(item(reopened, 'Section').tool, 'Tool');
|
||||
near(item(reopened, 'Section').topology.length, 18); assert.equal(item(reopened, 'Base').displayVisibility, false);
|
||||
near(item(await call('setPosition', { object: 'Tool', position: [5, 5, 5] }), 'Section').topology.length, 30);
|
||||
record({ actions: ['save', 'close', 'open', 'edit-source'] }, { bytes: saved.bytes.byteLength, length: 30 },
|
||||
'FCStd preserves native Section links and source visibility and supports subsequent recomputation');
|
||||
stage('native-complete'); kernel.PThread?.terminateAllThreads(); kernel = undefined;
|
||||
stage('browser-enter');
|
||||
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? '/usr/bin/google-chrome', headless: process.env.HEADLESS !== "0",
|
||||
args: ['--no-sandbox', '--disable-dev-shm-usage'] });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); page.setDefaultTimeout(20000);
|
||||
const errors = []; page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? 'http://127.0.0.1:5180'}/workbench.html?module=Part&command=Part_Section&document=${document}`);
|
||||
await page.getByLabel('Make section document', { exact: true }).fill(document);
|
||||
await page.getByLabel('Section FCStd file', { exact: true }).setInputFiles({ name: 'SectionBusiness.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(fixture.bytes) });
|
||||
await page.getByLabel('Section source Base', { exact: true }).check();
|
||||
assert.equal(await page.getByRole('button', { name: 'Create section', exact: true }).isEnabled(), false);
|
||||
await page.getByLabel('Section source Tool', { exact: true }).check();
|
||||
await page.getByRole('button', { name: 'Create section', exact: true }).click();
|
||||
await page.locator('[data-section="Section"]').filter({ hasText: '30.000' }).waitFor();
|
||||
assert.equal(await page.getByLabel('Section source Base', { exact: true }).isChecked(), true);
|
||||
await page.getByRole('button', { name: 'Section undo', exact: true }).click();
|
||||
await page.locator('[data-section="Section"]').waitFor({ state: 'detached' });
|
||||
await page.getByRole('button', { name: 'Section redo', exact: true }).click();
|
||||
await page.locator('[data-section="Section"]').filter({ hasText: '30.000' }).waitFor();
|
||||
const capture = async name => {
|
||||
const png = await page.locator('[aria-label="Section geometry"] canvas').screenshot({ path: path.join(directory, name) });
|
||||
const colors = await page.evaluate(async encoded => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${encoded}`; await image.decode();
|
||||
const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
|
||||
const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
const colors = new Set(); for (let i = 0; i < pixels.length; i += 4) colors.add(`${pixels[i]},${pixels[i+1]},${pixels[i+2]}`); return colors.size;
|
||||
}, png.toString('base64'));
|
||||
assert.ok(colors > 8, `Section canvas has only ${colors} colors`); return createHash('sha256').update(png).digest('hex');
|
||||
};
|
||||
const initial = await capture('desktop-geometry.png');
|
||||
const rect = await page.locator('[aria-label="Section geometry"] canvas').boundingBox();
|
||||
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2); await page.mouse.down();
|
||||
await page.mouse.move(rect.x + rect.width / 2 + 70, rect.y + rect.height / 2 + 30, { steps: 8 }); await page.mouse.up();
|
||||
assert.notEqual(await capture('rotated-geometry.png'), initial);
|
||||
await page.getByRole('button', { name: 'Save section document', exact: true }).click();
|
||||
await page.getByRole('link', { name: 'Open section in project', exact: true }).waitFor();
|
||||
const bytes = await page.evaluate(async () => { const { readDocumentFile } = await import('/src/storage.ts'); return [...new Uint8Array(await readDocumentFile('Section-SectionBusiness.FCStd'))]; });
|
||||
assert.ok(bytes.length > 1000); await page.screenshot({ path: path.join(directory, 'desktop.png'), fullPage: true });
|
||||
await page.reload(); await page.getByLabel('Make section document', { exact: true }).fill(document);
|
||||
await page.getByLabel('Section FCStd file', { exact: true }).setInputFiles({ name: 'SectionBusiness.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) });
|
||||
await page.locator('[data-section="Section"]').filter({ hasText: '30.000' }).waitFor();
|
||||
await page.getByLabel('Section source Base', { exact: true }).check(); await page.getByLabel('Section source Tool', { exact: true }).check();
|
||||
await page.getByRole('button', { name: 'Create section', exact: true }).click();
|
||||
await page.locator('[data-section="Section001"]').filter({ hasText: '30.000' }).waitFor();
|
||||
await page.setViewportSize({ width: 390, height: 844 }); await capture('mobile-geometry.png');
|
||||
await page.screenshot({ path: path.join(directory, 'mobile.png'), fullPage: true });
|
||||
const layout = await page.getByRole('region', { name: 'Section', exact: true }).evaluate(element => ({ width: element.clientWidth, scroll: element.scrollWidth }));
|
||||
assert.ok(layout.scroll <= layout.width + 1, JSON.stringify(layout)); assert.deepEqual(errors, []);
|
||||
for (const name of ['desktop.png', 'desktop-geometry.png', 'rotated-geometry.png', 'mobile.png', 'mobile-geometry.png']) {
|
||||
const file = path.join(directory, name); result.evidenceFiles[path.relative('.', file)] = createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
}
|
||||
record({ operations: ['FCStd-open', 'select', 'create', 'undo', 'redo', 'rotate', 'OPFS-save', 'reload', 'FCStd-open', 'create'], viewports: [[1440, 900], [390, 844]] },
|
||||
{ length: 30, restoredBytes: bytes.length, layout }, 'Mounted Section controls dispatch native geometry, retain selection and restore OPFS documents on desktop and mobile');
|
||||
stage('browser-complete'); result.status = 'passed';
|
||||
} catch (error) { result.error = [String(error.stack ?? error), error.stdout?.toString(), error.stderr?.toString()].filter(Boolean).join('\n'); }
|
||||
finally {
|
||||
stage('cleanup-enter'); await browser?.close(); kernel?.PThread?.terminateAllThreads(); fs.rmSync(temporary, { recursive: true, force: true });
|
||||
stage('cleanup-complete'); fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
|
||||
}
|
||||
return [result];
|
||||
}
|
||||
810
tools/part-section-cut-container-business-cases.mjs
Normal file
810
tools/part-section-cut-container-business-cases.mjs
Normal file
@@ -0,0 +1,810 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { playwright } from "./part-primitive-business-cases.mjs";
|
||||
|
||||
// Isolate the uncolored-base/colored-tool boundary without replaying the
|
||||
// already recorded placement, cutter-size, opacity and lifecycle scenarios.
|
||||
export const runSectionCutFaceAlphaCases = ids => runSectionCutToolColorCases(ids, true);
|
||||
export const runSectionCutFragmentColorCases = ids => runSectionCutToolColorCases(ids, true, true);
|
||||
export const runSectionCutFragmentTransparencyCases = ids => runSectionCutToolColorCases(ids, true, true, true);
|
||||
export const runSectionCutMultiSourceAppearanceCases = ids => runSectionCutToolColorCases(ids, true, true, true, true);
|
||||
export const runSectionCutSourceInheritanceCases = ids => runSectionCutToolColorCases(ids, false, false, false, false, true);
|
||||
|
||||
export async function runSectionCutToolColorCases(ids, faceAlpha = false, fragmentColor = false, fragmentAlpha = false, multiSource = false, sourceInheritance = false) {
|
||||
const capabilityId = "Part:desktop:Part_SectionCut";
|
||||
if (!ids.includes(capabilityId)) return [];
|
||||
const directory = path.resolve(sourceInheritance ? "docs/current/part-section-cut-source-inheritance" : multiSource ? "docs/current/part-section-cut-multi-source-appearance" : fragmentAlpha ? "docs/current/part-section-cut-fragment-transparency" : fragmentColor ? "docs/current/part-section-cut-fragment-color" : faceAlpha ? "docs/current/part-section-cut-face-alpha" : "docs/current/part-section-cut-tool-colors", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {},
|
||||
deferredCases: ["runSectionCutContainerCases", "runLegacySectionCutCases", "runSectionCutEmptySourcesCases",
|
||||
"runSectionCutFragmentsCases", "runSectionCutOpacityCases", "runSectionCutPersistenceCases",
|
||||
...(sourceInheritance ? ["runSectionCutCompoundHistoryCases", "runSectionCutMultiSourceAppearanceCases"] : [])],
|
||||
remaining: [sourceInheritance ? "Curved and transformed BooleanFragments source material coverage; desktop automatic color controls" : multiSource ? "Source face material inheritance in BooleanFragments" : fragmentAlpha ? "BooleanFragments appearance with multiple intersecting sources; source face material inheritance" : faceAlpha ? "Fragment color/transparency and desktop cut/fragment appearance interaction" : "Independent cut-face and fragment appearance/transparency",
|
||||
"Container reparenting", "Unexpected post-mutation failure history behavior"] };
|
||||
const started = performance.now();
|
||||
const stages = [];
|
||||
const stage = name => {
|
||||
stages.push({ name, elapsedMs: performance.now() - started });
|
||||
fs.writeFileSync(path.join(directory, "stages.json"), JSON.stringify(stages, null, 2) + "\n");
|
||||
process.stderr.write(`Section cut tool colors: ${name}\n`);
|
||||
};
|
||||
const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
|
||||
let browser;
|
||||
try {
|
||||
for (const file of ["tools/part-section-cut-container-business-cases.mjs", "tools/part-section-cut-business-cases.mjs",
|
||||
"web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts",
|
||||
"web/src/workbench-shell.tsx", "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartColoredIO.h",
|
||||
"web/src/scene-viewport.tsx", "freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp",
|
||||
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h",
|
||||
...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
|
||||
result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
stage("browser-launch-enter");
|
||||
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? "/usr/bin/google-chrome",
|
||||
headless: process.env.HEADLESS !== "0", args: ["--no-sandbox", "--disable-dev-shm-usage"] });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
||||
const errors = []; page.on("pageerror", error => errors.push(String(error)));
|
||||
const documentId = "SectionCutToolColors";
|
||||
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`);
|
||||
const run = async (args, expectError = false) => {
|
||||
stage(`request-${args.action}-enter`);
|
||||
await page.locator("aside > button.command").filter({ has: page.getByText("part.document", { exact: true }) }).click();
|
||||
await page.locator("#payload-editor").fill(JSON.stringify({ schema: "freecad-web-part/document/v1", module: "Part",
|
||||
document: documentId, builderInfo: true, includeMesh: true, ...args }));
|
||||
await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; });
|
||||
await page.getByRole("button", { name: "执行选中命令", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled);
|
||||
const reply = await page.evaluate(() => window.__freecadWorkbenchState.response);
|
||||
assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply));
|
||||
stage(`request-${args.action}-complete`);
|
||||
return expectError ? reply.error : reply.result;
|
||||
};
|
||||
if (sourceInheritance) {
|
||||
await assertSourceInheritance({ page, run, record, stage, directory, result, documentId });
|
||||
assert.deepEqual(errors, []);
|
||||
} else if (multiSource) {
|
||||
await assertMultiSourceAppearance({ page, run, record, stage, directory, result });
|
||||
assert.deepEqual(errors, []);
|
||||
} else {
|
||||
await run({ action: "create" });
|
||||
await run({ action: "setBox", object: "Box", dimensions: [10,10,10] });
|
||||
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
|
||||
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
|
||||
const ready = () => page.waitForFunction(() => {
|
||||
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled;
|
||||
});
|
||||
await ready();
|
||||
await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check();
|
||||
await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("5");
|
||||
await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00");
|
||||
if (faceAlpha) await panel.getByLabel("Cut face transparency", { exact: true }).fill("65");
|
||||
if (fragmentColor) {
|
||||
await panel.getByLabel("Custom fragment color", { exact: true }).check();
|
||||
await panel.getByLabel("Fragment color", { exact: true }).fill("#ffff00");
|
||||
}
|
||||
if (fragmentAlpha) await panel.getByLabel("Fragment transparency", { exact: true }).fill("60");
|
||||
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
|
||||
assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
|
||||
const initial = await run({ action: "snapshot" });
|
||||
const session = state => state.objects.find(item => item.sectionCutSession).sectionCutSession;
|
||||
const cut = state => state.objects.find(item => item.name === session(state).result);
|
||||
const tool = initial.objects.find(item => item.type === "Part::Box" && item.name.startsWith("SectionCutBox"));
|
||||
assert.ok(tool); assert.equal(initial.objects.find(item => item.name === "Box").faceColors?.length ?? 0, 0);
|
||||
const green = [0,1,0,faceAlpha ? 0.35 : 1], red = [1,0,0,faceAlpha ? 0.7 : 1];
|
||||
const baseAlpha = fragmentAlpha ? 0.4 : 1;
|
||||
const check = (state, color, volume) => {
|
||||
const output = cut(state);
|
||||
assert.ok(Math.abs(output.volume - volume) < 1e-6); assert.equal(output.topology.valid, true);
|
||||
assert.equal(output.faceColors.length, 6);
|
||||
const matches = value => value.slice(0,3).every((channel, i) => Math.abs(channel - color[i]) < 1e-6);
|
||||
assert.equal(output.faceColors.filter(matches).length, 1, "Only the new section face inherits the cutter color");
|
||||
const expectedBase = fragmentColor ? [1, 1, 0] : [0.8, 0.8, 0.8];
|
||||
for (const value of output.faceColors.filter(value => !matches(value)))
|
||||
value.slice(0,3).forEach((channel, i) => assert.ok(Math.abs(channel - expectedBase[i]) < 1e-6, "Surviving source faces retain the selected fragment material"));
|
||||
assert.equal(output.mesh.colors.length, output.mesh.triangleCount * 9);
|
||||
const rgb = output.mesh.colors;
|
||||
const coloredVertices = Array.from({ length: rgb.length / 3 }, (_, i) => rgb.slice(i * 3, i * 3 + 3)).filter(matches).length;
|
||||
assert.equal(coloredVertices, 6, "Two native cut-face triangles carry the tool material");
|
||||
if (faceAlpha) {
|
||||
const near = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
|
||||
output.faceColors.forEach(value => near(value[3], matches(value) ? color[3] : baseAlpha));
|
||||
assert.equal(output.mesh.alphas.length, output.mesh.triangleCount * 3);
|
||||
output.mesh.alphas.forEach((alpha, i) => near(alpha, matches(rgb.slice(i * 3, i * 3 + 3)) ? color[3] : baseAlpha));
|
||||
assert.equal(output.displayOpacity, 1, "Cut transparency does not fade surviving source faces");
|
||||
}
|
||||
return { volume: output.volume, faceColors: output.faceColors, coloredVertices };
|
||||
};
|
||||
const setColor = color => run({ action: "setFaceColors", selection: [{ documentId, object: tool.name }],
|
||||
faceColors: Array.from({ length: tool.topology.Face }, () => color) });
|
||||
const colored = initial;
|
||||
assert.equal(session(colored).cutColor, "#00ff00");
|
||||
if (fragmentColor) assert.equal(session(colored).fragmentColor, "#ffff00");
|
||||
if (fragmentAlpha) assert.equal(session(colored).fragmentTransparency, 60);
|
||||
if (faceAlpha) assert.equal(session(colored).cutTransparency, 65);
|
||||
fs.writeFileSync(path.join(directory, "colored.json"), JSON.stringify(colored, null, 2) + "\n");
|
||||
record({ source: "uncolored Box", planeX: 5, toolColor: green }, check(colored, green, 500),
|
||||
"Native Boolean history separates the generated cut-face material from the five surviving source faces");
|
||||
const recolored = await setColor(red); check(recolored, red, 500);
|
||||
const undone = await run({ action: "undo" }); check(undone, green, 500);
|
||||
const failure = await run({ action: "sectionCut", sectionCut: { operation: "apply", cutColor: "not-a-color" } }, true);
|
||||
assert.match(failure.message, /six-digit RGB/);
|
||||
const afterFailure = await run({ action: "snapshot" });
|
||||
assert.deepEqual(afterFailure.objects, undone.objects);
|
||||
assert.equal(afterFailure.undoCount, undone.undoCount); assert.equal(afterFailure.redoCount, undone.redoCount);
|
||||
if (fragmentColor) {
|
||||
for (const value of ["red", "#12345g", 123, null, true]) {
|
||||
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", fragmentColor: value } }, true);
|
||||
assert.match(rejected.message, /Fragment color/);
|
||||
const preserved = await run({ action: "snapshot" });
|
||||
assert.deepEqual(preserved.objects, undone.objects);
|
||||
assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount);
|
||||
}
|
||||
}
|
||||
if (faceAlpha) {
|
||||
for (const cutTransparency of [-1, 101, 0.5, "50", true]) {
|
||||
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", cutTransparency } }, true);
|
||||
assert.match(rejected.message, /Cut face transparency/);
|
||||
const preserved = await run({ action: "snapshot" });
|
||||
assert.deepEqual(preserved.objects, undone.objects);
|
||||
assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount);
|
||||
}
|
||||
}
|
||||
if (fragmentAlpha) {
|
||||
for (const fragmentTransparency of [-1, 101, 0.5, "60", true, null]) {
|
||||
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", fragmentTransparency } }, true);
|
||||
assert.match(rejected.message, /Fragment transparency/);
|
||||
const preserved = await run({ action: "snapshot" });
|
||||
assert.deepEqual(preserved.objects, undone.objects);
|
||||
assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount);
|
||||
}
|
||||
}
|
||||
check(await run({ action: "redo" }), red, 500);
|
||||
const edited = await run({ action: "setBox", object: "Box", dimensions: [10,10,12] });
|
||||
record({ toolColor: red, sourceDimensions: [10,10,12], operations: ["recolor", "undo", "redo", "source edit"] },
|
||||
check(edited, red, 600), "Tool material follows native history through color history and source recompute");
|
||||
await run({ action: "save", path: "/tmp/SectionCutToolColors.FCStd" }); await run({ action: "close" });
|
||||
const reopened = await run({ action: "open", path: "/tmp/SectionCutToolColors.FCStd" });
|
||||
assert.equal(session(reopened).cutColor, "#00ff00");
|
||||
if (fragmentColor) assert.equal(session(reopened).fragmentColor, "#ffff00");
|
||||
if (fragmentAlpha) assert.equal(session(reopened).fragmentTransparency, 60);
|
||||
if (faceAlpha) assert.equal(session(reopened).cutTransparency, 65);
|
||||
// FCStd packs App::PropertyColorList channels into eight-bit RGBA values.
|
||||
const savedRed = faceAlpha ? red.map(channel => Math.round(channel * 255) / 255) : red;
|
||||
record({ operation: "save-close-open", expectedStoredColor: savedRed }, check(reopened, savedRed, 600),
|
||||
"FCStd restores packed native tool material and recomputed face-history mapping");
|
||||
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
|
||||
assert.equal(await panel.getByLabel("Cut face color", { exact: true }).inputValue(), "#00ff00");
|
||||
if (fragmentColor) {
|
||||
assert.equal(await panel.getByLabel("Custom fragment color", { exact: true }).isChecked(), true);
|
||||
assert.equal(await panel.getByLabel("Fragment color", { exact: true }).inputValue(), "#ffff00");
|
||||
}
|
||||
if (faceAlpha) assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "65");
|
||||
if (fragmentAlpha) assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60");
|
||||
await panel.getByLabel("Cut face color", { exact: true }).fill("#0000ff");
|
||||
await panel.getByRole("checkbox", { name: "Cut Y", exact: true }).check();
|
||||
await panel.getByRole("spinbutton", { name: "Cut Y position", exact: true }).fill("4");
|
||||
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
|
||||
const twoAxes = await run({ action: "snapshot" });
|
||||
const blueFaces = cut(twoAxes).faceColors.filter(color => color[0] === 0 && color[1] === 0 && color[2] === 1);
|
||||
assert.equal(blueFaces.length, 2, "Both sequential cut faces receive the chosen material through native history");
|
||||
if (faceAlpha) {
|
||||
assert.ok(blueFaces.every(color => Math.abs(color[3] - 0.35) < 1e-6));
|
||||
assert.equal(cut(twoAxes).mesh.alphas.filter(alpha => Math.abs(alpha - 0.35) < 1e-6).length, 12);
|
||||
assert.equal(cut(twoAxes).mesh.alphas.filter(alpha => Math.abs(alpha - baseAlpha) < 1e-6).length, 24);
|
||||
}
|
||||
assert.equal(cut(twoAxes).faceColors.length, 6); assert.ok(Math.abs(cut(twoAxes).volume - 240) < 1e-6);
|
||||
assert.equal(session(twoAxes).cutColor, "#0000ff");
|
||||
await panel.getByRole("button", { name: "Refresh cut sources", exact: true }).click(); await ready();
|
||||
const refreshed = await run({ action: "snapshot" });
|
||||
assert.deepEqual(cut(refreshed).faceColors, cut(twoAxes).faceColors);
|
||||
assert.equal(session(refreshed).cutColor, "#0000ff");
|
||||
if (fragmentColor) {
|
||||
assert.equal(session(refreshed).fragmentColor, "#ffff00");
|
||||
assert.equal(cut(refreshed).faceColors.filter(color => color[0] === 1 && color[1] === 1 && color[2] === 0 && Math.abs(color[3] - baseAlpha) < 1e-6).length, 4);
|
||||
assert.equal(refreshed.objects.find(item => item.name === "Box").faceColors?.length ?? 0, 0);
|
||||
}
|
||||
if (faceAlpha) assert.equal(session(refreshed).cutTransparency, 65);
|
||||
if (fragmentAlpha) assert.equal(session(refreshed).fragmentTransparency, 60);
|
||||
record({ operation: "mounted color change and source refresh", axes: ["X=5", "Y=4"], cutColor: "#0000ff" },
|
||||
{ faceColors: cut(refreshed).faceColors, volume: cut(refreshed).volume },
|
||||
"Mounted color control restores native session state and colors both sequential section faces across refresh");
|
||||
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
|
||||
assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
|
||||
const pixels = [];
|
||||
for (const width of [1440, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const canvas = panel.locator("canvas").first(); await canvas.waitFor();
|
||||
await page.waitForTimeout(300);
|
||||
const imageFile = path.join(directory, `tool-color-canvas-${width}.png`);
|
||||
const bytes = await canvas.screenshot({ path: imageFile });
|
||||
const bluePixels = await page.evaluate(async data => {
|
||||
const img = new Image(); img.src = `data:image/png;base64,${data}`; await img.decode();
|
||||
const target = document.createElement("canvas"); target.width = img.width; target.height = img.height;
|
||||
const context = target.getContext("2d"); context.drawImage(img, 0, 0);
|
||||
const rgba = context.getImageData(0, 0, target.width, target.height).data;
|
||||
let blue = 0;
|
||||
for (let i = 0; i < rgba.length; i += 4)
|
||||
if (rgba[i + 2] > 40 && rgba[i + 2] > rgba[i] * 1.4 && rgba[i + 2] > rgba[i + 1] * 1.4) ++blue;
|
||||
return blue;
|
||||
}, bytes.toString("base64"));
|
||||
assert.ok(bluePixels > 30, `Native blue cut faces must render at width ${width}: ${bluePixels}`);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
|
||||
pixels.push({ width, bluePixels });
|
||||
result.evidenceFiles[path.relative(process.cwd(), imageFile)] = createHash("sha256").update(bytes).digest("hex");
|
||||
if (fragmentAlpha) {
|
||||
await panel.getByLabel("Fragment transparency", { exact: true }).fill("100");
|
||||
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
|
||||
const hidden = await run({ action: "snapshot" });
|
||||
const isBlue = color => color[0] === 0 && color[1] === 0 && color[2] === 1;
|
||||
assert.equal(session(hidden).fragmentTransparency, 100);
|
||||
assert.equal(cut(hidden).faceColors.filter(color => !isBlue(color) && color[3] === 0).length, 4);
|
||||
assert.equal(cut(hidden).faceColors.filter(color => isBlue(color) && Math.abs(color[3] - 0.35) < 1e-6).length, 2);
|
||||
assert.ok(Math.abs(cut(hidden).volume - 240) < 1e-6);
|
||||
await page.waitForTimeout(300);
|
||||
const file = path.join(directory, `transparent-fragment-canvas-${width}.png`);
|
||||
const hiddenBytes = await canvas.screenshot({ path: file });
|
||||
const count = async data => page.evaluate(async encoded => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${encoded}`; await image.decode();
|
||||
const target = document.createElement("canvas"); target.width = image.width; target.height = image.height;
|
||||
const context = target.getContext("2d"); context.drawImage(image, 0, 0);
|
||||
const values = context.getImageData(0, 0, target.width, target.height).data;
|
||||
let blue = 0, yellow = 0;
|
||||
for (let i = 0; i < values.length; i += 4) {
|
||||
if (values[i + 2] > 40 && values[i + 2] > values[i] * 1.4 && values[i + 2] > values[i + 1] * 1.4) ++blue;
|
||||
if (values[i] > 40 && values[i + 1] > 40 && values[i] > values[i + 2] * 1.4 && values[i + 1] > values[i + 2] * 1.4) ++yellow;
|
||||
}
|
||||
return { blue, yellow };
|
||||
}, data.toString("base64"));
|
||||
const before = await count(bytes), after = await count(hiddenBytes);
|
||||
assert.ok(before.yellow > 100, "Partially transparent fragment faces remain visible");
|
||||
assert.ok(after.yellow < before.yellow * 0.05, "Fully transparent fragments remove yellow surface pixels");
|
||||
assert.ok(after.blue > 30, "Independent blue cut faces remain visible");
|
||||
pixels.at(-1).fragments = { before, after };
|
||||
result.evidenceFiles[path.relative(process.cwd(), file)] = createHash("sha256").update(hiddenBytes).digest("hex");
|
||||
await panel.getByRole("button", { name: "Section cut undo", exact: true }).click(); await ready();
|
||||
assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60");
|
||||
}
|
||||
if (faceAlpha) {
|
||||
await panel.getByLabel("Cut face transparency", { exact: true }).fill("100");
|
||||
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
|
||||
await page.waitForTimeout(300);
|
||||
const clearFile = path.join(directory, `transparent-cut-canvas-${width}.png`);
|
||||
const clearBytes = await canvas.screenshot({ path: clearFile });
|
||||
const clearPixels = await page.evaluate(async data => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${data}`; await image.decode();
|
||||
const target = document.createElement("canvas"); target.width = image.width; target.height = image.height;
|
||||
const context = target.getContext("2d"); context.drawImage(image, 0, 0);
|
||||
const values = context.getImageData(0, 0, target.width, target.height).data;
|
||||
let blue = 0, geometry = 0, yellow = 0;
|
||||
for (let i = 0; i < values.length; i += 4) {
|
||||
if (values[i + 2] > 40 && values[i + 2] > values[i] * 1.4 && values[i + 2] > values[i + 1] * 1.4) ++blue;
|
||||
if (Math.max(...values.slice(i, i + 3)) - Math.min(...values.slice(i, i + 3)) < 12 && values[i] < 225) ++geometry;
|
||||
if (values[i] > 40 && values[i + 1] > 40 && values[i] > values[i + 2] * 1.4 && values[i + 1] > values[i + 2] * 1.4) ++yellow;
|
||||
}
|
||||
return { blue, geometry, yellow };
|
||||
}, clearBytes.toString("base64"));
|
||||
assert.ok(clearPixels.blue < bluePixels * 0.05, "Fully transparent cut faces remove the blue pixels");
|
||||
assert.ok((fragmentColor ? clearPixels.yellow : clearPixels.geometry) > 100, "Fragment faces remain rendered behind transparent cuts");
|
||||
assert.notEqual(createHash("sha256").update(clearBytes).digest("hex"), createHash("sha256").update(bytes).digest("hex"));
|
||||
result.evidenceFiles[path.relative(process.cwd(), clearFile)] = createHash("sha256").update(clearBytes).digest("hex");
|
||||
pixels.at(-1).transparent = clearPixels;
|
||||
const panelFile = path.join(directory, `section-cut-panel-${width}.png`);
|
||||
const panelBytes = await panel.screenshot({ path: panelFile });
|
||||
result.evidenceFiles[path.relative(process.cwd(), panelFile)] = createHash("sha256").update(panelBytes).digest("hex");
|
||||
await canvas.scrollIntoViewIfNeeded();
|
||||
const bounds = await canvas.boundingBox(); assert.ok(bounds);
|
||||
await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + bounds.width / 2 + 40, bounds.y + bounds.height / 2 + 20, { steps: 8 });
|
||||
await page.mouse.up(); await page.waitForTimeout(200);
|
||||
const orbitFile = path.join(directory, `transparent-cut-orbit-${width}.png`);
|
||||
const orbitBytes = await canvas.screenshot({ path: orbitFile });
|
||||
const orbitHash = createHash("sha256").update(orbitBytes).digest("hex");
|
||||
assert.notEqual(orbitHash, createHash("sha256").update(clearBytes).digest("hex"), "Native transparent mesh responds to orbit");
|
||||
result.evidenceFiles[path.relative(process.cwd(), orbitFile)] = orbitHash;
|
||||
pixels.at(-1).orbitChanged = true;
|
||||
await panel.getByRole("button", { name: "Section cut undo", exact: true }).click(); await ready();
|
||||
assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "65");
|
||||
}
|
||||
}
|
||||
record({ operation: "render native face colors", widths: [1440, 390] }, pixels,
|
||||
"Chosen cut-face color is visible in desktop and mobile native-mesh canvases without horizontal overflow");
|
||||
if (faceAlpha) record({ cutTransparency: [65, 100], editedToolAlpha: 0.7, sourceAlpha: baseAlpha,
|
||||
operations: ["apply", "undo", "redo", "invalid native values", "edit source", "FCStd reopen", "sequential cuts", "refresh"] },
|
||||
{ pixels, fragmentAlpha: baseAlpha }, "Independent native face alpha survives history and persistence and changes actual desktop/mobile pixels");
|
||||
assert.deepEqual(errors, []);
|
||||
if (fragmentColor) {
|
||||
await panel.getByLabel("Custom fragment color", { exact: true }).uncheck();
|
||||
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
|
||||
const automatic = await run({ action: "snapshot" });
|
||||
assert.equal(session(automatic).fragmentColor, "");
|
||||
assert.equal(cut(automatic).faceColors.filter(color => color.slice(0, 3).every(channel => Math.abs(channel - 0.8) < 1e-6)).length, 4);
|
||||
assert.equal(cut(automatic).faceColors.filter(color => color[2] === 1 && Math.abs(color[3] - 0.35) < 1e-6).length, 2);
|
||||
const restored = await run({ action: "undo" });
|
||||
assert.equal(session(restored).fragmentColor, "#ffff00");
|
||||
assert.equal(cut(restored).faceColors.filter(color => color[0] === 1 && color[1] === 1 && color[2] === 0).length, 4);
|
||||
assert.equal(session(await run({ action: "redo" })).fragmentColor, "");
|
||||
record({ fragmentColor: "#ffff00", cutColor: "#0000ff", cutTransparency: 65, reset: "source appearance" },
|
||||
{ pixels, sourceUnmodified: true, automaticFaces: cut(automatic).faceColors },
|
||||
"Mounted fragment color changes only surviving source faces, persists through refresh and FCStd, and resets with undo/redo");
|
||||
}
|
||||
if (fragmentAlpha) {
|
||||
const minimum = await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(refreshed).axes, cutTransparency: 0 } });
|
||||
assert.equal(session(minimum).cutTransparency, 1);
|
||||
assert.equal(session(minimum).fragmentTransparency, 60);
|
||||
const blue = color => color[0] === 0 && color[1] === 0 && color[2] === 1;
|
||||
assert.equal(cut(minimum).faceColors.filter(blue).length, 2);
|
||||
cut(minimum).faceColors.forEach(color => assert.ok(Math.abs(color[3] - (blue(color) ? 0.99 : 0.4)) < 1e-6));
|
||||
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
|
||||
assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "1");
|
||||
const input = panel.getByLabel("Fragment transparency", { exact: true });
|
||||
await input.fill("");
|
||||
assert.equal(await panel.getByRole("button", { name: "Apply section cut", exact: true }).isDisabled(), true);
|
||||
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
|
||||
assert.equal(await input.inputValue(), "60");
|
||||
await input.fill("0");
|
||||
await panel.getByLabel("Cut face transparency", { exact: true }).fill("0");
|
||||
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
|
||||
const opaque = await run({ action: "snapshot" });
|
||||
assert.equal(session(opaque).fragmentTransparency, 0); assert.equal(session(opaque).cutTransparency, 0);
|
||||
assert.ok(cut(opaque).faceColors.every(color => color[3] === 1));
|
||||
const undo = await run({ action: "undo" });
|
||||
assert.deepEqual(cut(undo).faceColors, cut(minimum).faceColors);
|
||||
assert.deepEqual(cut(await run({ action: "redo" })).faceColors, cut(opaque).faceColors);
|
||||
record({ fragmentTransparency: [60, 0], cutTransparency: 0, operations: ["minimum", "invalid UI", "undo", "redo"] },
|
||||
{ minimum: cut(minimum).faceColors, opaque: cut(opaque).faceColors },
|
||||
"Transparent fragments enforce the desktop one-percent cut minimum; clearing transparency restores opaque faces through history");
|
||||
}
|
||||
}
|
||||
result.status = "not_implemented";
|
||||
stage("assertions-complete");
|
||||
} catch (error) { result.error = error.stack ?? String(error); stage("failed"); }
|
||||
finally { await browser?.close(); stage("cleanup-complete"); }
|
||||
fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n");
|
||||
return [result];
|
||||
}
|
||||
|
||||
async function assertSourceInheritance({ page, run, record, stage, directory, result, documentId }) {
|
||||
await run({ action: "create" });
|
||||
await run({ action: "setBox", object: "Box", dimensions: [10,8,10] });
|
||||
await run({ action: "setBox", object: "CrossingBox", dimensions: [8,10,10] });
|
||||
const setColor = (object, color) => run({ action: "setFaceColors", selection: [{ documentId, object }],
|
||||
faceColors: Array.from({ length: 6 }, () => color) });
|
||||
await setColor("Box", [1,0,0,1]);
|
||||
await setColor("CrossingBox", [0,0,1,1]);
|
||||
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
|
||||
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
|
||||
const ready = () => page.waitForFunction(() => {
|
||||
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset');
|
||||
return fieldset && !fieldset.disabled;
|
||||
});
|
||||
const click = async name => { await panel.getByRole("button", { name, exact: true }).click(); await ready(); };
|
||||
await ready();
|
||||
await panel.getByLabel("Intersecting objects", { exact: true }).check();
|
||||
await panel.getByLabel("Cut Z", { exact: true }).check();
|
||||
await panel.getByLabel("Cut Z position", { exact: true }).fill("5");
|
||||
await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00");
|
||||
await panel.getByLabel("Custom fragment color", { exact: true }).uncheck();
|
||||
await click("Apply section cut");
|
||||
assert.deepEqual(await panel.getByRole("status").allTextContents(), [], "Mounted Section Cut apply must succeed");
|
||||
const check = (state, firstColor = [1,0,0], height = 5) => {
|
||||
const session = state.objects.find(item => item.sectionCutSession)?.sectionCutSession;
|
||||
assert.ok(session, JSON.stringify(state));
|
||||
const output = state.objects.find(item => item.name === session.result);
|
||||
assert.equal(session.fragmentColor, "");
|
||||
assert.equal(output.topology.valid, true);
|
||||
assert.ok(Math.abs(output.volume - 96 * height) < 1e-6);
|
||||
const fragments = state.objects.find(item => item.name.startsWith("SectionCutCompound"));
|
||||
assert.equal(fragments.topology.Solid, 3);
|
||||
assert.ok(fragments.mesh.triangleCount > fragments.faceColors.length * 2,
|
||||
"Fixture exercises repeated shared rectangular faces, not just disjoint solids");
|
||||
const { positions, colors, alphas, triangleCount } = output.mesh;
|
||||
assert.equal(colors.length, triangleCount * 9);
|
||||
assert.equal(alphas.length, triangleCount * 3);
|
||||
let red = 0, blue = 0, green = 0;
|
||||
for (let t = 0; t < triangleCount; ++t) {
|
||||
const vertices = [0,3,6].map(v => positions.slice(t * 9 + v, t * 9 + v + 3));
|
||||
const section = vertices.every(v => Math.abs(v[2] - height) < 1e-6);
|
||||
// Exterior x=10 belongs only to Box; y=10 only to CrossingBox.
|
||||
const onlyFirst = vertices.every(v => Math.abs(v[0] - 10) < 1e-6);
|
||||
const onlySecond = vertices.every(v => Math.abs(v[1] - 10) < 1e-6);
|
||||
const rgb = colors.slice(t * 9, t * 9 + 3);
|
||||
const expected = section ? [0,1,0] : onlyFirst ? firstColor : onlySecond ? [0,0,1] : null;
|
||||
if (expected) assert.deepEqual(rgb, expected, JSON.stringify({ vertices, rgb, expected }));
|
||||
else assert.ok([firstColor, [0,0,1]].some(c => c.every((v,i) => v === rgb[i])), JSON.stringify({vertices,rgb}));
|
||||
for (let v = 0; v < 3; ++v) {
|
||||
assert.deepEqual(colors.slice(t * 9 + v * 3, t * 9 + v * 3 + 3), rgb);
|
||||
assert.equal(alphas?.[t * 3 + v] ?? 1, 1);
|
||||
}
|
||||
if (section) green++; else if (rgb[2] === 1) blue++; else red++;
|
||||
}
|
||||
assert.ok(red > 0 && blue > 0 && green > 0, JSON.stringify({red,blue,green}));
|
||||
return { volume: output.volume, red, blue, green, faceColors: output.faceColors };
|
||||
};
|
||||
const initial = check(await run({ action: "snapshot" }));
|
||||
record({ sources: ["red Box", "blue CrossingBox"], cut: "green Z=5", fragmentColor: "inherited" }, initial,
|
||||
"OCCT split faces inherit source materials; spatially distinct source faces and cut faces carry correct RGB");
|
||||
check(await setColor("Box", [1,1,0,1]), [1,1,0]);
|
||||
check(await run({ action: "undo" }));
|
||||
check(await run({ action: "redo" }), [1,1,0]);
|
||||
await run({ action: "save", path: "/tmp/SectionCutSourceInheritance.FCStd" });
|
||||
await run({ action: "close" });
|
||||
check(await run({ action: "open", path: "/tmp/SectionCutSourceInheritance.FCStd" }), [1,1,0]);
|
||||
await click("Refresh section cut");
|
||||
assert.equal(await panel.getByLabel("Custom fragment color", { exact: true }).isChecked(), false);
|
||||
await panel.getByLabel("Cut Z position", { exact: true }).fill("4");
|
||||
await click("Apply section cut");
|
||||
check(await run({ action: "snapshot" }), [1,1,0], 4);
|
||||
await click("Refresh cut sources");
|
||||
const restored = check(await run({ action: "snapshot" }), [1,1,0], 4);
|
||||
record({ operations: ["live source color", "undo", "redo", "FCStd reopen", "plane edit", "source refresh"] }, restored,
|
||||
"Inherited fragment colors follow current source properties and regenerated topology through native history and persistence");
|
||||
await click("Refresh section cut");
|
||||
const canvas = panel.locator("canvas").first();
|
||||
for (const width of [1440,390]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await canvas.scrollIntoViewIfNeeded(); await page.waitForTimeout(300);
|
||||
const file = path.join(directory, `inherited-${width}.png`);
|
||||
const png = await canvas.screenshot({ path: file });
|
||||
result.evidenceFiles[file] = createHash("sha256").update(png).digest("hex");
|
||||
const pixels = await page.evaluate(async base64 => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
|
||||
const raster = document.createElement("canvas"); raster.width = image.width; raster.height = image.height;
|
||||
const ctx = raster.getContext("2d"); ctx.drawImage(image,0,0);
|
||||
const data = ctx.getImageData(0,0,raster.width,raster.height).data;
|
||||
let yellow = 0, blue = 0, green = 0;
|
||||
for (let i=0;i<data.length;i+=4) {
|
||||
if (data[i] > data[i+2]+20 && data[i+1] > data[i+2]+20) yellow++;
|
||||
if (data[i+2] > data[i]+20 && data[i+2] > data[i+1]+20) blue++;
|
||||
if (data[i+1] > data[i]+20 && data[i+1] > data[i+2]+20) green++;
|
||||
}
|
||||
return { yellow, blue, green };
|
||||
}, png.toString("base64"));
|
||||
assert.ok(pixels.yellow > 100 && pixels.blue > 100 && pixels.green > 100, JSON.stringify(pixels));
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
record({ viewport: width }, pixels, "Mounted native geometry shows both inherited materials and the independent section material");
|
||||
}
|
||||
stage("source-inheritance-complete");
|
||||
}
|
||||
|
||||
async function assertMultiSourceAppearance({ page, run, record, stage, directory, result }) {
|
||||
await run({ action: "create" });
|
||||
await run({ action: "setBox", object: "Box", dimensions: [10, 8, 10] });
|
||||
await run({ action: "setBox", object: "CrossingBox", dimensions: [8, 10, 10] });
|
||||
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
|
||||
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
|
||||
const ready = () => page.waitForFunction(() => {
|
||||
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset');
|
||||
return fieldset && !fieldset.disabled;
|
||||
});
|
||||
const click = async name => { await panel.getByRole("button", { name, exact: true }).click(); await ready(); };
|
||||
await ready();
|
||||
await panel.getByLabel("Intersecting objects", { exact: true }).check();
|
||||
await panel.getByLabel("Cut X", { exact: true }).check();
|
||||
await panel.getByLabel("Cut X position", { exact: true }).fill("5");
|
||||
await panel.getByLabel("Custom fragment color", { exact: true }).check();
|
||||
await panel.getByLabel("Fragment color", { exact: true }).fill("#ffff00");
|
||||
await panel.getByLabel("Fragment transparency", { exact: true }).fill("60");
|
||||
await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00");
|
||||
await panel.getByLabel("Cut face transparency", { exact: true }).fill("65");
|
||||
await click("Apply section cut");
|
||||
const session = state => state.objects.find(item => item.sectionCutSession).sectionCutSession;
|
||||
const output = state => state.objects.find(item => item.name === session(state).result);
|
||||
const near = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
|
||||
const check = (state, volume, plane, fragmentAlpha = 0.4, cutAlpha = 0.35) => {
|
||||
const cut = output(state), settings = session(state);
|
||||
assert.equal(settings.intersecting, true);
|
||||
assert.deepEqual([...settings.sources].sort(), ["Box", "CrossingBox"]);
|
||||
assert.equal(cut.topology.valid, true); near(cut.volume, volume);
|
||||
const compound = state.objects.find(item => item.name.startsWith("SectionCutCompound"));
|
||||
assert.equal(compound.type, "Part::FeaturePython");
|
||||
assert.equal(compound.topology.Solid, 3, "Actual BooleanFragments partition overlapping sources");
|
||||
const { positions, colors, alphas, triangleCount } = cut.mesh;
|
||||
assert.equal(colors.length, triangleCount * 9); assert.equal(alphas.length, triangleCount * 3);
|
||||
let sectionTriangles = 0, sourceTriangles = 0;
|
||||
for (let triangle = 0; triangle < triangleCount; ++triangle) {
|
||||
const start = triangle * 9;
|
||||
const section = [0, 3, 6].every(offset => Math.abs(positions[start + offset] - plane) < 1e-6);
|
||||
section ? ++sectionTriangles : ++sourceTriangles;
|
||||
for (let vertex = 0; vertex < 3; ++vertex) {
|
||||
const rgb = colors.slice(start + vertex * 3, start + vertex * 3 + 3);
|
||||
assert.deepEqual(rgb, section ? [0, 1, 0] : [1, 1, 0],
|
||||
JSON.stringify({ triangle, section, positions: positions.slice(start, start + 9), rgb, faceColors: cut.faceColors }));
|
||||
near(alphas[triangle * 3 + vertex], section ? cutAlpha : fragmentAlpha);
|
||||
}
|
||||
}
|
||||
assert.ok(sectionTriangles > 0 && sourceTriangles > 0);
|
||||
return { volume: cut.volume, solids: compound.topology.Solid, sectionTriangles, sourceTriangles };
|
||||
};
|
||||
const initial = await run({ action: "snapshot" });
|
||||
const snapshotFile = path.join(directory, "initial-native-snapshot.json");
|
||||
fs.writeFileSync(snapshotFile, JSON.stringify(initial, null, 2) + "\n");
|
||||
result.evidenceFiles[snapshotFile] = createHash("sha256").update(fs.readFileSync(snapshotFile)).digest("hex");
|
||||
record({ boxes: [[10,8,10], [8,10,10]], cutX: 5, intersecting: true }, check(initial, 500, 5),
|
||||
"Overlapping sources produce partitioned OCCT geometry and spatially correct independent cut and fragment RGBA");
|
||||
await panel.getByLabel("Cut X position", { exact: true }).fill("4");
|
||||
await click("Apply section cut");
|
||||
const changed = await run({ action: "snapshot" }); check(changed, 400, 4);
|
||||
check(await run({ action: "undo" }), 500, 5);
|
||||
check(await run({ action: "redo" }), 400, 4);
|
||||
await run({ action: "save", path: "/tmp/SectionCutMultiSourceAppearance.FCStd" });
|
||||
await run({ action: "close" });
|
||||
const reopened = await run({ action: "open", path: "/tmp/SectionCutMultiSourceAppearance.FCStd" });
|
||||
const restoredCutAlpha = Math.round(0.35 * 255) / 255;
|
||||
check(reopened, 400, 4, 0.4, restoredCutAlpha);
|
||||
output(reopened).faceColors.forEach((color, face) => color.forEach((value, channel) =>
|
||||
near(value, Math.round(output(changed).faceColors[face][channel] * 255) / 255)));
|
||||
await click("Refresh section cut");
|
||||
assert.equal(await panel.getByLabel("Intersecting objects", { exact: true }).isChecked(), true);
|
||||
assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60");
|
||||
await click("Refresh cut sources");
|
||||
check(await run({ action: "snapshot" }), 400, 4);
|
||||
record({ operations: ["plane edit", "undo", "redo", "FCStd reopen", "source refresh"] }, check(reopened, 400, 4, 0.4, restoredCutAlpha),
|
||||
"Intersecting-source materials follow edited topology and survive transactions and FCStd restoration");
|
||||
const pixels = [];
|
||||
const canvas = panel.locator("canvas").first();
|
||||
const sample = async file => {
|
||||
// The renderer does not preserve its drawing buffer after composition.
|
||||
// Read the visible canvas image, as the other appearance cases do.
|
||||
const png = await canvas.screenshot({ path: file });
|
||||
result.evidenceFiles[file] = createHash("sha256").update(png).digest("hex");
|
||||
return page.evaluate(async base64 => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
|
||||
const raster = document.createElement("canvas"); raster.width = image.width; raster.height = image.height;
|
||||
const ctx = raster.getContext("2d"); ctx.drawImage(image, 0, 0);
|
||||
const bytes = ctx.getImageData(0, 0, raster.width, raster.height).data;
|
||||
let yellow = 0, green = 0;
|
||||
for (let i = 0; i < bytes.length; i += 4) {
|
||||
if (bytes[i] > bytes[i+2] + 20 && bytes[i+1] > bytes[i+2] + 20) ++yellow;
|
||||
if (bytes[i+1] > bytes[i] + 20 && bytes[i+1] > bytes[i+2] + 20) ++green;
|
||||
}
|
||||
return { yellow, green };
|
||||
}, png.toString("base64"));
|
||||
};
|
||||
for (const width of [1440, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 }); await canvas.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(500);
|
||||
const file = path.join(directory, `multi-source-${width}.png`);
|
||||
const before = await sample(file); assert.ok(before.yellow > 100); assert.ok(before.green > 100);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
await panel.getByLabel("Fragment transparency", { exact: true }).fill("100");
|
||||
await click("Apply section cut"); check(await run({ action: "snapshot" }), 400, 4, 0);
|
||||
await canvas.scrollIntoViewIfNeeded(); await page.waitForTimeout(500);
|
||||
const after = await sample(path.join(directory, `multi-source-hidden-${width}.png`));
|
||||
assert.ok(after.yellow < before.yellow * 0.05); assert.ok(after.green > 100);
|
||||
pixels.push({ width, before, after });
|
||||
await panel.getByLabel("Fragment transparency", { exact: true }).fill("60");
|
||||
await click("Apply section cut");
|
||||
}
|
||||
record({ widths: [1440,390], fragmentTransparency: [60,100] }, pixels,
|
||||
"Actual desktop/mobile canvases hide transparent BooleanFragments surfaces while retaining independent cut faces");
|
||||
stage("multi-source-appearance-complete");
|
||||
}
|
||||
|
||||
export async function runSectionCutContainerCases(ids) {
|
||||
const capabilityId = "Part:desktop:Part_SectionCut";
|
||||
if (!ids.includes(capabilityId)) return [];
|
||||
const directory = path.resolve("docs/current/part-section-cut-containers", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const started = performance.now();
|
||||
const stages = [];
|
||||
const stage = (name, detail = {}) => {
|
||||
stages.push({ name, elapsedMs: performance.now() - started, ...detail });
|
||||
fs.writeFileSync(path.join(directory, "stages.json"), JSON.stringify(stages, null, 2) + "\n");
|
||||
};
|
||||
const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {},
|
||||
deferredCases: ["runLegacySectionCutCases", "runSectionCutEmptySourcesCases", "runSectionCutFragmentsCases", "runSectionCutOpacityCases", "runSectionCutPersistenceCases"],
|
||||
remaining: ["Automatic cut-face coloring and color controls", "Independent cut-face and fragment appearance/transparency",
|
||||
"Container reparenting", "Unexpected post-mutation failure history behavior"] };
|
||||
const record = (input, actual, name) => {
|
||||
result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
|
||||
fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n");
|
||||
};
|
||||
const session = state => state.objects.find(item => item.sectionCutSession)?.sectionCutSession;
|
||||
const objects = state => Object.fromEntries(state.objects.map(item => [item.name, item]));
|
||||
const signature = state => ({ objects: objects(state), undoCount: state.undoCount, redoCount: state.redoCount });
|
||||
const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
|
||||
const check = (state, bounds, volume) => {
|
||||
const cut = state.objects.find(item => item.name === session(state)?.result);
|
||||
assert.ok(cut); near(cut.volume, volume); assert.equal(cut.topology.valid, true);
|
||||
assert.ok(cut.mesh.triangleCount > 0); cut.mesh.bounds.forEach((value, i) => near(value, bounds[i]));
|
||||
assert.equal(cut.faceColors?.length, 6, "Cut retains a material for each native face after edits/history/reopen");
|
||||
assert.ok(new Set(cut.faceColors.map(color => color.join(","))).size >= 5,
|
||||
"Five distinct surviving source materials persist through geometry edits, history and FCStd reopen");
|
||||
assert.equal(cut.mesh.colors?.length, cut.mesh.triangleCount * 9, "Native face materials reach every rendered vertex");
|
||||
assert.deepEqual(session(state).sources, ["Box"]);
|
||||
return { bounds: cut.mesh.bounds, volume: cut.volume, triangles: cut.mesh.triangleCount };
|
||||
};
|
||||
const sameNativeResult = (state, expected, bounds, volume) => {
|
||||
assert.deepEqual(state.objects.map(item => item.name).sort(), expected.objects.map(item => item.name).sort());
|
||||
assert.equal(session(state).result, session(expected).result);
|
||||
return check(state, bounds, volume);
|
||||
};
|
||||
let browser;
|
||||
try {
|
||||
for (const file of ["tools/part-section-cut-container-business-cases.mjs", "tools/part-section-cut-business-cases.mjs",
|
||||
"web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts",
|
||||
"web/src/part-view-facade.ts", "web/src/workbench-shell.tsx",
|
||||
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h",
|
||||
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartColoredIO.h",
|
||||
...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
|
||||
result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
stage("browser-launch-enter");
|
||||
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? "/usr/bin/google-chrome",
|
||||
headless: process.env.HEADLESS !== "0", args: ["--no-sandbox", "--disable-dev-shm-usage"] });
|
||||
stage("browser-launch-complete");
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
||||
const errors = []; page.on("pageerror", error => errors.push(String(error)));
|
||||
const documentId = "SectionCutContainers";
|
||||
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`);
|
||||
const dispatch = async (command, payload, expectError = false) => {
|
||||
stage("request-enter", { command, action: payload.action ?? payload.parameters?.operation });
|
||||
await page.locator("aside > button.command").filter({ has: page.getByText(command, { exact: true }) }).click();
|
||||
await page.locator("#payload-editor").fill(JSON.stringify(payload));
|
||||
await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; });
|
||||
await page.getByRole("button", { name: "执行选中命令", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled);
|
||||
const reply = await page.evaluate(() => window.__freecadWorkbenchState.response);
|
||||
assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply));
|
||||
stage("request-complete", { command, action: payload.action ?? payload.parameters?.operation, kind: reply.kind });
|
||||
return expectError ? reply.error : reply.result;
|
||||
};
|
||||
const run = (args, expectError = false) => dispatch("part.document", { schema: "freecad-web-part/document/v1", module: "Part",
|
||||
document: documentId, builderInfo: true, includeMesh: true, ...args }, expectError);
|
||||
const python = async source => {
|
||||
const reply = await dispatch("part.documentViewCommand", { schema: "freecad-web/document-view/v1", owner: "DocumentProbe",
|
||||
document: documentId, command: "Std_CommandLine", parameters: { operation: "submit", source: `exec(${JSON.stringify(source)})` } });
|
||||
assert.equal(reply.stderr, "", JSON.stringify(reply));
|
||||
};
|
||||
const snapshot = () => run({ action: "snapshot" });
|
||||
await run({ action: "create" });
|
||||
await python(`import FreeCAD as App\nd=App.getDocument('${documentId}')\np=d.addObject('App::Part','Outer')\nn=d.addObject('App::Part','Inner')\np.addObject(n)\nb=d.addObject('Part::Box','Box')\nb.Length=2\nb.Width=4\nb.Height=6\nn.addObject(b)\np.Placement=App.Placement(App.Vector(20,30,40),App.Rotation(App.Vector(0,0,1),90))\nn.Placement.Base=App.Vector(3,0,0)\nb.Placement.Base=App.Vector(1,0,0)\nd.recompute()`);
|
||||
const palette = [[1,0,0,1],[0,1,0,1],[0,0,1,1],[1,1,0,1],[1,0,1,1],[0,1,1,1]];
|
||||
await python(`b.addProperty('App::PropertyColorList','WebFaceColors')\nb.WebFaceColors=[tuple(float(x) for x in color) for color in ${JSON.stringify(palette)}]\nd.recompute()`);
|
||||
const before = await snapshot();
|
||||
const source = objects(before).Box; source.mesh.bounds.forEach((v, i) => near(v, [16,34,40,20,36,46][i]));
|
||||
const other = await run({ action: "create", document: "ContainerCutOther" }); await snapshot();
|
||||
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
|
||||
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
|
||||
const ready = () => page.waitForFunction(() => {
|
||||
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled;
|
||||
});
|
||||
const click = async name => {
|
||||
stage("panel-request-enter", { button: name });
|
||||
await panel.getByRole("button", { name, exact: true }).click(); await ready();
|
||||
assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
|
||||
stage("panel-request-complete", { button: name });
|
||||
};
|
||||
await ready(); await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check();
|
||||
await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("18");
|
||||
await click("Apply section cut"); const first = await snapshot();
|
||||
const firstGeometry = check(first, [16,34,40,18,36,46], 24);
|
||||
const firstCut = objects(first)[session(first).result];
|
||||
// Under the parent's Z rotation, the blue source Y-min face is the
|
||||
// removed world X-max face. All five other source planes survive.
|
||||
const faceRgb = firstCut.faceColors.map(color => color.slice(0, 3).join(","));
|
||||
for (const color of [palette[0], palette[1], palette[3], palette[4], palette[5]])
|
||||
assert.ok(faceRgb.includes(color.slice(0,3).join(",")), `Surviving source face lost material ${color}`);
|
||||
assert.ok(!faceRgb.includes("0,0,1"), "Removed source face cannot color the result");
|
||||
const vertexColors = new Set(Array.from({ length: firstCut.mesh.colors.length / 3 },
|
||||
(_, i) => firstCut.mesh.colors.slice(i * 3, i * 3 + 3).join(",")));
|
||||
assert.deepEqual([...vertexColors].sort(), [...new Set(faceRgb)].sort());
|
||||
await python("d.openTransaction('Edit section source colors')\nb.WebFaceColors=[(0.25,0.5,0.75,1)]\nd.recompute()\nd.commitTransaction()");
|
||||
const recolored = await snapshot();
|
||||
const recoloredCut = objects(recolored)[session(recolored).result];
|
||||
assert.deepEqual(recoloredCut.faceColors, Array.from({ length: 6 }, () => [0.25,0.5,0.75,1]));
|
||||
assert.deepEqual(recolored.objects.map(item => item.name), first.objects.map(item => item.name));
|
||||
assert.deepEqual(recoloredCut.mesh.colors, Array.from({ length: recoloredCut.mesh.triangleCount * 3 }, () => [0.25,0.5,0.75]).flat());
|
||||
const colorUndo = await run({ action: "undo" });
|
||||
assert.deepEqual(objects(colorUndo)[session(colorUndo).result].faceColors, firstCut.faceColors);
|
||||
const colorRedo = await run({ action: "redo" });
|
||||
assert.deepEqual(objects(colorRedo)[session(colorRedo).result].faceColors, recoloredCut.faceColors);
|
||||
await run({ action: "undo" });
|
||||
record({ operation: "inherit six source face colors through rotated link, compound and cut; edit and undo/redo colors" },
|
||||
{ faceColors: firstCut.faceColors, renderedVertexColors: [...vertexColors], liveColorEdit: true },
|
||||
"Native face history preserves surviving source materials and current colors reach browser mesh without rebuilding helpers");
|
||||
assert.deepEqual(objects(first).Outer, objects(before).Outer); assert.deepEqual(objects(first).Inner, objects(before).Inner);
|
||||
const link = first.objects.find(item => item.type === "App::Link");
|
||||
link.mesh.bounds.forEach((v, i) => near(v, source.mesh.bounds[i]));
|
||||
await click("Section cut undo"); assert.deepEqual(objects(await snapshot()), objects(before));
|
||||
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(first));
|
||||
record({ outer: { position: [20,30,40], rotationZ: 90 }, inner: [3,0,0], source: [1,0,0], planeX: 18 }, firstGeometry,
|
||||
"Nested container rotation and translation reach the native cut link and world-space plane without changing source membership");
|
||||
|
||||
await python("d.openTransaction('Move outer')\np.Placement.Base=App.Vector(21,30,40)\nd.recompute()\nd.commitTransaction()");
|
||||
const automatic = await snapshot(); check(automatic, [17,34,40,18,36,46], 12);
|
||||
assert.deepEqual(automatic.objects.map(item => item.name).sort(), first.objects.map(item => item.name).sort());
|
||||
assert.equal(session(automatic).result, session(first).result);
|
||||
await click("Section cut undo"); check(await snapshot(), [16,34,40,18,36,46], 24);
|
||||
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(automatic));
|
||||
record({ operation: "move ancestor and recompute without sources refresh" }, check(automatic, [17,34,40,18,36,46], 12),
|
||||
"Ancestor placement changes recompute the existing native cut, with undo/redo and stable helper identity");
|
||||
await click("Refresh cut sources"); const moved = await snapshot(); check(moved, [17,34,40,18,36,46], 12);
|
||||
await click("Section cut undo"); check(await snapshot(), [17,34,40,18,36,46], 12);
|
||||
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(moved));
|
||||
await run({ action: "setPosition", object: "Box", position: [2,0,0] });
|
||||
const edited = await snapshot(); check(edited, [17,35,40,18,37,46], 12);
|
||||
await click("Section cut undo"); const stable = await snapshot(); check(stable, [17,34,40,18,36,46], 12);
|
||||
assert.ok(stable.redoCount > 0);
|
||||
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply",
|
||||
axes: session(stable).axes.map((axis, i) => i ? axis : { ...axis, position: 1 }) } }, true);
|
||||
assert.match(rejected.message, /outside source bounds/); assert.deepEqual(signature(await snapshot()), signature(stable));
|
||||
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(edited));
|
||||
record({ operation: "move ancestor, refresh, edit source, reject local-space plane, redo" }, { volumes: [24,12], redoPreserved: true },
|
||||
"Refresh preserves ancestor movement; linked source edits recompute in container coordinates and invalid world planes preserve redo");
|
||||
|
||||
await python("d.openTransaction('Move beyond original cutter')\np.Placement.Base=App.Vector(21,130,140)\nd.recompute()\nd.commitTransaction()");
|
||||
const distant = await snapshot(); check(distant, [17,135,140,18,137,146], 12);
|
||||
assert.deepEqual(distant.objects.map(item => item.name).sort(), edited.objects.map(item => item.name).sort());
|
||||
await click("Section cut undo"); sameNativeResult(await snapshot(), edited, [17,35,40,18,37,46], 12);
|
||||
await click("Section cut redo"); sameNativeResult(await snapshot(), distant, [17,135,140,18,137,146], 12);
|
||||
await python("d.openTransaction('Enlarge linked source')\nb.Height=120\nd.recompute()\nd.commitTransaction()");
|
||||
const enlarged = await snapshot(); check(enlarged, [17,135,140,18,137,260], 240);
|
||||
const flipped = await run({ action: "sectionCut", sectionCut: { operation: "apply",
|
||||
axes: session(enlarged).axes.map((axis, i) => i ? axis : { ...axis, flipped: true }) } });
|
||||
check(flipped, [18,135,140,21,137,260], 720);
|
||||
await python("d.openTransaction('Move flipped cutter bounds')\np.Placement.Base=App.Vector(21,230,240)\nd.recompute()\nd.commitTransaction()");
|
||||
const flippedMoved = await snapshot(); check(flippedMoved, [18,235,240,21,237,360], 720);
|
||||
await click("Section cut undo"); sameNativeResult(await snapshot(), flipped, [18,135,140,21,137,260], 720);
|
||||
await click("Section cut redo"); sameNativeResult(await snapshot(), flippedMoved, [18,235,240,21,237,360], 720);
|
||||
await click("Section cut undo");
|
||||
await click("Section cut undo"); sameNativeResult(await snapshot(), enlarged, [17,135,140,18,137,260], 240);
|
||||
await click("Section cut undo"); sameNativeResult(await snapshot(), distant, [17,135,140,18,137,146], 12);
|
||||
await click("Section cut undo"); sameNativeResult(await snapshot(), edited, [17,35,40,18,37,46], 12);
|
||||
record({ operation: "move source 100 mm in Y/Z and enlarge height to 120 without refresh", planeX: 18 },
|
||||
{ moved: check(distant, [17,135,140,18,137,146], 12), enlarged: check(enlarged, [17,135,140,18,137,260], 240),
|
||||
flippedMoved: check(flippedMoved, [18,235,240,21,237,360], 720) },
|
||||
"Native cutter bounds follow movement and resizing beyond original extents in both cut directions, preserving helper identity and undo/redo");
|
||||
|
||||
await run({ action: "save", path: "/tmp/SectionCutContainers.FCStd" }); await run({ action: "close" });
|
||||
const reopened = await run({ action: "open", path: "/tmp/SectionCutContainers.FCStd" });
|
||||
check(reopened, [17,35,40,18,37,46], 12);
|
||||
assert.deepEqual(session(reopened), session(edited));
|
||||
assert.deepEqual(objects(reopened).Outer.groupMembers, ["Inner"]); assert.deepEqual(objects(reopened).Inner.groupMembers, ["Box"]);
|
||||
await python(`d=App.getDocument('${documentId}')\nn=d.getObject('Inner')\nd.openTransaction('Rotate restored inner')\nn.Placement.Rotation=App.Rotation(App.Vector(0,0,1),90)\nd.recompute()\nd.commitTransaction()`);
|
||||
const rotated = await snapshot(); check(rotated, [17,29,40,18,33,46], 24);
|
||||
await click("Section cut undo"); check(await snapshot(), [17,35,40,18,37,46], 12);
|
||||
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(rotated));
|
||||
record({ operation: "rotate inner ancestor after FCStd reopen without sources refresh", rotationZ: 90 },
|
||||
check(rotated, [17,29,40,18,33,46], 24), "FCStd preserves native ancestor expression dependencies and noncommuting placement order");
|
||||
await python("p=d.getObject('Outer')\nd.openTransaction('Move restored cutter bounds')\np.Placement.Base=App.Vector(21,130,140)\nd.recompute()\nd.commitTransaction()");
|
||||
const restoredDistant = await snapshot(); check(restoredDistant, [17,129,140,18,133,146], 24);
|
||||
await click("Section cut undo"); assert.deepEqual(objects(await snapshot()), objects(rotated));
|
||||
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(restoredDistant));
|
||||
await click("Section cut undo");
|
||||
record({ operation: "move restored ancestor beyond original cutter extents without refresh" },
|
||||
check(restoredDistant, [17,129,140,18,133,146], 24),
|
||||
"FCStd restores cutter bound expressions as live native dependencies with executable undo/redo");
|
||||
await click("Refresh section cut");
|
||||
for (const [name, width, height] of [["desktop",1440,900],["mobile",390,844]]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
const canvas = panel.locator('[aria-label="Section cut geometry"] canvas');
|
||||
const beforeOrbit = await canvas.screenshot();
|
||||
const area = await canvas.boundingBox(); assert.ok(area);
|
||||
await page.mouse.move(area.x + area.width * 0.5, area.y + area.height * 0.5);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(area.x + area.width * 0.65, area.y + area.height * 0.6, { steps: 8 });
|
||||
await page.mouse.up(); await page.waitForTimeout(150);
|
||||
const png = await canvas.screenshot();
|
||||
assert.notDeepEqual(png, beforeOrbit, `${name}: orbit must change rendered geometry`);
|
||||
const count = await page.evaluate(async base64 => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
|
||||
const canvas = document.createElement("canvas"); canvas.width=image.width; canvas.height=image.height;
|
||||
const ctx=canvas.getContext("2d");ctx.drawImage(image,0,0);const data=ctx.getImageData(0,0,canvas.width,canvas.height).data;
|
||||
let count=0;for(let i=0;i<data.length;i+=4) if(Math.max(data[i],data[i+1],data[i+2])-Math.min(data[i],data[i+1],data[i+2])>12)count++;
|
||||
return count;
|
||||
},png.toString("base64"));
|
||||
assert.ok(count>100,`${name}: ${count} geometry pixels`);
|
||||
const file=path.join(directory,`${name}-canvas.png`);fs.writeFileSync(file,png);
|
||||
result.evidenceFiles[path.relative(process.cwd(),file)]=createHash("sha256").update(png).digest("hex");
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
record({operation:"FCStd restored container cut after ancestor rotation",viewport:[width,height]},{pixels:count,volume:24,orbitChanged:true},
|
||||
"Saved container/link placement restores actual world-space cut geometry and visible desktop/mobile canvas");
|
||||
}
|
||||
assert.deepEqual(signature(await run({action:"snapshot",document:"ContainerCutOther"})),signature(other));
|
||||
assert.deepEqual(errors,[]);result.status="not_implemented";
|
||||
} catch(error) {result.error=String(error.stack??error);process.stderr.write(result.error+"\n");}
|
||||
finally {stage("cleanup-enter"); await browser?.close(); stage("cleanup-complete");}
|
||||
fs.writeFileSync(path.join(directory,"result.json"),JSON.stringify(result,null,2)+"\n");return [result];
|
||||
}
|
||||
165
tools/part-section-cut-opacity-cases.mjs
Normal file
165
tools/part-section-cut-opacity-cases.mjs
Normal file
@@ -0,0 +1,165 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { playwright } from "./part-primitive-business-cases.mjs";
|
||||
|
||||
export async function runSectionCutOpacityCases(ids) {
|
||||
const capabilityId = "Part:desktop:Part_SectionCut";
|
||||
if (!ids.includes(capabilityId)) return [];
|
||||
const directory = path.resolve("docs/current/part-section-cut-opacity", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {},
|
||||
deferredCases: ["runLegacySectionCutCases", "runSectionCutEmptySourcesCases", "runSectionCutFragmentsCases"],
|
||||
remaining: ["Automatic cut-face coloring and color controls", "Independent cut-face and fragment appearance/transparency"] };
|
||||
const record = (input, actual, name) => {
|
||||
result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
|
||||
fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n");
|
||||
};
|
||||
const session = state => state.objects.find(item => item.sectionCutSession)?.sectionCutSession;
|
||||
const objects = state => Object.fromEntries(state.objects.map(item => [item.name, item]));
|
||||
const signature = state => ({ objects: objects(state), undoCount: state.undoCount, redoCount: state.redoCount });
|
||||
const near = (a, b) => assert.ok(Number.isFinite(a) && Math.abs(a - b) < 1e-6, `${a} != ${b}`);
|
||||
const check = (state, transparency, volume = 800) => {
|
||||
const cut = state.objects.find(item => item.name === session(state).result);
|
||||
assert.equal(session(state).resultTransparency, transparency);
|
||||
near(cut.displayOpacity, 1 - transparency / 100); near(cut.volume, volume);
|
||||
assert.equal(cut.topology.valid, true); assert.ok(cut.mesh.triangleCount > 0);
|
||||
for (const name of session(state).sources) assert.equal(state.objects.find(item => item.name === name).displayOpacity, undefined);
|
||||
return cut;
|
||||
};
|
||||
let browser;
|
||||
try {
|
||||
for (const file of ["tools/part-section-cut-opacity-cases.mjs", "tools/part-section-cut-business-cases.mjs",
|
||||
"web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts",
|
||||
"web/src/workbench-shell.tsx", "web/src/scene-viewport.tsx", "web/src/scene-document.ts",
|
||||
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h",
|
||||
"freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp",
|
||||
...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
|
||||
result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? "/usr/bin/google-chrome",
|
||||
headless: process.env.HEADLESS !== "0", args: ["--no-sandbox", "--disable-dev-shm-usage"] });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
||||
const errors = []; page.on("pageerror", error => errors.push(String(error)));
|
||||
const documentId = "SectionCutOpacity";
|
||||
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`);
|
||||
const run = async (args, expectError = false) => {
|
||||
await page.locator("aside > button.command").filter({ has: page.locator("span", { hasText: /^part.document$/ }) }).click();
|
||||
await page.locator("#payload-editor").fill(JSON.stringify({ schema: "freecad-web-part/document/v1", module: "Part",
|
||||
document: documentId, builderInfo: true, includeMesh: true, ...args }));
|
||||
await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; });
|
||||
await page.getByRole("button", { name: "执行选中命令", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled);
|
||||
const reply = await page.evaluate(() => window.__freecadWorkbenchState.response);
|
||||
assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply)); return expectError ? reply.error : reply.result;
|
||||
};
|
||||
const snapshot = () => run({ action: "snapshot" });
|
||||
await run({ action: "create" }); await run({ action: "setBox", object: "A", dimensions: [10, 10, 10] });
|
||||
await run({ action: "setBox", object: "B", dimensions: [10, 10, 10] });
|
||||
await run({ action: "setPosition", object: "B", position: [5, 0, 0] });
|
||||
const other = await run({ action: "create", document: "OpacityOther" }); await snapshot();
|
||||
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
|
||||
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
|
||||
const ready = () => page.waitForFunction(() => {
|
||||
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled;
|
||||
});
|
||||
const click = async name => {
|
||||
await panel.getByRole("button", { name, exact: true }).click(); if (name === "Close section cutting") return;
|
||||
await ready(); assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
|
||||
};
|
||||
const transparency = panel.getByRole("spinbutton", { name: "Result surface transparency", exact: true });
|
||||
const apply = panel.getByRole("button", { name: "Apply section cut", exact: true });
|
||||
const canvas = panel.locator('[aria-label="Section cut geometry"] canvas');
|
||||
const pixels = async name => {
|
||||
const png = await canvas.screenshot();
|
||||
const metrics = await page.evaluate(async base64 => {
|
||||
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
|
||||
const canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height;
|
||||
const ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0);
|
||||
const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data; let contrast = 0;
|
||||
for (let i = 0; i < data.length; i += 4) contrast += Math.abs(data[i] - 241) + Math.abs(data[i+1] - 243) + Math.abs(data[i+2] - 245);
|
||||
return { contrast, width: canvas.width, height: canvas.height };
|
||||
}, png.toString("base64"));
|
||||
const file = path.join(directory, `${name}.png`); fs.writeFileSync(file, png);
|
||||
result.evidenceFiles[path.relative(process.cwd(), file)] = createHash("sha256").update(png).digest("hex");
|
||||
return metrics;
|
||||
};
|
||||
await ready(); await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check();
|
||||
await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("8");
|
||||
await panel.getByRole("checkbox", { name: "Intersecting objects", exact: true }).check();
|
||||
await click("Apply section cut"); const opaque = await snapshot(); check(opaque, 0);
|
||||
const opaquePixels = await pixels("opaque");
|
||||
await transparency.fill("65"); await click("Apply section cut"); const partial = await snapshot(); check(partial, 65);
|
||||
const partialPixels = await pixels("partial");
|
||||
assert.ok(partialPixels.contrast < opaquePixels.contrast * .85, JSON.stringify({ opaquePixels, partialPixels }));
|
||||
await click("Section cut undo"); assert.equal(await transparency.inputValue(), "0");
|
||||
assert.deepEqual(objects(await snapshot()), objects(opaque));
|
||||
await click("Section cut redo"); assert.equal(await transparency.inputValue(), "65");
|
||||
assert.deepEqual(objects(await snapshot()), objects(partial));
|
||||
await transparency.fill("100"); await click("Apply section cut"); check(await snapshot(), 100);
|
||||
const clearPixels = await pixels("clear");
|
||||
assert.ok(clearPixels.contrast < opaquePixels.contrast * .3, JSON.stringify({ opaquePixels, clearPixels }));
|
||||
assert.ok(partialPixels.contrast > clearPixels.contrast * 1.5);
|
||||
await click("Section cut undo"); check(await snapshot(), 65);
|
||||
record({ values: [0, 65, 100], intersecting: true }, { opaquePixels, partialPixels, clearPixels },
|
||||
"Native opacity changes surface pixels while preserving topology, source appearance, and reversible session state");
|
||||
|
||||
const stable = await snapshot();
|
||||
for (const invalid of [-1, 101, 2.5, "65", null, true]) {
|
||||
const error = await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(stable).axes, resultTransparency: invalid } }, true);
|
||||
assert.match(error.message, /Result transparency must be an integer in 0\.\.100/);
|
||||
assert.deepEqual(signature(await snapshot()), signature(stable));
|
||||
}
|
||||
for (const invalid of ["-1", "101", "2.5", ""]) {
|
||||
await transparency.fill(invalid); assert.equal(await apply.isDisabled(), true);
|
||||
assert.deepEqual(signature(await snapshot()), signature(stable));
|
||||
}
|
||||
await click("Refresh section cut"); assert.equal(await transparency.inputValue(), "65");
|
||||
await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(stable).axes.map((axis, i) => i ? axis : { ...axis, position: 100 }), resultTransparency: 5 } }, true);
|
||||
assert.deepEqual(signature(await snapshot()), signature(stable));
|
||||
record({ invalidValues: [-1, 101, 2.5, "65", null, true], failedRebuildTransparency: 5 }, { retained: 65 },
|
||||
"Native invalid opacity and geometry failures roll back appearance and history; invalid UI input cannot apply");
|
||||
|
||||
await run({ action: "save", path: "/tmp/SectionCutOpacity.FCStd" }); await run({ action: "close" });
|
||||
const reopened = await run({ action: "open", path: "/tmp/SectionCutOpacity.FCStd" });
|
||||
assert.deepEqual(objects(reopened), objects(stable)); check(reopened, 65);
|
||||
await click("Refresh section cut"); assert.equal(await transparency.inputValue(), "65");
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const mobilePartial = await pixels("mobile-partial");
|
||||
await transparency.fill("0"); await click("Apply section cut"); const mobileOpaque = await pixels("mobile-opaque");
|
||||
assert.ok(mobilePartial.contrast < mobileOpaque.contrast * .85);
|
||||
await click("Section cut undo"); assert.equal(await transparency.inputValue(), "65"); check(await snapshot(), 65);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
|
||||
record({ operation: "FCStd restore and mobile rendering", viewport: [390, 844] }, { mobilePartial, mobileOpaque },
|
||||
"Saved native opacity restores the control and actual transparent surface on mobile without overflow");
|
||||
|
||||
const edited = await run({ action: "setBox", object: "B", dimensions: [10, 10, 20] }); check(edited, 65, 1100);
|
||||
await click("Refresh cut sources"); check(await snapshot(), 65, 1100);
|
||||
await run({ action: "remove", object: "B" }); check(await snapshot(), 65);
|
||||
await click("Refresh section cut"); assert.equal(await transparency.inputValue(), "65");
|
||||
await run({ action: "remove", object: "A" });
|
||||
const empty = await snapshot(); assert.equal(session(empty).resultTransparency, 65);
|
||||
await run({ action: "setBox", object: "Replacement", dimensions: [10, 10, 10] });
|
||||
await click("Refresh cut sources"); check(await snapshot(), 65);
|
||||
await run({ action: "setBox", object: "Small", dimensions: [1, 1, 1] });
|
||||
await click("Refresh cut sources"); check(await snapshot(), 65);
|
||||
await transparency.fill("25"); await click("Apply section cut");
|
||||
await click("Section cut undo"); const deletionGuard = await snapshot(); check(deletionGuard, 65);
|
||||
assert.ok(deletionGuard.redoCount > 0);
|
||||
const rejectedRemoval = await run({ action: "remove", object: "Replacement" }, true);
|
||||
assert.match(rejectedRemoval.message, /outside source bounds/);
|
||||
assert.deepEqual(signature(await snapshot()), signature(deletionGuard));
|
||||
await click("Section cut redo"); check(await snapshot(), 25);
|
||||
await click("Section cut undo"); check(await snapshot(), 65);
|
||||
await click("Close section cutting"); await panel.waitFor({ state: "detached" });
|
||||
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
|
||||
await ready(); assert.equal(await transparency.inputValue(), "65");
|
||||
assert.deepEqual(signature(await run({ action: "snapshot", document: "OpacityOther" })), signature(other));
|
||||
assert.deepEqual(errors, []);
|
||||
record({ operation: "edit source, recollect, fall back to compound, empty session, recover, reject out-of-bounds source removal and reenter" }, { transparency: 65, volume: 800, redoPreserved: true },
|
||||
"Source lifecycle retains result opacity in both modes; failed source removal preserves the executable redo branch and other documents");
|
||||
result.status = "not_implemented";
|
||||
} catch (error) { result.error = String(error.stack ?? error); process.stderr.write(result.error + "\n"); }
|
||||
finally { await browser?.close(); }
|
||||
fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n"); return [result];
|
||||
}
|
||||
119
tools/prepare_format_business_batch.py
Normal file
119
tools/prepare_format_business_batch.py
Normal file
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare module-level import/export workflows without API-sized tasks."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from implementation_first import all_implementation_ready_ids
|
||||
from scheduler_progress import cooling_ids, retry_details
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "docs/p6/format-coverage-kernel.json"
|
||||
STATE = ROOT / "docs/current/task-state.json"
|
||||
OUTPUT = ROOT / "docs/current/module-batch-manifest.json"
|
||||
MODULE_ORDER = {
|
||||
"Part": 0, "Mesh": 1, "Import": 2, "TechDraw": 3, "Spreadsheet": 4,
|
||||
"Points": 5, "BIM": 6, "Draft": 7, "Fem": 9, "CAM": 10,
|
||||
}
|
||||
|
||||
|
||||
def business_id(module: str, direction: str, extension: str) -> str:
|
||||
return f"business-format:{module}:{direction}:{extension}"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
source = json.loads(SOURCE.read_text(encoding="utf-8"))
|
||||
ready = all_implementation_ready_ids()
|
||||
cooling = cooling_ids(candidates={business_id(str(row.get("module")), str(row.get("direction")), str(row.get("extension"))) for row in source.get("records", []) if isinstance(row, dict)})
|
||||
deferred_ids = set()
|
||||
grouped: dict[tuple[str, str, str], list[dict]] = defaultdict(list)
|
||||
for row in source.get("records", []):
|
||||
if not isinstance(row, dict) or row.get("direction") not in {"import", "export"}:
|
||||
continue
|
||||
key = (str(row.get("module")), str(row.get("direction")), str(row.get("extension")))
|
||||
grouped[key].append(row)
|
||||
pending: dict[str, list[dict]] = defaultdict(list)
|
||||
for (module, direction, extension), rows in grouped.items():
|
||||
record_id = business_id(module, direction, extension)
|
||||
if record_id in ready or any(row.get("status") == "passed" for row in rows):
|
||||
continue
|
||||
if record_id in cooling:
|
||||
deferred_ids.add(record_id)
|
||||
continue
|
||||
source_row = min(rows, key=lambda row: (str(row.get("path", "")), int(row.get("line", 0) or 0)))
|
||||
pending[module].append({
|
||||
"id": record_id,
|
||||
"name": f"{direction} {extension}",
|
||||
"direction": direction,
|
||||
"extension": extension,
|
||||
"source": source_row.get("path"),
|
||||
"sourceLine": source_row.get("line"),
|
||||
"sourceHandlerCount": len(rows),
|
||||
})
|
||||
if not pending:
|
||||
result = {
|
||||
"schema": "freecad-web-module-function-batch/v1",
|
||||
"status": "no_ready_batch",
|
||||
"generatedAt": datetime.now(timezone.utc).isoformat(),
|
||||
"strategy": "module-function-direct-deferred-validation",
|
||||
"reason": "all source-declared import/export workflows have module implementation receipts",
|
||||
"records": [],
|
||||
"queue": [],
|
||||
**retry_details(deferred_ids),
|
||||
}
|
||||
OUTPUT.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"status": result["status"], "formatWorkflows": len(grouped), "records": 0}, ensure_ascii=False))
|
||||
return 0
|
||||
module = min(pending, key=lambda value: (MODULE_ORDER.get(value, 50), value))
|
||||
records = sorted(pending[module], key=lambda row: (row["extension"], row["direction"]))
|
||||
identity = "|".join([module, "format-workflow", "import-export", *(str(row["id"]) for row in records)])
|
||||
batch_id = hashlib.sha256(identity.encode("utf-8")).hexdigest()[:24]
|
||||
state = json.loads(STATE.read_text(encoding="utf-8"))
|
||||
queue = [
|
||||
{"module": name, "tier": "format-workflow", "family": "import-export", "unresolved": len(rows), "nextSize": len(rows)}
|
||||
for name, rows in sorted(pending.items(), key=lambda item: (MODULE_ORDER.get(item[0], 50), item[0]))
|
||||
]
|
||||
result = {
|
||||
"schema": "freecad-web-module-function-batch/v1",
|
||||
"status": "ready",
|
||||
"generatedAt": datetime.now(timezone.utc).isoformat(),
|
||||
"taskId": state.get("active_task"),
|
||||
"batchId": batch_id,
|
||||
"strategy": "module-function-direct-deferred-validation",
|
||||
"businessBundle": {
|
||||
"module": module,
|
||||
"implementationUnit": "module-import-export-dispatcher",
|
||||
"selectedRecordsAreUserWorkflows": True,
|
||||
"sourceHandlerCount": sum(int(row["sourceHandlerCount"]) for row in records),
|
||||
},
|
||||
"minimumRecords": 1,
|
||||
"singletonFallback": len(records) == 1,
|
||||
"selected": {
|
||||
"module": module,
|
||||
"tier": "format-workflow",
|
||||
"family": "import-export",
|
||||
"recordCount": len(records),
|
||||
"dispositionCounts": {"not_implemented": len(records)},
|
||||
},
|
||||
"fields": ["id", "name", "disposition", "source", "sourceLine"],
|
||||
"records": [[row["id"], row["name"], "not_implemented", row["source"], row["sourceLine"]] for row in records],
|
||||
"queue": queue,
|
||||
"boundaries": [
|
||||
"One record is one user-visible module import/export workflow, not a Python API.",
|
||||
"All same-module extensions share the existing native dispatcher, Worker and WASM artifact.",
|
||||
"Source mentions with unknown direction are not user format handlers and are excluded.",
|
||||
"Implementation performs build/sync/receipt only; validation is disabled.",
|
||||
],
|
||||
}
|
||||
OUTPUT.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"status": "ready", "batchId": batch_id, "module": module, "family": "import-export", "records": len(records)}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
1047
tools/prepare_module_implementation_packet.py
Normal file
1047
tools/prepare_module_implementation_packet.py
Normal file
File diff suppressed because it is too large
Load Diff
526
tools/run_p6_chrome_harness.mjs
Normal file
526
tools/run_p6_chrome_harness.mjs
Normal file
@@ -0,0 +1,526 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const toolsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const projectRoot = path.resolve(toolsRoot, "..");
|
||||
const docsRoot = path.join(projectRoot, "docs");
|
||||
const distRoot = path.join(projectRoot, "web", "dist");
|
||||
const scenario = process.env.P6_CHROME_SCENARIO ?? "baseline";
|
||||
const preloadModules = (process.env.P6_CHROME_PRELOAD_MODULES ?? "").split(",").map((value) => value.trim()).filter(Boolean);
|
||||
const preloadManifest = process.env.P6_CHROME_MODULE_MANIFEST ?? "/modules/manifest.json";
|
||||
const preloadConcurrency = Math.max(1, Math.min(2, Number(process.env.P6_CHROME_PRELOAD_CONCURRENCY ?? 2)));
|
||||
const preloadKinds = (process.env.P6_CHROME_PRELOAD_ASSETS ?? "wasm,data").split(",").map((value) => value.trim()).filter(Boolean);
|
||||
const isOpenScadScenario = false;
|
||||
const isPartScenario = scenario === "part" || scenario === "part-io" || scenario === "part-inspect" || scenario === "part-python" || scenario === "part-save";
|
||||
const isPartDesignScenario = scenario === "partdesign";
|
||||
const isPartDesignInspectScenario = scenario === "partdesign-inspect";
|
||||
const isPartDesignPythonScenario = scenario === "partdesign-python";
|
||||
const isPointsScenario = scenario === "points" || scenario === "points-inspect" || scenario === "points-python";
|
||||
const isPointsInspectScenario = scenario === "points-inspect";
|
||||
const isPointsPythonScenario = scenario === "points-python";
|
||||
const isPointsSaveScenario = scenario === "points-save";
|
||||
const isSandboxScenario = scenario === "sandbox";
|
||||
const isSandboxInspectScenario = scenario === "sandbox-inspect";
|
||||
const isSandboxPythonScenario = scenario === "sandbox-python";
|
||||
const isSandboxSaveScenario = scenario === "sandbox-save";
|
||||
const isSketcherScenario = scenario === "sketcher";
|
||||
const isSketcherInspectScenario = scenario === "sketcher-inspect";
|
||||
const isSketcherPythonScenario = scenario === "sketcher-python";
|
||||
const isSpreadsheetScenario = scenario === "spreadsheet";
|
||||
const isSpreadsheetInspectScenario = scenario === "spreadsheet-inspect";
|
||||
const isSpreadsheetPythonScenario = scenario === "spreadsheet-python";
|
||||
const isSpreadsheetSaveScenario = scenario === "spreadsheet-save";
|
||||
const isSurfaceScenario = scenario === "surface";
|
||||
const isSurfacePythonScenario = scenario === "surface-python";
|
||||
const isSurfaceSaveScenario = scenario === "surface-save";
|
||||
const isStartScenario = scenario === "start";
|
||||
const isStartInspectScenario = scenario === "start-inspect";
|
||||
const isStartPythonScenario = scenario === "start-python";
|
||||
const isTemplatePyModScenario = scenario === "templatepymod";
|
||||
const isTemplatePyModPythonScenario = scenario === "templatepymod-python";
|
||||
const isTuxScenario = scenario === "tux";
|
||||
const isWebScenario = scenario === "web";
|
||||
const isWebPersistenceScenario = scenario === "web-action-03";
|
||||
const isTestScenario = scenario === "test";
|
||||
const isTechDrawScenario = scenario === "techdraw";
|
||||
const isTechDrawNativeScenario = scenario === "techdraw-native";
|
||||
const isTechDrawInspectScenario = scenario === "techdraw-inspect";
|
||||
const isTechDrawPythonScenario = scenario === "techdraw-python";
|
||||
const isTechDrawSaveScenario = scenario === "techdraw-save";
|
||||
const isCoreScenario = scenario === "core";
|
||||
const isDataPropertyScenario = scenario === "data-property";
|
||||
const isDocumentScenario = scenario === "document";
|
||||
const isWorkbenchScenario = scenario === "workbench";
|
||||
const isViewScenario = scenario === "view";
|
||||
const isWebLikeScenario = isWebScenario || isWebPersistenceScenario;
|
||||
const isActionScenario = isOpenScadScenario || isPartScenario || isPartDesignScenario || isPartDesignInspectScenario || isPartDesignPythonScenario || isPointsScenario || isPointsSaveScenario || isSandboxScenario || isSandboxInspectScenario || isSandboxPythonScenario || isSandboxSaveScenario || isSketcherScenario || isSketcherInspectScenario || isSketcherPythonScenario || isSpreadsheetScenario || isSpreadsheetInspectScenario || isSpreadsheetPythonScenario || isSpreadsheetSaveScenario || isSurfaceScenario || isSurfacePythonScenario || isSurfaceSaveScenario || isStartScenario || isStartInspectScenario || isStartPythonScenario || isTemplatePyModScenario || isTemplatePyModPythonScenario || isTuxScenario || isWebLikeScenario || isTestScenario || isTechDrawScenario || isTechDrawNativeScenario || isTechDrawInspectScenario || isTechDrawPythonScenario || isTechDrawSaveScenario || isCoreScenario || isDataPropertyScenario || isDocumentScenario || isWorkbenchScenario || isViewScenario;
|
||||
const scenarioStem = process.env.P6_CHROME_OUTPUT_STEM ?? (scenario === "view" ? "view-interaction-chrome" : scenario === "workbench" ? "workbench-command-chrome" : scenario === "document" ? "document-contract-chrome" : scenario === "data-property" ? "data-property-family-chrome" : scenario === "core" ? "core-shell-chrome" : scenario === "techdraw-save" ? "techdraw-action-05-native-chrome" : scenario === "techdraw-python" ? "techdraw-action-04-native-chrome" : scenario === "techdraw-inspect" ? "techdraw-action-03-native-chrome" : scenario === "techdraw-native" ? "techdraw-action-02-native-chrome" : scenario === "techdraw" ? "techdraw-chrome" : scenario === "test" ? "test-chrome" : scenario === "web-action-03" ? "web-action-03-chrome" : scenario === "web" ? "web-chrome" : scenario === "tux" ? "tux-chrome" : scenario === "templatepymod-python" ? "templatepymod-action-02-chrome" : scenario === "templatepymod" ? "templatepymod-chrome" : scenario === "start-python" ? "start-action-03-chrome" : scenario === "start-inspect" ? "start-action-02-chrome" : scenario === "start" ? "start-chrome" : scenario === "surface-save" ? "surface-action-04-chrome" : scenario === "surface-python" ? "surface-action-03-chrome" : scenario === "surface" ? "surface-chrome" : scenario === "spreadsheet-save" ? "spreadsheet-action-04-chrome" : scenario === "spreadsheet-python" ? "spreadsheet-action-03-chrome" : scenario === "spreadsheet-inspect" ? "spreadsheet-action-02-chrome" : scenario === "spreadsheet" ? "spreadsheet-chrome" : scenario === "sketcher-python" ? "sketcher-action-03-chrome" : scenario === "sketcher-inspect" ? "sketcher-action-02-chrome" : scenario === "sketcher" ? "sketcher-chrome" : scenario === "sandbox-save" ? "sandbox-action-04-chrome" : scenario === "sandbox-python" ? "sandbox-action-03-chrome" : scenario === "sandbox-inspect" ? "sandbox-action-02-chrome" : scenario === "sandbox" ? "sandbox-chrome" : scenario === "points-python" ? "points-python-chrome" : scenario === "points-inspect" ? "points-inspect-chrome" : scenario === "points-save" ? "points-action-04-chrome" : scenario === "openscad-python" ? "openscad-python-chrome" : scenario === "openscad" ? "openscad-chrome" : scenario === "points" ? "points-chrome" : scenario === "partdesign" ? "partdesign-chrome" : scenario === "partdesign-inspect" ? "partdesign-action-02-chrome" : scenario === "partdesign-python" ? "partdesign-action-03-chrome" : scenario === "part-save" ? "part-save-chrome" : scenario === "part-python" ? "part-python-chrome" : scenario === "part-inspect" ? "part-inspect-chrome" : scenario === "part-io" ? "part-io-chrome" : scenario === "part" ? "part-chrome" : "chrome-harness");
|
||||
const outputPath = path.join(docsRoot, "p6", `${scenarioStem}.json`);
|
||||
const schemaPath = path.join(docsRoot, "p6", "chrome-harness.schema.json");
|
||||
const defaultLogPath = path.join(docsRoot,
|
||||
scenario === "view" ? "freecad-p6-view-interaction-chrome.log" :
|
||||
scenario === "workbench" ? "freecad-p6-workbench-command-chrome.log" :
|
||||
scenario === "document" ? "freecad-p6-document-contract-chrome.log" :
|
||||
scenario === "data-property" ? "freecad-p6-data-property-family-chrome.log" :
|
||||
scenario === "core" ? "freecad-p6-core-shell-chrome.log" :
|
||||
scenario === "points-python" ? "freecad-p6-points-action-03-f-chrome.log" : scenario === "points-inspect" ? "freecad-p6-points-action-02-f-chrome.log" : scenario === "points" ? "freecad-p6-points-f-chrome.log" :
|
||||
scenario === "partdesign" ? "freecad-p6-partdesign-f-chrome.log" : scenario === "partdesign-inspect" ? "freecad-p6-partdesign-action-02-f-chrome.log" : scenario === "partdesign-python" ? "freecad-p6-partdesign-action-03-f-chrome.log" : scenario === "points-save" ? "freecad-p6-points-action-04-f-chrome.log" :
|
||||
scenario === "part-save" ? "freecad-p6-part-action-05-f-chrome.log" :
|
||||
scenario === "part-python" ? "freecad-p6-part-action-04-f-chrome.log" :
|
||||
scenario === "part-inspect" ? "freecad-p6-part-action-03-f-chrome.log" :
|
||||
scenario === "part-io" ? "freecad-p6-part-action-02-f-chrome.log" :
|
||||
scenario === "part" ? "freecad-p6-part-f-chrome.log" :
|
||||
scenario === "sandbox" ? "freecad-p6-sandbox-f-chrome.log" :
|
||||
scenario === "sandbox-inspect" ? "freecad-p6-sandbox-action-02-f-chrome.log" :
|
||||
scenario === "sandbox-python" ? "freecad-p6-sandbox-action-03-f-chrome.log" :
|
||||
scenario === "sandbox-save" ? "freecad-p6-sandbox-action-04-f-chrome.log" :
|
||||
scenario === "sketcher" ? "freecad-p6-sketcher-f-chrome.log" :
|
||||
scenario === "sketcher-inspect" ? "freecad-p6-sketcher-action-02-f-chrome.log" :
|
||||
scenario === "sketcher-python" ? "freecad-p6-sketcher-action-03-f-chrome.log" :
|
||||
scenario === "spreadsheet" ? "freecad-p6-spreadsheet-f-chrome.log" :
|
||||
scenario === "spreadsheet-inspect" ? "freecad-p6-spreadsheet-action-02-f-chrome.log" :
|
||||
scenario === "spreadsheet-python" ? "freecad-p6-spreadsheet-action-03-f-chrome.log" :
|
||||
scenario === "spreadsheet-save" ? "freecad-p6-spreadsheet-action-04-f-chrome.log" :
|
||||
scenario === "surface" ? "freecad-p6-surface-f-chrome.log" :
|
||||
scenario === "surface-python" ? "freecad-p6-surface-action-03-f-chrome.log" :
|
||||
scenario === "surface-save" ? "freecad-p6-surface-action-04-f-chrome.log" :
|
||||
scenario === "start" ? "freecad-p6-start-f-chrome.log" :
|
||||
scenario === "start-inspect" ? "freecad-p6-start-action-02-f-chrome.log" :
|
||||
scenario === "start-python" ? "freecad-p6-start-action-03-f-chrome.log" :
|
||||
scenario === "templatepymod" ? "freecad-p6-templatepymod-f-chrome.log" :
|
||||
scenario === "tux" ? "freecad-p6-tux-f-chrome.log" :
|
||||
scenario === "web" ? "freecad-p6-web-f-chrome.log" :
|
||||
scenario === "templatepymod-python" ? "freecad-p6-templatepymod-action-02-f-chrome.log" :
|
||||
scenario === "web-action-03" ? "freecad-p6-web-action-03-f-chrome.log" :
|
||||
scenario === "test" ? "freecad-p6-test-f-chrome.log" :
|
||||
scenario === "techdraw" ? "freecad-p6-techdraw-frontend-chrome.log" :
|
||||
scenario === "techdraw-native" ? "freecad-p6-techdraw-action-02-native-f-chrome.log" :
|
||||
scenario === "techdraw-inspect" ? "freecad-p6-techdraw-action-03-native-f-chrome.log" :
|
||||
scenario === "techdraw-python" ? "freecad-p6-techdraw-action-04-native-f-chrome.log" :
|
||||
scenario === "techdraw-save" ? "freecad-p6-techdraw-action-05-native-f-chrome.log" :
|
||||
"freecad-p6-003-chrome-harness.log");
|
||||
const logPath = process.env.P6_CHROME_LOG_PATH ? path.resolve(projectRoot, process.env.P6_CHROME_LOG_PATH) : defaultLogPath;
|
||||
const screenshotPath = path.join(docsRoot, "p6", `${scenarioStem}.png`);
|
||||
const viewport = { width: 1440, height: 900, deviceScaleFactor: 1 };
|
||||
const timeoutMs = 30000;
|
||||
|
||||
function sha256(value) {
|
||||
return crypto.createHash("sha256").update(value).digest("hex");
|
||||
}
|
||||
|
||||
function findChrome() {
|
||||
return [
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/google-chrome-stable",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/opt/google/chrome/google-chrome",
|
||||
].find((candidate) => fs.existsSync(candidate)) ?? null;
|
||||
}
|
||||
|
||||
function contentType(filePath) {
|
||||
return {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".wasm": "application/wasm",
|
||||
".step": "application/step",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
}[path.extname(filePath)] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
function withPreload(url) {
|
||||
if (!preloadModules.length) return url;
|
||||
const value = new URL(url);
|
||||
value.searchParams.set("moduleManifest", preloadManifest);
|
||||
value.searchParams.set("preloadModules", preloadModules.join(","));
|
||||
value.searchParams.set("preloadConcurrency", String(preloadConcurrency));
|
||||
value.searchParams.set("preloadKinds", preloadKinds.join(","));
|
||||
return value.href;
|
||||
}
|
||||
|
||||
async function listen(server) {
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
return server.address().port;
|
||||
}
|
||||
|
||||
class CdpSession {
|
||||
constructor(url) {
|
||||
this.socket = new WebSocket(url);
|
||||
this.nextId = 1;
|
||||
this.pending = new Map();
|
||||
this.listeners = new Map();
|
||||
this.ready = new Promise((resolve, reject) => {
|
||||
this.socket.addEventListener("open", resolve, { once: true });
|
||||
this.socket.addEventListener("error", reject, { once: true });
|
||||
});
|
||||
this.socket.addEventListener("message", (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id !== undefined) {
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) return;
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.code}: ${message.error.message}`));
|
||||
else pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
for (const listener of this.listeners.get(message.method) ?? []) listener(message.params);
|
||||
});
|
||||
}
|
||||
|
||||
// Keep the method name on rejected protocol calls for deterministic recovery logs.
|
||||
|
||||
async send(method, params = {}) {
|
||||
await this.ready;
|
||||
const id = this.nextId++;
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pending.set(id, { resolve, reject, method });
|
||||
this.socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
}
|
||||
|
||||
on(method, listener) {
|
||||
const listeners = this.listeners.get(method) ?? [];
|
||||
listeners.push(listener);
|
||||
this.listeners.set(method, listeners);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function waitFor(label, predicate, evaluate, timeout = timeoutMs) {
|
||||
const deadline = Date.now() + timeout;
|
||||
let last;
|
||||
while (Date.now() < deadline) {
|
||||
last = await evaluate();
|
||||
if (predicate(last)) return last;
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
throw new Error(`${label} timed out: ${JSON.stringify(last)}`);
|
||||
}
|
||||
|
||||
const log = [];
|
||||
const chromePath = findChrome();
|
||||
if (!chromePath) {
|
||||
const blocked = {
|
||||
schema: "freecad-web-p6-chrome-harness/v1",
|
||||
result: "blocked_chrome_unavailable",
|
||||
environmentError: "Google Chrome executable was not found; no alternate browser was attempted",
|
||||
policy: { browser: "Google Chrome only", nonChromeBrowsersAttempted: false },
|
||||
};
|
||||
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(blocked, null, 2)}\n`);
|
||||
fs.writeFileSync(logPath, `${blocked.environmentError}\n`);
|
||||
console.error(blocked.environmentError);
|
||||
process.exitCode = 2;
|
||||
} else {
|
||||
const entry = isViewScenario ? "index.html" : isWorkbenchScenario ? "workbench.html" : isDocumentScenario ? "document.html" : isDataPropertyScenario ? "core.html" : isCoreScenario ? "core.html" : isSurfaceSaveScenario ? "surface-save.html" : isSurfacePythonScenario ? "surface-python.html" : isSurfaceScenario ? "surface.html" : isSketcherPythonScenario ? "sketcher-python.html" : isSketcherInspectScenario ? "sketcher-inspect.html" : isSketcherScenario ? "sketcher.html" : isSandboxSaveScenario ? "sandbox-save.html" : isSandboxPythonScenario ? "sandbox-python.html" : isSandboxInspectScenario ? "sandbox-inspect.html" : isSandboxScenario ? "sandbox.html" : isOpenScadScenario ? "openscad.html" : isPointsPythonScenario ? "points-python.html" : isPointsInspectScenario ? "points-inspect.html" : isPointsSaveScenario ? "points-save.html" : isPointsScenario ? "points.html" : isPartDesignPythonScenario ? "partdesign-python.html" : isPartDesignInspectScenario ? "partdesign-inspect.html" : isPartDesignScenario ? "partdesign.html" : isPartScenario ? (scenario === "part-io" ? "part-io.html" : scenario === "part-inspect" ? "part-inspect.html" : scenario === "part-python" ? "part-python.html" : scenario === "part-save" ? "part-save.html" : "part.html") : "index.html";
|
||||
if (!fs.existsSync(path.join(distRoot, entry))) throw new Error(`${entry} is missing; run npm run build first`);
|
||||
const server = http.createServer((request, response) => {
|
||||
const requestPath = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname);
|
||||
if (requestPath === "/favicon.ico") {
|
||||
response.writeHead(204);
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
const relative = requestPath === "/" ? "index.html" : requestPath.replace(/^\/+/, "");
|
||||
const filePath = path.resolve(distRoot, relative);
|
||||
if (filePath !== distRoot && !filePath.startsWith(`${distRoot}${path.sep}`)) {
|
||||
response.writeHead(403); response.end("forbidden"); return;
|
||||
}
|
||||
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
|
||||
response.writeHead(404); response.end("not found"); return;
|
||||
}
|
||||
const cacheControl = requestPath.startsWith("/kernel/") || requestPath.startsWith("/modules/")
|
||||
? "public, max-age=3600"
|
||||
: "no-store";
|
||||
response.writeHead(200, {
|
||||
"content-type": contentType(filePath),
|
||||
"cache-control": cacheControl,
|
||||
// FreeCAD WASM uses SharedArrayBuffer; the smoke server must be
|
||||
// cross-origin isolated just like the production deployment.
|
||||
"cross-origin-opener-policy": "same-origin",
|
||||
"cross-origin-embedder-policy": "require-corp",
|
||||
});
|
||||
fs.createReadStream(filePath).pipe(response);
|
||||
});
|
||||
const serverPort = await listen(server);
|
||||
const origin = `http://127.0.0.1:${serverPort}`;
|
||||
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-p6-chrome-"));
|
||||
const chrome = spawn(chromePath, [
|
||||
"--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage",
|
||||
"--remote-debugging-port=0", "--remote-allow-origins=*", `--user-data-dir=${userDataDir}`,
|
||||
`--window-size=${viewport.width},${viewport.height}`, withPreload(isViewScenario ? `${origin}/?sample=1` : isDataPropertyScenario ? `${origin}/core.html` : isCoreScenario ? `${origin}/core.html` : isSurfacePythonScenario ? `${origin}/surface-python.html` : isSurfaceScenario ? `${origin}/surface.html` : isSpreadsheetSaveScenario ? `${origin}/spreadsheet-save.html` : isSpreadsheetPythonScenario ? `${origin}/spreadsheet-python.html` : isSpreadsheetInspectScenario ? `${origin}/spreadsheet-inspect.html` : isSpreadsheetScenario ? `${origin}/spreadsheet.html` : isSketcherPythonScenario ? `${origin}/sketcher-python.html` : isSketcherInspectScenario ? `${origin}/sketcher-inspect.html` : isSketcherScenario ? `${origin}/sketcher.html` : isSandboxSaveScenario ? `${origin}/sandbox-save.html` : isSandboxPythonScenario ? `${origin}/sandbox-python.html` : isSandboxInspectScenario ? `${origin}/sandbox-inspect.html` : isSandboxScenario ? `${origin}/sandbox.html` : isOpenScadScenario ? `${origin}/openscad.html${scenario === "openscad-python" ? "?action=python-api" : ""}` : isPointsPythonScenario ? `${origin}/points-python.html` : isPointsInspectScenario ? `${origin}/points-inspect.html` : isPointsSaveScenario ? `${origin}/points-save.html` : isPointsScenario ? `${origin}/points.html` : isPartDesignPythonScenario ? `${origin}/partdesign-python.html` : isPartDesignInspectScenario ? `${origin}/partdesign-inspect.html` : isPartDesignScenario ? `${origin}/partdesign.html` : isPartScenario ? (scenario === "part-io" ? `${origin}/part-io.html` : scenario === "part-inspect" ? `${origin}/part-inspect.html` : scenario === "part-python" ? `${origin}/part-python.html` : scenario === "part-save" ? `${origin}/part-save.html` : `${origin}/part.html`) : `${origin}/?sample=1`),
|
||||
], { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let chromeOutput = "";
|
||||
chrome.stdout.on("data", (chunk) => { chromeOutput += chunk.toString(); });
|
||||
chrome.stderr.on("data", (chunk) => { chromeOutput += chunk.toString(); });
|
||||
|
||||
let cdp;
|
||||
try {
|
||||
let target;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!target && Date.now() < deadline) {
|
||||
try {
|
||||
const match = chromeOutput.match(/DevTools listening on ws:\/\/([^\s]+)/);
|
||||
if (match) {
|
||||
const port = match[1].split(":")[1].split("/")[0];
|
||||
const targets = await fetch(`http://127.0.0.1:${port}/json/list`).then((response) => response.json());
|
||||
target = targets.find((item) => item.type === "page");
|
||||
}
|
||||
} catch {
|
||||
// Chrome is still starting.
|
||||
}
|
||||
if (!target) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
if (!target?.webSocketDebuggerUrl) throw new Error(`Chrome CDP target unavailable: ${chromeOutput.trim()}`);
|
||||
cdp = new CdpSession(target.webSocketDebuggerUrl);
|
||||
const requests = [];
|
||||
const responses = [];
|
||||
const consoleEntries = [];
|
||||
const exceptions = [];
|
||||
cdp.on("Network.requestWillBeSent", (event) => requests.push({ requestId: event.requestId, url: event.request.url, method: event.request.method, type: event.type }));
|
||||
cdp.on("Network.responseReceived", (event) => responses.push({ requestId: event.requestId, url: event.response.url, status: event.response.status }));
|
||||
cdp.on("Runtime.consoleAPICalled", (event) => consoleEntries.push({ type: event.type, text: event.args?.map((arg) => arg.value ?? arg.description ?? "").join(" ") ?? "" }));
|
||||
cdp.on("Runtime.exceptionThrown", (event) => exceptions.push(event.exceptionDetails?.text ?? "runtime exception"));
|
||||
cdp.on("Log.entryAdded", (event) => { if (event.entry.level === "error") consoleEntries.push({ type: "log", text: event.entry.text }); });
|
||||
await cdp.send("Runtime.enable");
|
||||
await cdp.send("Network.enable");
|
||||
await cdp.send("Log.enable");
|
||||
await cdp.send("Page.enable");
|
||||
await cdp.send("Emulation.setDeviceMetricsOverride", { ...viewport, mobile: false });
|
||||
if (isSurfaceSaveScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/surface-save.html`) });
|
||||
if (isStartScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/start.html`) });
|
||||
if (isStartInspectScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/start-inspect.html`) });
|
||||
if (isStartPythonScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/start-python.html`) });
|
||||
if (isTemplatePyModScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/templatepymod.html`) });
|
||||
if (isTemplatePyModPythonScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/templatepymod-python.html`) });
|
||||
if (isTuxScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/tux.html`) });
|
||||
if (isWebScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/web.html`) });
|
||||
if (isWebPersistenceScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/web-persistence.html`) });
|
||||
if (isTestScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/test.html`) });
|
||||
if (isTechDrawScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw.html`) });
|
||||
if (isTechDrawNativeScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-native.html`) });
|
||||
if (isTechDrawInspectScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-inspect.html`) });
|
||||
if (isTechDrawPythonScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-python.html`) });
|
||||
if (isTechDrawSaveScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-save.html`) });
|
||||
if (isCoreScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/core.html`) });
|
||||
if (isDataPropertyScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/core.html`) });
|
||||
if (isDocumentScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/document.html?mode=full`) });
|
||||
if (isWorkbenchScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/workbench.html`) });
|
||||
|
||||
async function evaluate(expression) {
|
||||
const result = await cdp.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
|
||||
if (result.exceptionDetails) throw new Error(result.exceptionDetails.text ?? "Runtime.evaluate failed");
|
||||
return result.result?.value;
|
||||
}
|
||||
const modulePreload = preloadModules.length
|
||||
? await waitFor("module artifact preload", (value) => value?.phase === "ready" || value?.phase === "error", () => evaluate("window.__freecadModulePreloadState ?? null"), 180000)
|
||||
: { phase: "disabled", manifestUrl: null, requestedModules: [], requestedAssets: 0, loadedAssets: 0, failedAssets: [], loadedBytes: 0 };
|
||||
if (modulePreload.phase === "error") throw new Error(`module artifact preload failed: ${JSON.stringify(modulePreload.failedAssets)}`);
|
||||
async function state() {
|
||||
if (isViewScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', stage: window.__freecadViewState?.stage ?? 'starting', view: window.__freecadViewState ?? null, canvasPixels: (() => { const c = document.querySelector('#viewport canvas'); if (!c) return 0; const ctx = c.getContext('2d'); return ctx ? 0 : c.width * c.height; })(), controls: [...document.querySelectorAll('button,select,input')].filter((item) => !item.disabled).map((item) => item.id)}))()");
|
||||
if (isWorkbenchScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadWorkbenchState?.stage ?? 'ready', response: window.__freecadWorkbenchState?.response ?? null, matrix: window.__freecadWorkbenchState?.matrix ?? null, selected: window.__freecadWorkbenchState?.selected ?? null}))()");
|
||||
if (isWebScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadWebState?.stage ?? 'ready', response: window.__freecadWebState?.response ?? null}))()");
|
||||
if (isWebPersistenceScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadWebPersistenceState?.stage ?? 'ready', response: window.__freecadWebPersistenceState?.response ?? null}))()");
|
||||
if (isTestScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTestState?.stage ?? 'ready', response: window.__freecadTestState?.response ?? null}))()");
|
||||
if (isTechDrawScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawState?.stage ?? 'ready', response: window.__freecadTechDrawState?.response ?? null}))()");
|
||||
if (isTechDrawNativeScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawNativeState?.stage ?? 'ready', response: window.__freecadTechDrawNativeState?.response ?? null}))()");
|
||||
if (isTechDrawInspectScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawInspectState?.stage ?? 'ready', response: window.__freecadTechDrawInspectState?.response ?? null}))()");
|
||||
if (isTechDrawPythonScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawPyState?.stage ?? 'ready', response: window.__freecadTechDrawPyState?.response ?? null}))()");
|
||||
if (isTechDrawSaveScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawSaveState?.stage ?? 'ready', response: window.__freecadTechDrawSaveState?.response ?? null}))()");
|
||||
if (isCoreScenario) return evaluate("(() => { const s = window.__freecadCoreShellState ?? {}; const error = s.response?.error?.code ?? null; return {status: document.querySelector('.status')?.textContent ?? '', stage: s.stage ?? 'ready', response: s.response ?? null, progress: s.progress ?? [], duplicate: s.duplicate ?? (error === 'duplicate_request' ? error : null), cancel: s.cancel ?? (error === 'cancelled' ? error : null)}; })()");
|
||||
if (isDataPropertyScenario) return evaluate("(() => { const s = window.__freecadCoreShellState ?? {}; const error = s.response?.error?.code ?? null; return {status: document.querySelector('.status')?.textContent ?? '', stage: s.stage ?? 'ready', response: s.response ?? null, progress: s.progress ?? [], duplicate: s.duplicate ?? (error === 'duplicate_request' ? error : null), cancel: s.cancel ?? (error === 'cancelled' ? error : null)}; })()");
|
||||
if (isDocumentScenario) return evaluate("(() => { const s = window.__freecadCoreShellState ?? {}; const error = s.response?.error?.code ?? null; return {status: document.querySelector('.status')?.textContent ?? '', stage: s.stage ?? 'ready', response: s.response ?? null, progress: s.progress ?? [], duplicate: s.duplicate ?? (error === 'duplicate_request' ? error : null), cancel: s.cancel ?? (error === 'cancelled' ? error : null)}; })()");
|
||||
if (isTuxScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTuxState?.stage ?? 'ready', response: window.__freecadTuxState?.response ?? null}))()");
|
||||
if (isTemplatePyModPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadTpmPyState?.stage ?? '', requestId: window.__freecadTpmPyState?.requestId ?? null, response: window.__freecadTpmPyState?.response ?? null, api: document.querySelector('#api')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()");
|
||||
if (isTemplatePyModScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadTpmState?.stage ?? '', requestId: window.__freecadTpmState?.requestId ?? null, response: window.__freecadTpmState?.response ?? null, lines: document.querySelector('#lines')?.textContent ?? '', pythonOnly: document.querySelector('#pythonOnly')?.textContent ?? ''}))()");
|
||||
if (isStartPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadStartPyState?.stage ?? '', requestId: window.__freecadStartPyState?.requestId ?? null, response: window.__freecadStartPyState?.response ?? null, module: document.querySelector('#module')?.textContent ?? '', api: document.querySelector('#api')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()");
|
||||
if (isStartInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadStartInventoryState?.stage ?? '', requestId: window.__freecadStartInventoryState?.requestId ?? null, response: window.__freecadStartInventoryState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', readOnly: document.querySelector('#readOnly')?.textContent ?? ''}))()");
|
||||
if (isStartScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadStartState?.stage ?? '', requestId: window.__freecadStartState?.requestId ?? null, response: window.__freecadStartState?.response ?? null, module: document.querySelector('#module')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()");
|
||||
if (isSurfaceSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSurfaceSaveState?.stage ?? '', requestId: window.__freecadSurfaceSaveState?.requestId ?? null, response: window.__freecadSurfaceSaveState?.response ?? null, path: document.querySelector('#path')?.textContent ?? '', objects: document.querySelector('#objects')?.textContent ?? '', round: document.querySelector('#round')?.textContent ?? ''}))()");
|
||||
if (isSurfacePythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSurfacePyState?.stage ?? '', requestId: window.__freecadSurfacePyState?.requestId ?? null, response: window.__freecadSurfacePyState?.response ?? null, count: document.querySelector('#count')?.textContent ?? '', names: document.querySelector('#names')?.textContent ?? ''}))()");
|
||||
if (isSurfaceScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSurfaceState?.stage ?? '', requestId: window.__freecadSurfaceState?.requestId ?? null, response: window.__freecadSurfaceState?.response ?? null, object: document.querySelector('#object')?.textContent ?? '', objects: document.querySelector('#objects')?.textContent ?? '', recompute: document.querySelector('#recompute')?.textContent ?? ''}))()");
|
||||
if (isSpreadsheetSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetSaveState?.stage ?? '', requestId: window.__freecadSpreadsheetSaveState?.requestId ?? null, response: window.__freecadSpreadsheetSaveState?.response ?? null, path: document.querySelector('#path')?.textContent ?? '', size: document.querySelector('#size')?.textContent ?? '', round: document.querySelector('#round')?.textContent ?? ''}))()");
|
||||
if (isSpreadsheetPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetPythonState?.stage ?? '', requestId: window.__freecadSpreadsheetPythonState?.requestId ?? null, response: window.__freecadSpreadsheetPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? '', cells: document.querySelector('#cells')?.textContent ?? ''}))()");
|
||||
if (isSpreadsheetInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetInspectState?.stage ?? '', requestId: window.__freecadSpreadsheetInspectState?.requestId ?? null, response: window.__freecadSpreadsheetInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', formats: document.querySelector('#formats')?.textContent ?? '', bindings: document.querySelector('#bindings')?.textContent ?? ''}))()");
|
||||
if (isSpreadsheetScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetState?.stage ?? '', requestId: window.__freecadSpreadsheetState?.requestId ?? null, response: window.__freecadSpreadsheetState?.response ?? null, type: document.querySelector('#type')?.textContent ?? '', a1: document.querySelector('#a1')?.textContent ?? '', b1: document.querySelector('#b1')?.textContent ?? ''}))()");
|
||||
if (isSandboxScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxState?.stage ?? '', requestId: window.__freecadSandboxState?.requestId ?? null, response: window.__freecadSandboxState?.response ?? null, object: document.querySelector('#object')?.textContent ?? '', integer: document.querySelector('#integer')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()");
|
||||
if (isSandboxInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxInspectState?.stage ?? '', requestId: window.__freecadSandboxInspectState?.requestId ?? null, response: window.__freecadSandboxInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', python: document.querySelector('#python')?.textContent ?? ''}))()");
|
||||
if (isSandboxPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxPythonState?.stage ?? '', requestId: window.__freecadSandboxPythonState?.requestId ?? null, response: window.__freecadSandboxPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? ''}))()");
|
||||
if (isSandboxSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxSaveState?.stage ?? '', requestId: window.__freecadSandboxSaveState?.requestId ?? null, response: window.__freecadSandboxSaveState?.response ?? null, object: document.querySelector('#object')?.textContent ?? '', size: document.querySelector('#size')?.textContent ?? '', round: document.querySelector('#round')?.textContent ?? ''}))()");
|
||||
if (isSketcherScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSketcherState?.stage ?? '', requestId: window.__freecadSketcherState?.requestId ?? null, response: window.__freecadSketcherState?.response ?? null, geometry: document.querySelector('#geometry')?.textContent ?? '', constraints: document.querySelector('#constraints')?.textContent ?? '', dof: document.querySelector('#dof')?.textContent ?? ''}))()");
|
||||
if (isSketcherInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSketcherInspectState?.stage ?? '', requestId: window.__freecadSketcherInspectState?.requestId ?? null, response: window.__freecadSketcherInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', object: document.querySelector('#object')?.textContent ?? ''}))()");
|
||||
if (isSketcherPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSketcherPythonState?.stage ?? '', requestId: window.__freecadSketcherPythonState?.requestId ?? null, response: window.__freecadSketcherPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? ''}))()");
|
||||
if (isOpenScadScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status-dot')?.dataset.level ?? '', stage: window.__freecadOpenScadState?.stage ?? '', requestId: window.__freecadOpenScadState?.requestId ?? null, response: window.__freecadOpenScadState?.response ?? null, formats: document.querySelector('#formats')?.textContent ?? '', readonly: document.querySelector('#readonly')?.textContent ?? ''}))()");
|
||||
if (isPartDesignPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartDesignPythonState?.stage ?? '', requestId: window.__freecadPartDesignPythonState?.requestId ?? null, response: window.__freecadPartDesignPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', exports: document.querySelector('#exports')?.textContent ?? '', bindings: document.querySelector('#bindings')?.textContent ?? ''}))()");
|
||||
if (isPartDesignInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartDesignInspectState?.stage ?? '', requestId: window.__freecadPartDesignInspectState?.requestId ?? null, response: window.__freecadPartDesignInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', formats: document.querySelector('#formats')?.textContent ?? '', bindings: document.querySelector('#bindings')?.textContent ?? ''}))()");
|
||||
if (isPartDesignScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartDesignState?.stage ?? '', requestId: window.__freecadPartDesignState?.requestId ?? null, response: window.__freecadPartDesignState?.response ?? null, volume: document.querySelector('#volume')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()");
|
||||
if (isPointsSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPointsSaveState?.stage ?? '', requestId: window.__freecadPointsSaveState?.requestId ?? null, response: window.__freecadPointsSaveState?.response ?? null, path: document.querySelector('#path')?.textContent ?? '', object: document.querySelector('#object')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? '', size: document.querySelector('#size')?.textContent ?? ''}))()");
|
||||
if (isPointsScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPointsState?.stage ?? '', requestId: window.__freecadPointsState?.requestId ?? null, response: window.__freecadPointsState?.response ?? null, count: document.querySelector('#count')?.textContent ?? '', bounds: document.querySelector('#bounds')?.textContent ?? ''}))()");
|
||||
if (isPartScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartState?.stage ?? '', requestId: window.__freecadPartState?.requestId ?? null, response: window.__freecadPartState?.response ?? null, volume: document.querySelector('#volume')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()");
|
||||
return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', file: document.querySelector('#file-name')?.textContent ?? '', vertex: document.querySelector('#vertex-count')?.textContent ?? '', triangle: document.querySelector('#triangle-count')?.textContent ?? '', face: document.querySelector('#face-count')?.textContent ?? '', requestId: window.__freecadLastResponseRequestId ?? null}))()");
|
||||
}
|
||||
async function navigate(url) {
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await cdp.send("Page.navigate", { url: withPreload(url) });
|
||||
await waitFor("kernel startup", (value) => value.status !== "" && !value.status.includes("初始化") && !value.status.includes("等待"), state);
|
||||
}
|
||||
function caseEvidence(id, value, screenshotHash = null) {
|
||||
const externalRequests = requests.filter((request) => !request.url.startsWith(origin)).map((request) => request.url);
|
||||
return { id, status: "pass", state: value, requests: [...requests], responses: [...responses], externalRequests, console: [...consoleEntries], exceptions: [...exceptions], screenshotSha256: screenshotHash };
|
||||
}
|
||||
|
||||
const cases = [];
|
||||
if (isActionScenario) {
|
||||
if (isViewScenario) {
|
||||
const readyState = await waitFor("view sample", (value) => value.stage === "ready" && value.view?.objectCount === 1, state);
|
||||
cases.push(caseEvidence("view-ready", readyState));
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#object-tree-primary').click()");
|
||||
cases.push(caseEvidence("view-selection", await waitFor("view selection", (value) => value.view?.selected === true, state)));
|
||||
await evaluate("document.querySelector('#object-tree-primary').dispatchEvent(new PointerEvent('pointermove', {bubbles:true}))").catch(() => undefined);
|
||||
await evaluate("document.querySelector('#section-button').click()");
|
||||
cases.push(caseEvidence("view-section", await waitFor("view section", (value) => value.view?.section === true, state)));
|
||||
await evaluate("document.querySelector('#visibility-button').click()");
|
||||
cases.push(caseEvidence("view-hidden", await waitFor("view hidden", (value) => value.view?.visible === false, state)));
|
||||
await evaluate("document.querySelector('#visibility-button').click(); document.querySelector('#front-button').click(); document.dispatchEvent(new KeyboardEvent('keydown', {key:'f', bubbles:true}))");
|
||||
const desktop = await waitFor("view desktop", (value) => value.view?.visible === true && value.view?.section === true, state);
|
||||
const desktopScreenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true });
|
||||
const desktopBytes = Buffer.from(desktopScreenshot.data, "base64");
|
||||
const desktopPath = path.join(docsRoot, "p6", "view-interaction-desktop.png");
|
||||
fs.writeFileSync(desktopPath, desktopBytes);
|
||||
cases.push(caseEvidence("view-desktop", desktop, sha256(desktopBytes)));
|
||||
await cdp.send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
|
||||
const mobile = await waitFor("view mobile layout", (value) => value.controls.includes("fit-button") && value.controls.includes("section-button"), state);
|
||||
const mobileScreenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true });
|
||||
const mobileBytes = Buffer.from(mobileScreenshot.data, "base64");
|
||||
const mobilePath = path.join(docsRoot, "p6", "view-interaction-mobile.png");
|
||||
fs.writeFileSync(mobilePath, mobileBytes);
|
||||
cases.push(caseEvidence("view-mobile", mobile, sha256(mobileBytes)));
|
||||
} else {
|
||||
const actionLabel = isWorkbenchScenario ? "Workbench command matrix" : isDataPropertyScenario ? "Data-property family" : isCoreScenario ? "React Core" : isTechDrawSaveScenario ? "TechDraw save/reopen" : isTechDrawPythonScenario ? "TechDraw Python" : isTechDrawInspectScenario ? "TechDraw inventory" : isTechDrawNativeScenario ? "TechDraw native" : isTechDrawScenario ? "TechDraw frontend" : isTestScenario ? "Test inventory" : isWebPersistenceScenario ? "Web save/reopen" : isWebScenario ? "Web" : isTuxScenario ? "Tux" : isTemplatePyModPythonScenario ? "TemplatePyMod Python" : isTemplatePyModScenario ? "TemplatePyMod" : isStartPythonScenario ? "Start Python" : isStartInspectScenario ? "Start inventory" : isStartScenario ? "Start" : isSurfaceSaveScenario ? "Surface save" : isSurfacePythonScenario ? "Surface Python" : isSurfaceScenario ? "Surface" : isSpreadsheetSaveScenario ? "Spreadsheet save" : isSpreadsheetPythonScenario ? "Spreadsheet Python" : isSpreadsheetInspectScenario ? "Spreadsheet inventory" : isSpreadsheetScenario ? "Spreadsheet" : isSketcherPythonScenario ? "Sketcher Python" : isSketcherInspectScenario ? "Sketcher inventory" : isSketcherScenario ? "Sketcher" : isSandboxSaveScenario ? "Sandbox save" : isSandboxPythonScenario ? "Sandbox Python" : isSandboxInspectScenario ? "Sandbox inventory" : isSandboxScenario ? "Sandbox" : isPointsSaveScenario ? "Points save" : isPointsScenario ? "Points" : isPartDesignPythonScenario ? "PartDesign Python" : isPartDesignInspectScenario ? "PartDesign inventory" : isPartDesignScenario ? "PartDesign" : isPartScenario ? "Part" : "OpenSCAD";
|
||||
const casePrefix = scenario;
|
||||
if (isWorkbenchScenario) await waitFor("Workbench React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#validate-command-matrix'))"));
|
||||
if (isWebScenario) await waitFor("Web React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
const readyState = await waitFor(`${actionLabel} ready`, (value) => value.stage === "ready", state);
|
||||
cases.push(caseEvidence(`${casePrefix}-ready`, readyState));
|
||||
if (isTuxScenario) await waitFor("Tux React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isWebPersistenceScenario) await waitFor("Web persistence React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isTestScenario) await waitFor("Test React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isTechDrawScenario) await waitFor("TechDraw React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isTechDrawNativeScenario) await waitFor("TechDraw native React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isTechDrawInspectScenario) await waitFor("TechDraw inspect React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isTechDrawPythonScenario) await waitFor("TechDraw Python React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isTechDrawSaveScenario) await waitFor("TechDraw save React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isCoreScenario) await waitFor("Core React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
if (isDataPropertyScenario) await waitFor("Data-property React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#data-property-family'))"));
|
||||
if (isDocumentScenario) await waitFor("Document React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))"));
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate(isWorkbenchScenario ? "document.querySelector('#validate-command-matrix').click()" : isDataPropertyScenario ? "document.querySelector('#data-property-family').click()" : "document.querySelector('#run').click()");
|
||||
const actionState = await waitFor(`${actionLabel} action`, (value) => isWorkbenchScenario ? value.stage === "success" && value.matrix?.records === 778 : value.stage === "success", state);
|
||||
const screenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true });
|
||||
const screenshotBytes = Buffer.from(screenshot.data, "base64");
|
||||
fs.writeFileSync(screenshotPath, screenshotBytes);
|
||||
cases.push(caseEvidence(`${casePrefix}-action`, actionState, sha256(screenshotBytes)));
|
||||
if (isWorkbenchScenario) {
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#error').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-expected-error`, await waitFor(`${actionLabel} expected error`, (value) => value.stage === "expected-error" && value.response?.error?.code === "invalid_request", state)));
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#cancel').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled" && value.response?.error?.code === "cancelled", state)));
|
||||
}
|
||||
if (isCoreScenario) {
|
||||
cases.push(caseEvidence(`${casePrefix}-duplicate`, await waitFor(`${actionLabel} duplicate`, (value) => value.duplicate === "duplicate_request", state)));
|
||||
}
|
||||
if (isDataPropertyScenario) {
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#cancel').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled", state)));
|
||||
}
|
||||
if (isDocumentScenario) {
|
||||
cases.push(caseEvidence(`${casePrefix}-duplicate`, await waitFor(`${actionLabel} duplicate`, (value) => value.duplicate === "duplicate_request", state)));
|
||||
}
|
||||
if (!isWorkbenchScenario) {
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#error').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-expected-error`, await waitFor(`${actionLabel} expected error`, (value) => value.stage === "expected-error", state)));
|
||||
}
|
||||
if (isCoreScenario) {
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#cancel').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled", state)));
|
||||
}
|
||||
if (isDocumentScenario) {
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#cancel').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled", state)));
|
||||
}
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate("document.querySelector('#reset').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-reset`, await waitFor(`${actionLabel} reset`, (value) => value.stage === "reset", state)));
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await evaluate(isWorkbenchScenario ? "document.querySelector('#validate-command-matrix').click()" : isDataPropertyScenario ? "document.querySelector('#data-property-family').click()" : "document.querySelector('#run').click()");
|
||||
cases.push(caseEvidence(`${casePrefix}-repeat`, await waitFor(`${actionLabel} repeat`, (value) => isWorkbenchScenario ? value.stage === "success" : value.stage === "success", state)));
|
||||
}
|
||||
} else {
|
||||
const importState = await waitFor("sample import", (value) => value.status.startsWith("已加载 "), state);
|
||||
const screenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true });
|
||||
const screenshotBytes = Buffer.from(screenshot.data, "base64");
|
||||
fs.writeFileSync(screenshotPath, screenshotBytes);
|
||||
cases.push(caseEvidence("sample-import", importState, sha256(screenshotBytes)));
|
||||
await evaluate("document.querySelector('#reset-button').click()");
|
||||
cases.push(caseEvidence("reset", await waitFor("reset", (value) => value.status === "已清空", state)));
|
||||
|
||||
await navigate(`${origin}/?storage=1`);
|
||||
cases.push(caseEvidence("opfs", await waitFor("OPFS smoke", (value) => value.status.includes("OPFS smoke passed"), state)));
|
||||
await navigate(`${origin}/?cache=1`);
|
||||
cases.push(caseEvidence("mesh-cache", await waitFor("mesh cache smoke", (value) => value.status === "网格缓存 smoke passed", state)));
|
||||
|
||||
requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0;
|
||||
await cdp.send("Page.navigate", { url: `${origin}/missing-fixture` });
|
||||
const missingResponse = await waitFor("expected HTTP error", (value) => value?.status === 404, () => Promise.resolve(responses.find((response) => response.url.endsWith("/missing-fixture"))), 5000);
|
||||
cases.push({ id: "expected-error", status: missingResponse.status === 404 ? "pass" : "fail", expected: { status: 404 }, observed: missingResponse, requests: [...requests], responses: [...responses], externalRequests: requests.filter((request) => !request.url.startsWith(origin)).map((request) => request.url), console: [...consoleEntries], exceptions: [...exceptions], screenshotSha256: null });
|
||||
}
|
||||
|
||||
const allExternal = cases.flatMap((item) => item.externalRequests);
|
||||
const allExceptions = cases.flatMap((item) => item.exceptions);
|
||||
const result = {
|
||||
schema: "freecad-web-p6-chrome-harness/v1",
|
||||
result: cases.every((item) => item.status === "pass") && allExternal.length === 0 && allExceptions.length === 0 ? "pass" : "fail",
|
||||
chrome: { path: chromePath, version: (await new Promise((resolve) => { const version = spawn(chromePath, ["--version"], { stdio: ["ignore", "pipe", "ignore"] }); let output = ""; version.stdout.on("data", (chunk) => { output += chunk; }); version.on("close", () => resolve(output.trim())); })) },
|
||||
mode: "headless-new",
|
||||
origin,
|
||||
viewport,
|
||||
timeoutMs,
|
||||
networkPolicy: "intercept-and-require-zero-external-requests",
|
||||
modulePreload,
|
||||
cases,
|
||||
evidence: { screenshot: `FreeCAD/docs/p6/${scenarioStem}.png`, screenshotSha256: cases.find((item) => item.screenshotSha256)?.screenshotSha256 ?? null, resultHash: sha256(JSON.stringify(cases)) },
|
||||
policy: { browser: "Google Chrome only", nonChromeBrowsersAttempted: false },
|
||||
};
|
||||
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(result, null, 2)}\n`);
|
||||
log.push(`origin=${origin}`, `chrome=${result.chrome.version}`, `cases=${cases.length}`, `externalRequests=${allExternal.length}`, `exceptions=${allExceptions.length}`, `result=${result.result}`);
|
||||
fs.writeFileSync(logPath, `${log.join("\n")}\n`);
|
||||
console.log(JSON.stringify({ result: result.result, cases: cases.length, externalRequests: allExternal.length, exceptions: allExceptions.length }));
|
||||
if (result.result !== "pass") process.exitCode = 1;
|
||||
} finally {
|
||||
cdp?.close();
|
||||
chrome.kill("SIGTERM");
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
119
tools/run_p6_python_api_module_batch_gate.py
Normal file
119
tools/run_p6_python_api_module_batch_gate.py
Normal file
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
module = sys.argv[1] if len(sys.argv) > 1 else "Part"
|
||||
tier = sys.argv[2] if len(sys.argv) > 2 else "tier-2-pure"
|
||||
manifest_path = ROOT / "docs/p6/python-api-manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
rows = [row for row in manifest["records"] if row["module"] == module and row["tier"] == tier]
|
||||
counts = Counter(row["disposition"] for row in rows)
|
||||
safe = "".join(ch if ch.isalnum() else "-" for ch in module.lower())
|
||||
terminal = {"exposed", "restricted", "nonportable", "not_implemented"}
|
||||
records = [
|
||||
{
|
||||
"id": row["id"],
|
||||
"name": row["name"],
|
||||
"disposition": row["disposition"],
|
||||
"evidence": row.get("dispositionEvidence", []),
|
||||
"reason": row.get("dispositionReason"),
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
extra = {}
|
||||
if tier == "tier-3-stateful":
|
||||
runtime_path = ROOT / "docs/p6/python-api-stateful-family-runtime.json"
|
||||
adapter_path = ROOT / "docs/p6/tier3-stateful-adapter-manifest.json"
|
||||
runtime = json.loads(runtime_path.read_text())
|
||||
adapter = json.loads(adapter_path.read_text())
|
||||
native_by_id = {record["apiId"]: record for record in runtime.get("result", {}).get("records", [])}
|
||||
summary_by_id = {record["apiId"]: record for record in runtime.get("records", [])}
|
||||
adapter_module = next((item for item in adapter.get("modules", []) if item.get("module") == module), None)
|
||||
adapter_route = adapter_module.get("route", {}) if adapter_module else {}
|
||||
native_route = runtime.get("route", {})
|
||||
|
||||
def native_record_valid(row):
|
||||
native = native_by_id.get(row["id"])
|
||||
summary = summary_by_id.get(row["id"])
|
||||
if not native or not summary:
|
||||
return False
|
||||
compact = json.dumps(native, ensure_ascii=False, separators=(",", ":"))
|
||||
native_sha256 = hashlib.sha256(compact.encode()).hexdigest()
|
||||
return (
|
||||
native.get("module") == row["module"]
|
||||
and native.get("name") == row["name"]
|
||||
and native.get("family") == row["family"]
|
||||
and native.get("sourceEntry") == row.get("evidence", {}).get("path")
|
||||
and native.get("status") == row["disposition"]
|
||||
and native.get("status") in terminal
|
||||
and native.get("native") is True
|
||||
and native.get("resourcesReleased") is True
|
||||
and isinstance(native.get("parameterSchema"), str)
|
||||
and bool(native["parameterSchema"])
|
||||
and isinstance(native.get("returnSchema"), str)
|
||||
and bool(native["returnSchema"])
|
||||
and isinstance(native.get("documentDiff"), dict)
|
||||
and isinstance(native.get("errorRecovery"), dict)
|
||||
and summary.get("evidenceSha256") == native_sha256
|
||||
and runtime_path.relative_to(ROOT).as_posix() in row.get("dispositionEvidence", [])
|
||||
)
|
||||
|
||||
valid = (
|
||||
bool(rows)
|
||||
and runtime.get("status") == "pass_with_boundaries"
|
||||
and adapter_module is not None
|
||||
and adapter_module.get("count") == len(rows)
|
||||
and isinstance(adapter_route.get("worker"), str)
|
||||
and bool(adapter_route["worker"])
|
||||
and isinstance(adapter_route.get("command"), str)
|
||||
and bool(adapter_route["command"])
|
||||
and native_route.get("command") == "web.statefulFamilyBatch"
|
||||
and "fc_web_dispatch_json" in native_route.get("native", "")
|
||||
and all(row["disposition"] in terminal and native_record_valid(row) for row in rows)
|
||||
)
|
||||
records = [
|
||||
{
|
||||
**record,
|
||||
"family": row["family"],
|
||||
"sourceEntry": summary_by_id.get(row["id"], {}).get("sourceEntry"),
|
||||
"sourceRevision": summary_by_id.get(row["id"], {}).get("sourceRevision"),
|
||||
"parameterSchema": summary_by_id.get(row["id"], {}).get("parameterSchema"),
|
||||
"returnSchema": summary_by_id.get(row["id"], {}).get("returnSchema"),
|
||||
"documentDiffSha256": summary_by_id.get(row["id"], {}).get("documentDiffSha256"),
|
||||
"errorRecoverySha256": summary_by_id.get(row["id"], {}).get("errorRecoverySha256"),
|
||||
"evidenceSha256": summary_by_id.get(row["id"], {}).get("evidenceSha256"),
|
||||
}
|
||||
for row, record in zip(rows, records)
|
||||
]
|
||||
extra = {
|
||||
"nativeRuntime": runtime_path.relative_to(ROOT).as_posix(),
|
||||
"nativeRuntimeSha256": hashlib.sha256(runtime_path.read_bytes()).hexdigest(),
|
||||
"adapterManifest": adapter_path.relative_to(ROOT).as_posix(),
|
||||
"adapterManifestSha256": hashlib.sha256(adapter_path.read_bytes()).hexdigest(),
|
||||
"route": adapter_route or None,
|
||||
"nativeRoute": native_route or None,
|
||||
"resources": runtime.get("resources"),
|
||||
}
|
||||
else:
|
||||
valid = bool(rows) and all(row["disposition"] in terminal | {"planned"} for row in rows)
|
||||
report = {
|
||||
"schema": "freecad-web-p6-python-api-module-batch-gate/v1",
|
||||
"taskId": f"FW-P6-FPA-F{tier.split('-')[1]}-{module.upper()}",
|
||||
"module": module,
|
||||
"tier": tier,
|
||||
"result": ("pass" if tier == "tier-3-stateful" else "pass_with_pending") if valid else "fail",
|
||||
"coverage": {"records": len(rows), "counts": dict(sorted(counts.items()))},
|
||||
"records": records,
|
||||
"manifestSha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
|
||||
**extra,
|
||||
"boundaries": ["Terminal disposition does not claim that restricted or not_implemented APIs are callable.", "Only exact module-scoped native evidence can promote a symbol."]
|
||||
}
|
||||
out = ROOT / "docs/p6" / f"python-api-{safe}-{tier}-gate.json"
|
||||
out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
(ROOT / "docs" / f"freecad-p6-python-api-{safe}-{tier}-gate.log").write_text(json.dumps({"result": report["result"], "coverage": report["coverage"]}) + "\n")
|
||||
print(json.dumps({"module": module, "tier": tier, "result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False))
|
||||
raise SystemExit(0 if valid else 1)
|
||||
48
tools/run_p6_python_api_pure_aggregate_gate.py
Normal file
48
tools/run_p6_python_api_pure_aggregate_gate.py
Normal file
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that every canonical Tier-2 pure API has terminal native evidence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
P6 = ROOT / "docs/p6"
|
||||
MANIFEST = P6 / "python-api-manifest.json"
|
||||
manifest_bytes = MANIFEST.read_bytes()
|
||||
manifest = json.loads(manifest_bytes)
|
||||
rows = [row for row in manifest["records"] if row.get("tier") == "tier-2-pure"]
|
||||
terminal = {"exposed", "restricted", "nonportable", "not_implemented"}
|
||||
missing = [row["id"] for row in rows if row.get("disposition") not in terminal or not row.get("dispositionEvidence")]
|
||||
modules = sorted({row["module"] for row in rows})
|
||||
artifact_index = {}
|
||||
for module in modules:
|
||||
candidates = sorted(P6.glob(f"{module.lower()}*tier2*pure*family-runtime.json"))
|
||||
if not candidates:
|
||||
missing.append(f"artifact:{module}")
|
||||
continue
|
||||
path = candidates[-1]
|
||||
raw = path.read_bytes()
|
||||
value = json.loads(raw)
|
||||
artifact_index[module] = {"path": str(path.relative_to(ROOT)), "sha256": hashlib.sha256(raw).hexdigest(), "status": value.get("status")}
|
||||
if value.get("status") not in {"pass", "pass_with_boundaries"}:
|
||||
missing.append(f"artifact_status:{module}")
|
||||
counts = Counter(row.get("disposition") for row in rows)
|
||||
report = {
|
||||
"schema": "freecad-web-p6-python-api-pure-aggregate-gate/v1",
|
||||
"taskId": "FW-P6-FPA-F2",
|
||||
"result": "pass_with_boundaries" if len(rows) == 6417 and not missing else "fail",
|
||||
"source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(manifest_bytes).hexdigest()},
|
||||
"coverage": {"tier": "tier-2-pure", "records": len(rows), "counts": dict(sorted(counts.items())), "modules": modules, "missing": missing},
|
||||
"evidence": artifact_index,
|
||||
"boundaries": [
|
||||
"Every Tier-2 record has a terminal disposition and a module-scoped native evidence reference.",
|
||||
"Terminal not_implemented/restricted records remain capability denials; no JavaScript result is substituted.",
|
||||
"Later Tier-3/stateful and exhaustive Chrome gates remain outside this aggregate implementation gate.",
|
||||
],
|
||||
}
|
||||
(P6 / "python-api-pure-aggregate-gate.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
(ROOT / "docs/freecad-p6-python-api-pure-aggregate-gate.log").write_text(json.dumps({"result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False))
|
||||
raise SystemExit(0 if report["result"] != "fail" else 1)
|
||||
29
tools/run_p6_python_api_pure_gate.py
Normal file
29
tools/run_p6_python_api_pure_gate.py
Normal file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
import hashlib
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
manifest_path = ROOT / "docs/p6/python-api-manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
pure = [row for row in manifest["records"] if row["tier"] == "tier-2-pure" and row["disposition"] == "exposed"]
|
||||
# Runtime evidence is append-only: new native family probes may safely expose
|
||||
# more pure APIs. The contract is evidence-backed membership, not a frozen
|
||||
# historical count.
|
||||
valid = bool(pure) and all(row.get("dispositionEvidence") for row in pure)
|
||||
report = {
|
||||
"schema": "freecad-web-p6-python-api-pure-gate/v1",
|
||||
"taskId": "FW-P6-FPA-F2",
|
||||
"result": "pass_with_pending" if valid else "fail",
|
||||
"coverage": {"pureTierRecords": sum(row["tier"] == "tier-2-pure" for row in manifest["records"]), "exposedPureRecords": len(pure), "plannedRecords": sum(row["disposition"] == "planned" for row in manifest["records"]), "restrictedRecords": sum(row["disposition"] == "restricted" for row in manifest["records"]), "totalRecords": len(manifest["records"])},
|
||||
"byModule": dict(sorted(Counter(row["module"] for row in pure).items())),
|
||||
"records": [{"id": row["id"], "module": row["module"], "name": row["name"], "artifacts": row["dispositionEvidence"]} for row in pure],
|
||||
"manifestSha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
|
||||
"boundaries": ["Only passing native Python API artifacts are used; external non-native process calls remain subject to capability policy.", "Pure-tier records without native evidence remain planned and are not implied by this partial gate."],
|
||||
}
|
||||
out = ROOT / "docs/p6/python-api-pure-gate.json"
|
||||
out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
(ROOT / "docs/freecad-p6-python-api-pure-gate.log").write_text(json.dumps({"result": report["result"], "coverage": report["coverage"]}) + "\n")
|
||||
print(json.dumps({"result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False))
|
||||
raise SystemExit(0 if valid else 1)
|
||||
480
tools/run_web_module_smoke_once.py
Normal file
480
tools/run_web_module_smoke_once.py
Normal file
@@ -0,0 +1,480 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run exactly one unattended smoke entry for each FreeCAD Web module.
|
||||
|
||||
The smoke run is intentionally separate from the historical scheduler ledger:
|
||||
one module has one selected entry, one attempt, and one recorded result.
|
||||
Missing JS/WASM glue is prepared with a targeted build before that module's
|
||||
single smoke invocation; it is not retried as another smoke test.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import hashlib
|
||||
import fcntl
|
||||
import signal
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BUILD = ROOT / "web/public/kernel"
|
||||
CONFIGURE_BUILD = ROOT / "freecad-source/build-web/configure/bin"
|
||||
CLOUD_BUILD = ROOT / "freecad-source/build-web/cloud-configure-r2/bin"
|
||||
try:
|
||||
campaign = json.loads((ROOT / "docs/current/execution-policy.json").read_text()).get("smokeRun", {}).get("directory")
|
||||
except (OSError, ValueError):
|
||||
campaign = None
|
||||
RUN_DIR = Path(os.environ.get("FREECAD_SMOKE_RUN_DIR", str(ROOT / (campaign or "docs/current/module-smoke-once")))).expanduser().resolve()
|
||||
MANIFEST = RUN_DIR / "manifest.json"
|
||||
TSC = ROOT / "web/node_modules/.bin/tsc"
|
||||
SMOKE_TIMEOUT_SECONDS = int(os.environ.get("FREECAD_SMOKE_TIMEOUT_SECONDS", "120"))
|
||||
BUILD_TIMEOUT_SECONDS = int(os.environ.get("FREECAD_SMOKE_BUILD_TIMEOUT_SECONDS", "180"))
|
||||
|
||||
|
||||
def spec(module: str, script: str, args: list[str] | None = None, *, compile_sources: list[str] | None = None, build_tree: Path | None = None, build_target: str | None = None, runtime_probe: str | None = None) -> dict[str, object]:
|
||||
return {
|
||||
"module": module,
|
||||
"script": script,
|
||||
"args": args or [],
|
||||
"compileSources": compile_sources or [],
|
||||
"buildTree": str(build_tree or BUILD),
|
||||
"buildTarget": build_target,
|
||||
"runtimeProbe": runtime_probe,
|
||||
}
|
||||
|
||||
|
||||
SPECS = [
|
||||
spec("Assembly", "tools/run_p6_assembly_action02_kernel_smoke.mjs"),
|
||||
spec("BIM", "tools/run_p6_bim_runtime_smoke.mjs"),
|
||||
spec("CAM", "tools/run_p6_cam_action02_kernel_smoke.mjs", ["{out}/cam-import-export-facade.js"], compile_sources=["web/src/facade-envelope.ts", "web/src/cam-import-export-facade.ts"]),
|
||||
spec("Cloud", "tools/run_p6_cloud_action03_kernel_smoke.mjs", [str(CLOUD_BUILD)]),
|
||||
spec("Draft", "tools/run_p6_draft_runtime_smoke.mjs"),
|
||||
spec("Fem", "tools/run_p6_fem_runtime_smoke.mjs"),
|
||||
spec("Help", "tools/run_p6_help_runtime_smoke.mjs"),
|
||||
spec("Import", "tools/run_p6_import_runtime_smoke.mjs", [str(BUILD)]),
|
||||
spec("Inspection", "tools/run_p6_inspection_action02_kernel_smoke.mjs", [str(BUILD)]),
|
||||
spec("JtReader", "tools/run_p6_jtreader_kernel_smoke.mjs", [str(BUILD)]),
|
||||
spec("Material", "tools/run_p6_material_runtime_smoke.mjs", [str(CONFIGURE_BUILD)], build_tree=CONFIGURE_BUILD),
|
||||
spec("Measure", "tools/run_p6_measure_runtime_smoke.mjs", [str(CONFIGURE_BUILD)], build_tree=CONFIGURE_BUILD, runtime_probe="FreeCADWebMeasureRuntimeProbe"),
|
||||
spec("Mesh", "tools/run_p6_mesh_runtime_smoke.mjs", [str(BUILD)]),
|
||||
spec("MeshPart", "tools/run_p6_meshpart_runtime_smoke.mjs", [str(BUILD)]),
|
||||
spec("Part", "tools/run_p6_part_facade_smoke.mjs", [str(BUILD), "{out}"], compile_sources=["web/src/facade-envelope.ts", "web/src/part-facade.ts"]),
|
||||
spec("PartDesign", "tools/run_p6_partdesign_runtime.mjs", [str(BUILD)]),
|
||||
spec("Plot", "tools/run_p6_plot_runtime_smoke.mjs", [str(BUILD)]),
|
||||
spec("Points", "tools/run_p6_points_runtime.mjs", [str(BUILD)]),
|
||||
spec("ReverseEngineering", "tools/run_p6_reverseengineering_runtime.mjs", [str(BUILD)]),
|
||||
spec("Robot", "tools/run_p6_robot_runtime.mjs", [str(BUILD)]),
|
||||
spec("Sandbox", "tools/run_p6_sandbox_action02_facade_smoke.mjs", ["{out}/sandbox-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/sandbox-facade.ts"]),
|
||||
spec("Show", "tools/run_p6_show_facade.mjs", [str(BUILD)]),
|
||||
spec("Sketcher", "tools/run_p6_sketcher_action02_facade_smoke.mjs", ["{out}/sketcher-inspect-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/sketcher-inspect-facade.ts"]),
|
||||
spec("Spreadsheet", "tools/run_p6_spreadsheet_action02_facade_smoke.mjs", ["{out}/spreadsheet-inspect-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/spreadsheet-inspect-facade.ts"]),
|
||||
spec("Start", "tools/run_start_facade_smoke.mjs", ["{out}/start-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/start-facade.ts"]),
|
||||
spec("Surface", "tools/run_surface_facade_smoke.mjs", ["{out}/surface-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/surface-facade.ts"]),
|
||||
spec("TechDraw", "tools/run_techdraw_inspect_facade_smoke.mjs", ["{out}/techdraw-inspect-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/techdraw-inspect-facade.ts"]),
|
||||
spec("TemplatePyMod", "tools/run_templatepymod_facade_smoke.mjs", ["{out}/templatepymod-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/templatepymod-facade.ts"]),
|
||||
spec("Test", "web/src/test-facade-smoke.mjs", ["{out}/test-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/test-facade.ts"]),
|
||||
spec("Tux", "tools/run_tux_facade_smoke.mjs", ["{out}/tux-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/tux-facade.ts"]),
|
||||
spec("Web", "tools/run_web_facade_smoke.mjs", ["{out}/web-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/web-facade.ts"]),
|
||||
]
|
||||
|
||||
|
||||
# Current campaign uses real published WASM, not legacy source-inventory mocks.
|
||||
if "comprehensive-smoke" in str(RUN_DIR):
|
||||
SPECS = [dict(spec(row["module"], "tools/module-runtime-load-smoke.mjs", [row["module"]]), coverage="runtime-load") for row in SPECS]
|
||||
SPECS.append(dict(spec("UI-all-workbench-panels", "tools/workbench-panels-smoke.mjs"), owner="Web", coverage="browser-panel-mount", timeout=900))
|
||||
SPECS.append(dict(spec("Recent-shaft-current", "tools/shaft-current-smoke.mjs"), owner="PartDesign", coverage="current-native-shaft", timeout=120))
|
||||
for owner in ("Part", "PartDesign", "Sketcher"):
|
||||
ids = [owner + ":" + owner.lower() + suffix for suffix in (".createRecompute", ".saveReopen")]
|
||||
SPECS.append(dict(spec("Core-" + owner, "tools/run_business_acceptance.py",
|
||||
["--module", owner, "--ids", *ids, "--reuse", "--validate-deferred"]), owner=owner,
|
||||
coverage="core-native-model-and-FCStd", timeout=240))
|
||||
SPECS.append(dict(spec("Repaired-browser-workers", "tools/repaired-workers-browser-smoke.mjs"), owner="Web", additionalOwners=["Help", "Plot", "Show"], coverage="browser-native-request", timeout=240))
|
||||
groups = {
|
||||
"UI-shell-files": ["product:document-workspace", "product:react-primary-shell", "product:model-tree-properties", "product:multi-object-viewport", "product:desktop-command-ui", "product:task-panel", "product:workbench-navigation", "product:dynamic-module-session", "product:file-workflows", "product:recovery-status"],
|
||||
"UI-desktop-workspace": ["product:desktop-workspace-parity"],
|
||||
"UI-task-interactions": ["product:desktop-task-interaction-parity"],
|
||||
"UI-cross-workbench": ["product:cross-workbench-document-editing"],
|
||||
"Recent-shaft": ["PartDesign:desktop:PartDesign_WizardShaft", "PartDesign:desktop:PartDesign_WizardShaftCallBack"],
|
||||
}
|
||||
for name, ids in groups.items():
|
||||
owner = "PartDesign" if name == "Recent-shaft" else "Web"
|
||||
SPECS.append(dict(spec(name, "tools/run_business_acceptance.py", ["--module", owner, "--ids", *ids, "--reuse", "--validate-deferred"]), owner=owner, coverage="business-browser", timeout=600))
|
||||
|
||||
|
||||
for contract_path in sorted((ROOT / "docs/business-acceptance").glob("*.json")):
|
||||
owner = contract_path.stem
|
||||
if owner == "Web":
|
||||
continue
|
||||
contract = json.loads(contract_path.read_text())
|
||||
ids = contract.get("coveredIds") or contract.get("selectedIds") or []
|
||||
ids = [key for key in ids if key not in groups["Recent-shaft"]]
|
||||
if ids:
|
||||
SPECS.append(dict(spec("Business-" + owner, "tools/run_business_acceptance.py",
|
||||
["--module", owner, "--ids", *ids, "--reuse", "--validate-deferred"]), owner=owner,
|
||||
coverage="declared-business-cases", timeout=600))
|
||||
|
||||
|
||||
for row in SPECS:
|
||||
if row["module"] in {"Business-Part", "Business-PartDesign", "Business-Sketcher"}:
|
||||
row["script"] = "tools/run_smoke_business_records.py"
|
||||
row["args"] = [value for value in row["args"] if value not in {"--reuse", "--validate-deferred"}]
|
||||
row["timeout"] = 18000
|
||||
row["coverage"] = "declared-business-cases-with-per-ID-checkpoints"
|
||||
|
||||
web_contract = json.loads((ROOT / "docs/business-acceptance/Web.json").read_text())
|
||||
covered_web_ids = {key for row in SPECS if row.get("owner") == "Web" for key in row.get("args", [])}
|
||||
remaining_web_ids = [key for key in web_contract.get("coveredIds", []) if key not in covered_web_ids]
|
||||
if remaining_web_ids:
|
||||
# Several command IDs share the same existing manual workflow. The
|
||||
# Web runner deduplicates those workflows when submitted together.
|
||||
SPECS.append(dict(spec("UI-declared-desktop-commands", "tools/run_business_acceptance.py",
|
||||
["--module", "Web", "--ids", *remaining_web_ids, "--reuse", "--validate-deferred"]), owner="Web",
|
||||
coverage="declared-desktop-command-workflows", timeout=600))
|
||||
|
||||
|
||||
def inputs_for(row):
|
||||
from business_acceptance import digest, module_inputs
|
||||
owner = row.get("owner", row["module"])
|
||||
registry = json.loads((ROOT / "web/public/modules/manifest.json").read_text())
|
||||
paths = {ROOT / str(row["script"]), ROOT / "tools/wasm-probe-runtime.mjs"}
|
||||
for dependency_owner in [owner, *row.get("additionalOwners", [])]:
|
||||
sources = module_inputs(dependency_owner)
|
||||
paths.update(ROOT / name for name in sources["sources"])
|
||||
for worker in registry["modules"].get(dependency_owner, {}).get("workers", {}).values():
|
||||
paths.update(ROOT / "web/public" / value.lstrip("/") for key, value in worker.items() if key.endswith("Url") and isinstance(value, str))
|
||||
contract_path = ROOT / "docs/business-acceptance" / (owner + ".json")
|
||||
if row.get("owner") and contract_path.is_file():
|
||||
contract = json.loads(contract_path.read_text())
|
||||
command = contract.get("command", [])
|
||||
if len(command) > 1:
|
||||
paths.add(ROOT / command[1])
|
||||
for name in contract.get("dependencies", []) + contract.get("caseDependencies", []):
|
||||
dependency = ROOT / name
|
||||
if dependency.is_dir():
|
||||
paths.update(p for p in dependency.rglob("*") if p.is_file() and "__pycache__" not in p.parts)
|
||||
else:
|
||||
paths.add(dependency)
|
||||
# Track imported helper code recursively, without loading it into a runtime.
|
||||
todo = list(paths)
|
||||
while todo:
|
||||
current = todo.pop()
|
||||
if current.suffix not in {".mjs", ".ts", ".tsx", ".py"} or not current.is_file():
|
||||
continue
|
||||
for relative in re.findall(r"(?:from\s*|import\s*)[\"'](\.[^\"']+)[\"']", current.read_text()):
|
||||
child = (current.parent / relative).resolve()
|
||||
if not child.is_file() and child.suffix == ".js":
|
||||
child = child.with_suffix(".ts")
|
||||
if child.is_relative_to(ROOT) and child.is_file() and child not in paths:
|
||||
paths.add(child); todo.append(child)
|
||||
if row.get("owner"):
|
||||
paths.add(ROOT / "docs/business-acceptance" / (owner + ".json"))
|
||||
paths.update((ROOT / "web/dist/assets").glob("*"))
|
||||
paths.update(p for p in (ROOT / "web/dist").glob("*.html") if p.name != "execution.html")
|
||||
if row.get("owner") == "Web":
|
||||
# web-acceptance-cases launches the manual runner only for IDs in
|
||||
# manual-business-mapping; other UI groups never execute that branch.
|
||||
mapping_path = ROOT / "tools/manual-business-mapping.json"
|
||||
mapping = json.loads(mapping_path.read_text())["records"]
|
||||
paths.add(mapping_path)
|
||||
if not any(key in mapping for key in row.get("args", [])):
|
||||
paths.discard(ROOT / "tools/run_user_manual_tests.mjs")
|
||||
paths.discard(ROOT / "tools/user-manual-remaining-cases.mjs")
|
||||
files = {str(p.relative_to(ROOT)): digest(p) for p in sorted(paths) if p.is_file()}
|
||||
return hashlib.sha256(json.dumps({"spec":row,"files":files},sort_keys=True).encode()).hexdigest(), files
|
||||
|
||||
|
||||
def reusable_inputs(previous, row, fingerprint, inputs):
|
||||
if not previous:
|
||||
return False
|
||||
if previous.get("fingerprint") == fingerprint:
|
||||
return True
|
||||
old = previous.get("inputs", {})
|
||||
# A dependency-scope correction may remove unrelated files. Reuse only
|
||||
# when every retained input was already measured with the same contents
|
||||
# and the old hash proves the identical executable specification.
|
||||
old_key = hashlib.sha256(json.dumps({"spec": row, "files": old}, sort_keys=True).encode()).hexdigest()
|
||||
return bool(inputs) and old_key == previous.get("fingerprint") and all(old.get(p) == value for p, value in inputs.items())
|
||||
|
||||
|
||||
def run_isolated(command, timeout):
|
||||
# Own and reap the entire process group, including browser/worker children.
|
||||
process = subprocess.Popen(command, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
|
||||
try:
|
||||
stdout, stderr = process.communicate(timeout=timeout)
|
||||
return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
|
||||
finally:
|
||||
# Let a Python business runner reap its own isolated case/browser
|
||||
# group before enforcing termination of this wrapper group.
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
process.wait(timeout=5)
|
||||
except (ProcessLookupError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
try: os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError: pass
|
||||
process.wait()
|
||||
|
||||
|
||||
def load_manifest() -> dict[str, object]:
|
||||
if MANIFEST.exists():
|
||||
try:
|
||||
value = json.loads(MANIFEST.read_text(encoding="utf-8"))
|
||||
if isinstance(value, dict) and value.get("schema") == "freecad-web-module-smoke-once/v1":
|
||||
return value
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return {
|
||||
"schema": "freecad-web-module-smoke-once/v1",
|
||||
"startedAt": None,
|
||||
"status": "planned",
|
||||
"oneSmokePerModule": True,
|
||||
"policy": {
|
||||
"preflightBuildAllowed": True,
|
||||
"automaticRetry": False,
|
||||
"fixOnFailure": True,
|
||||
},
|
||||
"plan": [dict(row) for row in SPECS],
|
||||
"modules": [row["module"] for row in SPECS],
|
||||
"results": {},
|
||||
}
|
||||
|
||||
|
||||
def save_manifest(manifest: dict[str, object]) -> None:
|
||||
RUN_DIR.mkdir(parents=True, exist_ok=True)
|
||||
temporary = MANIFEST.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
temporary.replace(MANIFEST)
|
||||
if "comprehensive-smoke" in str(RUN_DIR):
|
||||
results = manifest.get("results", {})
|
||||
payload = {"schema": "freecad-web-smoke-progress/v1", "status": manifest.get("status"),
|
||||
"updatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"total": len(manifest.get("modules", [])), "completed": len(results),
|
||||
"passed": sum(row.get("status") == "pass" for row in results.values()),
|
||||
"current": manifest.get("current"),
|
||||
"failed": [name for name, row in results.items() if row.get("status") != "pass"]}
|
||||
public = ROOT / "web/public/smoke-status.json"
|
||||
staging = public.with_suffix(".tmp")
|
||||
staging.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
|
||||
staging.replace(public)
|
||||
|
||||
|
||||
def compile_facade(sources: list[str], out: Path) -> tuple[int, str, str]:
|
||||
if not sources:
|
||||
return 0, "", ""
|
||||
if not TSC.exists():
|
||||
return 127, "", f"missing TypeScript compiler: {TSC}"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
command = [
|
||||
str(TSC), "--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler",
|
||||
"--strict", "--skipLibCheck", "--outDir", str(out), "--declaration", "false", "--noEmit", "false",
|
||||
*[str(ROOT / source) for source in sources],
|
||||
]
|
||||
run = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=180)
|
||||
return run.returncode, run.stdout, run.stderr
|
||||
|
||||
|
||||
def prepare_build(row: dict[str, object]) -> tuple[int, str, str]:
|
||||
target = row.get("buildTarget")
|
||||
if not target:
|
||||
return 0, "", ""
|
||||
tree = Path(str(row["buildTree"]))
|
||||
js_candidates = list(tree.glob(f"{target}.js"))
|
||||
wasm_candidates = list(tree.glob(f"{target}.wasm"))
|
||||
if js_candidates and wasm_candidates:
|
||||
return 0, "artifact already present\n", ""
|
||||
command = ["cmake", "--build", str(tree.parent), "--target", str(target), f"-j{os.cpu_count() or 1}"]
|
||||
run = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=BUILD_TIMEOUT_SECONDS)
|
||||
return run.returncode, run.stdout, run.stderr
|
||||
|
||||
|
||||
def stage_runtime_build(row: dict[str, object]) -> Path | None:
|
||||
"""Make pthread workers CommonJS-compatible without modifying source artifacts."""
|
||||
probe = row.get("runtimeProbe")
|
||||
if not probe:
|
||||
return None
|
||||
build = Path(str(row["buildTree"]))
|
||||
runtime = build / f"{probe}.js"
|
||||
worker = build / f"{probe}.worker.js"
|
||||
wasm = build / f"{probe}.wasm"
|
||||
if not (runtime.exists() and worker.exists() and wasm.exists()):
|
||||
return None
|
||||
stage = Path(tempfile.mkdtemp(prefix=f"freecad-smoke-stage-{str(row['module']).lower()}-"))
|
||||
runtime_text = runtime.read_text(encoding="utf-8")
|
||||
runtime_text = runtime_text.replace(f"{probe}.worker.js", f"{probe}.worker.cjs")
|
||||
(stage / f"{probe}.js").write_text(runtime_text, encoding="utf-8")
|
||||
(stage / f"{probe}.worker.cjs").write_text(worker.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
shutil.copy2(wasm, stage / wasm.name)
|
||||
for suffix in (".data",):
|
||||
optional = build / f"{probe}{suffix}"
|
||||
if optional.exists():
|
||||
shutil.copy2(optional, stage / optional.name)
|
||||
return stage
|
||||
|
||||
|
||||
def module_command(row: dict[str, object], out: Path | None, build_override: Path | None = None) -> list[str]:
|
||||
original_build = str(row["buildTree"])
|
||||
args = [str(value).replace("{out}", str(out or "")) for value in row.get("args", [])]
|
||||
if build_override is not None:
|
||||
args = [value.replace(original_build, str(build_override)) for value in args]
|
||||
return [sys.executable if str(row["script"]).endswith(".py") else "node", str(ROOT / str(row["script"])), *args]
|
||||
|
||||
|
||||
def result_status(returncode: int, stdout: str) -> str:
|
||||
if returncode != 0:
|
||||
return "fail"
|
||||
matches = re.findall(r'"(?:result|status)"\s*:\s*"(pass|passed|fail|failed|blocked)"', stdout)
|
||||
if any(value in {"fail", "failed", "blocked"} for value in matches):
|
||||
return "fail"
|
||||
return "pass"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--only", nargs="+", help="Resume only named checks; other results remain recorded")
|
||||
parser.add_argument("--collect-business-records", action="store_true",
|
||||
help="Audit cumulative Part/PartDesign/Sketcher ID evidence after targeted repair; does not recertify historical inputs")
|
||||
options = parser.parse_args()
|
||||
if options.collect_business_records and (not options.only or set(options.only) - {"Business-Part", "Business-PartDesign", "Business-Sketcher"}):
|
||||
parser.error("--collect-business-records requires --only with the checkpointed business groups")
|
||||
def interrupted(_signum, _frame):
|
||||
raise KeyboardInterrupt
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
if options.only and set(options.only) - {row["module"] for row in SPECS}:
|
||||
parser.error("Unknown smoke check name")
|
||||
RUN_DIR.mkdir(parents=True, exist_ok=True)
|
||||
lock = (RUN_DIR / "run.lock").open("a")
|
||||
try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
print("Smoke campaign already running"); return 2
|
||||
manifest = load_manifest()
|
||||
# Keep the executable plan visible even when resuming an older manifest.
|
||||
manifest.setdefault("oneSmokePerModule", True)
|
||||
manifest.setdefault("policy", {
|
||||
"preflightBuildAllowed": True,
|
||||
"automaticRetry": False,
|
||||
"fixOnFailure": True,
|
||||
})
|
||||
manifest["plan"] = [dict(row) for row in SPECS]
|
||||
manifest["modules"] = [row["module"] for row in SPECS]
|
||||
if manifest.get("status") not in {"completed", "completed_with_failures"}:
|
||||
manifest["status"] = "running"
|
||||
if manifest.get("startedAt") is None:
|
||||
manifest["startedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
manifest["status"] = "running"
|
||||
save_manifest(manifest)
|
||||
results = manifest.setdefault("results", {})
|
||||
assert isinstance(results, dict)
|
||||
overall = 0
|
||||
manifest["status"] = "running"
|
||||
manifest["pid"] = os.getpid()
|
||||
manifest.pop("completedAt", None)
|
||||
for row in SPECS:
|
||||
module = str(row["module"])
|
||||
if options.only and module not in options.only:
|
||||
continue
|
||||
fingerprint, inputs = inputs_for(row)
|
||||
record_digest = None
|
||||
if options.collect_business_records:
|
||||
from business_acceptance import digest
|
||||
record_path = RUN_DIR / ("records-" + str(row["owner"]) + ".json")
|
||||
record_digest = digest(record_path)
|
||||
previous = results.get(module)
|
||||
if reusable_inputs(previous, row, fingerprint, inputs) and (not options.collect_business_records or previous.get("recordFingerprint") == record_digest):
|
||||
print(json.dumps({"module":module,"status":"reused","originalStatus":previous["status"]}),flush=True)
|
||||
continue
|
||||
if previous:
|
||||
manifest.setdefault("history", []).append(previous)
|
||||
started = time.time()
|
||||
result: dict[str, object] = {"module": module, "script": row["script"], "attempt": 1, "status": "preparing", "fingerprint": fingerprint, "inputs": inputs, "coverage": row.get("coverage", "legacy-smoke")}
|
||||
if options.collect_business_records:
|
||||
result["recordFingerprint"] = record_digest
|
||||
manifest["current"] = {"module": module, "phase": "preparing", "startedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "startedEpoch": started}
|
||||
save_manifest(manifest)
|
||||
out: Path | None = None
|
||||
if row.get("compileSources"):
|
||||
manifest["current"]["phase"] = "compile" # type: ignore[index]
|
||||
save_manifest(manifest)
|
||||
phase_started = time.time()
|
||||
out = Path(tempfile.mkdtemp(prefix=f"freecad-smoke-{module.lower()}-"))
|
||||
result["compileSources"] = row["compileSources"]
|
||||
code, stdout, stderr = compile_facade(list(row["compileSources"]), out)
|
||||
result["compileExitCode"] = code
|
||||
result["compileDurationSeconds"] = round(time.time() - phase_started, 3)
|
||||
if code != 0:
|
||||
result.update(status="fail", phase="compile", stdout=stdout[-4000:], stderr=stderr[-4000:])
|
||||
results[module] = result; manifest.pop("current", None); save_manifest(manifest); overall = 1
|
||||
print(json.dumps({"module": module, "status": result["status"], "phase": "compile", "durationSeconds": result.get("compileDurationSeconds")}, ensure_ascii=False), flush=True)
|
||||
continue
|
||||
manifest["current"]["phase"] = "build" # type: ignore[index]
|
||||
manifest["current"]["timeoutSeconds"] = BUILD_TIMEOUT_SECONDS # type: ignore[index]
|
||||
save_manifest(manifest)
|
||||
phase_started = time.time()
|
||||
code, stdout, stderr = prepare_build(row)
|
||||
result["buildExitCode"] = code
|
||||
result["buildDurationSeconds"] = round(time.time() - phase_started, 3)
|
||||
if code != 0:
|
||||
result.update(status="fail", phase="build", stdout=stdout[-4000:], stderr=stderr[-4000:])
|
||||
results[module] = result; manifest.pop("current", None); save_manifest(manifest); overall = 1
|
||||
print(json.dumps({"module": module, "status": result["status"], "phase": "build", "durationSeconds": result.get("buildDurationSeconds")}, ensure_ascii=False), flush=True)
|
||||
continue
|
||||
staged_build = stage_runtime_build(row)
|
||||
if staged_build is not None:
|
||||
result["stagedBuild"] = str(staged_build)
|
||||
command = module_command(row, out, staged_build)
|
||||
if options.collect_business_records:
|
||||
command.append("--summarize-only")
|
||||
result["validationBasis"] = "Cumulative original-ID evidence plus targeted repairs; original per-ID fingerprints and execution dates retained"
|
||||
result["recordSummary"] = "summary-" + str(row["owner"]) + ".json"
|
||||
result["command"] = command
|
||||
manifest["current"]["phase"] = "smoke" # type: ignore[index]
|
||||
manifest["current"]["timeoutSeconds"] = row.get("timeout", SMOKE_TIMEOUT_SECONDS) # type: ignore[index]
|
||||
save_manifest(manifest)
|
||||
phase_started = time.time()
|
||||
try:
|
||||
run = run_isolated(command, row.get("timeout", SMOKE_TIMEOUT_SECONDS))
|
||||
(RUN_DIR / (module + ".stdout.log")).write_text(run.stdout)
|
||||
(RUN_DIR / (module + ".stderr.log")).write_text(run.stderr)
|
||||
log_stem = module + "-" + fingerprint[:16]
|
||||
(RUN_DIR / (log_stem + ".stdout.log")).write_text(run.stdout)
|
||||
(RUN_DIR / (log_stem + ".stderr.log")).write_text(run.stderr)
|
||||
result["logs"] = [log_stem + ".stdout.log", log_stem + ".stderr.log"]
|
||||
status = result_status(run.returncode, run.stdout)
|
||||
result["smokeDurationSeconds"] = round(time.time() - phase_started, 3)
|
||||
result.update(status=status, phase="smoke", exitCode=run.returncode, stdout=run.stdout[-8000:], stderr=run.stderr[-8000:], durationSeconds=round(time.time() - started, 3))
|
||||
nested_timeout = re.search(r"timed out after (\d+) seconds", run.stdout)
|
||||
if nested_timeout:
|
||||
result["timeoutSeconds"] = int(nested_timeout.group(1))
|
||||
result["timeoutOwner"] = "business-case-runner"
|
||||
if status != "pass": overall = 1
|
||||
except subprocess.TimeoutExpired as error:
|
||||
result["smokeDurationSeconds"] = round(time.time() - phase_started, 3)
|
||||
result.update(status="fail", phase="smoke", exitCode=None, stdout=str(error.stdout or "")[-8000:], stderr=str(error.stderr or "")[-8000:], timeoutSeconds=SMOKE_TIMEOUT_SECONDS, durationSeconds=round(time.time() - started, 3)); overall = 1
|
||||
results[module] = result
|
||||
manifest.pop("current", None)
|
||||
save_manifest(manifest)
|
||||
print(json.dumps({"module": module, "status": result["status"], "durationSeconds": result.get("durationSeconds")}, ensure_ascii=False), flush=True)
|
||||
failed = [name for name, result in results.items() if isinstance(result, dict) and result.get("status") != "pass"]
|
||||
manifest["status"] = "paused" if any(row["module"] not in results for row in SPECS) else "completed_with_failures" if failed else "completed"
|
||||
manifest.pop("current", None)
|
||||
manifest["failedModules"] = failed
|
||||
manifest["completedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
save_manifest(manifest)
|
||||
print(json.dumps({"status": manifest["status"], "modules": len(results), "failedModules": failed}, ensure_ascii=False))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except KeyboardInterrupt:
|
||||
checkpoint = load_manifest()
|
||||
checkpoint["status"] = "interrupted"
|
||||
save_manifest(checkpoint)
|
||||
raise SystemExit(130)
|
||||
235
tools/user-manual-remaining-cases.mjs
Normal file
235
tools/user-manual-remaining-cases.mjs
Normal file
@@ -0,0 +1,235 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
|
||||
export function createRemainingCases(h) {
|
||||
const {root,output,fixture,step,open,button,evaluate,send,until,wait,check,box,dimensions,volume,count,upload,save,reopen,idle,hash}=h;
|
||||
const objectCount="document.querySelectorAll('[role=treeitem]').length";
|
||||
const stage="document.querySelector('.stage > [role=status]')?.textContent";
|
||||
const json=(name,data)=>fs.writeFileSync(path.join(output,name),JSON.stringify(data,null,2)+'\n');
|
||||
async function memory() {
|
||||
const rows=execFileSync('ps',['-eo','pid=,ppid=,rss='],{encoding:'utf8'}).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number));
|
||||
const pids=new Set([h.getBrowserPid()]);
|
||||
for(let changed=true;changed;){changed=false;for(const [pid,parent]of rows)if(pids.has(parent)&&!pids.has(pid)){pids.add(pid);changed=true;}}
|
||||
const rss=rows.filter(([pid])=>pids.has(pid)).reduce((n,row)=>n+row[2],0)*1024;
|
||||
await send('Performance.enable');
|
||||
const {metrics}=await send('Performance.getMetrics');
|
||||
return {at:new Date().toISOString(),browserTreeRssBytes:rss,processes:pids.size,
|
||||
rendererJsHeapBytes:metrics.find(m=>m.name==='JSHeapUsedSize')?.value,
|
||||
note:'RSS sums browser descendants and can double-count shared pages; JS heap excludes Worker WASM. Not a physical-memory measurement.'};
|
||||
}
|
||||
async function importFixture(file) {
|
||||
const n=await count();
|
||||
if (!await evaluate("Boolean(document.querySelector('[aria-label=\"Import task\"]'))")) {
|
||||
const command = /\.(step|stp)$/i.test(file) ? 'Part_ImportStep' : '';
|
||||
if (command) await evaluate(`(()=>{const b=document.querySelector('[data-import-command="${command}"]');if(!b||b.disabled)throw Error('Import command unavailable: ${command}');b.click();})()`);
|
||||
}
|
||||
await upload(file);
|
||||
const accept=await evaluate("[...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='Accept import'&&!e.disabled)");
|
||||
if (accept) await button('Accept import');
|
||||
await until('Native import complete',`({count:${objectCount},status:${stage},busy:Boolean(document.querySelector('[aria-label="Import task"]')?.matches(':disabled'))})`,s=>{
|
||||
if(!s.busy&&s.status&&!/^(Importing|Imported|Opened|Import cancelled)/.test(s.status))throw Error(s.status);
|
||||
return !s.busy&&s.count>n;
|
||||
},60000);
|
||||
const v=await evaluate("Number(document.querySelector('[data-native-volume]')?.textContent)");
|
||||
check(v>0,'Imported shape has no positive native volume');return v;
|
||||
}
|
||||
async function chooseLocalFile(file) {
|
||||
await until('Open command registration loaded',"window.__freecadWorkbenchState?.selected?.command",s=>s==='Std_Open');
|
||||
await send('Page.setInterceptFileChooserDialog',{enabled:true});
|
||||
const eventStart=h.getEvents().length;
|
||||
const point=await evaluate("(()=>{const b=[...document.querySelectorAll('button')].find(b=>b.textContent==='Choose files');if(!b||b.disabled)throw Error('File chooser button unavailable');b.scrollIntoView({block:'center'});const r=b.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()");
|
||||
await send('Input.dispatchMouseEvent',{type:'mousePressed',...point,button:'left',clickCount:1});
|
||||
await send('Input.dispatchMouseEvent',{type:'mouseReleased',...point,button:'left',clickCount:1});
|
||||
let chooser;
|
||||
for(let i=0;i<100;i++){chooser=h.getEvents().slice(eventStart).find(e=>e.method==='Page.fileChooserOpened');if(chooser)break;await wait(100);}
|
||||
check(chooser?.params.backendNodeId,'Native file chooser did not open');
|
||||
await send('DOM.setFileInputFiles',{backendNodeId:chooser.params.backendNodeId,files:[file]});
|
||||
await send('Page.setInterceptFileChooserDialog',{enabled:false});
|
||||
}
|
||||
async function openResult() {
|
||||
return until('Native open response',"window.__freecadWorkbenchState?.response",r=>{
|
||||
if(r?.kind==='error')throw Error(JSON.stringify(r.error));
|
||||
return r?.kind==='result';
|
||||
},180000);
|
||||
}
|
||||
const downloadSnapshot=()=>Object.fromEntries(fs.readdirSync(path.join(output,'downloads')).map(n=>[n,fs.statSync(path.join(output,'downloads',n)).mtimeMs]));
|
||||
async function downloadedFile(extension,previous={}) {
|
||||
for(let i=0;i<200;i++) {
|
||||
const names=fs.readdirSync(path.join(output,'downloads')).filter(n=>n.toLowerCase().endsWith('.'+extension.toLowerCase())&&previous[n]!==fs.statSync(path.join(output,'downloads',n)).mtimeMs);
|
||||
if(names.length)return path.join(output,'downloads',names.at(-1));
|
||||
await wait(100);
|
||||
}
|
||||
throw Error(`Missing completed .${extension} download`);
|
||||
}
|
||||
async function nativeExport(format) {
|
||||
const previous=downloadSnapshot();
|
||||
await h.select('Native export format',format);await button('导出选中对象');
|
||||
await until('Native export',stage,s=>{if(s?.startsWith('Error:'))throw Error(s);return s?.startsWith('Exported ');},30000);
|
||||
return downloadedFile(format,previous);
|
||||
}
|
||||
async function command(module,name,args={}) {
|
||||
await evaluate(`(()=>{const b=[...document.querySelectorAll('button.module')].find(b=>b.querySelector('strong')?.textContent===${JSON.stringify(module)});if(!b)throw Error('Module missing');b.click();})()`);
|
||||
await until('Command registration loaded',`[...document.querySelectorAll('button.command')].some(b=>b.querySelector('span')?.textContent===${JSON.stringify(name)})`);
|
||||
await evaluate(`(()=>{const b=[...document.querySelectorAll('button.command')].find(b=>b.querySelector('span')?.textContent===${JSON.stringify(name)});b.click();})()`);
|
||||
await h.input('命令 JSON 参数',JSON.stringify(args));
|
||||
await until('Selected command ready',"[...document.querySelectorAll('button')].some(b=>b.textContent==='执行选中命令'&&!b.disabled)");
|
||||
await button('执行选中命令');
|
||||
const response=await until('Native command result',"window.__freecadWorkbenchState?.response",r=>{if(r?.kind==='error')throw Error(JSON.stringify(r.error));return r?.kind==='result';},180000);
|
||||
const row=response.result?.records?.[0];
|
||||
if(row&&'status' in row)check(['success','exposed','ok'].includes(row.status),JSON.stringify(row));
|
||||
const result=row?.result??response.result;
|
||||
check(!result?.sceneError,`Scene refresh failed: ${result?.sceneError}`);
|
||||
return result;
|
||||
}
|
||||
async function workbenchDocument() {
|
||||
await open();await box();await box([3,4,5]);await save();
|
||||
const previous=downloadSnapshot();await button('下载 native FCStd');
|
||||
const file=await downloadedFile('fcstd',previous);
|
||||
await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(file);
|
||||
const r=await openResult(),v=r.result.records[0].result;
|
||||
check(!v.sceneError&&v.errors.length===0,'Native open failed');return v.activeDocument;
|
||||
}
|
||||
async function inspect(documentId,expression) {
|
||||
const value=await command('Web','Std_CommandLine',{documentId,runtimeOwner:'PartBox',operation:'submit',source:`import json; print(json.dumps(${expression}))`});
|
||||
check(!value.stderr,'Native console returned an error: '+value.stderr);
|
||||
return JSON.parse(value.stdout.trim().split('\n').at(-1));
|
||||
}
|
||||
async function saveAndReopenNative(documentId,name) {
|
||||
const saved=await command('Web','Std_SaveAs',{documentId,runtimeOwner:'PartBox',filename:name});
|
||||
const file=saved.files?.[0];check(file?.contentsBase64,'Save returned no FCStd bytes');
|
||||
const local=path.join(output,name);fs.writeFileSync(local,Buffer.from(file.contentsBase64,'base64'));
|
||||
await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(local);
|
||||
const r=await openResult(),v=r.result.records[0].result;check(!v.sceneError&&v.errors.length===0,'Restore failed');return v.activeDocument;
|
||||
}
|
||||
const cases={
|
||||
'FIX-IFC-REOPEN':async()=>{
|
||||
let documentId;
|
||||
await step('打开实际 IFC 导入后保存的 FCStd',async()=>{
|
||||
const file=path.join(root,'docs/current/user-tests-20260915/ifc-native-2026-09-15T15-50-07-990Z/IfcValidation.FCStd');
|
||||
await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(file);
|
||||
const response=await openResult(),value=response.result.records[0].result;
|
||||
check(value.errors.length===0&&!value.sceneError,'FCStd restore or scene failed');
|
||||
documentId=value.activeDocument;
|
||||
await until('Restored native mesh viewport',"Number(document.querySelector('[data-native-mesh-count]')?.dataset.nativeMeshCount)",n=>n>20,180000);
|
||||
return {documentId,documents:value.opened[0].documents,meshCount:value.scene?.meshes.length};
|
||||
},'147 个对象恢复,空间层级及原生几何仍存在,视口非空');
|
||||
await step('核对恢复后实体及原始 IFC 附件',async()=>{
|
||||
const value=await inspect(documentId,`{'groups':sum(1 for o in App.getDocument('${documentId}').Objects if o.isDerivedFrom('App::DocumentObjectGroup')),'solids':sum(1 for o in App.getDocument('${documentId}').Objects if o.isDerivedFrom('Part::Feature') and not o.Shape.isNull()),'source':App.getDocument('${documentId}').getObject('IfcSource').OriginalIFC,'ids':sum(1 for o in App.getDocument('${documentId}').Objects if 'IfcGlobalId' in o.PropertiesList)}`);
|
||||
check(value.groups>=3&&value.solids>20&&value.source&&value.ids>20,'IFC provenance or native objects not restored');return value;
|
||||
},'实体、空间分组、IFC GlobalId 和内嵌源文件保留');
|
||||
},
|
||||
'GEO-01':async()=>{
|
||||
await step('创建 2 x 3 x 4 Box',async()=>{await open();return box();},'1 个对象,原生体积约 24');
|
||||
await step('读取原生包围盒属性',async()=>{const bounds=await evaluate("JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds)");check(bounds.length===6&&bounds.every((n,i)=>Math.abs(n-[0,0,0,2,3,4][i])<1e-5),'OCCT bounds differ');return {bounds,volume:await volume(24),tolerance:1e-5};},'原生返回 [0,0,0]-[2,3,4],容差 1e-5 mm');
|
||||
},
|
||||
'FILE-03':async()=>{
|
||||
let downloaded;
|
||||
await step('创建和编辑保存文档',async()=>{await open();await box();await h.input('Object Label','User acceptance box');await evaluate("document.querySelector('[aria-label=\"Object Label\"]').blur()");await idle();return save();},'FCStd ZIP 已写入 OPFS');
|
||||
await step('下载真实 FCStd 文件',async()=>{await button('下载 native FCStd');for(let i=0;i<100;i++){const files=fs.readdirSync(path.join(output,'downloads')).filter(n=>/\.FCStd$/i.test(n));if(files.length){downloaded=path.join(output,'downloads',files.at(-1));break;}await wait(100);}check(downloaded,'FCStd download missing');return {file:downloaded,bytes:fs.statSync(downloaded).size,sha256:hash(downloaded)};},'下载完成并记录文件指纹');
|
||||
await step('关闭后打开 OPFS 文档',async()=>{await button('关闭活动 Document');const state=await reopen();check(state.objects===1,'Object count differs');await volume(24);return state;},'对象数量和体积恢复');
|
||||
await step('通过 Std_Open 文件选择器重开下载文件',async()=>{await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(downloaded);const r=await openResult();const v=r.result.records[0].result;check(v.errors.length===0&&v.opened.length===1,'Native file open did not succeed');check(v.opened[0].documents[0].objectCount===1,'FCStd object count differs');check(!v.opened[0].documents[0].partialRestore&&!v.opened[0].documents[0].restoreError&&!v.sceneError,'Partial restore or scene failure');return v;},'本地 FCStd 完整恢复,不以 OPFS 回读代替');
|
||||
},
|
||||
'FILE-05':async()=>{
|
||||
let stl,before;
|
||||
await step('准备基准 Box',async()=>{await open();await box();before=await evaluate("JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds)");return {bounds:before,volume:await volume(24)};},'原生体积 24,包围盒 [0,0,0]-[2,3,4]');
|
||||
await step('使用原生 OCCT 导出 STL',async()=>{stl=await nativeExport('stl');return {file:stl,size:fs.statSync(stl).size,sha256:hash(stl)};},'下载非空 STL 文件');
|
||||
await step('真实文件回读和误差比较',async()=>{await open();await upload(stl);await until('STL object',objectCount,n=>n===1,30000);await idle();const bounds=await evaluate("JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds)");check(bounds.every((v,i)=>Math.abs(v-before[i])<1e-5),'STL bounds changed');return {bounds,volume:await volume(24),tolerance:1e-5};},'STL 回读体积约 24,包围盒误差小于 1e-5 mm');
|
||||
},
|
||||
'FILE-02':async()=>{
|
||||
const report=[];
|
||||
for(const format of ['step','iges','brep','stl'])await step(`${format.toUpperCase()} 原生文件导出及导入`,async()=>{
|
||||
await open();await box();const file=await nativeExport(format);
|
||||
if (format === 'stl') {
|
||||
await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(file);
|
||||
try { const response=await openResult(); check(false,'Std_Open unexpectedly accepted STL'); return response; }
|
||||
catch (error) { if (String(error).includes('unexpectedly accepted')) throw error; const value={format,file,sha256:hash(file),supported:false,imported:false,boundary:String(error)};report.push(value);json('format-validation.json',report);return value; }
|
||||
}
|
||||
const command={step:'Part_ImportStep',iges:'Import_Iges',brep:'Import_ReadBREP'}[format];
|
||||
await open(); await evaluate(`(()=>{const b=document.querySelector('[data-import-command="${command}"]');if(!b||b.disabled)throw Error('Import command unavailable: ${command}');b.click();})()`);
|
||||
await until('Import source input',"Boolean([...document.querySelectorAll('input[type=file]')].find(e=>e.getAttribute('aria-label')==='Import source file'&&!e.disabled))",Boolean,10000);
|
||||
const v=await importFixture(file); const bounds=await evaluate("document.querySelector('[data-native-bounds]') ? JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds) : null");
|
||||
const result={format,file,sha256:hash(file),supported:true,imported:true,volume:v,bounds};report.push(result);json('format-validation.json',report);return result;
|
||||
},'STEP/IGES/BREP 走 Part 专用导入;STL 的 Std_Open 边界明确记录');
|
||||
await step('DXF 本地桌面样本导入',async()=>{
|
||||
const file=path.join(root,'FreeCADBaseLib/sources/src/Qt-5.15.13/qt3d/src/3rdparty/assimp/test/models/DXF/floor.dxf');
|
||||
await open('/workbench.html?module=Draft');const result=await command('Draft','draft.formatBatch',{schema:'freecad-web-draft/format-batch/v1',module:'Draft',records:[{format:'dxf',direction:'import',documentId:'DxfValidation',payload:fs.readFileSync(file,'utf8')}]});
|
||||
const row=result.records[0];check(row.objectCount>0&&row.objects.some(o=>o.length>0||o.area>0),'DXF has no native geometry');
|
||||
report.push({format:'dxf',file,sha256:hash(file),supported:true,imported:true,result:row});json('format-validation.json',report);return row;
|
||||
},'复用桌面 DXF 导入链路,非空原生对象');
|
||||
for(const [format,p]of [
|
||||
['obj','FreeCADBaseLib/sources/src/Qt-5.15.13/qt3d/src/3rdparty/assimp/src/test/models/OBJ/box_without_lineending.obj'],
|
||||
['ifc','FreeCADBaseLib/sources/src/Qt-5.15.13/qt3d/src/3rdparty/assimp/src/test/models/IFC/AC14-FZK-Haus.ifc'],
|
||||
])await step(`${format.toUpperCase()} 实际注册能力及文件处理`,async()=>{
|
||||
await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(path.join(root,p));
|
||||
const response=await until('File handled',"window.__freecadWorkbenchState?.response",r=>r?.kind==='result'||r?.kind==='error',format==='ifc'?600000:60000);
|
||||
if(response.kind==='error') {
|
||||
const error=response.error;
|
||||
check(error.code==='file_open_failed'&&error.diagnostic?.openResult?.errors?.length,'Unstructured format failure');
|
||||
const value={format,file:p,sha256:hash(path.join(root,p)),supported:false,imported:false,error};report.push(value);json('format-validation.json',report);
|
||||
throw new Error(`${format.toUpperCase()} native import is not available: ${error.message}`);
|
||||
}
|
||||
const value=response.result.records[0].result;
|
||||
check(value.opened.length>0&&!value.sceneError,'Imported document or display missing');
|
||||
if(format==='ifc') {
|
||||
check(value.opened[0].documents[0].objectCount>20,'IFC import returned no real building document');
|
||||
check(!value.opened[0].documents[0].partialRestore&&!value.opened[0].documents[0].restoreError,'IFC restore incomplete');
|
||||
value.testScope='Real IfcOpenShellNative import-only binding. Not the full ifcopenshell Python authoring/export API.';
|
||||
await until('IFC meshes rendered',"({count:Number(document.querySelector('[data-native-mesh-count]')?.dataset.nativeMeshCount),canvas:!!document.querySelector('canvas')})",s=>s.count>20&&s.canvas,180000);
|
||||
}
|
||||
report.push({format,file:p,sha256:hash(path.join(root,p)),supported:true,imported:true,result:value});json('format-validation.json',report);return value;
|
||||
},'支持则完整导入;依赖或登记缺口记录失败,不伪装支持');
|
||||
},
|
||||
'ERR-01':async()=>{
|
||||
await step('准备已有文档对象',async()=>{await open();return box();},'已有体积 24 对象');
|
||||
await step('在原生导入中请求取消',async()=>{await upload(path.join(root,'freecad-source/data/examples/Schenkel.stp'));await until('Import entered native operation',"document.querySelector('[data-import-phase]')?.dataset.importPhase",v=>v==='native',30000);await button('取消导入');return {phase:await evaluate("document.querySelector('[data-import-phase]')?.dataset.importPhase"),status:await evaluate(stage)};},'原生事务尚未提交,显示取消中');
|
||||
await step('等待回滚并核对原文档',async()=>{await until('Import rolled back',stage,s=>s?.startsWith('Import cancelled'),60000);await idle();check(await count()===1,'Cancelled import left an object');return {objects:await count(),volume:await volume(24)};},'取消后无半成品,原对象保留');
|
||||
await step('取消后正常导入恢复',async()=>{const v=await importFixture(fixture);check(await count()===2,'Recovery import missing');return {objects:await count(),volume:v};},'Worker 和原生文档可继续使用');
|
||||
},
|
||||
'DOC-02':async()=>{
|
||||
let doc,part,varset,boxes;
|
||||
await step('准备含两个实体的原生工作台文档',async()=>{doc=await workbenchDocument();boxes=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).Objects if o.TypeId=='Part::Box']`);check(boxes.length===2,'Two native boxes were not restored');return {doc,boxes};},'两个实体从 FCStd 打开在 PartBox 宿主');
|
||||
await step('创建 Part 并按桌面语义组合选择',async()=>{const v=await command('Web','Std_Part',{documentId:doc,label:'Validation Part',action:'create',selection:boxes.map(object=>({documentId:doc,object}))});part=v.createdObject;check(v.activePart===part&&v.objects.find(o=>o.name===part).children.length===2,'Part grouping or document Tip differs');return v;},'Part 包含两个实体,文档 Tip 指向新 Part');
|
||||
await step('移出一个对象再加入',async()=>{for(const names of [[boxes[0]],[...boxes]]){await command('Web','Std_Properties',{documentId:doc,operation:'apply',object:part,selection:[{documentId:doc,object:part}],property:'Group',value:JSON.stringify(names.map(object=>({documentId:doc,object})))});const actual=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);check(JSON.stringify(actual.sort())===JSON.stringify(names.sort()),'Group edit not applied');}return {part,children:boxes};},'原生 Group 属性执行移出/加入,层级正确');
|
||||
await step('创建 VarSet 并设置变量',async()=>{const v=await command('Web','Std_VarSet',{documentId:doc,action:'create',label:'Validation Variables',selection:[{documentId:doc,object:part}]});varset=v.createdObject;await command('Web','Std_VarSet',{documentId:doc,action:'set-variable',object:varset,name:'Width',type:'App::PropertyFloat',value:'7.5',expression:'',selection:[]});const read=await command('Web','Std_VarSet',{documentId:doc,action:'read',object:varset,selection:[]});check(read.objects.find(o=>o.name===varset).properties.some(p=>p.name==='Width'&&p.value===7.5),'Variable not stored');return read;},'VarSet 动态变量为 7.5');
|
||||
await step('设置并清除变量表达式',async()=>{await command('Web','Std_VarSet',{documentId:doc,action:'set-variable',object:varset,name:'DoubleWidth',type:'App::PropertyFloat',value:'',expression:'Width * 2',selection:[]});const actual=await inspect(doc,`App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(varset)}).DoubleWidth`);check(actual===15,'Expression not evaluated');await command('Web','Std_VarSet',{documentId:doc,action:'remove-variable',object:varset,name:'DoubleWidth',selection:[]});return {evaluated:actual};},'表达式求值为 15,动态变量可以移除');
|
||||
await step('保存刷新重开结构与 Tip',async()=>{doc=await saveAndReopenNative(doc,'Structure.FCStd');const state=await inspect(doc,`{'tip':App.getDocument(${JSON.stringify(doc)}).Tip.Name,'children':[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group],'width':App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(varset)}).Width}`);check(state.tip===part&&state.children.includes(boxes[0])&&state.children.includes(varset)&&state.width===7.5,'Structure not restored');return state;},'FCStd 恢复树层级、文档 Tip 和变量');
|
||||
},
|
||||
'DOC-03':async()=>{
|
||||
let doc,part,link,boxes;
|
||||
await step('准备可替换引用的原生文档',async()=>{doc=await workbenchDocument();boxes=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).Objects if o.TypeId=='Part::Box']`);const v=await command('Web','Std_Part',{documentId:doc,action:'create',selection:boxes.map(object=>({documentId:doc,object}))});part=v.createdObject;return {doc,part,boxes};},'Part 包含两个原生对象');
|
||||
await step('用 Link 替换父容器引用',async()=>{const v=await command('Web','Std_LinkReplace',{documentId:doc,action:'apply',parentDocument:doc,parentObject:part,selection:[{documentId:doc,object:boxes[0]}]});const children=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);link=children.find(n=>n!==boxes[1]);check(link&&link!==boxes[0],'Reference was not replaced');const target=await inspect(doc,`App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(link)}).getLinkedObject().Name`);check(target===boxes[0],'Wrong link target');return {v,children,link,target};},'父容器引用 Link,Link 指向原对象');
|
||||
await step('撤销重做链接替换',async()=>{await command('Web','Std_Undo',{documentId:doc});const before=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);check(before.includes(boxes[0]),'Undo failed');await command('Web','Std_Redo',{documentId:doc});const after=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);check(after.includes(link),'Redo failed');return {before,after};},'事务准确恢复父容器引用');
|
||||
await step('保存重开链接并解除',async()=>{doc=await saveAndReopenNative(doc,'Links.FCStd');const restored=await inspect(doc,`[(o.Name,o.TypeId) for o in App.getDocument(${JSON.stringify(doc)}).Objects]`);const group=(restored.find(item=>item[1]=='App::Part')||restored.find(item=>item[1]=='App::DocumentObjectGroup'))?.[0];const target=restored.find(item=>item[1]=='App::Link')?.[0];check(group&&target,'Restored link graph missing');await command('Web','Std_LinkUnlink',{documentId:doc,action:'apply',parentDocument:doc,parentObject:group,selection:[{documentId:doc,object:target}]});const children=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(group)}).Group]`);check(children.length>=1&&!children.includes(target),'Unlink failed');return {restored,children};},'链接持久化后可解除,父容器重新引用原对象');
|
||||
},
|
||||
'PERF-01':async()=>{
|
||||
const files=[['small','freecad-source/src/Mod/Import/App/SCL/Product1.stp'],['medium','web/public/samples/freecad-sample.step'],['large','freecad-source/data/examples/Schenkel.stp']];
|
||||
const measurements=[];
|
||||
await step('登记本机实际样本和性能范围',async()=>{const data=files.map(([tier,p])=>({tier,path:p,bytes:fs.statSync(path.join(root,p)).size,sha256:hash(path.join(root,p))}));json('performance-fixtures.json',{scope:'Relative size tiers of provided desktop STEP examples, not production maximum-capacity certification',maxImportSeconds:60,fixtures:data});return data;},'样本来自本机桌面 FreeCAD;逐项记录字节数和 SHA-256');
|
||||
for(const [tier,p]of files)await step(`${tier} 样本加载与交互测量`,async()=>{
|
||||
await open();const samples=[await memory()],start=performance.now();
|
||||
let sampling=true;const sampler=(async()=>{while(sampling){await wait(250);if(sampling)samples.push(await memory());}})();
|
||||
let v;try{v=await importFixture(path.join(root,p));}finally{sampling=false;await sampler;}
|
||||
const seconds=(performance.now()-start)/1000;samples.push(await memory());
|
||||
check(seconds<60,'Import exceeds 60 second local test budget');
|
||||
const frames=await evaluate("new Promise(resolve=>{let n=0;const start=performance.now();const tick=now=>{n++;if(now-start>=1000)resolve({frames:n,seconds:(now-start)/1000});else requestAnimationFrame(tick);};requestAnimationFrame(tick);})");
|
||||
const value={tier,file:p,bytes:fs.statSync(path.join(root,p)).size,seconds,volume:v,peakBrowserTreeRssBytes:Math.max(...samples.map(s=>s.browserTreeRssBytes)),samples,animationCallbackHz:frames.frames/frames.seconds,rendering:'headless software WebGL; callback cadence is not CAD draw FPS'};
|
||||
measurements.push(value);json('performance-loading.json',measurements);return value;
|
||||
},'60 秒内完成导入,原生实体有正体积,记录内存采样和帧回调频率');
|
||||
},
|
||||
'PERF-02':async()=>{
|
||||
const results=[];
|
||||
for(let iteration=1;iteration<=20;iteration++)await step(`第 ${iteration}/20 轮导入、修改、保存、刷新重开`,async()=>{
|
||||
await open();const start=performance.now();const importedVolume=await importFixture(fixture);
|
||||
await box();await dimensions([3,4,5]);await button('应用尺寸并重算');await idle();await volume(60);
|
||||
await save();await open();const restored=await reopen();check(restored.objects===2,'Restored object count differs');
|
||||
await h.click('[role=treeitem]');await volume(importedVolume);await evaluate("document.querySelectorAll('[role=treeitem]')[1].click()");await volume(60);
|
||||
const filenames=await evaluate("[...document.querySelector('[aria-label=\"OPFS document\"]').options].map(o=>o.value).filter(Boolean)");check(new Set(filenames).size===filenames.length,'Duplicate OPFS entries');
|
||||
await wait(250);const mem=await memory();
|
||||
const result={iteration,seconds:(performance.now()-start)/1000,objects:restored.objects,importedVolume,boxVolume:60,files:filenames,memory:mem};results.push(result);json('stability-cycles.json',results);return result;
|
||||
},'每轮真实 STEP 和修改后的 Box 均恢复,无重复文件或对象');
|
||||
await step('检查稳定阶段内存趋势',async()=>{const values=results.slice(5).map(r=>r.memory.browserTreeRssBytes);const mean=a=>a.reduce((n,v)=>n+v,0)/a.length;const growth=mean(values.slice(-5))-mean(values.slice(0,5));const allRising=values.every((v,i)=>i===0||v>values[i-1]);const report={cycles:20,warmupCycles:5,earlyMean:mean(values.slice(0,5)),lateMean:mean(values.slice(-5)),growthBytes:growth,allRising,allowedGrowthBytes:256*1024*1024,scope:'Same host/software WebGL, process-tree RSS (shared pages counted per process)'};json('stability-summary.json',report);check(!allRising&&growth<report.allowedGrowthBytes,'Sustained browser memory growth requires investigation');return report;},'预热后不存在持续单调增长,后五轮平均 RSS 增长不超过 256 MiB');
|
||||
},
|
||||
};
|
||||
return cases;
|
||||
}
|
||||
1636
tools/web-freecad-29-case-tutor.mjs
Normal file
1636
tools/web-freecad-29-case-tutor.mjs
Normal file
File diff suppressed because it is too large
Load Diff
98
tools/web-freecad-29-case-tutor.py
Normal file
98
tools/web-freecad-29-case-tutor.py
Normal file
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Visible Web FreeCAD 29-case teaching runner.
|
||||
|
||||
Python owns the lesson order and evidence ledger. The browser actions are
|
||||
performed by the local Playwright helper so the user sees the real Web
|
||||
FreeCAD page instead of a simulated animation.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HELPER = ROOT / "tools" / "web-freecad-29-case-tutor.mjs"
|
||||
DEFAULT_ORIGIN = os.environ.get("FREECAD_BROWSER_ORIGIN", "http://127.0.0.1:5183")
|
||||
CASES = [
|
||||
("assembly", "Assembly", "Assembly", "创建装配、插入组件、检查关节和保存重开"),
|
||||
("bim", "BIM", "BIM", "创建 BIM 关系/分组并检查错误恢复"),
|
||||
("cam", "CAM", "CAM", "执行完整三轴刀路、导出和保存重开"),
|
||||
("cloud", "Cloud", "Cloud", "执行云文档保存和恢复"),
|
||||
("draft", "Draft", "Draft", "进入 Draft 并执行二维对象入口"),
|
||||
("fem", "Fem", "Fem", "进入 FEM 并执行分析任务入口"),
|
||||
("help", "Help", "Help", "打开帮助工作台和资源入口"),
|
||||
("import", "Import", "Import", "进入专用格式导入入口"),
|
||||
("inspection", "Inspection", "Inspection", "执行检查对象和报告入口"),
|
||||
("jtreader", "JtReader", "JtReader", "打开 JT/Inventor 入口"),
|
||||
("material", "Material", "Material", "读取和赋值材质"),
|
||||
("measure", "Measure", "Measure", "执行质量属性和距离测量"),
|
||||
("meshpart", "MeshPart", "MeshPart", "执行网格到形状转换入口"),
|
||||
("partdesign", "PartDesign", "PartDesign", "创建 Body、Sketch、Pad、Pocket"),
|
||||
("plot", "Plot", "Plot", "进入绘图和只读 API 入口"),
|
||||
("points", "Points", "Points", "读取点数据并检查显示"),
|
||||
("reverseengineering", "ReverseEngineering", "ReverseEngineering", "执行曲线/曲面反求入口"),
|
||||
("robot", "Robot", "Robot", "执行机器人路径和回放入口"),
|
||||
("sandbox", "Sandbox", "Sandbox", "执行 Sandbox 测试对象入口"),
|
||||
("show", "Show", "Show", "执行显示/生命周期入口"),
|
||||
("sketcher", "Sketcher", "Sketcher", "创建草图和约束入口"),
|
||||
("spreadsheet", "Spreadsheet", "Spreadsheet", "创建表格、公式和 CSV 入口"),
|
||||
("start", "Start", "Start", "打开启动页并进入工作台"),
|
||||
("surface", "Surface", "Surface", "执行曲面创建/重算入口"),
|
||||
("techdraw", "TechDraw", "TechDraw", "创建页面/视图并重算入口"),
|
||||
("templatepymod", "TemplatePyMod", "TemplatePyMod", "执行模板模块示例入口"),
|
||||
("test", "Test", "Test", "执行测试工作台入口"),
|
||||
("tux", "Tux", "Tux", "打开 Tux 示例入口"),
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="用可见 Chrome 逐案例教学运行 Web FreeCAD")
|
||||
parser.add_argument("--origin", default=DEFAULT_ORIGIN, help="Web FreeCAD 发布地址")
|
||||
parser.add_argument("--case", choices=[item[0] for item in CASES] + ["all"], default="all")
|
||||
parser.add_argument("--headless", action="store_true", help="无桌面环境时使用无头 Chrome,仅用于验收")
|
||||
parser.add_argument("--interactive", action="store_true", help="每个案例开始前暂停,按回车继续")
|
||||
parser.add_argument("--pause", type=float, default=2.0, help="每个案例完成后保持页面的秒数")
|
||||
parser.add_argument("--screenshot-dir", default="docs/current/29-case-tutor-20261011", help="截图和账本目录")
|
||||
parser.add_argument("--list", action="store_true", help="只列出案例,不启动浏览器")
|
||||
args = parser.parse_args()
|
||||
if args.list:
|
||||
for index, (case_id, module, _command, lesson) in enumerate(CASES, 1):
|
||||
print(f"{index:02d} {case_id:18s} {module:18s} {lesson}")
|
||||
return 0
|
||||
selected = CASES if args.case == "all" else [next(item for item in CASES if item[0] == args.case)]
|
||||
out_dir = ROOT / args.screenshot_dir
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
manifest = [{"index": i + 1, "id": c[0], "module": c[1], "command": c[2], "lesson": c[3]} for i, c in enumerate(selected)]
|
||||
manifest_path = out_dir / f"manifest-{run_id}.json"
|
||||
manifest_path.write_text(json.dumps({"schema": "freecad-web-29-case-tutor-manifest/v1", "origin": args.origin, "cases": manifest}, ensure_ascii=False, indent=2) + "\n")
|
||||
print(f"Web FreeCAD 29-case tutor: {args.origin}")
|
||||
print(f"本次案例数: {len(selected)},截图目录: {out_dir}")
|
||||
results = []
|
||||
for case in manifest:
|
||||
if args.interactive:
|
||||
input(f"\n[{case['index']:02d}/{len(manifest)}] {case['module']}:{case['lesson']}。按回车打开真实页面...")
|
||||
command = ["node", str(HELPER), "--origin", args.origin, "--case-json", json.dumps(case, ensure_ascii=False), "--out-dir", str(out_dir), "--pause", str(args.pause)]
|
||||
if args.headless:
|
||||
command.append("--headless")
|
||||
try:
|
||||
completed = subprocess.run(command, cwd=ROOT, text=True, check=False)
|
||||
results.append({"case": case, "exitCode": completed.returncode, "status": "passed" if completed.returncode == 0 else "failed"})
|
||||
except OSError as exc:
|
||||
results.append({"case": case, "status": "failed", "error": str(exc)})
|
||||
if results[-1]["status"] != "passed":
|
||||
print(f"案例失败:{case['module']},继续保留失败证据并进入下一个案例", file=sys.stderr)
|
||||
result_path = out_dir / f"run-{run_id}.json"
|
||||
result_path.write_text(json.dumps({"schema": "freecad-web-29-case-tutor-run/v1", "origin": args.origin, "runId": run_id, "results": results}, ensure_ascii=False, indent=2) + "\n")
|
||||
passed = sum(item["status"] == "passed" for item in results)
|
||||
print(f"完成:{passed}/{len(results)},账本:{result_path}")
|
||||
return 0 if passed == len(results) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
567
web/src/desktop-command-dispatcher.ts
Normal file
567
web/src/desktop-command-dispatcher.ts
Normal file
@@ -0,0 +1,567 @@
|
||||
import { executeSandboxMeshImport, SANDBOX_MESH_COMMANDS } from "./sandbox-mesh-import-adapter.js";
|
||||
import { executeMeasureDocument } from "./measure-document-adapter.js";
|
||||
import { executeSurfaceDocument } from "./surface-document-adapter.js";
|
||||
import { executeSandboxArchive } from "./sandbox-archive-adapter.js";
|
||||
import { prepareRobotWaypointArgs } from "./robot-waypoint-adapter.js";
|
||||
import { prepareTechDrawCommand, validateTechDrawResponse, techDrawRoutePolicy } from "./techdraw-desktop-adapter.js";
|
||||
import { executeDraftDesktop } from "./draft-desktop-adapter.js";
|
||||
import { executeMeshDesktop } from "./mesh-desktop-adapter.js";
|
||||
import { executeImportDesktop } from "./import-desktop-adapter.js";
|
||||
import { executeFemDesktop } from "./fem-desktop-adapter.js";
|
||||
import { prepareCamCommand, validateCamDesktopResponse } from "./cam-desktop-adapter.js";
|
||||
import { prepareBimDesktopArgs, validateBimDesktopResponse } from "./bim-desktop-adapter.js";
|
||||
import { validatePartDesktopResponse, executePartFixedBoxDesktop, preparePartDesktopCommand } from "./part-desktop-adapter.js";
|
||||
import { prepareMaterialDesktopArgs, validateMaterialDesktopResponse } from "./material-desktop-adapter.js";
|
||||
import { executePartDesignDesktop } from "./partdesign-desktop-adapter.js";
|
||||
import { executeDockOverlayCommand, DOCK_OVERLAY_COMMANDS } from "./dock-overlay-adapter.js";
|
||||
import { executeSceneDisplayCommand } from "./scene-command-adapter.js";
|
||||
import { executeWebDesktop } from "./web-desktop-adapter.js";
|
||||
import { prepareAssemblyCommand, applyAssemblyResponse } from "./assembly-desktop-adapter.js";
|
||||
import { createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js";
|
||||
import { getWebModuleRoute } from "./module-registry.generated.js";
|
||||
import { WebModuleRouter } from "./module-router.js";
|
||||
import type { WorkbenchCommandRecord } from "./workbench-command-facade.js";
|
||||
import { prepareTestCommand, validateTestDesktopResponse, TEST_DESKTOP_ROUTES, testDesktopRoutes } from "./test-desktop-adapter.js";
|
||||
import { executeSketcherDesktop, prepareSketcherCommand, validateSketcherResponse } from "./sketcher-desktop-adapter.js";
|
||||
import { executeMeshPartFlatten, executeMeshPartMesher, executeMeshPartCurve, executeMeshPartTrim, prepareMeshPartCommand, validateMeshPartResponse } from "./meshpart-desktop-adapter.js";
|
||||
import { validateInspectionDesktopResponse } from "./inspection-desktop-adapter.js";
|
||||
import { TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA, TEMPLATEPYMOD_GROUP_COMMANDS, TEMPLATEPYMOD_GROUP_DEFAULT } from "./templatepymod-python-family-facade.js";
|
||||
|
||||
function moduleSlug(module: string): string {
|
||||
return module.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
}
|
||||
|
||||
function familyRoute(module: string): string | undefined {
|
||||
const route = getWebModuleRoute(module);
|
||||
if (!route) return undefined;
|
||||
return route.commands.find((command) => command.endsWith(".pythonFamilyBatch"))
|
||||
?? route.commands.find((command) => command.endsWith(".pythonFamily"));
|
||||
}
|
||||
|
||||
function familySchema(route: string, module: string): string {
|
||||
return route.endsWith(".pythonFamilyBatch") || route === "techdraw.desktopCommand"
|
||||
? `freecad-web-${moduleSlug(module)}/python-family-batch/v1`
|
||||
: `freecad-web-${moduleSlug(module)}/python-family/v1`;
|
||||
}
|
||||
|
||||
interface DesktopCommandRoute {
|
||||
id: string;
|
||||
module: string;
|
||||
command: string;
|
||||
canonicalId: string;
|
||||
transport: "direct-command" | "family-batch" | "ui-container" | "browser-ui";
|
||||
sourcePath?: string;
|
||||
sourceLine?: number;
|
||||
}
|
||||
|
||||
interface DesktopCommandRouteIndex {
|
||||
schema: "freecad-web-desktop-command-routes/v1";
|
||||
records: DesktopCommandRoute[];
|
||||
}
|
||||
|
||||
function deliverNativeDxf(response: unknown): void {
|
||||
const visited = new Set<object>();
|
||||
const locate = (value: unknown): Record<string, unknown> | undefined => {
|
||||
if (!value || typeof value !== "object" || visited.has(value)) return undefined;
|
||||
visited.add(value);
|
||||
const item = value as Record<string, unknown>;
|
||||
if (item.nativeOperationCompleted === true && item.mimeType === "image/vnd.dxf"
|
||||
&& item.encoding === "base64" && typeof item.content === "string"
|
||||
&& typeof item.filename === "string" && typeof item.byteLength === "number") return item;
|
||||
for (const child of Object.values(item)) {
|
||||
const found = locate(child);
|
||||
if (found) return found;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const file = locate(response);
|
||||
// Native failures retain their original envelope and never trigger a download.
|
||||
if (!file) return;
|
||||
const binary = atob(file.content as string);
|
||||
if (binary.length === 0 || binary.length !== file.byteLength)
|
||||
throw new Error("Native DXF file length mismatch");
|
||||
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: "image/vnd.dxf" }));
|
||||
const link = document.createElement("a");
|
||||
try {
|
||||
link.href = url;
|
||||
link.download = (file.filename as string).replace(/[\\/\u0000-\u001f]/g, "_");
|
||||
link.hidden = true;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
} finally {
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 60000);
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes generated desktop-command records through a module's shared Worker. */
|
||||
export class DesktopCommandDispatcher {
|
||||
private routeIndex?: Promise<Map<string, DesktopCommandRoute>>;
|
||||
private spreadsheetHost?: (documentId: string, args: Record<string, unknown>) => Promise<FacadeResponse>;
|
||||
setSpreadsheetHost(host?: (documentId: string, args: Record<string, unknown>) => Promise<FacadeResponse>): void { this.spreadsheetHost = host; }
|
||||
private readonly activeAssemblies = new Map<string, string>();
|
||||
constructor(private readonly router: WebModuleRouter) {}
|
||||
|
||||
getActiveAssembly(documentId: string): string | undefined { return this.activeAssemblies.get(documentId); }
|
||||
setActiveAssembly(documentId: string, assembly?: string): void {
|
||||
if (assembly) this.activeAssemblies.set(documentId, assembly);
|
||||
else this.activeAssemblies.delete(documentId);
|
||||
}
|
||||
|
||||
private routes(): Promise<Map<string, DesktopCommandRoute>> {
|
||||
return this.routeIndex ??= fetch("/api/desktop-command-routes.json").then(async (response) => {
|
||||
if (!response.ok) throw new Error(`desktop command route index failed: HTTP ${response.status}`);
|
||||
const payload = await response.json() as DesktopCommandRouteIndex;
|
||||
if (payload.schema !== "freecad-web-desktop-command-routes/v1" || !Array.isArray(payload.records)) throw new Error("desktop command route index schema mismatch");
|
||||
return new Map(payload.records.map((route) => [route.id, route]));
|
||||
});
|
||||
}
|
||||
|
||||
async execute(record: WorkbenchCommandRecord, args: Record<string, unknown>, documentId = "workbench-document", applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise<FacadeResponse> {
|
||||
if (record.module === "TemplatePyMod" && record.command === "TemplatePyGroup") {
|
||||
if (args.action === "cancel" || args.action === "read")
|
||||
return createSuccess("desktop-TemplatePyGroup", { container: "TemplatePyGroup", choices: TEMPLATEPYMOD_GROUP_COMMANDS, defaultCommand: TEMPLATEPYMOD_GROUP_DEFAULT, cancelled: args.action === "cancel" });
|
||||
const child = args.childCommand ?? TEMPLATEPYMOD_GROUP_DEFAULT;
|
||||
if (!TEMPLATEPYMOD_GROUP_COMMANDS.includes(child as typeof TEMPLATEPYMOD_GROUP_COMMANDS[number]))
|
||||
return createFailure("desktop-TemplatePyGroup", "invalid_arguments", "Unknown group child command");
|
||||
const module = child === "Std_New" ? "Web" : "TemplatePyMod";
|
||||
const { childCommand, ...childArgs } = args;
|
||||
return this.execute({ ...record, module, command: String(child), id: `${module}:desktop:${child}` },
|
||||
child === "Std_New" ? { ...childArgs, runtimeOwner: "PartBox" } : childArgs, documentId, applySelection);
|
||||
}
|
||||
// Keep the Surface entry visible while using MeshPart's native record everywhere internally.
|
||||
if (record.module === "Surface" && record.command === "Surface_CurveOnMesh")
|
||||
record = { ...record, module: "MeshPart", command: "MeshPart_CurveOnMesh", id: "MeshPart:desktop:MeshPart_CurveOnMesh" };
|
||||
if (record.module === "Inspection" && ["Inspection_VisualInspection", "Inspection_InspectElement"].includes(record.command)) {
|
||||
const response = await this.router.request("Inspection", "inspection.pythonFamilyBatch", {
|
||||
schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId } }],
|
||||
}, documentId);
|
||||
const result = validateInspectionDesktopResponse(record, response, record.id);
|
||||
if (result.kind === "result") {
|
||||
const native = (result.result as any).records[0].result;
|
||||
if (["accept", "undo", "redo", "open"].includes(native?.action))
|
||||
applySelection?.(native.documentId, native.selection.map((object: string) => ({ documentId: native.documentId, object })));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (args.documentId !== undefined && (typeof args.documentId !== "string" || !args.documentId.trim())) {
|
||||
return createFailure(`desktop-${record.module}`, "invalid_request", "documentId must be a non-empty document identifier", { capabilityId: record.id });
|
||||
}
|
||||
if ((record.module === "Web" || record.module === "Std") &&
|
||||
Object.hasOwn(DOCK_OVERLAY_COMMANDS, record.command) &&
|
||||
args.documentId !== undefined && args.documentId !== documentId) {
|
||||
return createFailure(`desktop-${record.module}`, "document_mismatch", "Command document identifiers differ", { capabilityId: record.id });
|
||||
}
|
||||
documentId = typeof args.documentId === "string" ? args.documentId : documentId;
|
||||
if (record.module === "Sandbox" && record.command === "Std_TestGraphicsView")
|
||||
return createFailure("graphics-scene", "view_host_required", "Open Graphics scene from the mounted Sandbox task to view the active document");
|
||||
if (record.command === "Std_MassProperties") return executeMeasureDocument(this.router, { ...args, action: "massProperties" }, documentId);
|
||||
if (record.command === "Std_Measure") return executeMeasureDocument(this.router, args, documentId);
|
||||
if (record.module === "Surface" && ["Surface_BlendCurve", "Surface_Filling", "Surface_Sections", "Surface_ExtendFace"].includes(record.command)) {
|
||||
return (await executeSurfaceDocument(this.router, record.command, args, documentId))!;
|
||||
}
|
||||
if (record.module === "Web" || record.module === "Std" ||
|
||||
(record.module === "Show" && ["Std_ViewHome", "Std_ViewFitSelection"].includes(record.command))) {
|
||||
const response = executeDockOverlayCommand(record.command, { ...args, documentId });
|
||||
if (response) return response;
|
||||
}
|
||||
if (record.module === "Web" || record.module === "Std") {
|
||||
const response = executeSceneDisplayCommand(record.command, args, documentId);
|
||||
if (response) return response;
|
||||
}
|
||||
if (record.module === "Spreadsheet" && ["Spreadsheet_SetAlias", "Spreadsheet_AlignLeft", "Spreadsheet_AlignCenter", "Spreadsheet_AlignRight", "Spreadsheet_AlignTop", "Spreadsheet_AlignVCenter", "Spreadsheet_AlignBottom", "Spreadsheet_CreateSheet", "Spreadsheet_Import", "Spreadsheet_Export", "Spreadsheet_StyleBold", "Spreadsheet_StyleItalic", "Spreadsheet_StyleUnderline"].includes(record.command)) {
|
||||
if (!this.spreadsheetHost) return createFailure("spreadsheet-create", "document_owner_required", "Open the project workspace to create a sheet in its native document");
|
||||
const response = await this.spreadsheetHost(documentId, { ...args, command: record.command });
|
||||
if (response.kind === "result") {
|
||||
const result = response.result as { documentId: string; createdSheet: string };
|
||||
if (result.createdSheet) applySelection?.(result.documentId, [{ documentId: result.documentId, object: result.createdSheet }]);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.module === "Sandbox" && SANDBOX_MESH_COMMANDS.includes(record.command))
|
||||
return executeSandboxMeshImport(this.router, record, args, documentId);
|
||||
if (record.module === "Sandbox" && record.command === "Sandbox_SaveThread")
|
||||
return executeSandboxArchive(this.router, record, args);
|
||||
args = { ...args, documentId };
|
||||
if (record.module === "Robot") args = prepareRobotWaypointArgs(record.command, args, documentId);
|
||||
if (record.module === "Robot" && ["Robot_AddToolShape", "Robot_SetHomePos", "Robot_RestoreHomePos"].includes(record.command)) {
|
||||
const selection = Array.isArray(args.selection) ? args.selection : Array.isArray(args.selectedObjects)
|
||||
? args.selectedObjects.map(object => typeof object === "string" ? { documentId, object } : object) : [];
|
||||
args = { ...args, action: args.action ?? "read", documentId, selection };
|
||||
}
|
||||
if (record.module === "Robot" && record.command === "Robot_ExportKukaCompact" && !Array.isArray(args.selection))
|
||||
args = { ...args, selection: [] };
|
||||
if (record.module === "Import" || record.module === "Part") {
|
||||
const imported = executeImportDesktop(this.router, record.command, args, documentId);
|
||||
if (imported) return imported;
|
||||
}
|
||||
if (record.module === "Web" || record.module === "Std") {
|
||||
const response = executeWebDesktop(this.router, record.command, args, documentId, applySelection);
|
||||
if (response) return response;
|
||||
}
|
||||
if (record.module === "MeshPart" && ["MeshPart_CreateFlatFace", "MeshPart_CreateFlatMesh"].includes(record.command))
|
||||
return executeMeshPartFlatten(this.router, record, args, documentId, applySelection);
|
||||
if (record.module === "MeshPart" && record.command === "MeshPart_Mesher")
|
||||
return executeMeshPartMesher(this.router, record, args, documentId, applySelection);
|
||||
if (record.module === "MeshPart" && record.command === "MeshPart_CurveOnMesh")
|
||||
return executeMeshPartCurve(this.router, record, args, documentId, applySelection);
|
||||
if (record.module === "MeshPart" && record.command === "MeshPart_TrimByPlane") {
|
||||
const response = await executeMeshPartTrim(this.router, record, args, documentId);
|
||||
if (response.kind === "result") {
|
||||
const value = response.result as any;
|
||||
if (value.trimSelection?.length) applySelection?.(value.document, value.trimSelection.map((object: string) => ({ documentId: value.document, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.module === "MeshPart") {
|
||||
const failure = prepareMeshPartCommand(record, args, documentId);
|
||||
if (failure) return failure;
|
||||
}
|
||||
// Keep BIM desktop command preparation at the dispatch boundary so palette,
|
||||
// navigation, and direct callers share the native command contract.
|
||||
if (record.module === "BIM") args = prepareBimDesktopArgs(record, args);
|
||||
if (record.module === "Part") {
|
||||
const result = executePartFixedBoxDesktop(this.router, record.command, args, documentId, applySelection);
|
||||
if (result) return result;
|
||||
const validation = preparePartDesktopCommand(record.command, args, documentId);
|
||||
if (validation) return validation;
|
||||
}
|
||||
const sketcherFailure = prepareSketcherCommand(record, args); if (sketcherFailure) return sketcherFailure;
|
||||
const meshExecution = executeMeshDesktop(this.router, record, args, documentId);
|
||||
if (meshExecution) return meshExecution;
|
||||
const sketcherExecution = executeSketcherDesktop(this.router, record, args, documentId);
|
||||
if (sketcherExecution) return sketcherExecution;
|
||||
if (record.module === "Test") {
|
||||
const failure = prepareTestCommand(record, args); if (failure) return failure;
|
||||
if (!TEST_DESKTOP_ROUTES.includes(record.command as typeof TEST_DESKTOP_ROUTES[number]))
|
||||
return createFailure(`desktop-${record.module}`, "unsupported_command", "Unsupported Test desktop command", { capabilityId: record.id });
|
||||
if (record.command === "Test_InsertFeature") {
|
||||
if (args.cancelled || args.action === "cancel") return createFailure("desktop-Test", "cancelled", "Insertion cancelled");
|
||||
const owner = this.router.modelingDocumentOwners.get(documentId);
|
||||
if (!owner || this.router.assemblyModelingDocuments.has(documentId) || this.router.assemblyModelingDocuments.has(owner.document))
|
||||
return createFailure("desktop-Test", "document_owner_required", "Select an open Part or PartDesign document owned by the modeling workspace");
|
||||
if (this.spreadsheetHost) return this.spreadsheetHost(documentId, { ...args, command: record.command });
|
||||
return this.router.request(owner.module, owner.module === "Part" ? "part.document" : "partdesign.document", {
|
||||
schema: owner.module === "Part" ? "freecad-web-part/document/v1" : "freecad-web-partdesign/document/v1",
|
||||
module: owner.module, document: owner.document, action: "insertTestFeature", includeMesh: true,
|
||||
}, documentId);
|
||||
}
|
||||
const endpoint = testDesktopRoutes[record.command as keyof typeof testDesktopRoutes] ?? "test.inspectRegistry";
|
||||
const response = await this.router.request("Test", endpoint, {
|
||||
schema: "freecad-web/test/v1", module: "Test", action: "desktop-command",
|
||||
sourceEntry: "src/Mod/Test/Init.py", command: record.command, args,
|
||||
}, documentId);
|
||||
return validateTestDesktopResponse(record, response);
|
||||
}
|
||||
if (record.module === "CAM") {
|
||||
const failure = prepareCamCommand(record, args);
|
||||
if (failure) return failure;
|
||||
}
|
||||
if (record.module === "Fem") {
|
||||
const result = executeFemDesktop(this.router, record, args, documentId, applySelection);
|
||||
if (result) return result;
|
||||
}
|
||||
if (record.module === "Draft") {
|
||||
const result = executeDraftDesktop(this.router, record, args, documentId);
|
||||
if (result) return result;
|
||||
}
|
||||
if (record.module === "TemplatePyMod") {
|
||||
args = { ...args, documentId };
|
||||
const response = await this.router.request("TemplatePyMod", "templatepymod.pythonFamilyBatch", {
|
||||
schema: TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA,
|
||||
module: "TemplatePyMod",
|
||||
tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command-initgui", kind: "command", sourcePath: record.sourcePath, args }],
|
||||
}, documentId);
|
||||
return response;
|
||||
}
|
||||
if (record.module === "Material") {
|
||||
args = prepareMaterialDesktopArgs(record.command, args, documentId);
|
||||
if (record.command === "Materials_InspectMaterial" || record.command === "Materials_InspectAppearance") {
|
||||
const owner = this.router.modelingDocumentOwners.get(documentId);
|
||||
if (!owner) return createFailure("desktop-Material", "document_owner_required", "Select an open modeling document");
|
||||
const selection = Array.isArray(args.selection) ? args.selection : [];
|
||||
if (selection.some((item: any) => item?.documentId !== documentId && item?.documentId !== owner.document))
|
||||
return createFailure("desktop-Material", "invalid_selection", "Selection belongs to a different document");
|
||||
args = { ...args, documentId: owner.document, document: owner.document,
|
||||
selection: selection.map((item: any) => ({ ...item, documentId: owner.document })) };
|
||||
}
|
||||
if (record.command === "Std_SetMaterial" || record.command === "Std_SetAppearance") {
|
||||
const owner = this.router.modelingDocumentOwners.get(documentId);
|
||||
if (!owner) return createFailure("desktop-Material", "document_owner_required", "Select an open modeling document");
|
||||
if (args.documentId !== documentId && args.documentId !== owner.document)
|
||||
return createFailure("desktop-Material", "invalid_selection", "Selection belongs to a different document");
|
||||
const selection = Array.isArray(args.selection) ? args.selection : [];
|
||||
if (selection.some((item: any) => item?.documentId !== documentId && item?.documentId !== owner.document))
|
||||
return createFailure("desktop-Material", "invalid_selection", "Selection belongs to a different document");
|
||||
const materialAssignment = { ...args, document: owner.document, property: record.command === "Std_SetAppearance" ? "ShapeAppearance" : "ShapeMaterial",
|
||||
selection: selection.map((item: any) => ({ ...item, documentId: owner.document })) };
|
||||
if (this.spreadsheetHost) return this.spreadsheetHost(documentId, { command: record.command, materialAssignment });
|
||||
return this.router.request(owner.module, owner.module === "Part" ? "part.document" : "partdesign.document", {
|
||||
schema: owner.module === "Part" ? "freecad-web-part/document/v1" : "freecad-web-partdesign/document/v1",
|
||||
module: owner.module, document: owner.document, action: "materialAssignment", materialAssignment, includeMesh: true,
|
||||
}, documentId);
|
||||
}
|
||||
const response = await this.router.request("Material", "material.pythonFamilyBatch", {
|
||||
schema: "freecad-web-material/python-family-batch/v1", module: "Material", tier: "tier-3-stateful",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", sourcePath: record.sourcePath, sourceLine: record.sourceLine, args }],
|
||||
}, documentId);
|
||||
const failure = validateMaterialDesktopResponse(record, response, record.id);
|
||||
return failure ?? response;
|
||||
}
|
||||
if (record.module === "PartDesign") {
|
||||
const result = executePartDesignDesktop(this.router, record.command, args, documentId, applySelection);
|
||||
if (result) return result;
|
||||
}
|
||||
if (record.module === "Assembly") {
|
||||
const prepared = prepareAssemblyCommand(record, args, documentId, this.activeAssemblies);
|
||||
if ("response" in prepared) return prepared.response;
|
||||
args = prepared.args;
|
||||
}
|
||||
if (record.module === "TechDraw") {
|
||||
const prepared = prepareTechDrawCommand(record, args, documentId);
|
||||
if ("response" in prepared) return prepared.response;
|
||||
args = prepared.args;
|
||||
}
|
||||
if (record.module === "ReverseEngineering" && ["Reen_ApproxPlane", "Reen_ApproxCylinder", "Reen_ApproxSphere", "Reen_ApproxPolynomial"].includes(record.command)) {
|
||||
if (args.cancel || args.cancelled || args.action === "cancel")
|
||||
return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch");
|
||||
const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : [];
|
||||
if (!selection.length || selection.some(item => item.documentId !== documentId || !item.object)
|
||||
|| (args.document && args.document !== documentId) || (args.documentId && args.documentId !== documentId))
|
||||
return createFailure("native-fit", "invalid_selection", "Select geometry in one active native document");
|
||||
const response = await this.router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch", {
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, selection } }],
|
||||
}, documentId);
|
||||
if (response.kind === "result") {
|
||||
const row = (response.result as any).records?.[0];
|
||||
if (row?.status !== "exposed") return createFailure("native-fit", row?.code || "native_error", row?.message || "Native fitting failed");
|
||||
if (row.result?.documentChanged) applySelection?.(documentId, row.result.selection.map((object: string) => ({ documentId, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.command === "Reen_SegmentationFromComponents" && record.module === "ReverseEngineering") {
|
||||
if (args.cancel || args.cancelled || args.action === "cancel")
|
||||
return createFailure("components-segmentation", "cancelled", "Segmentation cancelled before dispatch");
|
||||
const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : [];
|
||||
if (!selection.length || selection.some(item => item.documentId !== documentId || !item.object)
|
||||
|| (args.document && args.document !== documentId))
|
||||
return createFailure("components-segmentation", "invalid_selection", "Select meshes in one active native document");
|
||||
const response = await this.router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch", {
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, selection } }],
|
||||
}, documentId);
|
||||
if (response.kind === "result") {
|
||||
const row = (response.result as any).records?.[0];
|
||||
if (row?.status !== "exposed") return createFailure("components-segmentation", row?.code || "native_error", row?.message || "Native segmentation failed");
|
||||
if (row.result?.documentChanged) applySelection?.(documentId, row.result.selection.map((object: string) => ({ documentId, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.command === "Reen_MeshBoundary" && record.module === "ReverseEngineering") {
|
||||
if (args.cancel || args.cancelled || args.action === "cancel")
|
||||
return createFailure("mesh-boundary", "cancelled", "Mesh boundary cancelled before dispatch");
|
||||
const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : [];
|
||||
if (!selection.length || selection.some(item => item.documentId !== documentId || !item.object) || (args.document && args.document !== documentId))
|
||||
return createFailure("mesh-boundary", "invalid_selection", "Select meshes in one active native document");
|
||||
const response = await this.router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch", {
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, selection } }],
|
||||
}, documentId);
|
||||
if (response.kind === "result") {
|
||||
const row = (response.result as any).records?.[0];
|
||||
if (row?.status !== "exposed") return createFailure("mesh-boundary", row?.code || "native_error", row?.message || "Native mesh boundary failed");
|
||||
if (row.documentChanged && Array.isArray(row.selection)) applySelection?.(documentId, row.selection.map((object: string) => ({ documentId, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.module === "ReverseEngineering" && record.command === "Reen_ViewTriangulation") {
|
||||
if (args.cancel || args.cancelled || args.action === "cancel")
|
||||
return createFailure("structured-triangulation", "cancelled", "Triangulation cancelled before dispatch");
|
||||
const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : [];
|
||||
const names = selection.map(item => item.object);
|
||||
if (args.runtimeOwner !== "Points" || args.document !== documentId || !names.length || new Set(names).size !== names.length || selection.some(item => item.documentId !== documentId || !item.object)
|
||||
|| (Array.isArray(args.objectNames) && (args.objectNames.length !== names.length || args.objectNames.some((name, i) => name !== names[i]))))
|
||||
return createFailure("structured-triangulation", "invalid_selection", "Select structured point clouds in one retained Points document");
|
||||
const response = await this.router.request("Points", "reverseengineering.pythonFamilyBatch", {
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, action: "accept", command: record.command, document: documentId, objectNames: names, selection } }],
|
||||
}, documentId);
|
||||
if (response.kind === "result") {
|
||||
const native = (response.result as any).records?.[0];
|
||||
if (native?.status !== "exposed") return createFailure("structured-triangulation", native?.code || "native_error", native?.message || "Native triangulation failed");
|
||||
applySelection?.(native.document, native.selection.map((object: string) => ({ documentId: native.document, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.module === "ReverseEngineering" && (record.command === "Reen_ApproxCurve" || record.command === "Reen_ApproxSurface" || record.command === "Reen_PoissonReconstruction")) {
|
||||
if ((args.action !== "accept" && !(record.command === "Reen_ApproxSurface" && args.action === "placement")) || args.cancel || args.cancelled)
|
||||
return createFailure("curve-task", "cancelled", "Use the fitting task Accept control");
|
||||
const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : [];
|
||||
const objects = Array.isArray(args.objectNames) ? args.objectNames : selection.map(item => item.object);
|
||||
if (args.runtimeOwner !== "Points" || args.document !== documentId || objects.length !== 1 || selection.some(item => item.documentId !== documentId))
|
||||
return createFailure("curve-task", "invalid_selection", "Select exactly one fitting source in the retained Points document");
|
||||
const response = await this.router.request("Points", "reverseengineering.pythonFamilyBatch", {
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly",
|
||||
records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, objectNames: objects } }],
|
||||
}, documentId);
|
||||
if (response.kind === "result") {
|
||||
const native = (response.result as any).records?.[0];
|
||||
if (native?.status !== "exposed") return createFailure("curve-task", native?.code || "native_error", native?.message || "Native fitting failed");
|
||||
applySelection?.(native.document, native.selection.map((object: string) => ({ documentId: native.document, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (record.module === "Points" && ["Points_Import", "Points_Export", "Points_Convert", "Points_PolyCut", "Points_Merge", "Points_Structure"].includes(record.command)) {
|
||||
if (args.cancel || args.cancelled || args.action === "cancel")
|
||||
return createFailure("points-merge", "cancelled", "Points command cancelled before mutation");
|
||||
const document = typeof args.document === "string" ? args.document : documentId;
|
||||
const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : [];
|
||||
if (document !== documentId || selection.some(item => item.documentId !== document))
|
||||
return createFailure("points-merge", "document_mismatch", "Select point clouds from one document");
|
||||
const objectNames = Array.isArray(args.objectNames) ? args.objectNames : Array.isArray(args.objects) ? args.objects : selection.map(item => item.object);
|
||||
if ((record.command === "Points_Structure" ? objectNames.length !== 1 : record.command === "Points_Merge" ? objectNames.length < 2 : record.command !== "Points_Import" && objectNames.length === 0) || objectNames.some(name => typeof name !== "string" || !name))
|
||||
return createFailure("points-merge", "invalid_selection", record.command === "Points_Structure" ? "Select exactly one point cloud" : record.command === "Points_Convert" ? "Select one or more geometry objects" : "Select at least two point clouds");
|
||||
if (record.command === "Points_Convert") {
|
||||
const tolerance = Number(args.tolerance);
|
||||
if (!Number.isFinite(tolerance) || tolerance <= 0 || tolerance > 10)
|
||||
return createFailure("points-convert", "invalid_tolerance", "Maximum distance must be greater than zero and no greater than 10");
|
||||
}
|
||||
const response = await this.router.request("Points", "points.desktopBatch", {
|
||||
schema: "freecad-web-points/desktop-batch/v1", module: "Points",
|
||||
records: [{ apiId: record.id, name: record.command, args: { ...args, document, objectNames, includePoints: true } }],
|
||||
}, document);
|
||||
if (response.kind === "result") {
|
||||
const native = (response.result as any).records?.[0];
|
||||
if (native?.status !== "exposed") return createFailure("points-merge", native?.code || "native_error", native?.message || "Merge failed");
|
||||
const names = native.selection ?? (native.objectName ? [native.objectName] : native.objectNames ?? []);
|
||||
applySelection?.(native.document, names.map((object: string) => ({ documentId: native.document, object })));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
let indexed: DesktopCommandRoute | undefined;
|
||||
try { indexed = (await this.routes()).get(record.id); }
|
||||
catch (error) { return createFailure(`desktop-${record.module}`, "route_index_unavailable", error instanceof Error ? error.message : String(error), { capabilityId: record.id }); }
|
||||
const policy = record.module === "TechDraw" ? techDrawRoutePolicy(record.command) : null;
|
||||
const nativeStdViewCommand = record.module === "Std" && [
|
||||
"Std_AlignToSelection", "Std_AxisCross", "Std_BoxElementSelection", "Std_BoxSelection",
|
||||
"Std_DrawStyle", "Std_FreezeViews", "Std_HideObjects", "Std_HideSelection",
|
||||
"Std_ToggleVisibility", "Std_ToggleTransparency", "Std_ToggleSelectability", "Std_ToggleObjects",
|
||||
"Std_MainFullscreen", "Std_OrthographicCamera", "Std_PerspectiveCamera",
|
||||
"Std_RecallWorkingView", "Std_SceneInspector", "Std_SelBack", "Std_SelBoundingBox",
|
||||
"Std_SelForward", "Std_SelectVisibleObjects", "Std_ShowObjects", "Std_ShowSelection",
|
||||
"Std_ClarifySelection", "Std_DemoMode", "Std_DockOverlay", "Std_DockOverlayAll",
|
||||
"Std_DockOverlayMouseTransparent", "Std_DockOverlayToggle", "Std_DockOverlayToggleBottom",
|
||||
"Std_DockOverlayToggleLeft", "Std_DockOverlayToggleRight", "Std_DockOverlayToggleTop",
|
||||
"Std_DockOverlayToggleTransparent", "Std_DockOverlayTransparentAll",
|
||||
].includes(record.command);
|
||||
const nativeStackGroup = record.module === "TechDraw" && record.command === "TechDraw_StackGroup";
|
||||
const partNativeCommand = record.module === "Part" && ["Part_Boolean", "Part_BoxSelection", "Part_Compound", "Part_CompSplitFeatures", "Part_Builder", "Part_Chamfer", "Part_CheckGeometry", "Part_CompCompoundTools", "Part_CompJoinFeatures", "Part_CompOffset", "Part_Export", "Part_Extrude", "Part_Fillet"].includes(record.command);
|
||||
if (indexed?.transport === "ui-container" && !nativeStdViewCommand && !policy?.nativeContainer && !nativeStackGroup && !partNativeCommand) {
|
||||
return createSuccess(`desktop-ui-${record.id}`, {
|
||||
schema: "freecad-web-ui-container/v1",
|
||||
module: record.module,
|
||||
command: record.command,
|
||||
role: "menu-or-toolbar-group",
|
||||
sourcePath: indexed.sourcePath ?? record.sourcePath,
|
||||
sourceLine: indexed.sourceLine ?? record.sourceLine,
|
||||
});
|
||||
}
|
||||
const executionModule = indexed?.module ?? record.module;
|
||||
if (executionModule === "Part" && record.module !== "Part") {
|
||||
const validation = preparePartDesktopCommand(record.command, args, documentId);
|
||||
if (validation) return validation;
|
||||
}
|
||||
const route = record.module === "TechDraw" && ["TechDraw_LeaderLine", "TechDraw_ProjectionGroup"].includes(record.command)
|
||||
? "techdraw.desktopCommand" : nativeStdViewCommand
|
||||
? (indexed?.command ?? familyRoute(executionModule))
|
||||
: (policy?.familyRoute || nativeStackGroup)
|
||||
&& indexed?.transport === "ui-container" ? familyRoute(executionModule)
|
||||
: indexed?.transport === "family-batch" ? familyRoute(executionModule)
|
||||
: indexed?.command ?? familyRoute(executionModule);
|
||||
if (!route) return createFailure(`desktop-${record.module}`, "not_implemented", `${record.module} has no desktop command family route`, { capabilityId: record.id, command: record.command });
|
||||
const response = indexed?.transport === "direct-command"
|
||||
? await this.router.request(executionModule, route, { module: executionModule, command: record.command, args }, documentId)
|
||||
: await this.router.request(executionModule, route, {
|
||||
schema: familySchema(route, executionModule), module: executionModule, tier: "tier-1-readonly",
|
||||
records: [{ apiId: indexed?.canonicalId ?? record.id, name: record.command, family: executionModule === "Measure" ? "desktop-command-command" : "desktop-command", sourcePath: indexed?.sourcePath ?? record.sourcePath, sourceLine: indexed?.sourceLine ?? record.sourceLine, args }],
|
||||
}, documentId);
|
||||
// Std_UserInterface is a native command even though its desktop route is
|
||||
// exposed through the shared GUI family. Keep its acceptance semantics in
|
||||
// this command-specific branch so a generic tail status cannot mask it.
|
||||
if (record.command === "Std_UserInterface" && response.kind === "result") {
|
||||
if (!response.result || typeof response.result !== "object" || Array.isArray(response.result)) {
|
||||
return createFailure("desktop-Std", "native_protocol_error", "Std_UserInterface result is invalid", { capabilityId: record.id, response });
|
||||
}
|
||||
const batch = response.result as { records?: Array<{ apiId?: string; status?: string; code?: string; message?: string }> };
|
||||
const native = batch.records?.find((item) => item.apiId === (indexed?.canonicalId ?? record.id));
|
||||
if (!native) return createFailure("desktop-Std", "native_protocol_error", "Std_UserInterface result is missing", { capabilityId: record.id, response });
|
||||
if (native.status !== "exposed") {
|
||||
return createFailure("desktop-Std", native.code || "native_desktop_command_failed", native.message || "Std_UserInterface command failed", { capabilityId: record.id, response });
|
||||
}
|
||||
return { ...response, result: { ...response.result, status: "exposed", command: "Std_UserInterface" } };
|
||||
}
|
||||
if (executionModule === "MeshPart" && indexed?.transport !== "direct-command") {
|
||||
return validateMeshPartResponse(record, response, indexed?.canonicalId ?? record.id);
|
||||
}
|
||||
if (executionModule === "CAM") {
|
||||
return validateCamDesktopResponse(record, response, indexed?.canonicalId ?? record.id);
|
||||
}
|
||||
if (executionModule === "BIM" && indexed?.transport !== "direct-command") {
|
||||
return validateBimDesktopResponse(record, response, indexed?.canonicalId ?? record.id, documentId, applySelection);
|
||||
}
|
||||
if (executionModule === "Material" && indexed?.transport !== "direct-command") {
|
||||
const failure = validateMaterialDesktopResponse(record, response, indexed?.canonicalId ?? record.id);
|
||||
if (failure) return failure;
|
||||
}
|
||||
if (executionModule === "Points" && response.kind === "result") {
|
||||
const batch = response.result as { records?: Array<{ apiId: string; status: string; code?: string; message?: string }> };
|
||||
const native = batch?.records?.find((item) => item.apiId === (indexed?.canonicalId ?? record.id));
|
||||
if (!native) return createFailure("desktop-Points", "native_protocol_error", "Points command result is missing", { capabilityId: record.id });
|
||||
if (native.status !== "exposed") {
|
||||
return createFailure("desktop-Points", native.code || "native_desktop_command_failed",
|
||||
native.message || "Points command failed", { capabilityId: record.id, response });
|
||||
}
|
||||
}
|
||||
if (executionModule === "Inspection" && indexed?.transport !== "direct-command") {
|
||||
return validateInspectionDesktopResponse(record, response, indexed?.canonicalId ?? record.id);
|
||||
}
|
||||
if (executionModule === "TechDraw"
|
||||
&& indexed?.transport !== "direct-command"
|
||||
&& response.kind === "result") {
|
||||
const failure = validateTechDrawResponse(record, response, indexed?.canonicalId ?? record.id);
|
||||
if (failure) return failure;
|
||||
}
|
||||
if (executionModule === "Part" && response.kind === "result") {
|
||||
const failure = validatePartDesktopResponse(record, response, indexed?.canonicalId ?? record.id, applySelection);
|
||||
if (failure) return failure;
|
||||
}
|
||||
if (executionModule === "Assembly" && response.kind === "result") {
|
||||
const applied = applyAssemblyResponse(record, response, indexed?.canonicalId ?? record.id,
|
||||
documentId, this.activeAssemblies, applySelection);
|
||||
if (applied.kind === "result") {
|
||||
const batch = applied.result as { records?: Array<{ result?: { documentId?: string; activeBody?: { documentId: string }; bundle?: { files: Array<{ documentId: string }> } } }> };
|
||||
for (const row of batch.records ?? []) {
|
||||
if (row.result?.activeBody) this.router.assemblyModelingDocuments.add(row.result.activeBody.documentId);
|
||||
for (const file of row.result?.bundle?.files ?? []) this.router.assemblyModelingDocuments.add(file.documentId);
|
||||
}
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
if (executionModule === "TechDraw" && record.command === "TechDraw_ExportPageDXF") {
|
||||
try { deliverNativeDxf(response); }
|
||||
catch (error) {
|
||||
return createFailure(`desktop-${record.module}`, "file_delivery_failed",
|
||||
error instanceof Error ? error.message : String(error), { capabilityId: record.id });
|
||||
}
|
||||
}
|
||||
if (executionModule === "BIM" && response.kind === "result") {
|
||||
const failure = validateBimDesktopResponse(record, response, indexed?.canonicalId ?? record.id);
|
||||
if (failure) return failure;
|
||||
}
|
||||
return record.module === "Sketcher" ? validateSketcherResponse(record, response) : response;
|
||||
}
|
||||
}
|
||||
40
web/src/format-dispatcher.ts
Normal file
40
web/src/format-dispatcher.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { createFailure, type FacadeResponse } from "./facade-envelope.js";
|
||||
import { IMPORT_FIXTURE } from "./import-facade.js";
|
||||
import { MESH_IO_FIXTURE } from "./mesh-io-facade.js";
|
||||
import { PART_IO_FIXTURE } from "./part-io-facade.js";
|
||||
import { PART_SAVE_FIXTURE } from "./part-save-facade.js";
|
||||
import { TECHDRAW_NATIVE_FIXTURE } from "./techdraw-native-facade.js";
|
||||
import { SPREADSHEET_CSV_FIXTURE } from "./spreadsheet-facade.js";
|
||||
import { createFormatRuntimeLookup, resolveFormatAction, type FormatRuntimeIndex, type FormatRuntimeRecord } from "./format-runtime.js";
|
||||
import { WebModuleRouter } from "./module-router.js";
|
||||
|
||||
const FIXTURES: Record<string, unknown> = {
|
||||
"import.step": IMPORT_FIXTURE,
|
||||
"part.importExport": PART_IO_FIXTURE,
|
||||
"part.saveReopen": PART_SAVE_FIXTURE,
|
||||
"mesh.importExport": MESH_IO_FIXTURE,
|
||||
"techdraw.nativeImportExport": TECHDRAW_NATIVE_FIXTURE,
|
||||
"spreadsheet.importExportCsv": SPREADSHEET_CSV_FIXTURE,
|
||||
"points.importPly": { schema: "freecad-web-points/desktop-batch/v1", module: "Points", records: [{ apiId: "business-format:Points:import:.ply", name: "Points_Import", args: { path: "/tmp/points.ply" } }] },
|
||||
"points.exportObj": { schema: "freecad-web-points/desktop-batch/v1", module: "Points", records: [{ apiId: "business-format:Points:export:.obj", name: "Points_Export", args: { path: "/tmp/points.obj", objectNames: ["Points"] } }] },
|
||||
};
|
||||
|
||||
export class FormatDispatcher {
|
||||
private readonly lookup: Map<string, FormatRuntimeRecord>;
|
||||
|
||||
constructor(private readonly router: WebModuleRouter, index: FormatRuntimeIndex) {
|
||||
this.lookup = createFormatRuntimeLookup(index);
|
||||
}
|
||||
|
||||
async dispatch(formatId: string, documentId = "main-chain-document"): Promise<FacadeResponse> {
|
||||
const record = this.lookup.get(formatId);
|
||||
if (!record) return createFailure(`format-${formatId}`, "unknown_format_id", "Format ID is not present in the generated runtime index", { formatId });
|
||||
const route = resolveFormatAction(record);
|
||||
if (!route) return createFailure(`format-${formatId}`, "not_implemented", "Format record has no runnable native route", { formatId, module: record.module, direction: record.direction, kind: record.kind });
|
||||
const payload = route.command === "draft.formatBatch"
|
||||
? { schema: "freecad-web-draft/format-batch/v1", module: "Draft", records: [{ format: record.name.slice(1), direction: record.direction, documentId }] }
|
||||
: FIXTURES[route.command];
|
||||
if (payload === undefined) return createFailure(`format-${formatId}`, "not_implemented", "Format route has no locked native fixture", { formatId, command: route.command });
|
||||
return this.router.request(route.module, route.command, payload, documentId);
|
||||
}
|
||||
}
|
||||
31
web/src/format-runtime.ts
Normal file
31
web/src/format-runtime.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
export interface FormatRuntimeIndex {
|
||||
schema: "freecad-web-format-runtime-index/v1";
|
||||
source: { inventory: string; inventoryRecords: number; inventorySha256: string };
|
||||
fields: { modules: string[]; directions: string[]; kinds: string[] };
|
||||
records: [string, number, number, string, number, number][];
|
||||
}
|
||||
|
||||
export interface FormatRuntimeRecord { id: string; module: string; kind: string; name: string; direction: string; evidenceCount: number; }
|
||||
|
||||
export function decodeFormatRuntimeRecord(index: FormatRuntimeIndex, row: FormatRuntimeIndex["records"][number]): FormatRuntimeRecord {
|
||||
return { id: row[0], module: index.fields.modules[row[1]] ?? "", kind: index.fields.kinds[row[2]] ?? "", name: row[3], direction: index.fields.directions[row[4]] ?? "", evidenceCount: row[5] };
|
||||
}
|
||||
|
||||
export function createFormatRuntimeLookup(index: FormatRuntimeIndex): Map<string, FormatRuntimeRecord> {
|
||||
return new Map(index.records.map((row) => { const record = decodeFormatRuntimeRecord(index, row); return [record.id, record] as const; }));
|
||||
}
|
||||
|
||||
export interface FormatActionRoute { module: string; command: string; worker?: string; reason: string; }
|
||||
|
||||
export function resolveFormatAction(record: FormatRuntimeRecord): FormatActionRoute | undefined {
|
||||
if (record.kind !== "extension") return undefined;
|
||||
if (record.module === "Import" && [".step", ".stp", ".iges", ".igs"].includes(record.name) && record.direction === "import") return { module: "Import", command: "import.step", reason: "native Import STEP/IGES route" };
|
||||
if (record.module === "Part" && [".brep", ".brp"].includes(record.name)) return { module: "Part", command: "part.importExport", worker: "part.worker.ts", reason: "native Part BREP route" };
|
||||
if (record.module === "Part" && record.name === ".fcstd") return { module: "Part", command: "part.saveReopen", worker: "part-save.worker.ts", reason: "native Part FCStd round-trip route" };
|
||||
if (record.module === "Mesh" && [".stl", ".obj", ".ply", ".off", ".3mf", ".amf"].includes(record.name)) return { module: "Mesh", command: "mesh.importExport", reason: "native Mesh import/export route" };
|
||||
if (record.module === "TechDraw" && [".svg", ".dxf"].includes(record.name)) return { module: "TechDraw", command: "techdraw.nativeImportExport", worker: "techdraw-native.worker.ts", reason: "native TechDraw projection route" };
|
||||
if (record.module === "Draft" && [".svg", ".dxf"].includes(record.name)) return { module: "Draft", command: "draft.formatBatch", worker: "draft.worker.ts", reason: "native Draft geometry format route" };
|
||||
if (record.module === "Spreadsheet" && record.name === ".fcstd") return { module: "Spreadsheet", command: "spreadsheet.saveReopen", worker: "spreadsheet-save.worker.ts", reason: "native Spreadsheet FCStd route" };
|
||||
if (record.module === "Spreadsheet" && record.name.toLowerCase() === ".csv") return { module: "Spreadsheet", command: "spreadsheet.importExportCsv", worker: "spreadsheet.worker.ts", reason: "native Spreadsheet CSV import/export route" };
|
||||
return undefined;
|
||||
}
|
||||
704
web/src/import-render-bridge.ts
Normal file
704
web/src/import-render-bridge.ts
Normal file
@@ -0,0 +1,704 @@
|
||||
import type { ProfileDirectionEdge } from "./part-profile-task.js";
|
||||
import type { ShowClipState } from "./show-python-family-facade.js";
|
||||
import { distanceAnnotation } from "./measure-annotation.js";
|
||||
import type { DistanceAnnotation } from "./measure-document-adapter.js";
|
||||
import * as THREE from "three";
|
||||
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||
import { TransformControls } from "three/addons/controls/TransformControls.js";
|
||||
import type { MeshPayload } from "./worker-protocol.js";
|
||||
import { SceneSessionRegistry } from "./scene-session-registry.js";
|
||||
import { attachSceneCommands } from "./scene-command-host.js";
|
||||
import { SceneNavigation } from "./scene-navigation.js";
|
||||
import { SelectionDecoration, type SelectionDecorationSnapshot } from "./selection-decoration.js";
|
||||
import type { NavigationPreferenceSource } from "./view-navigation-preferences.js";
|
||||
|
||||
export class ImportRenderBridge {
|
||||
constructor() {
|
||||
// FreeCAD native meshes and placements are Z-up. Make the Three.js world
|
||||
// convention explicit so free orbit, fit-all and restored cameras agree.
|
||||
THREE.Object3D.DEFAULT_UP.set(0, 0, 1);
|
||||
this.camera.up.set(0, 0, 1);
|
||||
}
|
||||
readonly scene = new THREE.Scene();
|
||||
camera: THREE.PerspectiveCamera | THREE.OrthographicCamera = new THREE.PerspectiveCamera(45, 1, 0.01, 100000);
|
||||
readonly renderer = new THREE.WebGLRenderer({ antialias: true });
|
||||
readonly scenes = new SceneSessionRegistry(this.scene, () => this.invalidate());
|
||||
private readonly clipping = new Map<string, ShowClipState>();
|
||||
setClipping(documentId: string, state: ShowClipState): void {
|
||||
this.clipping.set(documentId, state); this.invalidate();
|
||||
}
|
||||
private applyClipping(): void {
|
||||
const state = this.clipping.get(this.activeDocumentId);
|
||||
for (const entry of this.scenes.objects(this.activeDocumentId)) {
|
||||
const definitions = [state?.exempt === entry.id ? undefined : state?.document, state?.objects[entry.id]].filter(Boolean);
|
||||
const planes = definitions.map(plane => new THREE.Plane(new THREE.Vector3(...plane!.normal), plane!.constant));
|
||||
entry.object.traverse(object => {
|
||||
const material = (object as THREE.Mesh).material;
|
||||
if (!material) return;
|
||||
for (const item of Array.isArray(material) ? material : [material]) {
|
||||
// Preserve clipping supplied by other tools; this owner removes only its own planes.
|
||||
const old = item.userData.showClipPlanes ?? [];
|
||||
item.clippingPlanes = [...(item.clippingPlanes ?? []).filter(plane => !old.includes(plane)), ...planes];
|
||||
item.userData.showClipPlanes = planes;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
private directionPicker?: { hidden: Set<string>; edges: ProfileDirectionEdge[]; pick: (object: string, subelement: string) => void; documentId: string };
|
||||
private referencePicker?: {
|
||||
documentId: string; base: string; hidden: Set<string>; group: THREE.Group;
|
||||
kind: "Edge" | "Face"; pick: (subelement: string) => void;
|
||||
};
|
||||
beginReferencePick(documentId: string, base: string, hidden: string[],
|
||||
references: { subelement: string; positions: number[] }[], pick: (subelement: string) => void) {
|
||||
const group = new THREE.Group();
|
||||
for (const reference of references) {
|
||||
if (!reference.positions.length) continue;
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(reference.positions, 3));
|
||||
const edge = reference.subelement.startsWith("Edge");
|
||||
const item = edge
|
||||
? new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: "#f9b44d", transparent: true, depthTest: false }))
|
||||
: new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: "#f9b44d", side: THREE.DoubleSide,
|
||||
transparent: true, opacity: 0, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 }));
|
||||
item.userData.subelement = reference.subelement;
|
||||
item.renderOrder = edge ? 3 : 2; group.add(item);
|
||||
}
|
||||
const session = { documentId, base, hidden: new Set(hidden), group, kind: "Edge" as "Edge" | "Face", pick };
|
||||
this.referencePicker = session; this.scene.add(group); this.invalidate();
|
||||
let disposed = false;
|
||||
return {
|
||||
highlight: (selected: string[], kind: "Edge" | "Face", hovered?: string) => {
|
||||
session.kind = kind;
|
||||
for (const child of group.children) {
|
||||
const item = child as THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>;
|
||||
const sub = String(item.userData.subelement), chosen = selected.includes(sub) || hovered === sub;
|
||||
item.material.opacity = sub.startsWith("Edge") ? (chosen ? 1 : kind === "Edge" ? 0.35 : 0) : chosen ? 0.45 : 0;
|
||||
}
|
||||
this.invalidate();
|
||||
},
|
||||
dispose: () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
if (this.referencePicker === session) this.referencePicker = undefined;
|
||||
this.scene.remove(group);
|
||||
for (const child of group.children) {
|
||||
const item = child as THREE.Mesh<THREE.BufferGeometry, THREE.Material>;
|
||||
item.geometry.dispose(); item.material.dispose();
|
||||
}
|
||||
this.applyDirectionVisibility(); this.invalidate();
|
||||
},
|
||||
};
|
||||
}
|
||||
private pickReference(point: { x: number; y: number }): boolean {
|
||||
const session = this.referencePicker;
|
||||
if (!session || session.documentId !== this.activeDocumentId) return false;
|
||||
const bounds = this.renderer.domElement.getBoundingClientRect(), ray = new THREE.Raycaster();
|
||||
this.camera.updateMatrixWorld();
|
||||
ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1,
|
||||
1 - (point.y - bounds.top) / bounds.height * 2), this.camera);
|
||||
ray.params.Line.threshold = Math.max(0.01, this.camera.position.distanceTo(this.controls?.target ?? new THREE.Vector3()) / 200);
|
||||
session.group.updateWorldMatrix(true, true);
|
||||
const clip = this.clipping.get(this.activeDocumentId);
|
||||
const hit = ray.intersectObjects(session.group.children.filter(item => String(item.userData.subelement).startsWith(session.kind)))
|
||||
.find(hit => [clip?.exempt === session.base ? undefined : clip?.document, clip?.objects[session.base]]
|
||||
.every(plane => !plane || new THREE.Vector3(...plane.normal).dot(hit.point) + plane.constant >= 0));
|
||||
if (hit) session.pick(String(hit.object.userData.subelement));
|
||||
// A task owns viewport clicks, including misses, without changing tree selection.
|
||||
return true;
|
||||
}
|
||||
beginDirectionPick(documentId: string, hidden: string[], edges: ProfileDirectionEdge[], pick: (object: string, subelement: string) => void): () => void {
|
||||
const session = { documentId, hidden: new Set(hidden), edges, pick };
|
||||
this.directionPicker = session; this.invalidate();
|
||||
return () => { if (this.directionPicker === session) { this.directionPicker = undefined; this.invalidate(); } };
|
||||
}
|
||||
private applyDirectionVisibility(): void {
|
||||
const reference = this.referencePicker;
|
||||
if (reference) reference.group.visible = reference.documentId === this.activeDocumentId;
|
||||
for (const entry of this.scenes.objects(this.activeDocumentId)) {
|
||||
entry.object.visible = reference?.documentId === this.activeDocumentId && reference.base === entry.id ? true
|
||||
: entry.viewState.visible && !(reference?.documentId === this.activeDocumentId && reference.hidden.has(entry.id))
|
||||
&& !(this.directionPicker?.documentId === this.activeDocumentId && this.directionPicker.hidden.has(entry.id));
|
||||
}
|
||||
}
|
||||
private pickDirection(point: { x: number; y: number }): boolean {
|
||||
const session = this.directionPicker;
|
||||
if (!session || session.documentId !== this.activeDocumentId) return false;
|
||||
const bounds = this.renderer.domElement.getBoundingClientRect();
|
||||
const ray = new THREE.Raycaster();
|
||||
this.camera.updateMatrixWorld();
|
||||
ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1,
|
||||
1 - (point.y - bounds.top) / bounds.height * 2), this.camera);
|
||||
ray.params.Line.threshold = Math.max(0.01, this.camera.position.distanceTo(this.controls?.target ?? new THREE.Vector3()) / 200);
|
||||
const lines = session.edges.filter(edge => this.scenes.objects(this.activeDocumentId).some(entry => entry.id === edge.object && entry.object.visible))
|
||||
.map(edge => {
|
||||
const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(edge.points.map(p => new THREE.Vector3(...p as [number, number, number]))), new THREE.LineBasicMaterial());
|
||||
line.userData.edge = edge; line.updateMatrixWorld(); return line;
|
||||
});
|
||||
const clip = this.clipping.get(this.activeDocumentId);
|
||||
const hit = ray.intersectObjects(lines).find(hit => [clip?.exempt === hit.object.userData.edge.object ? undefined : clip?.document, clip?.objects[hit.object.userData.edge.object]]
|
||||
.every(plane => !plane || new THREE.Vector3(...plane.normal).dot(hit.point) + plane.constant >= 0));
|
||||
const edge = hit?.object.userData.edge as ProfileDirectionEdge | undefined;
|
||||
for (const line of lines) { line.geometry.dispose(); line.material.dispose(); }
|
||||
if (edge) session.pick(edge.object, edge.subelement);
|
||||
return true;
|
||||
}
|
||||
private controls: OrbitControls | null = null;
|
||||
// Object transform gizmo. The helper is a scene child; the handle is a proxy
|
||||
// placed at the selected object's placement so document coordinates and the
|
||||
// gizmo agree without moving the rendered mesh itself.
|
||||
private gizmo: TransformControls | null = null;
|
||||
private gizmoMode: "off" | "translate" | "rotate" = "off";
|
||||
private gizmoDocument: string | null = null;
|
||||
private gizmoObject: string | null = null;
|
||||
private readonly gizmoHandle = new THREE.Object3D();
|
||||
private gizmoDragging = false;
|
||||
private gizmoMoved = false;
|
||||
private gizmoBase = { position: new THREE.Vector3(), quaternion: new THREE.Quaternion() };
|
||||
// The one mesh the controller is allowed to move. Every drag writes only this
|
||||
// object's matrix; nothing else in the document is touched, which is what
|
||||
// "the controller operates the selected model" means for multi-object scenes.
|
||||
private gizmoTarget: THREE.Object3D | null = null;
|
||||
private gizmoMeshId: string | null = null;
|
||||
private gizmoTargetBase: THREE.Matrix4 | null = null;
|
||||
private gizmoHandleBase: THREE.Matrix4 | null = null;
|
||||
// A committed placement rebuilds the mesh, so the object captured at drag
|
||||
// start can be replaced mid-flight. Look the target up by document id at the
|
||||
// moment of use instead of trusting a cached reference.
|
||||
private resolveGizmoTarget(): THREE.Object3D | null {
|
||||
if (!this.gizmoMeshId) return this.gizmoTarget;
|
||||
const entry = this.scenes.objects(this.activeDocumentId).find(item => item.id === this.gizmoMeshId);
|
||||
if (entry) this.gizmoTarget = entry.object;
|
||||
return this.gizmoTarget;
|
||||
}
|
||||
// Local frame + selection focus. The triad is a scene child placed at the
|
||||
// object placement, not a child of the gizmo handle, so it stays visible with
|
||||
// the controller switched off and can follow a live drag frame by frame.
|
||||
// Selectable-frame decoration lives in a shared module so the standalone
|
||||
// three.js viewers (test view) can show the same triad and focus box.
|
||||
private readonly decoration = new SelectionDecoration(this.scene);
|
||||
// True until a host calls setTransformTarget. Hosts that never wire the
|
||||
// transform (PartDesign, BIM, assembly, TechDraw) still get the triad and the
|
||||
// focus box, anchored on the picked mesh's bounding-box centre.
|
||||
private decorationAutomatic = true;
|
||||
onTransformCommit: ((payload: { documentId: string; object: string; position: number[]; axis: number[]; angle: number }) => void) | null = null;
|
||||
private sceneCommands: ReturnType<typeof attachSceneCommands> | null = null;
|
||||
private frame = 0;
|
||||
private disposed = false;
|
||||
private readonly invalidate = (): void => {
|
||||
if (this.disposed || !this.viewport || this.frame) return;
|
||||
this.frame = requestAnimationFrame(() => {
|
||||
this.frame = 0;
|
||||
// OrbitControls emits change while damping still moves the camera.
|
||||
this.controls?.update();
|
||||
this.updateSelectionAxes();
|
||||
this.applyClipping();
|
||||
this.applyDirectionVisibility();
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
this.onRender?.();
|
||||
if (this.controls?.autoRotate) this.invalidate();
|
||||
});
|
||||
};
|
||||
private viewport: HTMLElement | null = null;
|
||||
private resizeObserver: ResizeObserver | null = null;
|
||||
private activeDocumentId = "active";
|
||||
private sketchEditing = false;
|
||||
private navigation: SceneNavigation | null = null;
|
||||
private annotations = new Map<string, THREE.Group>();
|
||||
onPick: ((objectId: string, point: number[]) => void) | null = null;
|
||||
onPrimitivePick: ((point: [number, number, number], normal?: [number, number, number]) => void) | null = null;
|
||||
primitivePickVertices: number[][] | null = null;
|
||||
onSelect: ((objectId: string | null, additive?: boolean) => void) | null = null;
|
||||
onRender: (() => void) | null = null;
|
||||
private hit(point: { x: number; y: number }) {
|
||||
const bounds = this.renderer.domElement.getBoundingClientRect();
|
||||
const ray = new THREE.Raycaster();
|
||||
this.camera.updateMatrixWorld();
|
||||
ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1,
|
||||
1 - (point.y - bounds.top) / bounds.height * 2), this.camera);
|
||||
const objects = this.scenes.objects(this.activeDocumentId).filter(entry => entry.object.visible).map(entry => entry.object);
|
||||
objects.forEach(object => object.updateWorldMatrix(true, true));
|
||||
return ray.intersectObjects(objects, true).find(hit => {
|
||||
const state = this.clipping.get(this.activeDocumentId);
|
||||
const id = String(hit.object.userData.documentObjectId);
|
||||
return [state?.exempt === id ? undefined : state?.document, state?.objects[id]].every(plane =>
|
||||
!plane || new THREE.Vector3(...plane.normal).dot(hit.point) + plane.constant >= 0);
|
||||
});
|
||||
}
|
||||
|
||||
mount(viewport: HTMLElement, preferences?: NavigationPreferenceSource): void {
|
||||
this.viewport = viewport;
|
||||
this.renderer.localClippingEnabled = true;
|
||||
this.scene.background = new THREE.Color("#0d1319");
|
||||
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
viewport.append(this.renderer.domElement);
|
||||
this.renderer.domElement.addEventListener("sketch-edit-capture", ((event: CustomEvent) => {
|
||||
if (event.detail.documentId !== this.activeDocumentId || this.disposed) return;
|
||||
event.detail.camera = this.captureCamera();
|
||||
this.sketchEditing = true;
|
||||
}) as EventListener);
|
||||
this.renderer.domElement.addEventListener("sketch-edit-restore", ((event: CustomEvent) => {
|
||||
this.sketchEditing = false;
|
||||
if (event.detail.documentId !== this.activeDocumentId || this.disposed) return;
|
||||
if (event.detail.camera) this.restoreCamera(event.detail.camera);
|
||||
for (const value of event.detail.displayProperties ?? []) {
|
||||
const object = this.scenes.objects(this.activeDocumentId).find(entry => entry.id === value.object)?.object;
|
||||
if (object) object.visible = value.visible;
|
||||
}
|
||||
this.invalidate();
|
||||
}) as EventListener);
|
||||
this.renderer.domElement.addEventListener("bim-capture-camera", ((event: CustomEvent) => {
|
||||
if (event.detail.documentId === this.activeDocumentId && !this.disposed)
|
||||
event.detail.camera = this.captureCamera();
|
||||
}) as EventListener);
|
||||
this.renderer.domElement.addEventListener("techdraw-capture", ((event: CustomEvent) => {
|
||||
if (event.detail.documentId !== this.activeDocumentId || this.disposed
|
||||
|| !this.scenes.objects(this.activeDocumentId).some(entry => entry.object.visible)) return;
|
||||
this.applyClipping();
|
||||
this.applyDirectionVisibility();
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
const options = event.detail.captureOptions ?? {};
|
||||
const crop = options.crop === true;
|
||||
const width = crop && Number.isFinite(options.width) ? Math.max(1, Math.round(Number(options.width))) : this.renderer.domElement.width;
|
||||
const height = crop && Number.isFinite(options.height) ? Math.max(1, Math.round(Number(options.height))) : this.renderer.domElement.height;
|
||||
const output = document.createElement("canvas");
|
||||
output.width = width; output.height = height;
|
||||
const context = output.getContext("2d");
|
||||
if (!context) return;
|
||||
if (options.solidBackground === true && typeof options.background === "string") {
|
||||
context.fillStyle = options.background; context.fillRect(0, 0, width, height);
|
||||
}
|
||||
context.drawImage(this.renderer.domElement, 0, 0, width, height);
|
||||
event.detail.capture = {
|
||||
image: output.toDataURL("image/png"), pixelWidth: width, pixelHeight: height,
|
||||
};
|
||||
}) as EventListener);
|
||||
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
|
||||
this.controls.enableDamping = true;
|
||||
this.controls.addEventListener("change", this.invalidate);
|
||||
// Read-only camera probe: strict tests must prove that rotating the selected
|
||||
// model does not move the viewpoint, while middle-drag orbit does.
|
||||
(window as unknown as { __freecadCameraState?: unknown }).__freecadCameraState = () => ({
|
||||
position: this.camera.position.toArray().map(value => Math.round(value * 10000) / 10000),
|
||||
quaternion: this.camera.quaternion.toArray().map(value => Math.round(value * 10000) / 10000),
|
||||
target: this.controls ? this.controls.target.toArray().map(value => Math.round(value * 10000) / 10000) : null,
|
||||
});
|
||||
// Read-only controller probe: proves which object the gizmo will move and
|
||||
// where every document mesh currently sits, so a drag can be asserted to
|
||||
// change the selected mesh only.
|
||||
(window as unknown as { __freecadGizmoState?: unknown }).__freecadGizmoState = () => ({
|
||||
mode: this.gizmoMode,
|
||||
dragging: this.gizmoDragging,
|
||||
target: this.gizmoObject,
|
||||
targetMeshId: this.gizmoTarget?.userData.documentObjectId ?? null,
|
||||
handle: this.gizmoHandle.position.toArray().map(value => Math.round(value * 1000) / 1000),
|
||||
// Screen point of the gizmo centre, so a probe can grab a handle instead
|
||||
// of guessing the canvas middle.
|
||||
handleScreen: (() => {
|
||||
const rect = this.renderer.domElement.getBoundingClientRect();
|
||||
this.gizmoHandle.updateMatrixWorld(true);
|
||||
const projected = new THREE.Vector3().setFromMatrixPosition(this.gizmoHandle.matrixWorld).project(this.camera);
|
||||
return [Math.round(rect.left + (projected.x + 1) * rect.width / 2),
|
||||
Math.round(rect.top + (1 - projected.y) * rect.height / 2)];
|
||||
})(),
|
||||
objects: this.scenes.objects(this.activeDocumentId).map(entry => {
|
||||
entry.object.updateMatrixWorld(true);
|
||||
// Two readings, both rounded: the world translation proves a live drag
|
||||
// preview (which writes the object matrix), and the world bounding-box
|
||||
// centre proves the committed placement (mesh triangles bake placement,
|
||||
// so a rebuilt mesh sits at the origin while its geometry has moved).
|
||||
const world = new THREE.Vector3().setFromMatrixPosition(entry.object.matrixWorld);
|
||||
const box = new THREE.Box3().setFromObject(entry.object);
|
||||
const center = box.isEmpty() ? null : box.getCenter(new THREE.Vector3());
|
||||
const round = (values: number[]) => values.map(value => Math.round(value * 1000) / 1000);
|
||||
return {
|
||||
id: entry.id,
|
||||
position: round(world.toArray()),
|
||||
center: center ? round(center.toArray()) : null,
|
||||
};
|
||||
}),
|
||||
});
|
||||
this.gizmo = new TransformControls(this.camera, this.renderer.domElement);
|
||||
this.gizmo.setTranslationSnap(1);
|
||||
this.gizmo.setRotationSnap(THREE.MathUtils.degToRad(15));
|
||||
this.gizmo.setSize(0.9);
|
||||
this.gizmo.enabled = false;
|
||||
this.gizmo.getHelper().visible = false;
|
||||
this.scene.add(this.gizmo.getHelper());
|
||||
this.scene.add(this.gizmoHandle);
|
||||
// TransformControls dispatches "change" from pointerHover whenever the axis
|
||||
// under the cursor changes; SceneNavigation reads this flag to hand the left
|
||||
// button to the gizmo without giving up middle-drag orbit.
|
||||
this.gizmo.addEventListener("change", () => { if (this.navigation) this.navigation.gizmoHover = this.gizmo?.axis != null; });
|
||||
this.gizmo.addEventListener("dragging-changed", (event: { value: unknown }) => {
|
||||
const busy = Boolean(event.value);
|
||||
this.gizmoDragging = busy;
|
||||
if (busy) {
|
||||
this.gizmoMoved = false;
|
||||
// Snapshot the selected mesh so every frame is recomputed from the drag
|
||||
// start instead of accumulating rounding error. The handle matrix is
|
||||
// read through updateMatrixWorld so it is current at drag start.
|
||||
this.gizmoHandle.updateMatrixWorld(true);
|
||||
this.gizmoHandleBase = this.gizmoHandle.matrixWorld.clone();
|
||||
const target = this.resolveGizmoTarget();
|
||||
if (target) {
|
||||
target.updateMatrixWorld(true);
|
||||
this.gizmoTargetBase = target.matrix.clone();
|
||||
target.matrixAutoUpdate = false;
|
||||
}
|
||||
}
|
||||
if (this.controls) this.controls.enabled = !busy;
|
||||
if (this.navigation) this.navigation.enabled = !busy;
|
||||
this.invalidate();
|
||||
});
|
||||
this.gizmo.addEventListener("objectChange", () => {
|
||||
if (this.gizmoDragging) {
|
||||
this.gizmoMoved = true;
|
||||
this.previewGizmoDrag();
|
||||
}
|
||||
this.invalidate();
|
||||
});
|
||||
this.gizmo.addEventListener("mouseUp", () => {
|
||||
// A plain click on the canvas also fires mouseUp; committing then would
|
||||
// write a spurious placement (angle 0) for an edit that never happened.
|
||||
const moved = this.gizmoMoved;
|
||||
this.gizmoMoved = false;
|
||||
// On a real drag the preview matrix stays until the kernel snapshot
|
||||
// republishes the re-meshed geometry; resetting it here would snap the
|
||||
// selected mesh back to its old position while the commit is in flight.
|
||||
if (!moved) this.endGizmoPreview();
|
||||
|
||||
if (this.gizmoMode === "off" || !this.gizmoDocument || !this.gizmoObject) { this.endGizmoPreview(); return; }
|
||||
const start = this.gizmoBase.quaternion.clone();
|
||||
const base = start; // handle started at the object's own orientation
|
||||
const delta = this.gizmoHandle.quaternion.clone().multiply(start.clone().invert());
|
||||
const final = delta.multiply(base);
|
||||
const angle = THREE.MathUtils.radToDeg(2 * Math.acos(Math.min(Math.max(final.w, -1), 1)));
|
||||
const sine = Math.sqrt(Math.max(1 - final.w * final.w, 0));
|
||||
const axis = sine < 1e-6 ? [1, 0, 0] : [final.x / sine, final.y / sine, final.z / sine];
|
||||
const payloadAngle = Number.isFinite(angle) ? angle : 0;
|
||||
// With no commit consumer the preview is the only thing holding the mesh
|
||||
// at its dragged pose, so it has to be released here.
|
||||
if (!this.onTransformCommit) { this.endGizmoPreview(); return; }
|
||||
this.onTransformCommit({
|
||||
documentId: this.gizmoDocument, object: this.gizmoObject,
|
||||
position: this.gizmoHandle.position.toArray(),
|
||||
axis, angle: payloadAngle,
|
||||
});
|
||||
});
|
||||
this.navigation = new SceneNavigation(this.renderer.domElement, this.controls, (point, additive) => {
|
||||
if (this.sketchEditing) return;
|
||||
this.applyDirectionVisibility();
|
||||
if (this.pickReference(point)) return;
|
||||
if (this.pickDirection(point)) return;
|
||||
const hit = this.hit(point);
|
||||
if (this.onPrimitivePick) {
|
||||
const bounds = this.renderer.domElement.getBoundingClientRect();
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1,
|
||||
1 - (point.y - bounds.top) / bounds.height * 2), this.camera);
|
||||
const nearest = this.primitivePickVertices?.map(value => {
|
||||
const vertex = new THREE.Vector3(...value).project(this.camera);
|
||||
return { value, pixels: Math.hypot((vertex.x + 1) * bounds.width / 2 + bounds.left - point.x,
|
||||
(1 - vertex.y) * bounds.height / 2 + bounds.top - point.y), depth: vertex.z };
|
||||
}).filter(value => value.pixels <= 10 && value.depth >= -1 && value.depth <= 1)
|
||||
.sort((a, b) => a.pixels - b.pixels || a.depth - b.depth)[0];
|
||||
if (nearest) { this.onPrimitivePick(nearest.value as [number, number, number]); return; }
|
||||
if (this.primitivePickVertices) return;
|
||||
if (hit) {
|
||||
const normal = hit.face?.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld));
|
||||
this.onPrimitivePick(hit.point.toArray() as [number, number, number], normal?.toArray() as [number, number, number] | undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (hit && this.onPick) { this.onPick(String(hit.object.userData.documentObjectId), hit.point.toArray()); return; }
|
||||
if (this.decorationAutomatic) this.decoratePicked(hit?.object ?? null);
|
||||
this.onSelect?.(hit ? String(hit.object.userData.documentObjectId) : null, additive);
|
||||
}, point => this.hit(point)?.point, command => { this.sceneCommands?.executeCamera(command); }, this.invalidate,
|
||||
next => this.sceneCommands?.replaceControls(next));
|
||||
this.sceneCommands = attachSceneCommands(this.scene, this.controls, viewport, () => this.activeDocumentId, this.invalidate, {
|
||||
canvas: this.renderer.domElement,
|
||||
objects: () => this.scenes.objects(this.activeDocumentId).map(entry => ({
|
||||
id: entry.id, label: entry.payload.fileName || entry.id, object: entry.object,
|
||||
})),
|
||||
select: id => {
|
||||
if (this.sketchEditing) return;
|
||||
if (this.decorationAutomatic) {
|
||||
const entry = this.scenes.objects(this.activeDocumentId).find(item => item.id === id);
|
||||
this.decoratePicked(entry?.object ?? null);
|
||||
}
|
||||
this.onSelect?.(id);
|
||||
},
|
||||
}, next => {
|
||||
this.controls?.removeEventListener("change", this.invalidate);
|
||||
this.controls = next;
|
||||
this.camera = next.object as THREE.PerspectiveCamera | THREE.OrthographicCamera;
|
||||
this.navigation?.bind(next);
|
||||
next.addEventListener("change", this.invalidate);
|
||||
if (this.gizmo) this.gizmo.camera = next.object as THREE.Camera;
|
||||
}, preferences ? { source: preferences, apply: values => this.navigation?.apply(values),
|
||||
cancel: () => this.navigation?.cancel() } : undefined);
|
||||
this.scene.add(new THREE.HemisphereLight(0xddeeff, 0x17212b, 1.8));
|
||||
const light = new THREE.DirectionalLight(0xffffff, 2.1); light.position.set(4, 8, 6); this.scene.add(light);
|
||||
const resize = () => { const width = Math.max(viewport.clientWidth, 1); const height = Math.max(viewport.clientHeight, 1); this.renderer.setSize(width, height, false); if (this.camera instanceof THREE.PerspectiveCamera) this.camera.aspect = width / height;
|
||||
else { const halfHeight = (this.camera.top - this.camera.bottom) / 2;
|
||||
this.camera.left = -halfHeight * width / height; this.camera.right = halfHeight * width / height; }
|
||||
this.camera.updateProjectionMatrix(); this.invalidate(); };
|
||||
this.resizeObserver = new ResizeObserver(resize); this.resizeObserver.observe(viewport); resize();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
// Places the gizmo on an object placement reported by the shell. Keeping the
|
||||
// base orientation lets a rotation commit compose with whatever rotation the
|
||||
// object already had.
|
||||
setTransformTarget(documentId: string, object: string, position: number[], axis?: number[], angle?: number, meshId?: string): void {
|
||||
this.decorationAutomatic = false;
|
||||
this.gizmoDocument = documentId; this.gizmoObject = object;
|
||||
this.gizmoHandle.position.fromArray(position);
|
||||
const orientation = new THREE.Quaternion();
|
||||
if (axis && axis.length === 3 && Number.isFinite(angle)) {
|
||||
const length = Math.hypot(axis[0], axis[1], axis[2]);
|
||||
if (length > 0) orientation.setFromAxisAngle(new THREE.Vector3(axis[0] / length, axis[1] / length, axis[2] / length),
|
||||
THREE.MathUtils.degToRad(angle ?? 0));
|
||||
}
|
||||
this.gizmoHandle.quaternion.copy(orientation);
|
||||
this.gizmoBase = { position: this.gizmoHandle.position.clone(), quaternion: orientation.clone() };
|
||||
const entry = this.scenes.objects(this.activeDocumentId).find(item => item.id === (meshId ?? object));
|
||||
this.gizmoTarget = entry?.object ?? null;
|
||||
this.gizmoMeshId = entry?.id ?? null;
|
||||
this.gizmoTargetBase = null;
|
||||
if (this.gizmoTarget) this.gizmoTarget.matrixAutoUpdate = true;
|
||||
this.decoration.setTarget(position, orientation, entry?.object ?? null);
|
||||
if (this.gizmo && this.gizmoMode !== "off" && !this.gizmoDragging) { this.gizmo.attach(this.gizmoHandle); this.gizmo.getHelper().visible = true; }
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
// Live preview while a drag is in flight: the gizmo handle has already moved,
|
||||
// so the selected mesh takes the same world-space delta. Nothing else in the
|
||||
// scene is rewritten — unselected objects keep their matrices untouched.
|
||||
private previewGizmoDrag(): void {
|
||||
const target = this.gizmoTarget, base = this.gizmoTargetBase, start = this.gizmoHandleBase;
|
||||
if (!target || !base || !start) return;
|
||||
const delta = new THREE.Matrix4().copy(this.gizmoHandle.matrixWorld)
|
||||
.multiply(new THREE.Matrix4().copy(start).invert());
|
||||
// `delta` is a world-space transform; `base` is the mesh's local matrix, so
|
||||
// it has to travel through the parent frame before landing back in local
|
||||
// space. Document groups are identity today, but this keeps the preview
|
||||
// correct if an object is ever parented.
|
||||
const parent = target.parent;
|
||||
if (parent) {
|
||||
parent.updateMatrixWorld(true);
|
||||
const inverse = new THREE.Matrix4().copy(parent.matrixWorld).invert();
|
||||
target.matrix.copy(inverse).multiply(delta).multiply(parent.matrixWorld).multiply(base);
|
||||
} else {
|
||||
target.matrix.copy(delta).multiply(base);
|
||||
}
|
||||
target.matrixWorldNeedsUpdate = true;
|
||||
target.updateMatrixWorld(true);
|
||||
}
|
||||
|
||||
// Drag finished: drop the preview matrix so the mesh goes back to following
|
||||
// its own transform. The kernel commit republishes the authoritative placement.
|
||||
private endGizmoPreview(): void {
|
||||
if (this.gizmoTarget) {
|
||||
this.gizmoTarget.matrixAutoUpdate = true;
|
||||
this.gizmoTarget.matrixWorldNeedsUpdate = true;
|
||||
}
|
||||
this.gizmoTargetBase = null;
|
||||
}
|
||||
|
||||
// Hosts without their own placement pipeline still show the selected local
|
||||
// frame: anchor it on the mesh's bounding-box centre with an identity basis.
|
||||
private decoratePicked(object: THREE.Object3D | null): void {
|
||||
if (!object || !object.visible) { this.decoration.clear(); return; }
|
||||
const box = new THREE.Box3().setFromObject(object);
|
||||
if (box.isEmpty()) { this.decoration.clear(); return; }
|
||||
this.decoration.setTarget(box.getCenter(new THREE.Vector3()).toArray(), new THREE.Quaternion(), object);
|
||||
}
|
||||
|
||||
// Read-only view of the selection decoration for headed acceptance probes.
|
||||
selectionFrameSnapshot(): SelectionDecorationSnapshot & { gizmoVisible: boolean; gizmoMode: string } {
|
||||
return { ...this.decoration.snapshot(), gizmoVisible: Boolean(this.gizmo?.getHelper().visible), gizmoMode: this.gizmoMode };
|
||||
}
|
||||
|
||||
clearTransformTarget(): void {
|
||||
this.gizmoDocument = null; this.gizmoObject = null;
|
||||
this.endGizmoPreview();
|
||||
this.gizmoTarget = null;
|
||||
if (this.gizmo) { this.gizmo.detach(); this.gizmo.getHelper().visible = false; }
|
||||
this.decoration.clear();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
// SolidWorks-style selection display: the triad and focus box come from the
|
||||
// shared SelectionDecoration; this wrapper only feeds it the camera frame.
|
||||
private updateSelectionAxes(): void {
|
||||
if (this.gizmoDragging) this.decoration.follow(this.gizmoHandle.position, this.gizmoHandle.quaternion);
|
||||
this.decoration.updateFrame(this.camera);
|
||||
}
|
||||
|
||||
setTransformMode(mode: "off" | "translate" | "rotate"): void {
|
||||
if (this.gizmoDragging) return;
|
||||
this.gizmoMode = mode;
|
||||
if (!this.gizmo) return;
|
||||
if (mode === "off") {
|
||||
this.gizmo.detach(); this.gizmo.enabled = false; this.gizmo.getHelper().visible = false;
|
||||
if (this.navigation) { this.navigation.gizmoActive = false; this.navigation.gizmoHover = false; }
|
||||
} else {
|
||||
// SceneNavigation listens in the capture phase and stops propagation, which
|
||||
// starves the gizmo's bubble-phase handlers. Rather than switching the whole
|
||||
// navigation off (that also loses middle-drag orbit and wheel zoom), the
|
||||
// navigation yields only left-button events while the pointer is over a
|
||||
// gizmo handle; every other gesture keeps working like SolidWorks.
|
||||
this.gizmo.setMode(mode);
|
||||
this.gizmo.enabled = true;
|
||||
this.gizmo.getHelper().visible = Boolean(this.gizmoDocument);
|
||||
if (this.navigation) { this.navigation.cancel(); this.navigation.gizmoActive = true; this.navigation.gizmoHover = false; }
|
||||
if (this.gizmoDocument) this.gizmo.attach(this.gizmoHandle);
|
||||
}
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
setNavigationEnabled(enabled: boolean): void {
|
||||
if (this.navigation) { this.navigation.cancel(); this.navigation.enabled = enabled; }
|
||||
if (this.controls) this.controls.enabled = enabled;
|
||||
}
|
||||
|
||||
requestRender(): void { this.invalidate(); }
|
||||
|
||||
captureCamera(): number[] {
|
||||
const camera = this.camera;
|
||||
camera.updateMatrixWorld();
|
||||
const focal = camera.position.distanceTo(this.controls?.target ?? new THREE.Vector3());
|
||||
const perspective = camera instanceof THREE.PerspectiveCamera;
|
||||
const aspect = perspective ? camera.aspect : (camera.right - camera.left) / (camera.top - camera.bottom);
|
||||
const height = perspective ? THREE.MathUtils.degToRad(camera.getEffectiveFOV()) : (camera.top - camera.bottom) / camera.zoom;
|
||||
return [...camera.position.toArray(), ...camera.quaternion.toArray(), camera.near, camera.far,
|
||||
aspect, Math.max(focal, 0.001), height, perspective ? 1 : 0];
|
||||
}
|
||||
|
||||
restoreCamera(data: number[]): void {
|
||||
if (data.length !== 13 || !data.every(Number.isFinite)) throw new Error("Invalid BIM camera state");
|
||||
const perspective = data[12] === 1;
|
||||
const aspect = this.viewport ? Math.max(this.viewport.clientWidth, 1) / Math.max(this.viewport.clientHeight, 1) : data[9];
|
||||
const camera = perspective
|
||||
? new THREE.PerspectiveCamera(THREE.MathUtils.radToDeg(data[11]), aspect, data[7], data[8])
|
||||
: new THREE.OrthographicCamera(-data[11] * aspect / 2, data[11] * aspect / 2, data[11] / 2, -data[11] / 2, data[7], data[8]);
|
||||
camera.position.fromArray(data);
|
||||
camera.quaternion.fromArray(data.slice(3, 7)).normalize();
|
||||
camera.up.set(0, 0, 1).applyQuaternion(camera.quaternion);
|
||||
const target = camera.position.clone().add(new THREE.Vector3(0, 0, -data[10]).applyQuaternion(camera.quaternion));
|
||||
this.controls?.removeEventListener("change", this.invalidate);
|
||||
this.controls?.dispose();
|
||||
this.camera = camera;
|
||||
const next = new OrbitControls(camera, this.renderer.domElement);
|
||||
next.target.copy(target);
|
||||
next.update(); camera.updateProjectionMatrix();
|
||||
if (this.sceneCommands) this.sceneCommands.replaceControls(next);
|
||||
else { this.controls = next; this.navigation?.bind(next); next.addEventListener("change", this.invalidate); }
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
show(id: string, payload: MeshPayload): void { this.showForDocument("active", id, payload); }
|
||||
|
||||
showForDocument(documentId: string, id: string, payload: MeshPayload): void {
|
||||
this.scenes.add(documentId, id, payload);
|
||||
this.activateDocument(documentId);
|
||||
this.fitDocument();
|
||||
}
|
||||
|
||||
fitDocument(objectIds?: readonly string[]): void {
|
||||
const bounds = new THREE.Box3();
|
||||
for (const entry of this.scenes.objects(this.activeDocumentId)) {
|
||||
if (entry.object.visible && (!objectIds || objectIds.includes(entry.id))) bounds.expandByObject(entry.object);
|
||||
}
|
||||
if (bounds.isEmpty()) return;
|
||||
const center = bounds.getCenter(new THREE.Vector3()); const radius = Math.max(bounds.getSize(new THREE.Vector3()).length() * 0.5, 0.01);
|
||||
this.controls?.target.copy(center); this.camera.position.copy(center).add(new THREE.Vector3(radius * 1.7, radius * 1.35, radius * 1.7)); this.camera.near = Math.max(radius / 1000, 0.0001); this.camera.far = Math.max(radius * 100, 100); this.camera.updateProjectionMatrix(); this.controls?.update();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
applyFraming(documentId: string, framing: { bounds: number[] | null; rotation?: number[] }): void {
|
||||
if (documentId !== this.activeDocumentId) return;
|
||||
this.navigation?.cancel();
|
||||
const rotation = framing.rotation;
|
||||
const previousTarget = this.controls?.target.clone() ?? this.camera.position.clone().add(
|
||||
new THREE.Vector3(0, 0, -1).applyQuaternion(this.camera.quaternion));
|
||||
const previousDistance = this.camera.position.distanceTo(previousTarget);
|
||||
if (rotation?.length === 4) this.camera.quaternion.fromArray(rotation).normalize();
|
||||
if (framing.bounds?.length === 6) {
|
||||
const box = new THREE.Box3(new THREE.Vector3(...framing.bounds.slice(0, 3)), new THREE.Vector3(...framing.bounds.slice(3, 6)));
|
||||
const center = box.getCenter(new THREE.Vector3());
|
||||
const radius = Math.max(box.getSize(new THREE.Vector3()).length() * 0.5, 0.01);
|
||||
this.controls?.target.copy(center);
|
||||
let distance = this.camera.position.distanceTo(this.controls?.target ?? center);
|
||||
if (this.camera instanceof THREE.PerspectiveCamera) {
|
||||
const halfAngle = Math.atan(Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2)) / this.camera.zoom);
|
||||
const limitingAngle = Math.min(halfAngle, Math.atan(Math.tan(halfAngle) * this.camera.aspect));
|
||||
distance = radius * 1.15 / Math.sin(limitingAngle);
|
||||
} else {
|
||||
this.camera.zoom = Math.min(this.camera.right - this.camera.left, this.camera.top - this.camera.bottom) / (radius * 2.3);
|
||||
distance = radius * 3;
|
||||
}
|
||||
this.camera.position.copy(center).add(new THREE.Vector3(0, 0, distance).applyQuaternion(this.camera.quaternion));
|
||||
this.camera.near = Math.max(Math.min(radius / 1000, distance - radius * 1.5), 0.0001);
|
||||
this.camera.far = Math.max(distance + radius * 2, radius * 100, 100);
|
||||
} else if (rotation?.length === 4) {
|
||||
this.camera.position.copy(previousTarget).add(
|
||||
new THREE.Vector3(0, 0, previousDistance).applyQuaternion(this.camera.quaternion));
|
||||
}
|
||||
this.camera.up.set(0, 0, 1).applyQuaternion(this.camera.quaternion);
|
||||
this.camera.updateProjectionMatrix();
|
||||
this.controls?.update();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
setMeasurements(documentId: string, objects: Array<{ name: string; measurement?: DistanceAnnotation; displayVisibility?: boolean }>): void {
|
||||
const prior = this.annotations.get(documentId);
|
||||
if (prior) { prior.children.forEach(child => child.userData.dispose?.()); this.scene.remove(prior); }
|
||||
const group = new THREE.Group();
|
||||
const visible = new Map(objects.map(object => [object.name, object.displayVisibility !== false]));
|
||||
for (const object of objects) {
|
||||
const measurement = object.measurement;
|
||||
const subjects = measurement?.subjects ?? [];
|
||||
const subjectsVisible = subjects.every(subject => visible.get(subject) !== false);
|
||||
if (measurement && object.displayVisibility !== false && subjectsVisible) {
|
||||
const annotation = distanceAnnotation(measurement);
|
||||
annotation.userData.subjects = subjects;
|
||||
group.add(annotation);
|
||||
}
|
||||
}
|
||||
group.visible = documentId === this.activeDocumentId; this.scene.add(group); this.annotations.set(documentId, group); this.invalidate();
|
||||
}
|
||||
private taskPreviewVisibility?: { documentId: string; restore: () => void };
|
||||
|
||||
// A task may hide committed geometry without changing document visibility.
|
||||
// The returned lease cannot clear a newer task's visibility override.
|
||||
hideForTaskPreview(documentId: string, objectIds: readonly string[]): () => void {
|
||||
this.clearTaskPreviewVisibility();
|
||||
const objects = this.scenes.objects(documentId)
|
||||
.filter(entry => objectIds.includes(entry.id))
|
||||
.map(entry => ({ object: entry.object, visible: entry.object.visible }));
|
||||
const lease = { documentId, restore: () => {
|
||||
for (const entry of objects) entry.object.visible = entry.visible;
|
||||
this.invalidate();
|
||||
} };
|
||||
for (const entry of objects) entry.object.visible = false;
|
||||
this.taskPreviewVisibility = lease;
|
||||
this.invalidate();
|
||||
return () => {
|
||||
if (this.taskPreviewVisibility === lease) this.clearTaskPreviewVisibility();
|
||||
};
|
||||
}
|
||||
|
||||
clearTaskPreviewVisibility(): void {
|
||||
const lease = this.taskPreviewVisibility;
|
||||
this.taskPreviewVisibility = undefined;
|
||||
lease?.restore();
|
||||
}
|
||||
|
||||
activateDocument(documentId: string): void { for (const [id, group] of this.annotations) group.visible = id === documentId; if (this.activeDocumentId !== documentId) { this.clearTaskPreviewVisibility(); this.navigation?.cancel(); } this.activeDocumentId = documentId; this.scenes.activate(documentId); }
|
||||
removeDocument(documentId: string): void { if (this.taskPreviewVisibility?.documentId === documentId) this.clearTaskPreviewVisibility(); this.clipping.delete(documentId); this.setMeasurements(documentId, []); this.scenes.removeDocument(documentId); }
|
||||
clear(): void { this.clearTaskPreviewVisibility(); this.clipping.clear(); for (const [id] of this.annotations) this.setMeasurements(id, []); for (const group of this.annotations.values()) this.scene.remove(group); this.annotations.clear(); this.scenes.clear(); }
|
||||
dispose(): void { this.disposed = true; cancelAnimationFrame(this.frame); this.sceneCommands?.dispose(); this.sceneCommands = null; this.controls?.removeEventListener("change", this.invalidate); this.resizeObserver?.disconnect(); this.navigation?.dispose(); this.navigation = null; this.onSelect = null; this.clear(); this.gizmo?.detach(); this.gizmo?.dispose(); this.gizmo = null; this.scene.remove(this.gizmoHandle); this.decoration.dispose(); this.controls?.dispose(); this.renderer.dispose(); this.viewport = null; }
|
||||
}
|
||||
58
web/src/module-metadata.generated.ts
Normal file
58
web/src/module-metadata.generated.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
/* Generated by tools/generate_web_module_registry.py; no Worker factories. */
|
||||
export const WEB_MODULE_REGISTRY_SCHEMA = "freecad-web-module-registry/v1" as const;
|
||||
|
||||
export interface WebModuleRoute {
|
||||
readonly module: string;
|
||||
readonly workers: readonly string[];
|
||||
readonly primaryWorker: string | null;
|
||||
readonly commands: readonly string[];
|
||||
readonly objectTypeCount: number;
|
||||
readonly pythonApiCount: number;
|
||||
readonly guiDependency: boolean;
|
||||
readonly formatExtensions: readonly string[];
|
||||
}
|
||||
|
||||
export const WEB_MODULE_REGISTRY = [
|
||||
{ module: "Assembly", workers: ["assembly.worker.ts"], primaryWorker: "assembly.worker.ts", commands: ["assembly.createRecompute", "assembly.inspectPythonApi", "assembly.inspectSourceInventory", "assembly.nativeTypeProbe", "assembly.pythonFamily", "assembly.saveReopen", "assembly.testCore"], objectTypeCount: 8, pythonApiCount: 552, guiDependency: true, formatExtensions: [".fcstd"] },
|
||||
{ module: "BIM", workers: ["bim.worker.ts"], primaryWorker: "bim.worker.ts", commands: ["bim.create2DViews", "bim.createAxis", "bim.document", "bim.extrusionData", "bim.inspectPythonApi", "bim.inspectSourceInventory", "bim.nativeProbe", "bim.pythonFamily", "bim.pythonFamilyBatch", "bim.testArchAxis", "bim.testArchBatch", "bim.testArchBuildingPart", "bim.testArchBuildingPartGui", "bim.testArchComponent", "bim.testArchCurtainWall", "bim.testArchEquipment", "bim.testArchFence", "bim.testArchFrame", "bim.testArchGrid", "bim.testArchImporters", "bim.testArchMaterial", "bim.testArchPanel", "bim.testArchPipe", "bim.testArchProfile", "bim.testArchProject", "bim.testArchRebar", "bim.testArchReference", "bim.testArchReport", "bim.testArchReportGui", "bim.testArchSiteGui", "bim.testArchWallGui", "bim.testWebGLExportGui"], objectTypeCount: 0, pythonApiCount: 2366, guiDependency: false, formatExtensions: [".brp", ".dae", ".dxf", ".fcstd", ".ifc", ".json", ".obj", ".stp", ".svg"] },
|
||||
{ module: "CAM", workers: ["cam.worker.ts"], primaryWorker: "cam.worker.ts", commands: ["cam.createRecompute", "cam.export", "cam.import", "cam.inspectPythonApi", "cam.inspectSourceInventory", "cam.pythonFamilyBatch", "cam.saveReopen", "cam.testCentroidLegacyPost", "cam.testCentroidPost", "cam.testDressupPost", "cam.testDrillCycleExpander", "cam.testFanucPost", "cam.testGcodeProcessingUtils", "cam.testGenericPlasma", "cam.testGenericPost", "cam.testGrblLegacyPost", "cam.testGrblPost", "cam.testLinkingGenerator", "cam.testLinuxCNCLegacyPost", "cam.testLinuxCNCPost", "cam.testMach3Mach4LegacyPost", "cam.testMach3Mach4Post", "cam.testMachine", "cam.testMassoG3Post", "cam.testMaterial", "cam.testPathAdaptive", "cam.testPathCommandAnnotations", "cam.testPathCore", "cam.testPathDepthParams", "cam.testPathDressupArray", "cam.testPathDressupDogboneII", "cam.testPathDressupHoldingTags", "cam.testPathDrillGenerator", "cam.testPathDrillable", "cam.testPathFacingGenerator", "cam.testPathGeneratorDogboneII", "cam.testPathGeom", "cam.testPathHelix", "cam.testPathHelixGenerator", "cam.testPathHelpers", "cam.testPathLanguage", "cam.testPathLog", "cam.testPathOpDeburr", "cam.testPathOpUtil", "cam.testPathPreferences", "cam.testPathProfile", "cam.testPathPropertyBag", "cam.testPathRotationGenerator", "cam.testPathSetupSheet", "cam.testPathSpiralGenerator", "cam.testPathStock", "cam.testPathTapGenerator", "cam.testPathThreadMilling", "cam.testPathThreadMillingGenerator", "cam.testPathToolAsset", "cam.testPathToolAssetCache", "cam.testPathToolAssetManager", "cam.testPathToolAssetStore", "cam.testPathToolAssetUri", "cam.testPathToolBit", "cam.testPathToolBitSerializer", "cam.testPathToolChangeGenerator", "cam.testPathToolController", "cam.testPathToolLibrary", "cam.testPathToolLibrarySerializer", "cam.testPathToolShapeClasses", "cam.testPathToolShapeDoc", "cam.testPathUtil", "cam.testPathVcarve", "cam.testPathVoronoi", "cam.testPostCore", "cam.testPostGCodes", "cam.testPostMCodes", "cam.testSanity", "cam.testSnapmakerPost", "cam.testTSPSolver", "cam.testTestPost"], objectTypeCount: 12, pythonApiCount: 2883, guiDependency: true, formatExtensions: [".fcstd", ".json", ".obj", ".step", ".svg"] },
|
||||
{ module: "Cloud", workers: ["cloud.worker.ts"], primaryWorker: "cloud.worker.ts", commands: ["cloud.configureRecompute", "cloud.inspectPythonApi", "cloud.inspectSourceInventory", "cloud.pythonFamilyBatch", "cloud.restore", "cloud.save", "cloud.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Draft", workers: ["draft.worker.ts"], primaryWorker: "draft.worker.ts", commands: ["draft.action", "draft.formatBatch", "draft.pythonFamilyBatch", "draft.testOfficialSuite"], objectTypeCount: 0, pythonApiCount: 2043, guiDependency: false, formatExtensions: [".dxf", ".obj", ".svg"] },
|
||||
{ module: "Fem", workers: ["fem.worker.ts"], primaryWorker: "fem.worker.ts", commands: ["fem.action", "fem.brep", "fem.document", "fem.nativeProbe", "fem.pythonFamilyBatch"], objectTypeCount: 53, pythonApiCount: 1305, guiDependency: true, formatExtensions: [".brep", ".json", ".obj", ".svg", ".txt"] },
|
||||
{ module: "Help", workers: ["help.worker.ts"], primaryWorker: "help.worker.ts", commands: ["help.inspectSourceInventory", "help.pythonApi"], objectTypeCount: 0, pythonApiCount: 14, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Import", workers: ["import.worker.ts"], primaryWorker: "import.worker.ts", commands: ["import.createRecompute", "import.inspectSourceInventory", "import.pythonApi", "import.pythonFamilyBatch", "import.saveReopen", "import.step"], objectTypeCount: 2, pythonApiCount: 1135, guiDependency: true, formatExtensions: [".ifc", ".igs", ".obj", ".step", ".stp"] },
|
||||
{ module: "Inspection", workers: ["inspection.worker.ts"], primaryWorker: "inspection.worker.ts", commands: ["inspection.createRecompute", "inspection.inspectPythonApi", "inspection.inspectSourceInventory", "inspection.pythonFamilyBatch", "inspection.saveReopen"], objectTypeCount: 3, pythonApiCount: 3, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "JtReader", workers: ["jtreader.worker.ts"], primaryWorker: "jtreader.worker.ts", commands: ["jtreader.createRecompute", "jtreader.document", "jtreader.inspectSourceInventory", "jtreader.saveReopen"], objectTypeCount: 1, pythonApiCount: 0, guiDependency: false, formatExtensions: [".fcstd", ".jt"] },
|
||||
{ module: "Material", workers: ["material-python.worker.ts", "material.worker.ts"], primaryWorker: "material-python.worker.ts", commands: ["material.createRecompute", "material.inspectSourceInventory", "material.pythonApi", "material.pythonFamilyBatch", "material.saveReopen"], objectTypeCount: 22, pythonApiCount: 178, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Measure", workers: ["measure.worker.ts"], primaryWorker: "measure.worker.ts", commands: ["measure.createRecompute", "measure.inspectSourceInventory", "measure.measurementApi", "measure.objectFamily", "measure.pythonApi", "measure.pythonFamilyBatch", "measure.saveReopen"], objectTypeCount: 11, pythonApiCount: 31, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Mesh", workers: ["mesh.worker.ts"], primaryWorker: "mesh.worker.ts", commands: ["mesh.createRecompute", "mesh.importExport", "mesh.inspectSourceInventory", "mesh.pythonApi", "mesh.pythonFamilyBatch", "mesh.saveReopen"], objectTypeCount: 31, pythonApiCount: 211, guiDependency: true, formatExtensions: [".3mf", ".amf", ".ast", ".obj", ".off", ".ply", ".stl"] },
|
||||
{ module: "MeshPart", workers: ["meshpart.worker.ts"], primaryWorker: "meshpart.worker.ts", commands: ["meshpart.createRecompute", "meshpart.inspectSourceInventory", "meshpart.pythonApi", "meshpart.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 13, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Part", workers: ["part-save.worker.ts", "part.worker.ts"], primaryWorker: "part.worker.ts", commands: ["part.createRecompute", "part.document", "part.documentViewCommand", "part.importExport", "part.inspectSourceInventory", "part.pythonApi", "part.pythonFamilyBatch", "part.pythonMethod", "part.saveReopen", "part.viewCommand"], objectTypeCount: 116, pythonApiCount: 1191, guiDependency: true, formatExtensions: [".brep", ".brp", ".fcstd", ".iges", ".igs", ".obj", ".step", ".stp", ".svg"] },
|
||||
{ module: "PartDesign", workers: ["partdesign-inspect.worker.ts", "partdesign-python.worker.ts", "partdesign-save.worker.ts", "partdesign.worker.ts"], primaryWorker: "partdesign.worker.ts", commands: ["PartDesign_AdditiveHelix", "PartDesign_AdditiveLoft", "PartDesign_AdditivePipe", "PartDesign_Body", "PartDesign_Boolean", "PartDesign_Chamfer", "PartDesign_Clone", "PartDesign_CompDatums", "PartDesign_CompPrimitiveAdditive", "PartDesign_CompPrimitiveSubtractive", "PartDesign_CompSketches", "PartDesign_CoordinateSystem", "PartDesign_Draft", "PartDesign_DuplicateSelection", "PartDesign_Fillet", "PartDesign_Groove", "PartDesign_Hole", "PartDesign_InvoluteGear", "PartDesign_Line", "PartDesign_LinearPattern", "PartDesign_Migrate", "PartDesign_Mirrored", "PartDesign_MoveFeature", "PartDesign_MoveFeatureInTree", "PartDesign_MoveTip", "PartDesign_MultiTransform", "PartDesign_NewSketch", "PartDesign_Pad", "PartDesign_Plane", "PartDesign_Pocket", "PartDesign_Point", "PartDesign_PolarPattern", "PartDesign_Revolution", "PartDesign_Scaled", "PartDesign_ShapeBinder", "PartDesign_Sprocket", "PartDesign_SubShapeBinder", "PartDesign_SubtractiveHelix", "PartDesign_SubtractiveLoft", "PartDesign_SubtractivePipe", "PartDesign_Thickness", "Sketcher_EditSketch", "Sketcher_MapSketch", "partdesign.createRecompute", "partdesign.document", "partdesign.geometryFamily", "partdesign.inspectSourceInventory", "partdesign.pythonApi", "partdesign.pythonFamilyBatch", "partdesign.saveReopen"], objectTypeCount: 65, pythonApiCount: 238, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Plot", workers: ["plot-python.worker.ts"], primaryWorker: "plot-python.worker.ts", commands: ["plot.pythonApi", "plot.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 28, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Points", workers: ["points-persistence.worker.ts", "points.worker.ts"], primaryWorker: "points.worker.ts", commands: ["points.createRecompute", "points.desktopBatch", "points.document", "points.inspectSource", "points.pythonApi", "points.pythonFamilyBatch", "points.saveReopen"], objectTypeCount: 8, pythonApiCount: 12, guiDependency: true, formatExtensions: [".obj", ".ply"] },
|
||||
{ module: "ReverseEngineering", workers: ["reverseengineering-create.worker.ts", "reverseengineering-inspect.worker.ts", "reverseengineering-python.worker.ts", "reverseengineering-save.worker.ts"], primaryWorker: "reverseengineering-create.worker.ts", commands: ["reverseengineering.createRecompute", "reverseengineering.inspectSourceInventory", "reverseengineering.pythonApi", "reverseengineering.pythonFamilyBatch", "reverseengineering.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Robot", workers: ["robot-create.worker.ts", "robot-inspect.worker.ts", "robot-python.worker.ts", "robot-save.worker.ts"], primaryWorker: "robot-create.worker.ts", commands: ["robot.createRecompute", "robot.inspectSourceInventory", "robot.pythonApi", "robot.pythonFamilyBatch", "robot.saveReopen"], objectTypeCount: 6, pythonApiCount: 16, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Sandbox", workers: ["sandbox-inspect.worker.ts", "sandbox-python.worker.ts", "sandbox-save.worker.ts", "sandbox.worker.ts"], primaryWorker: "sandbox-inspect.worker.ts", commands: ["sandbox.createRecompute", "sandbox.inspectSourceInventory", "sandbox.pythonApi", "sandbox.pythonFamilyBatch", "sandbox.saveReopen"], objectTypeCount: 2, pythonApiCount: 30, guiDependency: true, formatExtensions: [".ast", ".obj", ".stl"] },
|
||||
{ module: "Show", workers: ["show-inspect.worker.ts", "show-python.worker.ts"], primaryWorker: "show-inspect.worker.ts", commands: ["show.clipping", "show.documentLifecycle", "show.inspectSourceInventory", "show.pythonApi", "show.pythonFamilyBatch", "show.visibility"], objectTypeCount: 0, pythonApiCount: 104, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Sketcher", workers: ["sketcher-inspect.worker.ts", "sketcher-persistence.worker.ts", "sketcher-python.worker.ts", "sketcher.worker.ts"], primaryWorker: "sketcher.worker.ts", commands: ["sketcher.createRecompute", "sketcher.inspectSourceInventory", "sketcher.pythonApi", "sketcher.pythonFamilyBatch", "sketcher.pythonMethod", "sketcher.saveReopen"], objectTypeCount: 10, pythonApiCount: 141, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Spreadsheet", workers: ["spreadsheet-inspect.worker.ts", "spreadsheet-python.worker.ts", "spreadsheet-save.worker.ts", "spreadsheet.worker.ts"], primaryWorker: "spreadsheet-inspect.worker.ts", commands: ["spreadsheet.createRecompute", "spreadsheet.importExportCsv", "spreadsheet.inspectSourceInventory", "spreadsheet.pythonApi", "spreadsheet.pythonFamilyBatch", "spreadsheet.saveReopen"], objectTypeCount: 5, pythonApiCount: 63, guiDependency: true, formatExtensions: [".csv"] },
|
||||
{ module: "Start", workers: ["start-inventory.worker.ts", "start-python.worker.ts", "start.worker.ts"], primaryWorker: "start-inventory.worker.ts", commands: ["Start:desktop:Start_Start", "start.importSvg", "start.inspectSourceInventory", "start.moduleImport", "start.pythonApi"], objectTypeCount: 0, pythonApiCount: 2, guiDependency: true, formatExtensions: [".fcstd", ".svg"] },
|
||||
{ module: "Surface", workers: ["surface-inspect.worker.ts", "surface-python.worker.ts", "surface-save.worker.ts", "surface.worker.ts"], primaryWorker: "surface-inspect.worker.ts", commands: ["surface.createRecompute", "surface.desktopCommand", "surface.inspectSourceInventory", "surface.objectContractBatch", "surface.pythonApi", "surface.pythonFamilyBatch", "surface.saveReopen"], objectTypeCount: 7, pythonApiCount: 10, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "TechDraw", workers: ["techdraw-inspect.worker.ts", "techdraw-native.worker.ts", "techdraw-python.worker.ts", "techdraw-save.worker.ts", "techdraw.worker.ts"], primaryWorker: "techdraw-native.worker.ts", commands: ["techdraw.createRecompute", "techdraw.desktopCommand", "techdraw.nativeImportExport", "techdraw.nativeInventory", "techdraw.nativeSaveReopen", "techdraw.pythonApi", "techdraw.pythonFamilyBatch", "techdraw.pythonMethod"], objectTypeCount: 41, pythonApiCount: 247, guiDependency: true, formatExtensions: [".dxf", ".svg"] },
|
||||
{ module: "TemplatePyMod", workers: ["templatepymod-python.worker.ts", "templatepymod.worker.ts"], primaryWorker: "templatepymod-python.worker.ts", commands: ["templatepymod.inspectSourceInventory", "templatepymod.pythonApi", "templatepymod.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 244, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Test", workers: ["test.worker.ts"], primaryWorker: "test.worker.ts", commands: ["test.inspectRegistry"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: true, formatExtensions: [".fcstd", ".obj"] },
|
||||
{ module: "Tux", workers: ["tux.worker.ts"], primaryWorker: "tux.worker.ts", commands: ["tux.navigationBoundary"], objectTypeCount: 0, pythonApiCount: 25, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Web", workers: ["stateful-family.worker.ts", "web-dock-overlay.worker.ts", "web-persistence.worker.ts", "web.worker.ts"], primaryWorker: "stateful-family.worker.ts", commands: ["web.dockOverlay", "web.saveReopenBoundary", "web.serverContract", "web.statefulFamilyBatch"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: false, formatExtensions: [] },
|
||||
] as const satisfies readonly WebModuleRoute[];
|
||||
|
||||
const ROUTES: ReadonlyMap<string, WebModuleRoute> = new Map<string, WebModuleRoute>(WEB_MODULE_REGISTRY.map((route) => [route.module, route]));
|
||||
|
||||
export function getWebModuleRoute(module: string): WebModuleRoute | undefined {
|
||||
return ROUTES.get(module);
|
||||
}
|
||||
|
||||
export function listWebModuleCommands(module?: string): string[] {
|
||||
if (module) return [...(ROUTES.get(module)?.commands ?? [])];
|
||||
return WEB_MODULE_REGISTRY.flatMap((route) => route.commands);
|
||||
}
|
||||
341
web/src/module-registry.generated.ts
Normal file
341
web/src/module-registry.generated.ts
Normal file
@@ -0,0 +1,341 @@
|
||||
/* Generated by tools/generate_web_module_registry.py. */
|
||||
import { artifactForWorker, createDynamicModuleWorker, type WebModuleArtifact } from "./module-loader.js";
|
||||
import workerEntry0 from "./assembly.worker.ts?worker&url";
|
||||
import workerEntry1 from "./bim.worker.ts?worker&url";
|
||||
import workerEntry2 from "./cam.worker.ts?worker&url";
|
||||
import workerEntry3 from "./cloud.worker.ts?worker&url";
|
||||
import workerEntry4 from "./draft.worker.ts?worker&url";
|
||||
import workerEntry5 from "./fem.worker.ts?worker&url";
|
||||
import workerEntry6 from "./help.worker.ts?worker&url";
|
||||
import workerEntry7 from "./import.worker.ts?worker&url";
|
||||
import workerEntry8 from "./inspection.worker.ts?worker&url";
|
||||
import workerEntry9 from "./jtreader.worker.ts?worker&url";
|
||||
import workerEntry10 from "./material-python.worker.ts?worker&url";
|
||||
import workerEntry11 from "./material.worker.ts?worker&url";
|
||||
import workerEntry12 from "./measure.worker.ts?worker&url";
|
||||
import workerEntry13 from "./mesh.worker.ts?worker&url";
|
||||
import workerEntry14 from "./meshpart.worker.ts?worker&url";
|
||||
import workerEntry15 from "./part-save.worker.ts?worker&url";
|
||||
import workerEntry16 from "./part.worker.ts?worker&url";
|
||||
import workerEntry17 from "./partdesign-inspect.worker.ts?worker&url";
|
||||
import workerEntry18 from "./partdesign-python.worker.ts?worker&url";
|
||||
import workerEntry19 from "./partdesign-save.worker.ts?worker&url";
|
||||
import workerEntry20 from "./partdesign.worker.ts?worker&url";
|
||||
import workerEntry21 from "./plot-python.worker.ts?worker&url";
|
||||
import workerEntry22 from "./points-persistence.worker.ts?worker&url";
|
||||
import workerEntry23 from "./points.worker.ts?worker&url";
|
||||
import workerEntry24 from "./reverseengineering-create.worker.ts?worker&url";
|
||||
import workerEntry25 from "./reverseengineering-inspect.worker.ts?worker&url";
|
||||
import workerEntry26 from "./reverseengineering-python.worker.ts?worker&url";
|
||||
import workerEntry27 from "./reverseengineering-save.worker.ts?worker&url";
|
||||
import workerEntry28 from "./robot-create.worker.ts?worker&url";
|
||||
import workerEntry29 from "./robot-inspect.worker.ts?worker&url";
|
||||
import workerEntry30 from "./robot-python.worker.ts?worker&url";
|
||||
import workerEntry31 from "./robot-save.worker.ts?worker&url";
|
||||
import workerEntry32 from "./sandbox-inspect.worker.ts?worker&url";
|
||||
import workerEntry33 from "./sandbox-python.worker.ts?worker&url";
|
||||
import workerEntry34 from "./sandbox-save.worker.ts?worker&url";
|
||||
import workerEntry35 from "./sandbox.worker.ts?worker&url";
|
||||
import workerEntry36 from "./show-inspect.worker.ts?worker&url";
|
||||
import workerEntry37 from "./show-python.worker.ts?worker&url";
|
||||
import workerEntry38 from "./sketcher-inspect.worker.ts?worker&url";
|
||||
import workerEntry39 from "./sketcher-persistence.worker.ts?worker&url";
|
||||
import workerEntry40 from "./sketcher-python.worker.ts?worker&url";
|
||||
import workerEntry41 from "./sketcher.worker.ts?worker&url";
|
||||
import workerEntry42 from "./spreadsheet-inspect.worker.ts?worker&url";
|
||||
import workerEntry43 from "./spreadsheet-python.worker.ts?worker&url";
|
||||
import workerEntry44 from "./spreadsheet-save.worker.ts?worker&url";
|
||||
import workerEntry45 from "./spreadsheet.worker.ts?worker&url";
|
||||
import workerEntry46 from "./start-inventory.worker.ts?worker&url";
|
||||
import workerEntry47 from "./start-python.worker.ts?worker&url";
|
||||
import workerEntry48 from "./start.worker.ts?worker&url";
|
||||
import workerEntry49 from "./surface-inspect.worker.ts?worker&url";
|
||||
import workerEntry50 from "./surface-python.worker.ts?worker&url";
|
||||
import workerEntry51 from "./surface-save.worker.ts?worker&url";
|
||||
import workerEntry52 from "./surface.worker.ts?worker&url";
|
||||
import workerEntry53 from "./techdraw-inspect.worker.ts?worker&url";
|
||||
import workerEntry54 from "./techdraw-native.worker.ts?worker&url";
|
||||
import workerEntry55 from "./techdraw-python.worker.ts?worker&url";
|
||||
import workerEntry56 from "./techdraw-save.worker.ts?worker&url";
|
||||
import workerEntry57 from "./techdraw.worker.ts?worker&url";
|
||||
import workerEntry58 from "./templatepymod-python.worker.ts?worker&url";
|
||||
import workerEntry59 from "./templatepymod.worker.ts?worker&url";
|
||||
import workerEntry60 from "./test.worker.ts?worker&url";
|
||||
import workerEntry61 from "./tux.worker.ts?worker&url";
|
||||
import workerEntry62 from "./web-dock-overlay.worker.ts?worker&url";
|
||||
import workerEntry63 from "./web-persistence.worker.ts?worker&url";
|
||||
import workerEntry64 from "./web.worker.ts?worker&url";
|
||||
|
||||
export const WEB_MODULE_REGISTRY_SCHEMA = "freecad-web-module-registry/v1" as const;
|
||||
|
||||
export interface WebModuleRoute {
|
||||
readonly module: string;
|
||||
readonly workers: readonly string[];
|
||||
readonly primaryWorker: string | null;
|
||||
readonly commands: readonly string[];
|
||||
readonly objectTypeCount: number;
|
||||
readonly pythonApiCount: number;
|
||||
readonly guiDependency: boolean;
|
||||
readonly formatExtensions: readonly string[];
|
||||
}
|
||||
|
||||
export const WEB_MODULE_REGISTRY = [
|
||||
{ module: "Assembly", workers: ["assembly.worker.ts"], primaryWorker: "assembly.worker.ts", commands: ["assembly.createRecompute", "assembly.inspectPythonApi", "assembly.inspectSourceInventory", "assembly.nativeTypeProbe", "assembly.pythonFamily", "assembly.saveReopen", "assembly.testCore"], objectTypeCount: 8, pythonApiCount: 552, guiDependency: true, formatExtensions: [".fcstd"] },
|
||||
{ module: "BIM", workers: ["bim.worker.ts"], primaryWorker: "bim.worker.ts", commands: ["bim.create2DViews", "bim.createAxis", "bim.document", "bim.extrusionData", "bim.inspectPythonApi", "bim.inspectSourceInventory", "bim.nativeProbe", "bim.pythonFamily", "bim.pythonFamilyBatch", "bim.testArchAxis", "bim.testArchBatch", "bim.testArchBuildingPart", "bim.testArchBuildingPartGui", "bim.testArchComponent", "bim.testArchCurtainWall", "bim.testArchEquipment", "bim.testArchFence", "bim.testArchFrame", "bim.testArchGrid", "bim.testArchImporters", "bim.testArchMaterial", "bim.testArchPanel", "bim.testArchPipe", "bim.testArchProfile", "bim.testArchProject", "bim.testArchRebar", "bim.testArchReference", "bim.testArchReport", "bim.testArchReportGui", "bim.testArchSiteGui", "bim.testArchWallGui", "bim.testWebGLExportGui"], objectTypeCount: 0, pythonApiCount: 2366, guiDependency: false, formatExtensions: [".brp", ".dae", ".dxf", ".fcstd", ".ifc", ".json", ".obj", ".stp", ".svg"] },
|
||||
{ module: "CAM", workers: ["cam.worker.ts"], primaryWorker: "cam.worker.ts", commands: ["cam.createRecompute", "cam.export", "cam.import", "cam.inspectPythonApi", "cam.inspectSourceInventory", "cam.pythonFamilyBatch", "cam.saveReopen", "cam.testCentroidLegacyPost", "cam.testCentroidPost", "cam.testDressupPost", "cam.testDrillCycleExpander", "cam.testFanucPost", "cam.testGcodeProcessingUtils", "cam.testGenericPlasma", "cam.testGenericPost", "cam.testGrblLegacyPost", "cam.testGrblPost", "cam.testLinkingGenerator", "cam.testLinuxCNCLegacyPost", "cam.testLinuxCNCPost", "cam.testMach3Mach4LegacyPost", "cam.testMach3Mach4Post", "cam.testMachine", "cam.testMassoG3Post", "cam.testMaterial", "cam.testPathAdaptive", "cam.testPathCommandAnnotations", "cam.testPathCore", "cam.testPathDepthParams", "cam.testPathDressupArray", "cam.testPathDressupDogboneII", "cam.testPathDressupHoldingTags", "cam.testPathDrillGenerator", "cam.testPathDrillable", "cam.testPathFacingGenerator", "cam.testPathGeneratorDogboneII", "cam.testPathGeom", "cam.testPathHelix", "cam.testPathHelixGenerator", "cam.testPathHelpers", "cam.testPathLanguage", "cam.testPathLog", "cam.testPathOpDeburr", "cam.testPathOpUtil", "cam.testPathPreferences", "cam.testPathProfile", "cam.testPathPropertyBag", "cam.testPathRotationGenerator", "cam.testPathSetupSheet", "cam.testPathSpiralGenerator", "cam.testPathStock", "cam.testPathTapGenerator", "cam.testPathThreadMilling", "cam.testPathThreadMillingGenerator", "cam.testPathToolAsset", "cam.testPathToolAssetCache", "cam.testPathToolAssetManager", "cam.testPathToolAssetStore", "cam.testPathToolAssetUri", "cam.testPathToolBit", "cam.testPathToolBitSerializer", "cam.testPathToolChangeGenerator", "cam.testPathToolController", "cam.testPathToolLibrary", "cam.testPathToolLibrarySerializer", "cam.testPathToolShapeClasses", "cam.testPathToolShapeDoc", "cam.testPathUtil", "cam.testPathVcarve", "cam.testPathVoronoi", "cam.testPostCore", "cam.testPostGCodes", "cam.testPostMCodes", "cam.testSanity", "cam.testSnapmakerPost", "cam.testTSPSolver", "cam.testTestPost"], objectTypeCount: 12, pythonApiCount: 2883, guiDependency: true, formatExtensions: [".fcstd", ".json", ".obj", ".step", ".svg"] },
|
||||
{ module: "Cloud", workers: ["cloud.worker.ts"], primaryWorker: "cloud.worker.ts", commands: ["cloud.configureRecompute", "cloud.inspectPythonApi", "cloud.inspectSourceInventory", "cloud.pythonFamilyBatch", "cloud.restore", "cloud.save", "cloud.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Draft", workers: ["draft.worker.ts"], primaryWorker: "draft.worker.ts", commands: ["draft.action", "draft.formatBatch", "draft.pythonFamilyBatch", "draft.testOfficialSuite"], objectTypeCount: 0, pythonApiCount: 2043, guiDependency: false, formatExtensions: [".dxf", ".obj", ".svg"] },
|
||||
{ module: "Fem", workers: ["fem.worker.ts"], primaryWorker: "fem.worker.ts", commands: ["fem.action", "fem.brep", "fem.document", "fem.nativeProbe", "fem.pythonFamilyBatch"], objectTypeCount: 53, pythonApiCount: 1305, guiDependency: true, formatExtensions: [".brep", ".json", ".obj", ".svg", ".txt"] },
|
||||
{ module: "Help", workers: ["help.worker.ts"], primaryWorker: "help.worker.ts", commands: ["help.inspectSourceInventory", "help.pythonApi"], objectTypeCount: 0, pythonApiCount: 14, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Import", workers: ["import.worker.ts"], primaryWorker: "import.worker.ts", commands: ["import.createRecompute", "import.inspectSourceInventory", "import.pythonApi", "import.pythonFamilyBatch", "import.saveReopen", "import.step"], objectTypeCount: 2, pythonApiCount: 1135, guiDependency: true, formatExtensions: [".ifc", ".igs", ".obj", ".step", ".stp"] },
|
||||
{ module: "Inspection", workers: ["inspection.worker.ts"], primaryWorker: "inspection.worker.ts", commands: ["inspection.createRecompute", "inspection.inspectPythonApi", "inspection.inspectSourceInventory", "inspection.pythonFamilyBatch", "inspection.saveReopen"], objectTypeCount: 3, pythonApiCount: 3, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "JtReader", workers: ["jtreader.worker.ts"], primaryWorker: "jtreader.worker.ts", commands: ["jtreader.createRecompute", "jtreader.document", "jtreader.inspectSourceInventory", "jtreader.saveReopen"], objectTypeCount: 1, pythonApiCount: 0, guiDependency: false, formatExtensions: [".fcstd", ".jt"] },
|
||||
{ module: "Material", workers: ["material-python.worker.ts", "material.worker.ts"], primaryWorker: "material-python.worker.ts", commands: ["material.createRecompute", "material.inspectSourceInventory", "material.pythonApi", "material.pythonFamilyBatch", "material.saveReopen"], objectTypeCount: 22, pythonApiCount: 178, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Measure", workers: ["measure.worker.ts"], primaryWorker: "measure.worker.ts", commands: ["measure.createRecompute", "measure.inspectSourceInventory", "measure.measurementApi", "measure.objectFamily", "measure.pythonApi", "measure.pythonFamilyBatch", "measure.saveReopen"], objectTypeCount: 11, pythonApiCount: 31, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Mesh", workers: ["mesh.worker.ts"], primaryWorker: "mesh.worker.ts", commands: ["mesh.createRecompute", "mesh.importExport", "mesh.inspectSourceInventory", "mesh.pythonApi", "mesh.pythonFamilyBatch", "mesh.saveReopen"], objectTypeCount: 31, pythonApiCount: 211, guiDependency: true, formatExtensions: [".3mf", ".amf", ".ast", ".obj", ".off", ".ply", ".stl"] },
|
||||
{ module: "MeshPart", workers: ["meshpart.worker.ts"], primaryWorker: "meshpart.worker.ts", commands: ["meshpart.createRecompute", "meshpart.inspectSourceInventory", "meshpart.pythonApi", "meshpart.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 13, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Part", workers: ["part-save.worker.ts", "part.worker.ts"], primaryWorker: "part.worker.ts", commands: ["part.createRecompute", "part.document", "part.documentViewCommand", "part.importExport", "part.inspectSourceInventory", "part.pythonApi", "part.pythonFamilyBatch", "part.pythonMethod", "part.saveReopen", "part.viewCommand"], objectTypeCount: 116, pythonApiCount: 1191, guiDependency: true, formatExtensions: [".brep", ".brp", ".fcstd", ".iges", ".igs", ".obj", ".step", ".stp", ".svg"] },
|
||||
{ module: "PartDesign", workers: ["partdesign-inspect.worker.ts", "partdesign-python.worker.ts", "partdesign-save.worker.ts", "partdesign.worker.ts"], primaryWorker: "partdesign.worker.ts", commands: ["PartDesign_AdditiveHelix", "PartDesign_AdditiveLoft", "PartDesign_AdditivePipe", "PartDesign_Body", "PartDesign_Boolean", "PartDesign_Chamfer", "PartDesign_Clone", "PartDesign_CompDatums", "PartDesign_CompPrimitiveAdditive", "PartDesign_CompPrimitiveSubtractive", "PartDesign_CompSketches", "PartDesign_CoordinateSystem", "PartDesign_Draft", "PartDesign_DuplicateSelection", "PartDesign_Fillet", "PartDesign_Groove", "PartDesign_Hole", "PartDesign_InvoluteGear", "PartDesign_Line", "PartDesign_LinearPattern", "PartDesign_Migrate", "PartDesign_Mirrored", "PartDesign_MoveFeature", "PartDesign_MoveFeatureInTree", "PartDesign_MoveTip", "PartDesign_MultiTransform", "PartDesign_NewSketch", "PartDesign_Pad", "PartDesign_Plane", "PartDesign_Pocket", "PartDesign_Point", "PartDesign_PolarPattern", "PartDesign_Revolution", "PartDesign_Scaled", "PartDesign_ShapeBinder", "PartDesign_Sprocket", "PartDesign_SubShapeBinder", "PartDesign_SubtractiveHelix", "PartDesign_SubtractiveLoft", "PartDesign_SubtractivePipe", "PartDesign_Thickness", "Sketcher_EditSketch", "Sketcher_MapSketch", "partdesign.createRecompute", "partdesign.document", "partdesign.geometryFamily", "partdesign.inspectSourceInventory", "partdesign.pythonApi", "partdesign.pythonFamilyBatch", "partdesign.saveReopen"], objectTypeCount: 65, pythonApiCount: 238, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Plot", workers: ["plot-python.worker.ts"], primaryWorker: "plot-python.worker.ts", commands: ["plot.pythonApi", "plot.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 28, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Points", workers: ["points-persistence.worker.ts", "points.worker.ts"], primaryWorker: "points.worker.ts", commands: ["points.createRecompute", "points.desktopBatch", "points.document", "points.inspectSource", "points.pythonApi", "points.pythonFamilyBatch", "points.saveReopen"], objectTypeCount: 8, pythonApiCount: 12, guiDependency: true, formatExtensions: [".obj", ".ply"] },
|
||||
{ module: "ReverseEngineering", workers: ["reverseengineering-create.worker.ts", "reverseengineering-inspect.worker.ts", "reverseengineering-python.worker.ts", "reverseengineering-save.worker.ts"], primaryWorker: "reverseengineering-create.worker.ts", commands: ["reverseengineering.createRecompute", "reverseengineering.inspectSourceInventory", "reverseengineering.pythonApi", "reverseengineering.pythonFamilyBatch", "reverseengineering.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Robot", workers: ["robot-create.worker.ts", "robot-inspect.worker.ts", "robot-python.worker.ts", "robot-save.worker.ts"], primaryWorker: "robot-create.worker.ts", commands: ["robot.createRecompute", "robot.inspectSourceInventory", "robot.pythonApi", "robot.pythonFamilyBatch", "robot.saveReopen"], objectTypeCount: 6, pythonApiCount: 16, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Sandbox", workers: ["sandbox-inspect.worker.ts", "sandbox-python.worker.ts", "sandbox-save.worker.ts", "sandbox.worker.ts"], primaryWorker: "sandbox-inspect.worker.ts", commands: ["sandbox.createRecompute", "sandbox.inspectSourceInventory", "sandbox.pythonApi", "sandbox.pythonFamilyBatch", "sandbox.saveReopen"], objectTypeCount: 2, pythonApiCount: 30, guiDependency: true, formatExtensions: [".ast", ".obj", ".stl"] },
|
||||
{ module: "Show", workers: ["show-inspect.worker.ts", "show-python.worker.ts"], primaryWorker: "show-inspect.worker.ts", commands: ["show.clipping", "show.documentLifecycle", "show.inspectSourceInventory", "show.pythonApi", "show.pythonFamilyBatch", "show.visibility"], objectTypeCount: 0, pythonApiCount: 104, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Sketcher", workers: ["sketcher-inspect.worker.ts", "sketcher-persistence.worker.ts", "sketcher-python.worker.ts", "sketcher.worker.ts"], primaryWorker: "sketcher.worker.ts", commands: ["sketcher.createRecompute", "sketcher.inspectSourceInventory", "sketcher.pythonApi", "sketcher.pythonFamilyBatch", "sketcher.pythonMethod", "sketcher.saveReopen"], objectTypeCount: 10, pythonApiCount: 141, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "Spreadsheet", workers: ["spreadsheet-inspect.worker.ts", "spreadsheet-python.worker.ts", "spreadsheet-save.worker.ts", "spreadsheet.worker.ts"], primaryWorker: "spreadsheet-inspect.worker.ts", commands: ["spreadsheet.createRecompute", "spreadsheet.importExportCsv", "spreadsheet.inspectSourceInventory", "spreadsheet.pythonApi", "spreadsheet.pythonFamilyBatch", "spreadsheet.saveReopen"], objectTypeCount: 5, pythonApiCount: 63, guiDependency: true, formatExtensions: [".csv"] },
|
||||
{ module: "Start", workers: ["start-inventory.worker.ts", "start-python.worker.ts", "start.worker.ts"], primaryWorker: "start-inventory.worker.ts", commands: ["Start:desktop:Start_Start", "start.importSvg", "start.inspectSourceInventory", "start.moduleImport", "start.pythonApi"], objectTypeCount: 0, pythonApiCount: 2, guiDependency: true, formatExtensions: [".fcstd", ".svg"] },
|
||||
{ module: "Surface", workers: ["surface-inspect.worker.ts", "surface-python.worker.ts", "surface-save.worker.ts", "surface.worker.ts"], primaryWorker: "surface-inspect.worker.ts", commands: ["surface.createRecompute", "surface.desktopCommand", "surface.inspectSourceInventory", "surface.objectContractBatch", "surface.pythonApi", "surface.pythonFamilyBatch", "surface.saveReopen"], objectTypeCount: 7, pythonApiCount: 10, guiDependency: true, formatExtensions: [] },
|
||||
{ module: "TechDraw", workers: ["techdraw-inspect.worker.ts", "techdraw-native.worker.ts", "techdraw-python.worker.ts", "techdraw-save.worker.ts", "techdraw.worker.ts"], primaryWorker: "techdraw-native.worker.ts", commands: ["techdraw.createRecompute", "techdraw.desktopCommand", "techdraw.nativeImportExport", "techdraw.nativeInventory", "techdraw.nativeSaveReopen", "techdraw.pythonApi", "techdraw.pythonFamilyBatch", "techdraw.pythonMethod"], objectTypeCount: 41, pythonApiCount: 247, guiDependency: true, formatExtensions: [".dxf", ".svg"] },
|
||||
{ module: "TemplatePyMod", workers: ["templatepymod-python.worker.ts", "templatepymod.worker.ts"], primaryWorker: "templatepymod-python.worker.ts", commands: ["templatepymod.inspectSourceInventory", "templatepymod.pythonApi", "templatepymod.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 244, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Test", workers: ["test.worker.ts"], primaryWorker: "test.worker.ts", commands: ["test.inspectRegistry"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: true, formatExtensions: [".fcstd", ".obj"] },
|
||||
{ module: "Tux", workers: ["tux.worker.ts"], primaryWorker: "tux.worker.ts", commands: ["tux.navigationBoundary"], objectTypeCount: 0, pythonApiCount: 25, guiDependency: false, formatExtensions: [] },
|
||||
{ module: "Web", workers: ["stateful-family.worker.ts", "web-dock-overlay.worker.ts", "web-persistence.worker.ts", "web.worker.ts"], primaryWorker: "stateful-family.worker.ts", commands: ["web.dockOverlay", "web.saveReopenBoundary", "web.serverContract", "web.statefulFamilyBatch"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: false, formatExtensions: [] },
|
||||
] as const satisfies readonly WebModuleRoute[];
|
||||
|
||||
const ROUTES: ReadonlyMap<string, WebModuleRoute> = new Map<string, WebModuleRoute>(WEB_MODULE_REGISTRY.map((route) => [route.module, route]));
|
||||
|
||||
export function getWebModuleRoute(module: string): WebModuleRoute | undefined {
|
||||
return ROUTES.get(module);
|
||||
}
|
||||
|
||||
export function listWebModuleCommands(module?: string): string[] {
|
||||
if (module) return [...(ROUTES.get(module)?.commands ?? [])];
|
||||
return WEB_MODULE_REGISTRY.flatMap((route) => route.commands);
|
||||
}
|
||||
|
||||
export function createWebModuleWorker(module: string, workerFile?: string, artifact?: WebModuleArtifact): Worker | undefined {
|
||||
const route = ROUTES.get(module);
|
||||
const selectedWorker = workerFile ?? route?.primaryWorker;
|
||||
if (!route || !selectedWorker) return undefined;
|
||||
const entryUrl = (() => { switch (`${module}:${selectedWorker}`) {
|
||||
case "Assembly:assembly.worker.ts": return new URL(workerEntry0, import.meta.url);
|
||||
case "BIM:bim.worker.ts": return new URL(workerEntry1, import.meta.url);
|
||||
case "CAM:cam.worker.ts": return new URL(workerEntry2, import.meta.url);
|
||||
case "Cloud:cloud.worker.ts": return new URL(workerEntry3, import.meta.url);
|
||||
case "Draft:draft.worker.ts": return new URL(workerEntry4, import.meta.url);
|
||||
case "Fem:fem.worker.ts": return new URL(workerEntry5, import.meta.url);
|
||||
case "Help:help.worker.ts": return new URL(workerEntry6, import.meta.url);
|
||||
case "Import:import.worker.ts": return new URL(workerEntry7, import.meta.url);
|
||||
case "Inspection:inspection.worker.ts": return new URL(workerEntry8, import.meta.url);
|
||||
case "JtReader:jtreader.worker.ts": return new URL(workerEntry9, import.meta.url);
|
||||
case "Material:material-python.worker.ts": return new URL(workerEntry10, import.meta.url);
|
||||
case "Material:material.worker.ts": return new URL(workerEntry11, import.meta.url);
|
||||
case "Measure:measure.worker.ts": return new URL(workerEntry12, import.meta.url);
|
||||
case "Mesh:mesh.worker.ts": return new URL(workerEntry13, import.meta.url);
|
||||
case "MeshPart:meshpart.worker.ts": return new URL(workerEntry14, import.meta.url);
|
||||
case "Part:part-save.worker.ts": return new URL(workerEntry15, import.meta.url);
|
||||
case "Part:part.worker.ts": return new URL(workerEntry16, import.meta.url);
|
||||
case "PartDesign:partdesign-inspect.worker.ts": return new URL(workerEntry17, import.meta.url);
|
||||
case "PartDesign:partdesign-python.worker.ts": return new URL(workerEntry18, import.meta.url);
|
||||
case "PartDesign:partdesign-save.worker.ts": return new URL(workerEntry19, import.meta.url);
|
||||
case "PartDesign:partdesign.worker.ts": return new URL(workerEntry20, import.meta.url);
|
||||
case "Plot:plot-python.worker.ts": return new URL(workerEntry21, import.meta.url);
|
||||
case "Points:points-persistence.worker.ts": return new URL(workerEntry22, import.meta.url);
|
||||
case "Points:points.worker.ts": return new URL(workerEntry23, import.meta.url);
|
||||
case "ReverseEngineering:reverseengineering-create.worker.ts": return new URL(workerEntry24, import.meta.url);
|
||||
case "ReverseEngineering:reverseengineering-inspect.worker.ts": return new URL(workerEntry25, import.meta.url);
|
||||
case "ReverseEngineering:reverseengineering-python.worker.ts": return new URL(workerEntry26, import.meta.url);
|
||||
case "ReverseEngineering:reverseengineering-save.worker.ts": return new URL(workerEntry27, import.meta.url);
|
||||
case "Robot:robot-create.worker.ts": return new URL(workerEntry28, import.meta.url);
|
||||
case "Robot:robot-inspect.worker.ts": return new URL(workerEntry29, import.meta.url);
|
||||
case "Robot:robot-python.worker.ts": return new URL(workerEntry30, import.meta.url);
|
||||
case "Robot:robot-save.worker.ts": return new URL(workerEntry31, import.meta.url);
|
||||
case "Sandbox:sandbox-inspect.worker.ts": return new URL(workerEntry32, import.meta.url);
|
||||
case "Sandbox:sandbox-python.worker.ts": return new URL(workerEntry33, import.meta.url);
|
||||
case "Sandbox:sandbox-save.worker.ts": return new URL(workerEntry34, import.meta.url);
|
||||
case "Sandbox:sandbox.worker.ts": return new URL(workerEntry35, import.meta.url);
|
||||
case "Show:show-inspect.worker.ts": return new URL(workerEntry36, import.meta.url);
|
||||
case "Show:show-python.worker.ts": return new URL(workerEntry37, import.meta.url);
|
||||
case "Sketcher:sketcher-inspect.worker.ts": return new URL(workerEntry38, import.meta.url);
|
||||
case "Sketcher:sketcher-persistence.worker.ts": return new URL(workerEntry39, import.meta.url);
|
||||
case "Sketcher:sketcher-python.worker.ts": return new URL(workerEntry40, import.meta.url);
|
||||
case "Sketcher:sketcher.worker.ts": return new URL(workerEntry41, import.meta.url);
|
||||
case "Spreadsheet:spreadsheet-inspect.worker.ts": return new URL(workerEntry42, import.meta.url);
|
||||
case "Spreadsheet:spreadsheet-python.worker.ts": return new URL(workerEntry43, import.meta.url);
|
||||
case "Spreadsheet:spreadsheet-save.worker.ts": return new URL(workerEntry44, import.meta.url);
|
||||
case "Spreadsheet:spreadsheet.worker.ts": return new URL(workerEntry45, import.meta.url);
|
||||
case "Start:start-inventory.worker.ts": return new URL(workerEntry46, import.meta.url);
|
||||
case "Start:start-python.worker.ts": return new URL(workerEntry47, import.meta.url);
|
||||
case "Start:start.worker.ts": return new URL(workerEntry48, import.meta.url);
|
||||
case "Surface:surface-inspect.worker.ts": return new URL(workerEntry49, import.meta.url);
|
||||
case "Surface:surface-python.worker.ts": return new URL(workerEntry50, import.meta.url);
|
||||
case "Surface:surface-save.worker.ts": return new URL(workerEntry51, import.meta.url);
|
||||
case "Surface:surface.worker.ts": return new URL(workerEntry52, import.meta.url);
|
||||
case "TechDraw:techdraw-inspect.worker.ts": return new URL(workerEntry53, import.meta.url);
|
||||
case "TechDraw:techdraw-native.worker.ts": return new URL(workerEntry54, import.meta.url);
|
||||
case "TechDraw:techdraw-python.worker.ts": return new URL(workerEntry55, import.meta.url);
|
||||
case "TechDraw:techdraw-save.worker.ts": return new URL(workerEntry56, import.meta.url);
|
||||
case "TechDraw:techdraw.worker.ts": return new URL(workerEntry57, import.meta.url);
|
||||
case "TemplatePyMod:templatepymod-python.worker.ts": return new URL(workerEntry58, import.meta.url);
|
||||
case "TemplatePyMod:templatepymod.worker.ts": return new URL(workerEntry59, import.meta.url);
|
||||
case "Test:test.worker.ts": return new URL(workerEntry60, import.meta.url);
|
||||
case "Tux:tux.worker.ts": return new URL(workerEntry61, import.meta.url);
|
||||
case "Web:web-dock-overlay.worker.ts": return new URL(workerEntry62, import.meta.url);
|
||||
case "Web:web-persistence.worker.ts": return new URL(workerEntry63, import.meta.url);
|
||||
case "Web:web.worker.ts": return new URL(workerEntry64, import.meta.url);
|
||||
default: return undefined;
|
||||
} })();
|
||||
return entryUrl ? createDynamicModuleWorker(entryUrl, artifactForWorker(artifact, selectedWorker)) : undefined;
|
||||
}
|
||||
|
||||
export function getWebModuleWorkerForCommand(module: string, command: string): string | undefined {
|
||||
const route = ROUTES.get(module);
|
||||
if (!route) return undefined;
|
||||
switch (`${module}:${command}`) {
|
||||
case "Assembly:assembly.nativeTypeProbe": return "assembly.worker.ts";
|
||||
case "Assembly:assembly.saveReopen": return "assembly.worker.ts";
|
||||
case "BIM:bim.createAxis": return "bim.worker.ts";
|
||||
case "BIM:bim.extrusionData": return "bim.worker.ts";
|
||||
case "CAM:cam.pythonFamilyBatch": return "cam.worker.ts";
|
||||
case "CAM:cam.saveReopen": return "cam.worker.ts";
|
||||
case "Cloud:cloud.pythonFamilyBatch": return "cloud.worker.ts";
|
||||
case "Cloud:cloud.saveReopen": return "cloud.worker.ts";
|
||||
case "Draft:draft.pythonFamilyBatch": return "draft.worker.ts";
|
||||
case "Fem:fem.pythonFamilyBatch": return "fem.worker.ts";
|
||||
case "Import:import.pythonFamilyBatch": return "import.worker.ts";
|
||||
case "Import:import.saveReopen": return "import.worker.ts";
|
||||
case "Inspection:inspection.pythonFamilyBatch": return "inspection.worker.ts";
|
||||
case "Inspection:inspection.saveReopen": return "inspection.worker.ts";
|
||||
case "JtReader:jtreader.saveReopen": return "jtreader.worker.ts";
|
||||
case "Material:material.pythonApi": return "material.worker.ts";
|
||||
case "Material:material.pythonFamilyBatch": return "material.worker.ts";
|
||||
case "Material:material.saveReopen": return "material.worker.ts";
|
||||
case "Measure:measure.pythonFamilyBatch": return "measure.worker.ts";
|
||||
case "Measure:measure.saveReopen": return "measure.worker.ts";
|
||||
case "Mesh:mesh.pythonFamilyBatch": return "mesh.worker.ts";
|
||||
case "Mesh:mesh.saveReopen": return "mesh.worker.ts";
|
||||
case "MeshPart:meshpart.pythonFamilyBatch": return "meshpart.worker.ts";
|
||||
case "Part:part.document": return "part-save.worker.ts";
|
||||
case "Part:part.documentViewCommand": return "part-save.worker.ts";
|
||||
case "Part:part.saveReopen": return "part-save.worker.ts";
|
||||
case "Part:part.viewCommand": return "part.worker.ts";
|
||||
case "PartDesign:PartDesign_AdditiveHelix": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_AdditiveLoft": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_AdditivePipe": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Body": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Boolean": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Chamfer": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Clone": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_CompDatums": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_CompPrimitiveAdditive": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_CompPrimitiveSubtractive": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_CompSketches": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_CoordinateSystem": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Draft": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_DuplicateSelection": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Fillet": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Groove": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Hole": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_InvoluteGear": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Line": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_LinearPattern": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Migrate": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Mirrored": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_MoveFeature": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_MoveFeatureInTree": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_MoveTip": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_MultiTransform": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_NewSketch": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Pad": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Plane": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Pocket": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Point": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_PolarPattern": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Revolution": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Scaled": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_ShapeBinder": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Sprocket": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_SubShapeBinder": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_SubtractiveHelix": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_SubtractiveLoft": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_SubtractivePipe": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:PartDesign_Thickness": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:Sketcher_EditSketch": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:Sketcher_MapSketch": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:partdesign.geometryFamily": return "partdesign.worker.ts";
|
||||
case "PartDesign:partdesign.inspectSourceInventory": return "partdesign-inspect.worker.ts";
|
||||
case "PartDesign:partdesign.pythonApi": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:partdesign.pythonFamilyBatch": return "partdesign-python.worker.ts";
|
||||
case "PartDesign:partdesign.saveReopen": return "partdesign.worker.ts";
|
||||
case "Plot:plot.pythonApi": return "plot-python.worker.ts";
|
||||
case "Points:points.createRecompute": return "points.worker.ts";
|
||||
case "Points:points.desktopBatch": return "points.worker.ts";
|
||||
case "Points:points.document": return "points.worker.ts";
|
||||
case "Points:points.inspectSource": return "points.worker.ts";
|
||||
case "Points:points.pythonApi": return "points.worker.ts";
|
||||
case "Points:points.saveReopen": return "points.worker.ts";
|
||||
case "ReverseEngineering:reverseengineering.createRecompute": return "reverseengineering-create.worker.ts";
|
||||
case "ReverseEngineering:reverseengineering.inspectSourceInventory": return "reverseengineering-inspect.worker.ts";
|
||||
case "ReverseEngineering:reverseengineering.pythonApi": return "reverseengineering-python.worker.ts";
|
||||
case "ReverseEngineering:reverseengineering.pythonFamilyBatch": return "reverseengineering-python.worker.ts";
|
||||
case "ReverseEngineering:reverseengineering.saveReopen": return "reverseengineering-save.worker.ts";
|
||||
case "Robot:robot.createRecompute": return "robot-create.worker.ts";
|
||||
case "Robot:robot.inspectSourceInventory": return "robot-inspect.worker.ts";
|
||||
case "Robot:robot.pythonApi": return "robot-python.worker.ts";
|
||||
case "Robot:robot.saveReopen": return "robot-save.worker.ts";
|
||||
case "Sandbox:sandbox.createRecompute": return "sandbox.worker.ts";
|
||||
case "Sandbox:sandbox.inspectSourceInventory": return "sandbox-inspect.worker.ts";
|
||||
case "Sandbox:sandbox.pythonApi": return "sandbox-python.worker.ts";
|
||||
case "Sandbox:sandbox.pythonFamilyBatch": return "sandbox-python.worker.ts";
|
||||
case "Sandbox:sandbox.saveReopen": return "sandbox.worker.ts";
|
||||
case "Show:show.clipping": return "show-python.worker.ts";
|
||||
case "Show:show.documentLifecycle": return "show-python.worker.ts";
|
||||
case "Show:show.inspectSourceInventory": return "show-inspect.worker.ts";
|
||||
case "Show:show.pythonApi": return "show-python.worker.ts";
|
||||
case "Show:show.pythonFamilyBatch": return "show-python.worker.ts";
|
||||
case "Show:show.visibility": return "show-python.worker.ts";
|
||||
case "Sketcher:sketcher.inspectSourceInventory": return "sketcher-inspect.worker.ts";
|
||||
case "Sketcher:sketcher.pythonApi": return "sketcher-python.worker.ts";
|
||||
case "Sketcher:sketcher.pythonFamilyBatch": return "sketcher-python.worker.ts";
|
||||
case "Sketcher:sketcher.pythonMethod": return "sketcher-python.worker.ts";
|
||||
case "Sketcher:sketcher.saveReopen": return "sketcher-python.worker.ts";
|
||||
case "Spreadsheet:spreadsheet.createRecompute": return "spreadsheet.worker.ts";
|
||||
case "Spreadsheet:spreadsheet.inspectSourceInventory": return "spreadsheet-inspect.worker.ts";
|
||||
case "Spreadsheet:spreadsheet.pythonApi": return "spreadsheet-python.worker.ts";
|
||||
case "Spreadsheet:spreadsheet.pythonFamilyBatch": return "spreadsheet-python.worker.ts";
|
||||
case "Spreadsheet:spreadsheet.saveReopen": return "spreadsheet-save.worker.ts";
|
||||
case "Start:Start:desktop:Start_Start": return "start.worker.ts";
|
||||
case "Start:start.importSvg": return "start.worker.ts";
|
||||
case "Start:start.inspectSourceInventory": return "start-inventory.worker.ts";
|
||||
case "Start:start.moduleImport": return "start.worker.ts";
|
||||
case "Start:start.pythonApi": return "start-python.worker.ts";
|
||||
case "Surface:surface.createRecompute": return "surface.worker.ts";
|
||||
case "Surface:surface.inspectSourceInventory": return "surface-inspect.worker.ts";
|
||||
case "Surface:surface.pythonApi": return "surface-python.worker.ts";
|
||||
case "Surface:surface.pythonFamilyBatch": return "surface-python.worker.ts";
|
||||
case "Surface:surface.saveReopen": return "surface-save.worker.ts";
|
||||
case "TechDraw:techdraw.createRecompute": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.desktopCommand": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.nativeInventory": return "techdraw-inspect.worker.ts";
|
||||
case "TechDraw:techdraw.nativeSaveReopen": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonApi": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonFamilyBatch": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonMethod": return "techdraw-python.worker.ts";
|
||||
case "TemplatePyMod:templatepymod.pythonApi": return "templatepymod-python.worker.ts";
|
||||
case "Web:web.dockOverlay": return "web-dock-overlay.worker.ts";
|
||||
case "Web:web.saveReopenBoundary": return "web-persistence.worker.ts";
|
||||
case "Web:web.statefulFamilyBatch": return "stateful-family.worker.ts";
|
||||
default: return route.primaryWorker ?? undefined;
|
||||
}
|
||||
}
|
||||
352
web/src/module-router.ts
Normal file
352
web/src/module-router.ts
Normal file
@@ -0,0 +1,352 @@
|
||||
import type { TestViewExampleResult } from "./test-facade.js";
|
||||
import { executeMeasureDocument } from "./measure-document-adapter.js";
|
||||
import { executeMeshPartCurve } from "./meshpart-desktop-adapter.js";
|
||||
import { executeSurfaceDocument } from "./surface-document-adapter.js";
|
||||
import {
|
||||
createFailure,
|
||||
createSuccess,
|
||||
createCancel,
|
||||
createRequest,
|
||||
type FacadeFailure,
|
||||
type FacadeRequest,
|
||||
type FacadeResponse,
|
||||
} from "./facade-envelope.js";
|
||||
import { createWebModuleWorker, getWebModuleRoute, getWebModuleWorkerForCommand, type WebModuleRoute } from "./module-registry.generated.js";
|
||||
import { loadWebModuleManifest, type WebModuleArtifact } from "./module-loader.js";
|
||||
import { ResourceLifecycle } from "./resource-lifecycle.js";
|
||||
import { nativeSourceDecision } from "./native-source-policy.js";
|
||||
|
||||
type WorkerReady = { kind: "ready"; action: string };
|
||||
type WorkerReset = { kind: "reset"; requestId: string };
|
||||
type WorkerBootstrapError = { kind: "bootstrap-error"; message: string };
|
||||
type WorkerMessage = FacadeResponse | WorkerReady | WorkerReset | WorkerBootstrapError;
|
||||
|
||||
interface PendingRequest {
|
||||
resolve: (response: FacadeResponse) => void;
|
||||
reject: (error: Error) => void;
|
||||
cleanup?: () => void;
|
||||
}
|
||||
|
||||
interface ModuleSession {
|
||||
readonly route: WebModuleRoute;
|
||||
readonly worker: Worker;
|
||||
readonly ready: Promise<void>;
|
||||
readonly failReady: (error: Error) => void;
|
||||
readonly pending: Map<string, PendingRequest>;
|
||||
readonly artifactRevision?: string;
|
||||
}
|
||||
|
||||
/** Routes typed facade envelopes to the existing native module workers. */
|
||||
export class WebModuleRouter {
|
||||
private readonly sessions = new Map<string, ModuleSession>();
|
||||
private readonly artifacts = new Map<string, WebModuleArtifact>();
|
||||
private readonly lifecycle = new ResourceLifecycle();
|
||||
private sequence = 0;
|
||||
readonly testSceneDocuments = new Map<string, TestViewExampleResult>();
|
||||
// These documents remain in the Assembly Worker while using the shared body editor.
|
||||
readonly assemblyModelingDocuments = new Set<string>();
|
||||
private readonly inspectionDocumentOwners = new Map<string, { module: string; workerFile: string }>();
|
||||
readonly meshPartCurveDocuments = new Set<string>();
|
||||
readonly meshPartMesherDocuments = new Map<string, string>();
|
||||
readonly modelingDocumentOwners = new Map<string, { document: string; module: "Part" | "PartDesign" }>();
|
||||
/** Capture the retained worker identity, without an unrelated-worker fallback. */
|
||||
graphicsDocumentReader(documentId: string): (() => Promise<FacadeResponse>) | undefined {
|
||||
const document = this.modelingDocumentOwners.get(documentId)?.document ?? documentId;
|
||||
const owner = this.inspectionDocumentOwners.get(document);
|
||||
if (!owner) return;
|
||||
return () => {
|
||||
const current = this.inspectionDocumentOwners.get(document);
|
||||
if (current?.module !== owner.module || current?.workerFile !== owner.workerFile)
|
||||
return Promise.resolve(createFailure("graphics-scene", "document_closed", "The originating document owner is no longer available"));
|
||||
return this.request("Inspection", "inspection.pythonFamilyBatch", {
|
||||
schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly",
|
||||
records: [{ apiId: "Inspection:desktop:Inspection_VisualInspection", name: "Inspection_VisualInspection",
|
||||
family: "desktop-command", args: { document, action: "read", graphicsSceneRead: true } }],
|
||||
}, document);
|
||||
};
|
||||
}
|
||||
private readonly completionListeners = new Set<(module: string, command: string, payload: unknown, documentId: string, response: FacadeResponse) => void>();
|
||||
|
||||
onRequestCompleted(listener: (module: string, command: string, payload: unknown, documentId: string, response: FacadeResponse) => void): () => void {
|
||||
this.completionListeners.add(listener);
|
||||
return () => { this.completionListeners.delete(listener); };
|
||||
}
|
||||
|
||||
route(module: string): WebModuleRoute | undefined {
|
||||
return getWebModuleRoute(module);
|
||||
}
|
||||
|
||||
private open(module: string, workerFile?: string): ModuleSession | undefined {
|
||||
const route = getWebModuleRoute(module);
|
||||
const selectedWorker = workerFile ?? route?.primaryWorker ?? undefined;
|
||||
const sessionKey = `${module}:${selectedWorker ?? ""}`;
|
||||
const existing = this.sessions.get(sessionKey);
|
||||
if (existing) return existing;
|
||||
const artifact = this.artifacts.get(module);
|
||||
const worker = createWebModuleWorker(module, selectedWorker, artifact);
|
||||
if (!route || !worker) return undefined;
|
||||
const pending = new Map<string, PendingRequest>();
|
||||
let resolveReady!: () => void;
|
||||
let rejectReady!: (error: Error) => void;
|
||||
const ready = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const session: ModuleSession = { route, worker, ready, failReady: rejectReady, pending, artifactRevision: artifact?.revision };
|
||||
const failSession = (error: Error) => {
|
||||
rejectReady(error);
|
||||
for (const request of pending.values()) { request.cleanup?.(); request.reject(error); }
|
||||
pending.clear();
|
||||
if (this.sessions.get(sessionKey) === session) {
|
||||
this.sessions.delete(sessionKey);
|
||||
this.lifecycle.release(`worker:${sessionKey}`);
|
||||
}
|
||||
};
|
||||
worker.onmessage = (event: MessageEvent<WorkerMessage>) => {
|
||||
const message = event.data;
|
||||
if (message.kind === "ready") { resolveReady(); return; }
|
||||
if (message.kind === "reset") return;
|
||||
if (message.kind === "bootstrap-error") {
|
||||
failSession(new Error(`${module} worker bootstrap failed: ${message.message}`));
|
||||
return;
|
||||
}
|
||||
const request = pending.get(message.requestId);
|
||||
if (!request) {
|
||||
// Older workers use these sentinel IDs for startup/protocol errors.
|
||||
// They cannot be correlated to one command, so fail the broken session.
|
||||
if (message.kind === "error" && ["initialization", "invalid"].includes(message.requestId)) {
|
||||
failSession(new Error(`${module} ${selectedWorker} failed: ${message.error.code}: ${message.error.message}`));
|
||||
}
|
||||
return;
|
||||
}
|
||||
pending.delete(message.requestId);
|
||||
request.cleanup?.();
|
||||
request.resolve(message);
|
||||
};
|
||||
worker.onerror = (event) => {
|
||||
const error = new Error(`${module} worker failed: ${event.message}`);
|
||||
failSession(error);
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.lifecycle.track({ label: `worker:${sessionKey}`, dispose: () => worker.terminate() });
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Register or replace the independently built artifact for one module. */
|
||||
setArtifact(module: string, artifact: WebModuleArtifact): void {
|
||||
if (!getWebModuleRoute(module)) throw new Error(`module ${module} is not registered`);
|
||||
const previous = this.artifacts.get(module);
|
||||
this.artifacts.set(module, artifact);
|
||||
if (previous?.revision === artifact.revision) return;
|
||||
if (module === "Test") this.testSceneDocuments.clear();
|
||||
this.closeSessions(module, new Error(`module ${module} artifact changed to ${artifact.revision}`));
|
||||
}
|
||||
|
||||
clearArtifact(module: string): void {
|
||||
this.artifacts.delete(module);
|
||||
if (module === "Test") this.testSceneDocuments.clear();
|
||||
this.closeSessions(module, new Error(`module ${module} artifact cleared`));
|
||||
}
|
||||
|
||||
getArtifact(module: string): WebModuleArtifact | undefined {
|
||||
return this.artifacts.get(module);
|
||||
}
|
||||
|
||||
async loadManifest(url: string, init?: RequestInit): Promise<string[]> {
|
||||
const manifest = await loadWebModuleManifest(url, init);
|
||||
const loaded: string[] = [];
|
||||
for (const [module, artifact] of Object.entries(manifest.modules)) {
|
||||
if (!getWebModuleRoute(module)) continue;
|
||||
this.setArtifact(module, artifact);
|
||||
loaded.push(module);
|
||||
}
|
||||
return loaded.sort();
|
||||
}
|
||||
|
||||
listLoaded(): Array<{ module: string; worker: string; revision?: string }> {
|
||||
return [...this.sessions.entries()].map(([key, session]) => {
|
||||
const separator = key.indexOf(":");
|
||||
return {
|
||||
module: separator < 0 ? key : key.slice(0, separator),
|
||||
worker: separator < 0 ? key : key.slice(separator + 1),
|
||||
revision: session.artifactRevision,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Preload one command worker without issuing a native command. */
|
||||
async preload(module: string, workerFile?: string): Promise<void> {
|
||||
const selectedWorker = workerFile ?? getWebModuleRoute(module)?.primaryWorker ?? undefined;
|
||||
const session = this.open(module, selectedWorker);
|
||||
if (!session) throw new Error(`${module} has no runnable Web Worker route`);
|
||||
await session.ready;
|
||||
}
|
||||
|
||||
private closeSessions(module?: string, error?: Error): void {
|
||||
if (!module || module === "MeshPart") { this.meshPartCurveDocuments.clear(); this.meshPartMesherDocuments.clear(); }
|
||||
for (const [name, owner] of this.inspectionDocumentOwners) if (!module || owner.module === module) this.inspectionDocumentOwners.delete(name);
|
||||
for (const [key, session] of this.sessions) {
|
||||
if (module && !key.startsWith(`${module}:`)) continue;
|
||||
this.sessions.delete(key);
|
||||
session.failReady(error ?? new Error(`module ${key} closed`));
|
||||
if (error) for (const request of session.pending.values()) { request.cleanup?.(); request.reject(error); }
|
||||
session.pending.clear();
|
||||
session.worker.terminate();
|
||||
this.lifecycle.release(`worker:${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
async request<Payload = unknown>(module: string, command: string, payload: Payload, documentId = `${module.toLowerCase()}-document`, signal?: AbortSignal): Promise<FacadeResponse> {
|
||||
if (module === "ReverseEngineering" && command === "reverseengineering.pythonFamilyBatch") {
|
||||
const records = (payload as any)?.records;
|
||||
if (records?.some((row: any) => ["Reen_ApproxPlane", "Reen_ApproxCylinder", "Reen_ApproxSphere", "Reen_ApproxPolynomial"].includes(row.name))) {
|
||||
if (records.length !== 1) return createFailure("native-fit", "invalid_request", "Run one approximation command at a time");
|
||||
if (signal?.aborted) return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch");
|
||||
if (!this.inspectionDocumentOwners.has(documentId))
|
||||
return createFailure("native-fit", "missing_document", "Select geometry in an open native document");
|
||||
const response = await this.request("Inspection", "inspection.pythonFamilyBatch", {
|
||||
schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly",
|
||||
records: [{ apiId: "Inspection:desktop:Inspection_InspectElement", name: "Inspection_InspectElement", family: "desktop-command",
|
||||
args: { ...records[0].args, document: documentId, approximationCommand: records[0].name } }],
|
||||
}, documentId, signal);
|
||||
if (response.kind !== "result") return response;
|
||||
const batch = response.result as any;
|
||||
if (batch.ok === false || !Array.isArray(batch.records))
|
||||
return createFailure("native-fit", batch.code || "native_error", batch.error || "Native fitting failed");
|
||||
return createSuccess(response.requestId, { ...batch, module: "ReverseEngineering",
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1",
|
||||
records: batch.records.map((row: any) => ({ ...row, apiId: records[0].apiId, name: records[0].name, value: row.result })) });
|
||||
}
|
||||
if (records?.some((row: any) => ["Reen_Segmentation", "Reen_SegmentationManual", "Reen_SegmentationFromComponents"].includes(row.name))) {
|
||||
if (records.length !== 1) return createFailure("manual-segmentation", "active_task", "Open one manual segmentation task at a time");
|
||||
if (!this.inspectionDocumentOwners.has(documentId))
|
||||
return createFailure("manual-segmentation", "missing_document", "Choose an active native document before opening manual segmentation");
|
||||
const response = await this.request("Inspection", "inspection.pythonFamilyBatch", {
|
||||
schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly",
|
||||
records: [{ apiId: "Inspection:desktop:Inspection_InspectElement", name: "Inspection_InspectElement", family: "desktop-command",
|
||||
args: { ...records[0].args, document: documentId, manualSegmentation: records[0].name === "Reen_SegmentationManual",
|
||||
automaticSegmentation: records[0].name === "Reen_Segmentation",
|
||||
componentsSegmentation: records[0].name === "Reen_SegmentationFromComponents" } }],
|
||||
}, documentId, signal);
|
||||
if (response.kind !== "result") return response;
|
||||
const batch = response.result as any;
|
||||
return createSuccess(response.requestId, { ...batch, module: "ReverseEngineering",
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1",
|
||||
records: batch.records.map((row: any) => ({ ...row, apiId: records[0].apiId, name: records[0].name, value: row.result })) });
|
||||
}
|
||||
}
|
||||
if (module === "Measure" && command === "measure.pythonFamilyBatch") {
|
||||
const records = (payload as { records?: Array<{ apiId: string; args?: Record<string, unknown> }> }).records;
|
||||
if (records?.some(r => ["Measure:desktop:Std_Measure", "Measure:desktop:Std_MassProperties"].includes(r.apiId))) {
|
||||
if (records.length !== 1) return createFailure("measure-document", "invalid_request", "Measure one selection at a time");
|
||||
return executeMeasureDocument(this, { ...records[0].args, ...(records[0].apiId.endsWith(":Std_MassProperties") ? { action: "massProperties" } : {}) }, documentId);
|
||||
}
|
||||
}
|
||||
if (module === "Surface" && command === "Surface_CurveOnMesh") {
|
||||
const args = payload as Record<string, unknown>;
|
||||
return executeMeshPartCurve(this, { id: "MeshPart:desktop:MeshPart_CurveOnMesh", module: "MeshPart",
|
||||
command: "MeshPart_CurveOnMesh", kind: "desktop-gui", sourcePath: "src/Mod/Surface/Gui/Command.cpp" },
|
||||
args, typeof args.documentId === "string" ? args.documentId : documentId);
|
||||
}
|
||||
if (module === "Surface" && ["Surface_BlendCurve", "Surface_ExtendFace"].includes(command))
|
||||
return (await executeSurfaceDocument(this, command, payload as Record<string, unknown>, documentId))!;
|
||||
if (module === "Surface" && ["surface.desktopCommand", "surface.pythonFamilyBatch"].includes(command)) {
|
||||
const commands = (payload as { commands?: Array<{ apiId: string; args?: Record<string, unknown> }>; records?: Array<{ apiId: string; args?: Record<string, unknown> }> })?.[command === "surface.desktopCommand" ? "commands" : "records"];
|
||||
if (commands?.some(item => item.apiId === "Surface:desktop:Surface_CurveOnMesh")) {
|
||||
if (commands.length !== 1) return createFailure("surface-curve", "active_task", "Open one curve task at a time");
|
||||
return this.request("Surface", "Surface_CurveOnMesh", commands[0].args ?? {}, documentId, signal);
|
||||
}
|
||||
if (commands?.some(item => ["Surface:desktop:Surface_BlendCurve", "Surface:desktop:Surface_Filling", "Surface:desktop:Surface_Sections", "Surface:desktop:Surface_ExtendFace"].includes(item.apiId))) {
|
||||
if (commands.length !== 1) return createFailure("surface-document", "invalid_request", "Edit one Surface feature at a time");
|
||||
const response = await executeSurfaceDocument(this, commands[0].apiId.split(":").pop()!, commands[0].args ?? {}, documentId);
|
||||
if (!response || response.kind === "error") return response!;
|
||||
return createSuccess(response.requestId, { ok: true, cmd: command, module: "Surface", source: "freecad-source", count: 1,
|
||||
results: [{ apiId: commands[0].apiId, status: "exposed", native: true, runtimeOwner: "DocumentProbe", ...response.result as object }] });
|
||||
}
|
||||
}
|
||||
if (module === "Points" && ["points.saveReopen", "points.createRecompute"].includes(command)) {
|
||||
const args = payload as Record<string, unknown>;
|
||||
payload = { ...args, document: args.document ?? documentId } as Payload;
|
||||
}
|
||||
const inspectionTask = module === "Inspection" && command === "inspection.pythonFamilyBatch"
|
||||
&& (payload as any)?.records?.every((record: any) => ["Inspection_VisualInspection", "Inspection_InspectElement"].includes(record.name));
|
||||
const inspectionOwner = inspectionTask ? this.inspectionDocumentOwners.get(documentId) : undefined;
|
||||
if (module === "Test") {
|
||||
const scenePayload = payload as { command?: string; args?: Record<string, unknown> };
|
||||
if (["Std_ViewExample1", "Std_ViewExample2", "Std_ViewExample3"].includes(scenePayload.command ?? "")) {
|
||||
const id = String(scenePayload.args?.documentId ?? documentId);
|
||||
scenePayload.args = { ...scenePayload.args, documentId: id.startsWith("test-scene-") ? id : `test-scene-${id}` };
|
||||
}
|
||||
}
|
||||
const sourceDecision = nativeSourceDecision(module, command);
|
||||
if (sourceDecision) return createFailure(`module-${module.toLowerCase()}-native-source`, sourceDecision.code, sourceDecision.message, sourceDecision.diagnostic);
|
||||
const route = getWebModuleRoute(module);
|
||||
if (!route) return createFailure("invalid", "unknown_module", `module ${module} is not registered`, { module });
|
||||
const pointsCurveTask = module === "Points" && command === "reverseengineering.pythonFamilyBatch";
|
||||
if (!pointsCurveTask && !route.commands.includes(command)) return createFailure("invalid", "not_implemented", `command ${command} is not registered for ${module}`, { module, command });
|
||||
const assemblyModeling = command === "partdesign.document" && this.assemblyModelingDocuments.has(documentId);
|
||||
const workerFile = assemblyModeling ? "assembly.worker.ts" : inspectionOwner?.workerFile ?? (pointsCurveTask ? "points.worker.ts" : getWebModuleWorkerForCommand(module, command));
|
||||
const ownerModule = assemblyModeling ? "Assembly" : inspectionOwner?.module ?? module;
|
||||
const session = this.open(ownerModule, workerFile);
|
||||
if (!session) return createFailure("invalid", "not_implemented", `${module} has no runnable Web Worker route`, { module });
|
||||
await session.ready;
|
||||
if (inspectionTask && (payload as any)?.records?.some((row: any) => row.args?.approximationCommand) && signal?.aborted)
|
||||
return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch");
|
||||
const requestId = `module-${module.toLowerCase()}-${++this.sequence}`;
|
||||
const request = createRequest(requestId, command, payload, documentId) as FacadeRequest<Payload>;
|
||||
return new Promise<FacadeResponse>((resolve, reject) => {
|
||||
const onAbort = () => session.worker.postMessage(createCancel(`module-cancel-${++this.sequence}`, requestId, documentId));
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
session.pending.set(requestId, { resolve: (response) => {
|
||||
if ((command === "part.document" || command === "partdesign.document") && response.kind === "result") {
|
||||
const result = response.result as { document?: string; closed?: boolean };
|
||||
if (result.document) {
|
||||
if (result.closed) { for (const [key, owner] of this.modelingDocumentOwners) if (owner.document === result.document) this.modelingDocumentOwners.delete(key); }
|
||||
else { const owner = { document: result.document, module: command === "part.document" ? "Part" as const : "PartDesign" as const };
|
||||
this.modelingDocumentOwners.set(documentId, owner); this.modelingDocumentOwners.set(result.document, owner); }
|
||||
}
|
||||
}
|
||||
if (response.kind === "result" && workerFile && ["part-save.worker.ts", "part.worker.ts", "partdesign.worker.ts", "partdesign-python.worker.ts", "sketcher.worker.ts", "sketcher-python.worker.ts", "draft.worker.ts", "bim.worker.ts", "points.worker.ts", "mesh.worker.ts", "inspection.worker.ts"].includes(workerFile)) {
|
||||
const value = response.result as any;
|
||||
const candidates = [value, ...(value.records ?? []).flatMap((row: any) => row.status === "exposed" ? [row, row.result, row.value] : [])];
|
||||
for (const candidate of candidates) {
|
||||
const name = candidate?.documentId ?? candidate?.document ?? candidate?.documentHandle;
|
||||
if (typeof name === "string" && (Array.isArray(candidate?.objects) || Array.isArray(candidate?.shapes) || typeof candidate?.geometryCount === "number" || candidate?.closed)) {
|
||||
if (candidate.closed) this.inspectionDocumentOwners.delete(name);
|
||||
else this.inspectionDocumentOwners.set(name, { module: ownerModule, workerFile });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (module === "Test" && response.kind === "result") {
|
||||
const result = response.result as TestViewExampleResult;
|
||||
if (result.operation === "view-example") {
|
||||
if (result.closed) this.testSceneDocuments.delete(result.documentId);
|
||||
else if (result.documentName) this.testSceneDocuments.set(result.documentId, result);
|
||||
}
|
||||
}
|
||||
resolve(response);
|
||||
for (const listener of this.completionListeners) listener(module, command, payload, documentId, response);
|
||||
}, reject, cleanup: signal ? () => signal.removeEventListener("abort", onAbort) : undefined });
|
||||
session.worker.postMessage(request);
|
||||
});
|
||||
}
|
||||
|
||||
reset(module?: string): void {
|
||||
if (!module || module === "Test") this.testSceneDocuments.clear();
|
||||
for (const [name, owner] of this.inspectionDocumentOwners) if (!module || owner.module === module) this.inspectionDocumentOwners.delete(name);
|
||||
const sessions = module
|
||||
? [...this.sessions.entries()].filter(([key]) => key.startsWith(`${module}:`)).map(([, session]) => session)
|
||||
: [...this.sessions.values()];
|
||||
for (const session of sessions) {
|
||||
const requestId = `module-reset-${++this.sequence}`;
|
||||
session.worker.postMessage({ kind: "reset", requestId });
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.closeSessions(undefined, new Error("module router disposed"));
|
||||
this.lifecycle.disposeAll();
|
||||
this.testSceneDocuments.clear();
|
||||
this.sessions.clear();
|
||||
this.artifacts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export type WebModuleFailure = FacadeFailure;
|
||||
@@ -5,11 +5,9 @@ import { PartAttachmentTask } from "./part-attachment-task.js";
|
||||
import { PartTubeTask } from "./part-tube-task.js";
|
||||
import { PartToleranceTask } from "./part-tolerance-task.js";
|
||||
import { PartPrimitivesTask } from "./part-primitives-task.js";
|
||||
import { requestOpenScadExport, requestOpenScadExportPreferences } from "./openscad-format-facade.js";
|
||||
import { saved as savedExportPreferences, persist as persistExportPreferences } from "./parameter-storage.js";
|
||||
import { requestOpenScadFile, type OpenScadFileArgs } from "./openscad-format-facade.js";
|
||||
import { openScadDocumentSnapshot, saveOpenScadFile, type OpenScadDocument } from "./openscad-desktop-adapter.js";
|
||||
import { OpenScadDesktopView } from "./openscad-desktop-view.js";
|
||||
import type { SceneDocument } from "./scene-document.js";
|
||||
import { SceneViewport } from "./scene-viewport.js";
|
||||
import { MaterialDesktopTask } from "./material-desktop-task.js";
|
||||
import { SHOW_DOCUMENT_LIFECYCLE_COMMAND, type ShowDocumentLifecyclePayload, type ShowDocumentLifecycleResult } from "./show-python-family-facade.js";
|
||||
import { ShowClippingTask } from "./show-clipping-task.js";
|
||||
@@ -239,15 +237,6 @@ function App() {
|
||||
const [exportFileName, setExportFileName] = useState("");
|
||||
const [exportOptions, setExportOptions] = useState({ exportFa: 12, exportFs: 2, exportConvexity: 10, meshdeflection: 0 });
|
||||
const exportCancellation = useRef<AbortController | null>(null);
|
||||
const [exportPreferencesReady, setExportPreferencesReady] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!["csg", "scad"].includes(exportFormat) || exportPreferencesReady) return;
|
||||
let cancelled = false;
|
||||
void savedExportPreferences("OpenSCAD-export.FCParam").then(data => requestOpenScadExportPreferences(router, data))
|
||||
.then(options => { if (!cancelled) { setExportOptions(options); setExportPreferencesReady(true); } })
|
||||
.catch(error => { if (!cancelled) setStatus(String(error)); });
|
||||
return () => { cancelled = true; };
|
||||
}, [exportFormat, exportPreferencesReady, router]);
|
||||
useEffect(() => () => exportCancellation.current?.abort(), []);
|
||||
|
||||
const [selectedObjects, setSelectedObjects] = useState<Record<string, string | null>>({});
|
||||
@@ -286,23 +275,6 @@ function App() {
|
||||
const testDocuments = useRef(new Map<string, { command: string; documentName: string }>());
|
||||
const [testRevision, setTestRevision] = useState(0);
|
||||
const jtDocuments = useRef(new Set<string>());
|
||||
const openScadDocuments = useRef(new Map<string, OpenScadDocument>());
|
||||
const [openScadSnapshots, setOpenScadSnapshots] = useState<Record<string, OpenScadDocument>>({});
|
||||
const rememberOpenScad = (id: string, document: OpenScadDocument) => {
|
||||
openScadDocuments.current.set(id, document);
|
||||
nativeDocuments.current.add(id);
|
||||
setOpenScadSnapshots(previous => ({ ...previous, [id]: document }));
|
||||
};
|
||||
const openScadRequest = async (id: string, action: OpenScadFileArgs["action"], details: Partial<OpenScadFileArgs> = {}) => {
|
||||
const owner = openScadDocuments.current.get(id);
|
||||
const result = await requestOpenScadFile(router, { ...details, action,
|
||||
documentId: owner?.documentId, documentToken: owner?.documentToken });
|
||||
if (result.closed) {
|
||||
openScadDocuments.current.delete(id); nativeDocuments.current.delete(id);
|
||||
setOpenScadSnapshots(previous => { const next = { ...previous }; delete next[id]; return next; });
|
||||
} else rememberOpenScad(id, result);
|
||||
return result;
|
||||
};
|
||||
const remoteOwners = useRef(new Map<string, { document: string; module: "Part" | "PartDesign" }>());
|
||||
const remoteRequest = (id: string, action: string, details: Record<string, unknown> = {}): Promise<PartDocumentResult> => new Promise((resolve, reject) => {
|
||||
const owner = remoteOwners.current.get(id);
|
||||
@@ -410,7 +382,7 @@ function App() {
|
||||
return () => window.removeEventListener("freecad-document-framing", receive);
|
||||
}, [renderBridge, store]);
|
||||
useEffect(() => { const stage = document.querySelector<HTMLElement>("[data-developer-panel]"); if (!stage || !developerMode) return; const previous = stage.querySelector<HTMLElement>("[data-queue-recovery]"); previous?.remove(); return mountQueueRecoveryPanel(stage, store, recovery, () => setRecoveryVersion((value) => value + 1)); }, [recovery, recoveryVersion, store, developerMode]);
|
||||
const nativeName = (id: string) => openScadDocuments.current.get(id)?.documentId ?? testDocuments.current.get(id)?.documentName ?? remoteOwners.current.get(id)?.document ?? `web_${id.replace(/\W/g, "_")}`;
|
||||
const nativeName = (id: string) => testDocuments.current.get(id)?.documentName ?? remoteOwners.current.get(id)?.document ?? `web_${id.replace(/\W/g, "_")}`;
|
||||
const refresh = () => setDocuments(store.list());
|
||||
const currentDocument = documents.find(document => document.id === active);
|
||||
const objects = Object.values(currentDocument?.objects ?? {});
|
||||
@@ -603,12 +575,6 @@ function App() {
|
||||
};
|
||||
const nativeOwnerRequest = async (id: string, action: PartDocumentAction, details: Partial<PartDocumentPayload> = {}) => {
|
||||
validateRequestDocument(id, details.document);
|
||||
if (openScadDocuments.current.has(id)) {
|
||||
const mapped = action === "snapshot" ? "read" : action;
|
||||
if (!["read", "save", "close", "undo", "redo"].includes(mapped))
|
||||
throw new Error(`Use the OpenSCAD document controls for ${action}`);
|
||||
return openScadDocumentSnapshot(await openScadRequest(id, mapped as OpenScadFileArgs["action"]));
|
||||
}
|
||||
const testOwner = testDocuments.current.get(id);
|
||||
if (testOwner) {
|
||||
const mapped = action === "snapshot" ? "read" : action;
|
||||
@@ -777,8 +743,8 @@ function App() {
|
||||
&& document.objects[`native:${owner.name}`]?.properties.tip !== owner.tip
|
||||
? object.name === owner.tip : undefined;
|
||||
const nativeProperties = Object.fromEntries(Object.entries(object).filter(([key]) => key !== "mesh"));
|
||||
nextObjects[objectId] = { id: objectId, module: openScadDocuments.current.has(id) ? "OpenSCAD" : jtDocuments.current.has(id) ? "JtReader" : designDocuments.current.has(id) ? "PartDesign" : "Part",
|
||||
command: openScadDocuments.current.has(id) ? "openscad.pythonFamilyBatch" : jtDocuments.current.has(id) ? JTREADER_DOCUMENT_COMMAND : designDocuments.current.has(id) ? PARTDESIGN_DOCUMENT_COMMAND : PART_DOCUMENT_COMMAND, type: object.type,
|
||||
nextObjects[objectId] = { id: objectId, module: jtDocuments.current.has(id) ? "JtReader" : designDocuments.current.has(id) ? "PartDesign" : "Part",
|
||||
command: jtDocuments.current.has(id) ? JTREADER_DOCUMENT_COMMAND : designDocuments.current.has(id) ? PARTDESIGN_DOCUMENT_COMMAND : PART_DOCUMENT_COMMAND, type: object.type,
|
||||
links: [...new Set(object.dependencies ?? [object.base, object.tool, ...(object.tools ?? []), ...(object.links ?? [])].filter((name): name is string => Boolean(name)))].map(name => `native:${name}`), properties: {
|
||||
...document.objects[objectId]?.properties, ...nativeProperties, ...(object as unknown as { testProperties?: Record<string, string> }).testProperties, NativeName: object.name, Label: object.label,
|
||||
cells: (object as unknown as { cells?: SheetCell[] }).cells,
|
||||
@@ -1177,75 +1143,7 @@ function App() {
|
||||
return false;
|
||||
} finally { importCancellation.current = null; setImporting(false); setCancelRequested(false); setImportPhase(""); }
|
||||
};
|
||||
const importOpenScadFile = async (file: File, newDocument: boolean) => {
|
||||
if ((!active && !newDocument) || importing || importCancellation.current) return false;
|
||||
const id = newDocument ? allocateDocumentId() : active;
|
||||
const cancellation = new AbortController(); importCancellation.current = cancellation;
|
||||
setImporting(true); setCancelRequested(false); setImportPhase("reading");
|
||||
const owner = openScadDocuments.current.get(id);
|
||||
let pending: Awaited<ReturnType<typeof requestOpenScadFile>> | undefined;
|
||||
let committed = false;
|
||||
try {
|
||||
if (!file.size || file.size > 64 * 1024 * 1024) throw new Error("Choose a SCAD or CSG file between 1 byte and 64 MiB");
|
||||
const contentBase64 = encodeSceneFile(await file.arrayBuffer());
|
||||
cancellation.signal.throwIfAborted();
|
||||
let documentBase64: string | undefined;
|
||||
let documentObjects: Array<{ name: string; type: string }> | undefined;
|
||||
const hasOriginal = !newDocument && nativeDocuments.current.has(id) && !owner;
|
||||
if (!newDocument && !owner && Object.values(store.list().find(value => value.id === id)?.objects ?? {}).some(object => !object.properties.NativeName))
|
||||
throw new Error("Save or attach the existing imported views before inserting OpenSCAD source");
|
||||
if (hasOriginal) {
|
||||
const original = await nativeRequest(id, "save", { path: `/tmp/${nativeName(id)}.FCStd`, includeMesh: false });
|
||||
if (!original.bytes) throw new Error("The active document owner returned no FCStd data");
|
||||
if (!original.objects) throw new Error("The active document owner returned no object manifest");
|
||||
documentObjects = original.objects.map(object => ({ name: object.name, type: object.type }));
|
||||
documentBase64 = encodeSceneFile(original.bytes);
|
||||
}
|
||||
cancellation.signal.throwIfAborted();
|
||||
setImportPhase("native"); setStatus(`${newDocument ? "Opening" : "Inserting"} ${file.name}...`);
|
||||
pending = await requestOpenScadFile(router, { action: "import", fileName: file.name,
|
||||
extension: file.name.split(".").pop()!.toLowerCase(), contentBase64, documentBase64, documentObjects,
|
||||
newDocument: newDocument || (!owner && !documentBase64), documentId: owner?.documentId,
|
||||
documentToken: owner?.documentToken, operationToken: crypto.randomUUID() });
|
||||
cancellation.signal.throwIfAborted();
|
||||
// Geometry and identity are returned before acceptance. Cancellation stays
|
||||
// local until this point because synchronous native parsing cannot yield.
|
||||
importCancellation.current = null; setImportPhase("finishing");
|
||||
const result = await requestOpenScadFile(router, { action: "finishImport", documentId: pending.documentId,
|
||||
documentToken: pending.documentToken, operationToken: pending.operationToken, commitImport: true });
|
||||
if (result.cancelled) throw new Error("OpenSCAD import transaction expired before commit");
|
||||
committed = true; pending = undefined;
|
||||
let retirementError = "";
|
||||
if (hasOriginal) {
|
||||
try { await nativeOwnerRequest(id, "close", { includeMesh: false }); }
|
||||
catch (error) { retirementError = `; previous document owner could not close: ${String(error)}`; }
|
||||
}
|
||||
designDocuments.current.delete(id); jtDocuments.current.delete(id); remoteOwners.current.delete(id); testDocuments.current.delete(id);
|
||||
rememberOpenScad(id, result);
|
||||
if (newDocument) store.open(id, file.name);
|
||||
applyNativeDocument(id, openScadDocumentSnapshot(result));
|
||||
store.switchTo(id); setActive(id); setStartVisible(false);
|
||||
setSelectedObjects(previous => ({ ...previous, [id]: result.selection[0] ? `native:${result.selection[0]}` : null }));
|
||||
setNativeBytes(null);
|
||||
store.touchFile({ path: file.name, module: "OpenSCAD", format: file.name.split(".").pop()!.toLowerCase(), updatedAt: new Date().toISOString() });
|
||||
refresh(); setStatus(`${newDocument ? "Opened" : "Inserted"} ${file.name}${retirementError}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (pending && !committed) {
|
||||
try { await requestOpenScadFile(router, { action: "finishImport", documentId: pending.documentId,
|
||||
documentToken: pending.documentToken, operationToken: pending.operationToken, commitImport: false }); }
|
||||
catch (rollback) { setStatus(`OpenSCAD rollback: ${String(rollback)}; ${String(error)}`); return false; }
|
||||
}
|
||||
setStatus(cancellation.signal.aborted ? "OpenSCAD import cancelled; original document preserved" : String(error));
|
||||
if (newDocument && !cancellation.signal.aborted) throw error;
|
||||
return false;
|
||||
} finally { importCancellation.current = null; setImporting(false); setCancelRequested(false); setImportPhase(""); }
|
||||
};
|
||||
const importUserFiles = async (files: File[], desktopCommand?: ImportDesktopCommand, newDocument = false) => {
|
||||
if (files.some(file => /\.(scad|csg)$/i.test(file.name))) {
|
||||
if (files.length !== 1) throw new Error("Choose one SCAD or CSG source file at a time");
|
||||
return importOpenScadFile(files[0], newDocument);
|
||||
}
|
||||
if (files.some(file => /\.jt$/i.test(file.name))) {
|
||||
if (files.length !== 1) throw new Error("Choose one standalone JT file at a time");
|
||||
return newDocument ? openJtFile(files[0]) : insertJtFile(files[0]);
|
||||
@@ -1343,34 +1241,6 @@ function App() {
|
||||
setImporting(true);
|
||||
try {
|
||||
const name = String(selectedObject.properties.NativeName);
|
||||
if (["csg", "scad"].includes(exportFormat)) {
|
||||
const id = active;
|
||||
const cancellation = new AbortController(); exportCancellation.current = cancellation;
|
||||
const owner = openScadDocuments.current.get(id);
|
||||
const documentId = nativeName(id);
|
||||
const names = (compoundSelections[id]?.length ? compoundSelections[id]! : [name]).map(value => value.replace(/^native:/, ""));
|
||||
const args: OpenScadFileArgs = { action: "export", documentId, documentToken: owner?.documentToken,
|
||||
selection: names.map(object => ({ documentId, object })), extension: exportFormat,
|
||||
fileName: exportFileName.trim() || `${name}.${exportFormat}`, exportOptions,
|
||||
preferencesBase64: await savedExportPreferences("OpenSCAD-export.FCParam") };
|
||||
if (!owner) {
|
||||
const original = await nativeRequest(id, "save", { path: `/tmp/${documentId}.FCStd`, includeMesh: false });
|
||||
if (!original.bytes || !original.objects) throw new Error("The active owner returned no FCStd export snapshot");
|
||||
args.documentBase64 = encodeSceneFile(original.bytes);
|
||||
args.documentObjects = original.objects.map(object => ({ name: object.name, type: object.type }));
|
||||
}
|
||||
cancellation.signal.throwIfAborted();
|
||||
const result = await requestOpenScadExport(router, args);
|
||||
cancellation.signal.throwIfAborted();
|
||||
if (store.active()?.id !== id) throw new Error("Export cancelled because the active document changed");
|
||||
await persistExportPreferences(result.preferencesBase64, "OpenSCAD-export.FCParam");
|
||||
cancellation.signal.throwIfAborted();
|
||||
const bytes = Uint8Array.from(atob(result.base64), character => character.charCodeAt(0)).buffer;
|
||||
const exported = exporter.download({ module: "OpenSCAD", format: "text/plain", fileName: result.fileName, bytes });
|
||||
if (exported.status !== "ok") throw new Error(exported.error?.message || "OPFS write failed");
|
||||
setStatus(`已写入 OPFS:${result.fileName} (${bytes.byteLength} bytes)`);
|
||||
return;
|
||||
}
|
||||
const result = await nativeRequest(active, "exportShape", { object: name,
|
||||
path: `/tmp/${nativeName(active)}_${name}.${exportFormat}`, includeMesh: false });
|
||||
if (!result.bytes?.byteLength) throw new Error("Native export returned no file bytes");
|
||||
@@ -1484,16 +1354,6 @@ function App() {
|
||||
if (!active || importing) return;
|
||||
setImporting(true);
|
||||
try {
|
||||
if (openScadDocuments.current.has(active)) {
|
||||
const result = await openScadRequest(active, "save");
|
||||
if (!result.file) throw new Error("OpenSCAD returned no FCStd file");
|
||||
await saveOpenScadFile(result);
|
||||
const snapshot = openScadDocumentSnapshot(result);
|
||||
applyNativeDocument(active, snapshot, false); setNativeBytes(snapshot.bytes!);
|
||||
setSavedDocuments(await listDocumentFiles()); window.dispatchEvent(new Event("freecad-document-persistence")); setSavedDocument(`OpenSCAD/${result.file.name}`);
|
||||
setStatus(`Saved ${result.file.name} to OPFS`);
|
||||
return;
|
||||
}
|
||||
if (objects.some(object => !object.properties.NativeName)) throw new Error("Imported STEP views are not yet attached to this native FCStd document");
|
||||
if (!nativeDocuments.current.has(active)) await nativeRequest(active, "create");
|
||||
const fileName = `${jtDocuments.current.has(active) ? "JtReader_" : designDocuments.current.has(active) ? "PartDesign_" : ""}${nativeName(active)}.FCStd`;
|
||||
@@ -1512,19 +1372,9 @@ function App() {
|
||||
let id = allocateDocumentId();
|
||||
let registeredDesignOwner = false;
|
||||
try {
|
||||
if ((requestedFile.includes("/") && !/^(Test|OpenSCAD)\/[^/]+$/.test(requestedFile)) || requestedFile.includes("\\") || !/\.FCStd$/i.test(requestedFile))
|
||||
if ((requestedFile.includes("/") && !/^Test\/[^/]+$/.test(requestedFile)) || requestedFile.includes("\\") || !/\.FCStd$/i.test(requestedFile))
|
||||
throw new Error("Invalid FCStd file name");
|
||||
const bytes = suppliedBytes ?? await readDocumentFile(requestedFile);
|
||||
if (requestedFile.startsWith("OpenSCAD/") || requestedFile.startsWith("OpenSCAD_")) {
|
||||
const result = await openScadRequest(id, "open", { contentBase64: encodeSceneFile(bytes) });
|
||||
store.open(id, requestedFile.split("/").pop());
|
||||
applyNativeDocument(id, openScadDocumentSnapshot(result), false);
|
||||
store.switchTo(id); setActive(id); setStartVisible(false);
|
||||
setSelectedObjects(previous => ({ ...previous, [id]: result.selection[0] ? `native:${result.selection[0]}` : null }));
|
||||
setNativeBytes(bytes); setStatus(`Opened ${requestedFile}${suppliedBytes ? "" : " from OPFS"}`);
|
||||
const url = new URL(window.location.href); url.searchParams.delete("fcstd"); window.history.replaceState(null, "", url);
|
||||
return true;
|
||||
}
|
||||
if (requestedFile.startsWith("PartDesign_")) {
|
||||
designDocuments.current.add(id);
|
||||
registeredDesignOwner = true;
|
||||
@@ -1636,7 +1486,7 @@ function App() {
|
||||
}
|
||||
setStartVisible(!preferences.closeStart);
|
||||
};
|
||||
const downloadFcstd = () => { if (!nativeBytes) return; const result = exporter.download({ module: "Part", format: "application/octet-stream", fileName: `${openScadDocuments.current.has(active) ? "OpenSCAD_" : jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`, bytes: nativeBytes }); setStatus(result.status === "ok" ? "FCStd 已写入 OPFS" : result.error?.message || "FCStd OPFS write failed"); };
|
||||
const downloadFcstd = () => { if (!nativeBytes) return; const result = exporter.download({ module: "Part", format: "application/octet-stream", fileName: `${jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`, bytes: nativeBytes }); setStatus(result.status === "ok" ? "FCStd 已写入 OPFS" : result.error?.message || "FCStd OPFS write failed"); };
|
||||
const exportDependencyGraph = async () => {
|
||||
if (importing || !active || !nativeDocuments.current.has(active)) return;
|
||||
const documentId = nativeName(active);
|
||||
@@ -2023,7 +1873,7 @@ function App() {
|
||||
}
|
||||
setWorkspaceTask(""); setViewCommand(""); setWorkbenches(previous => ({ ...previous, [active]: next }));
|
||||
void startParameters(router, { LastModule: `${next}Workbench` }, true).catch(error => setStatus(String(error)));
|
||||
}}><option>Part</option><option>Sketcher</option><option>PartDesign</option><option>Spreadsheet</option><option>Surface</option><option>Assembly</option><option>Draft</option><option>Architecture</option><option>BIM</option><option>CAM</option><option>Cloud</option><option>Fem</option><option>Help</option><option>Import</option><option>Inspection</option><option>JtReader</option><option>Material</option><option>Measure</option><option>Mesh</option><option>MeshPart</option><option>OpenSCAD</option><option>Points</option><option>ReverseEngineering</option><option>Robot</option><option>Sandbox</option><option>Start</option><option>TechDraw</option><option>Test</option><option>Tux</option><option disabled={!nativeDocuments.current.has(active)}>TemplatePyMod</option></select></label>
|
||||
}}><option>Part</option><option>Sketcher</option><option>PartDesign</option><option>Spreadsheet</option><option>Surface</option><option>Assembly</option><option>Draft</option><option>Architecture</option><option>BIM</option><option>CAM</option><option>Cloud</option><option>Fem</option><option>Help</option><option>Import</option><option>Inspection</option><option>JtReader</option><option>Material</option><option>Measure</option><option>Mesh</option><option>MeshPart</option><option>Points</option><option>ReverseEngineering</option><option>Robot</option><option>Sandbox</option><option>Start</option><option>TechDraw</option><option>Test</option><option>Tux</option><option disabled={!nativeDocuments.current.has(active)}>TemplatePyMod</option></select></label>
|
||||
</ToolbarGroup>
|
||||
<ParityWorkbenchToolbars workbench={workbench} onCommand={executeManifestCommand} />
|
||||
{csvPanel && <SpreadsheetCsvPanel mode={csvPanel.mode} selected={csvPanel.selected}
|
||||
@@ -2223,10 +2073,7 @@ function App() {
|
||||
if (result.file) void listDocumentFiles().then(files => { setSavedDocuments(files); window.dispatchEvent(new Event("freecad-document-persistence")); }).catch(error => setStatus(String(error)));
|
||||
}} />
|
||||
</>}
|
||||
{openScadSnapshots[active] && <OpenScadDesktopView document={openScadSnapshots[active]}
|
||||
selected={selectedObjects[active] ? [selectedObjects[active]!.replace(/^native:/, "")] : []}
|
||||
onSelect={name => selectPrimaryObject(`native:${name}`)} />}
|
||||
<div ref={viewportRef} style={openScadDocuments.current.has(active) || testDocuments.current.has(active) || isExternalWorkbench(workbench) ? { display: "none" } : undefined} className="viewport" aria-label="Imported native 3D view" />
|
||||
<div ref={viewportRef} style={testDocuments.current.has(active) || isExternalWorkbench(workbench) ? { display: "none" } : undefined} className="viewport" aria-label="Imported native 3D view" />
|
||||
{isExternalWorkbench(workbench) && <WorkbenchFrame workbench={workbench} />}
|
||||
<div className="viewport-transform-bar" role="toolbar" aria-label="Object transform">
|
||||
{([["translate", "移动"], ["rotate", "旋转"], ["off", "关闭"]] as const).map(([mode, label]) => (
|
||||
@@ -2298,22 +2145,15 @@ function App() {
|
||||
<button disabled={!importFile} onClick={() => { if (importFile) void importUserFiles([importFile], importCommand); }}>Accept import</button>
|
||||
<button onClick={() => { setImportCommand(null); setImportFile(null); setReplaceImport(false); setStatus("Import cancelled"); }}>Cancel import task</button>
|
||||
</fieldset>}
|
||||
<details className="file-tools"><summary>Files</summary><label className="action">Open SCAD / CSG<input type="file" aria-label="Open OpenSCAD document" accept=".scad,.csg" disabled={importing} onChange={event => { const file = event.target.files?.[0]; event.target.value = ""; if (file) void importUserFiles([file], undefined, true).catch(error => setStatus(String(error))); }} /></label><label className="action">打开 JT<input type="file" aria-label="Open JT document" accept=".jt" disabled={importing} onChange={event => { const file = event.target.files?.[0]; event.target.value = ""; if (file) void openJtFile(file).catch(error => setStatus(String(error))); }} /></label><label className="action">打开 PLMXML / STEPZ<input type="file" aria-label="Open PLMXML or STEPZ document" accept=".plmxml,.stpz,.stepz" disabled={importing} onChange={event => { const file = event.target.files?.[0]; event.target.value = ""; if (file) void importUserFiles([file], undefined, true).catch(error => setStatus(String(error))); }} /></label><label className="action">导入 SCAD / CSG / JT / STEP / STEPZ / PLMXML / IGES / BREP / STL / 3MF / glTF<input type="file" aria-label="Import SCAD, CSG, JT, PLMXML, STEPZ, 3MF or shape files" accept=".scad,.csg,.jt,.step,.stp,.stpz,.stepz,.plmxml,.iges,.igs,.brep,.brp,.rle,.stl,.3mf,.gltf,.glb" multiple disabled={!active || importing} onChange={event => { const files = Array.from(event.target.files ?? []); event.target.value = ""; if (files.length) void importUserFiles(files).catch(error => setStatus(String(error))); }} /></label>
|
||||
<details className="file-tools"><summary>Files</summary><label className="action">打开 JT<input type="file" aria-label="Open JT document" accept=".jt" disabled={importing} onChange={event => { const file = event.target.files?.[0]; event.target.value = ""; if (file) void openJtFile(file).catch(error => setStatus(String(error))); }} /></label><label className="action">打开 PLMXML / STEPZ<input type="file" aria-label="Open PLMXML or STEPZ document" accept=".plmxml,.stpz,.stepz" disabled={importing} onChange={event => { const file = event.target.files?.[0]; event.target.value = ""; if (file) void importUserFiles([file], undefined, true).catch(error => setStatus(String(error))); }} /></label><label className="action">导入 JT / STEP / STEPZ / PLMXML / IGES / BREP / STL / 3MF / glTF<input type="file" aria-label="Import JT, PLMXML, STEPZ, 3MF or shape files" accept=".jt,.step,.stp,.stpz,.stepz,.plmxml,.iges,.igs,.brep,.brp,.rle,.stl,.3mf,.gltf,.glb" multiple disabled={!active || importing} onChange={event => { const files = Array.from(event.target.files ?? []); event.target.value = ""; if (files.length) void importUserFiles(files).catch(error => setStatus(String(error))); }} /></label>
|
||||
{importing && importCancellation.current && <button type="button" className="action" disabled={cancelRequested}
|
||||
aria-label="取消导入" onClick={() => { if (!importCancellation.current) return; importCancellation.current.abort();
|
||||
setCancelRequested(true); setStatus("Cancelling import; waiting for native rollback"); }}><ToolIcon nodes={X} />{cancelRequested ? "取消中" : "取消导入"}</button>}
|
||||
<label>导出格式<select aria-label="Native export format" value={exportFormat} disabled={importing} onChange={event => setExportFormat(event.target.value)}>
|
||||
<option value="stl">STL</option><option value="step">STEP</option><option value="iges">IGES</option><option value="brep">BREP</option><option value="gltf">glTF</option><option value="glb">glb</option><option value="csg">CSG</option><option value="scad">SCAD</option>
|
||||
<option value="stl">STL</option><option value="step">STEP</option><option value="iges">IGES</option><option value="brep">BREP</option><option value="gltf">glTF</option><option value="glb">glb</option>
|
||||
</select></label>
|
||||
{["csg", "scad"].includes(exportFormat) && <fieldset disabled={importing || !exportPreferencesReady} aria-label="OpenSCAD export options">
|
||||
<legend>Selected-object export</legend>
|
||||
<label>Filename<input value={exportFileName} placeholder={`Export.${exportFormat}`} onChange={event => setExportFileName(event.target.value)} /></label>
|
||||
{([['exportFa', 'Fragment angle'], ['exportFs', 'Fragment size'], ['exportConvexity', 'Convexity'], ['meshdeflection', 'Mesh deflection']] as const).map(([key, label]) =>
|
||||
<label key={key}>{label}<input type="number" min={key === 'exportConvexity' ? 1 : 0} step={key === 'exportConvexity' ? 1 : 'any'}
|
||||
value={exportOptions[key]} onChange={event => setExportOptions(previous => ({ ...previous, [key]: event.target.value === "" ? NaN : Number(event.target.value) }))} /></label>)}
|
||||
</fieldset>}
|
||||
{importing && exportCancellation.current && <button type="button" onClick={() => { exportCancellation.current?.abort(); setStatus("Export cancelled; no file will be downloaded"); }}>Cancel export</button>}
|
||||
<button className="tool" title="导出选中对象" aria-label="导出选中对象" disabled={importing || !selectedObject?.type.startsWith("Part::") || (["csg", "scad"].includes(exportFormat) && !exportPreferencesReady)}
|
||||
<button className="tool" title="导出选中对象" aria-label="导出选中对象" disabled={importing || !selectedObject?.type.startsWith("Part::")}
|
||||
onClick={() => void exportSelectedShape()}><ToolIcon nodes={Download} /></button>
|
||||
<button className="action" disabled={!objects.length} onClick={() => renderBridge.fitDocument()}>适合全部对象</button>
|
||||
<button className="action" disabled={!active || importing} onClick={() => void saveFcstd()}>保存 FCStd 到 OPFS</button>
|
||||
@@ -2894,8 +2734,7 @@ function App() {
|
||||
{workbench === "Part" && active && workspaceTask === "split" && <PartSplitDocumentTask key={`${active}:${workspaceTask}:${partTaskMode?.split ?? ""}`} fixedMode={partTaskMode?.task === "split" ? partTaskMode.split : undefined}
|
||||
router={router} documentId={nativeName(active)} response={null} busy={importing}
|
||||
embedded={{ snapshot: partSnapshots[active], selected: compoundSelection,
|
||||
onSelection: chooseCompoundSources, onCancel: cancelWorkspaceTask,
|
||||
onRefresh: refreshPartSnapshot }}
|
||||
onSelection: chooseCompoundSources, onCancel: cancelWorkspaceTask }}
|
||||
execute={args => void (async () => {
|
||||
if (importing) return;
|
||||
const id = active;
|
||||
@@ -2922,8 +2761,7 @@ function App() {
|
||||
{workbench === "Part" && active && workspaceTask === "join" && <PartJoinTask key={`${active}:${workspaceTask}:${partTaskMode?.join ?? ""}`} fixedMode={partTaskMode?.task === "join" ? partTaskMode.join : undefined}
|
||||
router={router} documentId={nativeName(active)} response={null} busy={importing}
|
||||
embedded={{ snapshot: partSnapshots[active], selected: compoundSelection,
|
||||
onSelection: chooseCompoundSources, onCancel: cancelWorkspaceTask,
|
||||
onRefresh: refreshPartSnapshot }}
|
||||
onSelection: chooseCompoundSources, onCancel: cancelWorkspaceTask }}
|
||||
execute={args => void (async () => {
|
||||
if (importing) return;
|
||||
const id = active;
|
||||
@@ -3222,7 +3060,7 @@ function App() {
|
||||
{shortcutsOpen && <ShortcutEditor onClose={() => setShortcutsOpen(false)} />}
|
||||
{paletteOpen && <CommandPalette workbench={workbench} onCommand={executeManifestCommand} onClose={() => setPaletteOpen(false)} />}
|
||||
{bottomDockOpen && <BottomDock report={reportLog}
|
||||
selection={compoundSelection.map(name => objects.find(object => String(object.properties.NativeName) === name)?.properties.Label ?? name)}
|
||||
selection={compoundSelection.map(name => String(objects.find(object => String(object.properties.NativeName) === name)?.properties.Label ?? name))}
|
||||
onClose={() => setBottomDockOpen(false)} />}
|
||||
<ShortcutManager onCommand={executeManifestCommand} />
|
||||
{lineReferenceOpen && <LineReferencePanel onClose={() => setLineReferenceOpen(false)} />}</div><footer className="desktop-status-bar" aria-label="Status bar"><p role="status" data-import-phase={importPhase} className={`status ${response?.kind === "error" ? "error" : response?.kind === "result" ? "ok" : ""}`}>{status}</p></footer></PersistentToolbarWorkspace></div>;
|
||||
|
||||
352
web/src/python-family-dispatcher.ts
Normal file
352
web/src/python-family-dispatcher.ts
Normal file
@@ -0,0 +1,352 @@
|
||||
import { createFailure, type FacadeResponse } from "./facade-envelope.js";
|
||||
import { MESH_PYTHON_FIXTURE } from "./mesh-python-facade.js";
|
||||
import { MEASURE_PYTHON_FIXTURE } from "./measure-python-facade.js";
|
||||
import { MEASUREMENT_API_FIXTURE } from "./measure-measurement-facade.js";
|
||||
import { POINTS_PYTHON_FIXTURE } from "./points-python-facade.js";
|
||||
import { ROBOT_PYTHON_FIXTURE } from "./robot-python-facade.js";
|
||||
import { ROBOT_PYTHON_FAMILY_SCHEMA } from "./robot-python-family-facade.js";
|
||||
import { SKETCHER_PY_FIXTURE } from "./sketcher-python-facade.js";
|
||||
import { PART_PYTHON_FIXTURE } from "./part-python-facade.js";
|
||||
import { PARTDESIGN_PYTHON_FIXTURE } from "./partdesign-python-facade.js";
|
||||
import { PLOT_PYTHON_FAMILY_SCHEMA } from "./plot-python-family-facade.js";
|
||||
import { POINTS_PYTHON_FAMILY_SCHEMA } from "./points-python-family-facade.js";
|
||||
import { TECHDRAW_PY_FIXTURE } from "./techdraw-python-facade.js";
|
||||
import { TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA } from "./templatepymod-python-family-facade.js";
|
||||
import { IMPORT_PYTHON_FIXTURE } from "./import-python-facade.js";
|
||||
import { SANDBOX_PYTHON_FAMILY_SCHEMA } from "./sandbox-python-family-facade.js";
|
||||
import { SHOW_PYTHON_FAMILY_SCHEMA } from "./show-python-family-facade.js";
|
||||
import { createPythonApiLookup, type PythonApiRecord, type PythonApiRuntimeIndex } from "./python-api-runtime.js";
|
||||
import { WebModuleRouter } from "./module-router.js";
|
||||
|
||||
interface PythonModuleAdapter { module: string; command: string; payload: unknown; buildPayload?: (records: PythonApiRecord[]) => unknown; }
|
||||
function showSourcePath(name: string): string {
|
||||
const owner = name.split(".", 1)[0];
|
||||
if (["Camera", "ClipPlane", "Pickability", "Workbench"].includes(owner)) return `src/Mod/Show/SceneDetails/${owner}.py`;
|
||||
if (["Container", "ContainerError", "ContainerTreeError", "NotAContainerError"].includes(owner)) return "src/Mod/Show/Containers.py";
|
||||
if (["MAINSTACK", "TempoVis"].includes(owner)) return "src/Mod/Show/mTempoVis.py";
|
||||
if (owner === "TVObserver") return "src/Mod/Show/TVObserver.py";
|
||||
if (owner === "TVStack") return "src/Mod/Show/TVStack.py";
|
||||
if (owner === "SceneDetail") return "src/Mod/Show/SceneDetail.py";
|
||||
return "src/Mod/Show/__init__.py";
|
||||
}
|
||||
function sketcherSourcePath(name: string): string {
|
||||
const owner = name.split(".", 1)[0];
|
||||
if (owner === "SketcherWorkbench") return "src/Mod/Sketcher/InitGui.py";
|
||||
if (owner.startsWith("ViewProvider")) return "src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.pyi";
|
||||
return `src/Mod/Sketcher/App/${owner}.pyi`;
|
||||
}
|
||||
function spreadsheetSourcePath(name: string): string {
|
||||
const owner = name.split(".", 1)[0];
|
||||
if (owner === "FormulaTranslator" || owner === "exprNode") return "src/Mod/Spreadsheet/importXLSX.py";
|
||||
if (owner.startsWith("ViewProvider")) return "src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.pyi";
|
||||
return `src/Mod/Spreadsheet/App/${owner}.pyi`;
|
||||
}
|
||||
function surfaceSourcePath(name: string): string {
|
||||
const owner = name.split(".", 1)[0];
|
||||
if (owner === "SurfaceWorkbench") return "src/Mod/Surface/InitGui.py";
|
||||
if (owner === "BlendCurve" || owner === "BlendPoint") return `src/Mod/Surface/App/Blending/${owner}.pyi`;
|
||||
return `src/Mod/Surface/App/Blending/${owner}.pyi`;
|
||||
}
|
||||
function techdrawSourcePath(name: string): string {
|
||||
const owner = name.split(".", 1)[0];
|
||||
if (owner.startsWith("Command")) return `src/Mod/TechDraw/TechDrawTools/${owner}.py`;
|
||||
if (owner.endsWith("Test")) return `src/Mod/TechDraw/TDTest/${owner}.py`;
|
||||
if (owner.startsWith("ViewProvider")) return `src/Mod/TechDraw/Gui/${owner}.pyi`;
|
||||
return `src/Mod/TechDraw/App/${owner}.pyi`;
|
||||
}
|
||||
function templatePyModSourcePath(name: string): string {
|
||||
const owner = name.split(".", 1)[0];
|
||||
if (owner === "DocumentObject" || owner === "ViewProvider") return "src/Mod/TemplatePyMod/DocumentObject.py";
|
||||
if (owner === "TaskPanel" || owner.startsWith("Task")) return "src/Mod/TemplatePyMod/TaskPanel.py";
|
||||
if (owner === "MainWindow" || owner === "PythonQtWorkbench") return "src/Mod/TemplatePyMod/PythonQt.py";
|
||||
if (owner === "Texture" || owner === "ViewProviderTexture") return "src/Mod/TemplatePyMod/Texture.py";
|
||||
if (owner.startsWith("ViewProvider")) return "src/Mod/TemplatePyMod/FeaturePython.py";
|
||||
if (owner.startsWith("TemplatePy") || owner === "SphereCreator") return "src/Mod/TemplatePyMod/Commands.py";
|
||||
return "src/Mod/TemplatePyMod/FeaturePython.py";
|
||||
}
|
||||
const ADAPTERS: Record<string, PythonModuleAdapter> = {
|
||||
Assembly: {
|
||||
module: "Assembly",
|
||||
command: "assembly.pythonFamily",
|
||||
payload: { schema: "freecad-web-assembly/python-family/v1", module: "Assembly", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-assembly/python-family/v1",
|
||||
module: "Assembly",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })),
|
||||
}),
|
||||
},
|
||||
BIM: {
|
||||
module: "BIM",
|
||||
command: "bim.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-bim/python-family-batch/v1", module: "BIM", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-bim/python-family-batch/v1",
|
||||
module: "BIM",
|
||||
tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, sourcePath: record.sourcePath, sourceLine: record.sourceLine, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
CAM: {
|
||||
module: "CAM",
|
||||
command: "cam.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-cam/python-family-batch/v1", module: "CAM", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-cam/python-family-batch/v1",
|
||||
module: "CAM",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })),
|
||||
}),
|
||||
},
|
||||
Measure: { module: "Measure", command: "measure.pythonApi", payload: MEASURE_PYTHON_FIXTURE },
|
||||
"Measure.family": { module: "Measure", command: "measure.pythonFamilyBatch", payload: { schema: "freecad-web-measure/python-family-batch/v1", module: "Measure", tier: "tier-1-readonly", records: [] }, buildPayload: (records) => ({ schema: "freecad-web-measure/python-family-batch/v1", module: "Measure", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })) }) },
|
||||
"Mesh.family": { module: "Mesh", command: "mesh.pythonFamilyBatch", payload: { schema: "freecad-web-mesh/python-family-batch/v1", module: "Mesh", tier: "tier-1-readonly", records: [] }, buildPayload: (records) => ({ schema: "freecad-web-mesh/python-family-batch/v1", module: "Mesh", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })) }) },
|
||||
"MeshPart.family": { module: "MeshPart", command: "meshpart.pythonFamilyBatch", payload: { schema: "freecad-web-meshpart/python-family-batch/v1", module: "MeshPart", tier: "tier-1-readonly", records: [] }, buildPayload: (records) => ({ schema: "freecad-web-meshpart/python-family-batch/v1", module: "MeshPart", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })) }) },
|
||||
"Measure.measurementApi": { module: "Measure", command: "measure.measurementApi", payload: MEASUREMENT_API_FIXTURE },
|
||||
Mesh: { module: "Mesh", command: "mesh.pythonApi", payload: MESH_PYTHON_FIXTURE },
|
||||
Sketcher: { module: "Sketcher", command: "sketcher.pythonApi", payload: SKETCHER_PY_FIXTURE },
|
||||
"Sketcher.family": {
|
||||
module: "Sketcher",
|
||||
command: "sketcher.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-sketcher/python-family-batch/v1", module: "Sketcher", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-sketcher/python-family-batch/v1",
|
||||
module: "Sketcher",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: sketcherSourcePath(record.name), disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"Spreadsheet.family": {
|
||||
module: "Spreadsheet",
|
||||
command: "spreadsheet.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-spreadsheet/python-family-batch/v1", module: "Spreadsheet", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-spreadsheet/python-family-batch/v1",
|
||||
module: "Spreadsheet",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: spreadsheetSourcePath(record.name), disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"Surface.family": {
|
||||
module: "Surface",
|
||||
command: "surface.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-surface/python-family-batch/v1", module: "Surface", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-surface/python-family-batch/v1",
|
||||
module: "Surface",
|
||||
tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: surfaceSourcePath(record.name), disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"TechDraw.family": {
|
||||
module: "TechDraw",
|
||||
command: "techdraw.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-techdraw/python-family-batch/v1", module: "TechDraw", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-techdraw/python-family-batch/v1",
|
||||
module: "TechDraw",
|
||||
tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, sourcePath: techdrawSourcePath(record.name), disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"TemplatePyMod.family": {
|
||||
module: "TemplatePyMod",
|
||||
command: "templatepymod.pythonFamilyBatch",
|
||||
payload: { schema: TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA, module: "TemplatePyMod", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA,
|
||||
module: "TemplatePyMod",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, sourcePath: templatePyModSourcePath(record.name), disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
Robot: { module: "Robot", command: "robot.pythonApi", payload: ROBOT_PYTHON_FIXTURE },
|
||||
"Robot.family": {
|
||||
module: "Robot",
|
||||
command: "robot.pythonFamilyBatch",
|
||||
payload: { schema: ROBOT_PYTHON_FAMILY_SCHEMA, module: "Robot", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({ schema: ROBOT_PYTHON_FAMILY_SCHEMA, module: "Robot", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })) }),
|
||||
},
|
||||
Points: { module: "Points", command: "points.pythonApi", payload: POINTS_PYTHON_FIXTURE },
|
||||
Part: { module: "Part", command: "part.pythonApi", payload: PART_PYTHON_FIXTURE },
|
||||
"Part.family": {
|
||||
module: "Part",
|
||||
command: "part.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-part/python-family-batch/v1", module: "Part", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-part/python-family-batch/v1",
|
||||
module: "Part",
|
||||
tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"PartDesign.family": {
|
||||
module: "PartDesign",
|
||||
command: "partdesign.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-partdesign/python-family-batch/v1", module: "PartDesign", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-partdesign/python-family-batch/v1",
|
||||
module: "PartDesign",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
PartDesign: { module: "PartDesign", command: "partdesign.pythonApi", payload: PARTDESIGN_PYTHON_FIXTURE },
|
||||
"Plot.family": {
|
||||
module: "Plot",
|
||||
command: "plot.pythonFamilyBatch",
|
||||
payload: { schema: PLOT_PYTHON_FAMILY_SCHEMA, module: "Plot", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({ schema: PLOT_PYTHON_FAMILY_SCHEMA, module: "Plot", tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })) }),
|
||||
},
|
||||
"Points.family": {
|
||||
module: "Points",
|
||||
command: "points.pythonFamilyBatch",
|
||||
payload: { schema: POINTS_PYTHON_FAMILY_SCHEMA, module: "Points", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({ schema: POINTS_PYTHON_FAMILY_SCHEMA, module: "Points", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })) }),
|
||||
},
|
||||
TechDraw: { module: "TechDraw", command: "techdraw.pythonApi", payload: TECHDRAW_PY_FIXTURE },
|
||||
"Import.pythonApi": { module: "Import", command: "import.pythonApi", payload: IMPORT_PYTHON_FIXTURE },
|
||||
Cloud: {
|
||||
module: "Cloud",
|
||||
command: "cloud.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-cloud/python-family-batch/v1", module: "Cloud", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-cloud/python-family-batch/v1",
|
||||
module: "Cloud",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })),
|
||||
}),
|
||||
},
|
||||
Draft: {
|
||||
module: "Draft",
|
||||
command: "draft.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-draft/python-family-batch/v1", module: "Draft", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-draft/python-family-batch/v1",
|
||||
module: "Draft",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
Fem: {
|
||||
module: "Fem",
|
||||
command: "fem.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-fem/python-family-batch/v1", module: "Fem", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-fem/python-family-batch/v1",
|
||||
module: "Fem",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
Import: {
|
||||
module: "Import",
|
||||
command: "import.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-import/python-family-batch/v1", module: "Import", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-import/python-family-batch/v1",
|
||||
module: "Import",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"ReverseEngineering.family": {
|
||||
module: "ReverseEngineering",
|
||||
command: "reverseengineering.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-reverseengineering/python-family-batch/v1",
|
||||
module: "ReverseEngineering",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
Inspection: {
|
||||
module: "Inspection",
|
||||
command: "inspection.pythonFamilyBatch",
|
||||
payload: { schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: "freecad-web-inspection/python-family-batch/v1",
|
||||
module: "Inspection",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"Sandbox.family": {
|
||||
module: "Sandbox",
|
||||
command: "sandbox.pythonFamilyBatch",
|
||||
payload: { schema: SANDBOX_PYTHON_FAMILY_SCHEMA, module: "Sandbox", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: SANDBOX_PYTHON_FAMILY_SCHEMA,
|
||||
module: "Sandbox",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
"Show.family": {
|
||||
module: "Show",
|
||||
command: "show.pythonFamilyBatch",
|
||||
payload: { schema: SHOW_PYTHON_FAMILY_SCHEMA, module: "Show", tier: "tier-1-readonly", records: [] },
|
||||
buildPayload: (records) => ({
|
||||
schema: SHOW_PYTHON_FAMILY_SCHEMA,
|
||||
module: "Show",
|
||||
tier: "tier-1-readonly",
|
||||
records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: showSourcePath(record.name), disposition: record.disposition })),
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
export interface PythonFamilyResult { apiId: string; module: string; name: string; disposition?: string; status: string; nativeSchema?: string; nativeResult?: unknown; error?: unknown; }
|
||||
|
||||
export class PythonFamilyDispatcher {
|
||||
private readonly lookup: Map<string, PythonApiRecord>;
|
||||
|
||||
constructor(private readonly router: WebModuleRouter, index: PythonApiRuntimeIndex) {
|
||||
this.lookup = createPythonApiLookup(index);
|
||||
}
|
||||
|
||||
async dispatchBatch(apiIds: string[], documentId = "main-chain-document", options: { includePlanned?: boolean } = {}): Promise<{ schema: string; count: number; results: PythonFamilyResult[]; resourcesReleased: boolean }> {
|
||||
const results: PythonFamilyResult[] = [];
|
||||
const grouped = new Map<string, { record: PythonApiRecord; ids: string[]; adapterKey: string }>();
|
||||
for (const apiId of apiIds) {
|
||||
const record = this.lookup.get(apiId);
|
||||
if (!record) { results.push({ apiId, module: "", name: "", status: "not_implemented", error: { code: "unknown_api_id", message: "API ID is not present in the generated runtime index" } }); continue; }
|
||||
const pending = record.disposition === "planned" && options.includePlanned === true;
|
||||
if (record.disposition !== "exposed" && !pending) { results.push({ apiId, module: record.module, name: record.name, disposition: record.disposition, status: record.disposition, error: { code: "capability_denied", message: `API disposition is ${record.disposition}` } }); continue; }
|
||||
const adapterKey = record.module === "Measure" && record.tier === "tier-1-readonly" ? "Measure.family" : record.module === "Measure" && record.name.startsWith("Measurement.") ? "Measure.measurementApi" : record.module === "Mesh" && record.tier === "tier-1-readonly" ? "Mesh.family" : record.module === "MeshPart" && record.tier === "tier-1-readonly" ? "MeshPart.family" : record.module === "Part" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "Part.family" : record.module === "PartDesign" && record.tier === "tier-1-readonly" ? "PartDesign.family" : record.module === "Plot" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "Plot.family" : record.module === "Points" && record.tier === "tier-1-readonly" ? "Points.family" : record.module === "ReverseEngineering" && record.tier === "tier-1-readonly" ? "ReverseEngineering.family" : record.module === "Robot" && record.tier === "tier-1-readonly" ? "Robot.family" : record.module === "Sandbox" && record.tier === "tier-1-readonly" ? "Sandbox.family" : record.module === "Show" && record.tier === "tier-1-readonly" ? "Show.family" : record.module === "Sketcher" && record.tier === "tier-1-readonly" ? "Sketcher.family" : record.module === "Spreadsheet" && record.tier === "tier-1-readonly" ? "Spreadsheet.family" : record.module === "Surface" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "Surface.family" : record.module === "TechDraw" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "TechDraw.family" : record.module === "TemplatePyMod" && record.tier === "tier-1-readonly" ? "TemplatePyMod.family" : record.module === "Import" && record.tier !== "tier-1-readonly" ? "Import.pythonApi" : record.module;
|
||||
const group = grouped.get(adapterKey) ?? { record, ids: [], adapterKey };
|
||||
group.ids.push(apiId); grouped.set(adapterKey, group);
|
||||
}
|
||||
for (const [adapterKey, group] of grouped) {
|
||||
const module = group.record.module;
|
||||
const adapter = ADAPTERS[adapterKey];
|
||||
if (!adapter) {
|
||||
for (const apiId of group.ids) results.push({ apiId, module, name: group.record.name, status: "not_implemented", error: { code: "module_adapter_pending", message: `No Python module adapter is registered for ${module}` } });
|
||||
continue;
|
||||
}
|
||||
const response: FacadeResponse = await this.router.request(adapter.module, adapter.command, adapter.buildPayload ? adapter.buildPayload(group.ids.map((id) => this.lookup.get(id)!)) : adapter.payload, documentId);
|
||||
for (const apiId of group.ids) {
|
||||
const record = this.lookup.get(apiId)!;
|
||||
if (response.kind !== "result") {
|
||||
results.push({ apiId, module, name: record.name, disposition: record.disposition, status: "adapter_error", error: response.error });
|
||||
continue;
|
||||
}
|
||||
const nativeResult = response.result;
|
||||
const nativeRecords = nativeResult && typeof nativeResult === "object" && Array.isArray((nativeResult as Record<string, unknown>).records)
|
||||
? (nativeResult as Record<string, unknown>).records as Array<Record<string, unknown>>
|
||||
: [];
|
||||
const nativeRecord = nativeRecords.find((item) => item.apiId === apiId);
|
||||
if (nativeRecord?.status === "restricted" || nativeRecord?.status === "not_implemented") {
|
||||
results.push({ apiId, module, name: record.name, disposition: nativeRecord.status, status: nativeRecord.status, nativeSchema: String((nativeResult as Record<string, unknown>).schema ?? ""), nativeResult: nativeRecord, error: { code: nativeRecord.code, message: nativeRecord.message } });
|
||||
} else {
|
||||
results.push({ apiId, module, name: record.name, disposition: record.disposition, status: record.disposition === "planned" ? "module_adapter_ready_pending_method" : "module_adapter_ready", nativeSchema: String((nativeResult as Record<string, unknown>).schema ?? ""), nativeResult });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { schema: "freecad-web-python-family-result/v1", count: results.length, results, resourcesReleased: results.every((result) => result.status !== "adapter_error") };
|
||||
}
|
||||
}
|
||||
|
||||
export function pythonFamilyFailure(apiId: string, message: string): FacadeResponse {
|
||||
return createFailure(`python-${apiId}`, "python_family_error", message, { apiId });
|
||||
}
|
||||
310
web/src/scene-command-host.ts
Normal file
310
web/src/scene-command-host.ts
Normal file
@@ -0,0 +1,310 @@
|
||||
import * as THREE from "three";
|
||||
import type { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||
import { createElement, ZoomIn, ZoomOut, Maximize, RotateCcw, RotateCw, Save, History, MousePointer2, Move, Rotate3d, Hand, Compass, Crosshair, Scan, Mouse, Navigation, LocateFixed, Orbit, Smartphone, type IconNode } from "lucide";
|
||||
import { registerSceneCommandHost, type SceneDisplayState } from "./scene-command-adapter.js";
|
||||
import "./scene-command-host.css";
|
||||
import { attachOverlapPicker, type PickableSceneObject } from "./scene-overlap-picker.js";
|
||||
import { attachCameraCommands } from "./scene-camera-commands.js";
|
||||
import { orbitStyles, orbitStyle } from "./scene-orbit-model.js";
|
||||
import { navigationStyles, defaultNavigationStyle } from "./scene-navigation.js";
|
||||
import type { NavigationPreferenceSource, ViewPreferences } from "./view-navigation-preferences.js";
|
||||
|
||||
export function attachSceneCommands(scene: THREE.Scene, controls: OrbitControls, container: HTMLElement,
|
||||
documentId: () => string, invalidate: () => void,
|
||||
picking?: { canvas: HTMLCanvasElement; objects(): PickableSceneObject[]; select(id: string): void },
|
||||
onControlsChanged?: (next: OrbitControls) => void,
|
||||
navigation?: { source: NavigationPreferenceSource; apply(values: ViewPreferences): void; cancel(): void }) {
|
||||
const picker = picking ? attachOverlapPicker(picking.canvas, container, () => controls.object,
|
||||
documentId, picking.objects, picking.select) : undefined;
|
||||
const cross = new THREE.AxesHelper(10);
|
||||
cross.visible = false;
|
||||
scene.add(cross);
|
||||
const toolbar = document.createElement("div");
|
||||
toolbar.className = "scene-display-tools";
|
||||
toolbar.setAttribute("aria-label", "3D display controls");
|
||||
const axes = document.createElement("input");
|
||||
axes.type = "checkbox"; axes.setAttribute("aria-label", "Axis cross");
|
||||
const play = document.createElement("input");
|
||||
play.type = "checkbox"; play.setAttribute("aria-label", "Turntable");
|
||||
const speed = document.createElement("input");
|
||||
speed.type = "range"; speed.min = "-10"; speed.max = "10"; speed.step = "0.25"; speed.value = "2";
|
||||
speed.setAttribute("aria-label", "Turntable speed");
|
||||
const label = (text: string, control: HTMLElement) => {
|
||||
const element = document.createElement("label");
|
||||
element.append(control, document.createTextNode(text));
|
||||
toolbar.append(element);
|
||||
};
|
||||
label("轴十字", axes); label("转台", play); label("速度", speed);
|
||||
const stop = document.createElement("button");
|
||||
stop.type = "button"; stop.textContent = "停止"; stop.title = "停止转台";
|
||||
toolbar.append(stop);
|
||||
if (picker) {
|
||||
const choose = document.createElement("button");
|
||||
choose.type = "button"; choose.textContent = "选择重叠对象"; choose.title = "选择重叠对象";
|
||||
choose.onclick = () => picker.show();
|
||||
toolbar.append(choose);
|
||||
}
|
||||
let disposed = false;
|
||||
let unsubscribeNavigation: (() => void) | undefined;
|
||||
if (navigation) {
|
||||
const select = document.createElement("select");
|
||||
select.setAttribute("aria-label", "Navigation style"); select.disabled = true;
|
||||
for (const style of navigationStyles) {
|
||||
const option = document.createElement("option");
|
||||
option.id = style.id; option.value = style.value; option.textContent = style.label;
|
||||
select.append(option);
|
||||
}
|
||||
select.value = defaultNavigationStyle;
|
||||
const orbit = document.createElement("select");
|
||||
orbit.setAttribute("aria-label", "Orbit style"); orbit.disabled = true;
|
||||
orbitStyles.forEach((name, value) => {
|
||||
const option = document.createElement("option");
|
||||
option.value = String(value); option.textContent = name; orbit.append(option);
|
||||
});
|
||||
orbit.value = "4";
|
||||
const error = document.createElement("span");
|
||||
error.setAttribute("role", "alert"); error.className = "scene-camera-error"; error.hidden = true;
|
||||
const indicator = document.createElement("label");
|
||||
indicator.className = "scene-navigation-indicator"; indicator.hidden = true;
|
||||
const caption = document.createElement("span"); caption.textContent = "Navigation";
|
||||
const iconNodes: Record<string, IconNode> = {
|
||||
Blender: Move, CAD: MousePointer2, Gesture: Rotate3d, MayaGesture: Hand,
|
||||
OpenCascade: Compass, OpenInventor: Crosshair, Revit: Mouse,
|
||||
SiemensNX: Navigation, SolidWorks: LocateFixed, TinkerCAD: Orbit, Touchpad: Smartphone,
|
||||
};
|
||||
let icon = createElement(MousePointer2, { width: 16, height: 16, "aria-hidden": "true" });
|
||||
indicator.append(icon, select, caption);
|
||||
const settings = document.createElement("details");
|
||||
const summary = document.createElement("summary"); summary.textContent = "Navigation settings";
|
||||
settings.append(summary);
|
||||
settings.addEventListener("keydown", event => {
|
||||
if (event.key === "Escape") { event.stopPropagation(); settings.open = false; summary.focus(); }
|
||||
});
|
||||
const toggles = new Map<string, HTMLInputElement>();
|
||||
let presentation: ViewPreferences = {};
|
||||
let styleHelp = "";
|
||||
const effectiveTheme = () => {
|
||||
const root = document.documentElement;
|
||||
const forced = root.dataset.theme || root.getAttribute("data-color-scheme") ||
|
||||
(root.classList.contains("dark") ? "dark" : root.classList.contains("light") ? "light" : "");
|
||||
if (forced) return forced.toLowerCase().includes("dark") ? "dark" : "light";
|
||||
return getComputedStyle(root).colorScheme.toLowerCase().includes("dark") ||
|
||||
(window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false) ? "dark" : "light";
|
||||
};
|
||||
const refreshIcon = () => {
|
||||
const style = navigationStyles.find(item => item.value === select.value);
|
||||
const name = style?.id.replace("Indicator_Navigation", "") ?? "CAD";
|
||||
const next = createElement(iconNodes[name] ?? MousePointer2, { width: 16, height: 16, "aria-hidden": "true" });
|
||||
next.dataset.theme = effectiveTheme();
|
||||
icon.replaceWith(next); icon = next;
|
||||
};
|
||||
const renderPresentation = () => {
|
||||
indicator.hidden = presentation.Enabled === false;
|
||||
indicator.classList.toggle("is-compact", presentation.Compact === true);
|
||||
select.title = presentation.Tooltip === false ? "" : styleHelp;
|
||||
for (const [name, input] of toggles) input.checked = name === "Compact" ? presentation[name] === true : presentation[name] !== false;
|
||||
};
|
||||
for (const [name, text] of [["Enabled", "Show navigation indicator"], ["Compact", "Compact"], ["Tooltip", "Tooltip"]]) {
|
||||
const row = document.createElement("label");
|
||||
const input = document.createElement("input"); input.type = "checkbox"; input.disabled = true;
|
||||
toggles.set(name, input); row.append(input, document.createTextNode(text)); settings.append(row);
|
||||
input.onchange = async () => {
|
||||
const value = input.checked;
|
||||
toggles.forEach(toggle => { toggle.disabled = true; });
|
||||
try {
|
||||
const result = await navigation.source.writeIndicator(name, value);
|
||||
if (disposed) return;
|
||||
presentation = result.values; renderPresentation();
|
||||
error.textContent = result.error ?? ""; error.hidden = !result.error;
|
||||
} catch (cause) {
|
||||
if (!disposed) { renderPresentation(); error.textContent = String(cause); error.hidden = false; }
|
||||
} finally { if (!disposed) toggles.forEach(toggle => { toggle.disabled = false; }); }
|
||||
};
|
||||
}
|
||||
let revision = 0;
|
||||
const apply = (result: { values: ViewPreferences; error?: string }) => {
|
||||
navigation.apply(result.values);
|
||||
orbit.value = String(orbitStyle(result.values.OrbitStyle));
|
||||
const value = String(result.values.NavigationStyle || defaultNavigationStyle);
|
||||
const normalized = value === "Undefined" ? defaultNavigationStyle : value;
|
||||
select.querySelector("[data-unknown-style]")?.remove();
|
||||
const known = navigationStyles.find(style => style.value === normalized);
|
||||
if (!known) {
|
||||
const option = document.createElement("option"); option.value = normalized;
|
||||
option.textContent = `Unknown: ${normalized} (CAD input)`; option.dataset.unknownStyle = "true";
|
||||
select.append(option);
|
||||
}
|
||||
select.value = normalized;
|
||||
select.setAttribute("aria-label", `Navigation style: ${known?.label ?? normalized}`);
|
||||
styleHelp = known?.help ?? `Unknown native navigation style: ${normalized}. CAD input fallback.`;
|
||||
refreshIcon();
|
||||
renderPresentation();
|
||||
error.textContent = result.error ?? ""; error.hidden = !result.error;
|
||||
};
|
||||
const refresh = async () => {
|
||||
const token = ++revision;
|
||||
try {
|
||||
const result = await navigation.source.read();
|
||||
const indicatorResult = await navigation.source.readIndicator();
|
||||
if (!disposed && token === revision) {
|
||||
presentation = indicatorResult.values;
|
||||
apply({ ...result, error: result.error ?? indicatorResult.error });
|
||||
toggles.forEach(toggle => { toggle.disabled = false; });
|
||||
}
|
||||
}
|
||||
catch (cause) { if (!disposed && token === revision) { error.textContent = String(cause); error.hidden = false; } }
|
||||
finally { if (!disposed && token === revision) select.disabled = orbit.disabled = false; }
|
||||
};
|
||||
select.onchange = async () => {
|
||||
const value = select.value;
|
||||
if (!navigationStyles.some(style => style.value === value)) return;
|
||||
navigation.cancel(); select.disabled = orbit.disabled = true;
|
||||
++revision;
|
||||
try {
|
||||
const result = await navigation.source.write(value);
|
||||
if (!disposed) apply(result);
|
||||
} catch (cause) {
|
||||
if (!disposed) { await refresh(); error.textContent = String(cause); error.hidden = false; }
|
||||
} finally { if (!disposed) select.disabled = orbit.disabled = false; }
|
||||
};
|
||||
select.addEventListener("pointerdown", refreshIcon);
|
||||
select.addEventListener("focus", refreshIcon);
|
||||
const themeObserver = new MutationObserver(refreshIcon);
|
||||
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme", "data-color-scheme"] });
|
||||
const themeMedia = window.matchMedia?.("(prefers-color-scheme: dark)");
|
||||
themeMedia?.addEventListener("change", refreshIcon);
|
||||
orbit.onchange = async () => {
|
||||
const value = Number(orbit.value);
|
||||
navigation.cancel(); select.disabled = orbit.disabled = true;
|
||||
++revision;
|
||||
try {
|
||||
const result = await navigation.source.writeOrbit(value);
|
||||
if (!disposed) apply(result);
|
||||
} catch (cause) {
|
||||
if (!disposed) { await refresh(); error.textContent = String(cause); error.hidden = false; }
|
||||
} finally { if (!disposed) select.disabled = orbit.disabled = false; }
|
||||
};
|
||||
toolbar.append(indicator, settings); label("Orbit style", orbit); toolbar.append(error);
|
||||
unsubscribeNavigation = navigation.source.subscribe(() => { void refresh(); });
|
||||
void refresh();
|
||||
const oldUnsubscribe = unsubscribeNavigation;
|
||||
unsubscribeNavigation = () => {
|
||||
oldUnsubscribe?.(); themeObserver.disconnect(); themeMedia?.removeEventListener("change", refreshIcon);
|
||||
};
|
||||
}
|
||||
const oldPosition = container.style.position;
|
||||
if (getComputedStyle(container).position === "static") container.style.position = "relative";
|
||||
container.append(toolbar);
|
||||
const states = new Map<string, SceneDisplayState>();
|
||||
const state = () => states.get(documentId()) ?? { axes: false, rotating: false, speed: 2 };
|
||||
const apply = (next: SceneDisplayState) => {
|
||||
states.set(documentId(), next);
|
||||
cross.visible = next.axes;
|
||||
controls.autoRotate = next.rotating;
|
||||
controls.autoRotateSpeed = next.speed;
|
||||
axes.checked = next.axes; play.checked = next.rotating; speed.value = String(next.speed);
|
||||
invalidate();
|
||||
return { ...next };
|
||||
};
|
||||
axes.onchange = () => apply({ ...state(), axes: axes.checked });
|
||||
play.onchange = () => apply({ ...state(), rotating: play.checked });
|
||||
speed.oninput = () => apply({ ...state(), speed: Number(speed.value) });
|
||||
stop.onclick = () => apply({ ...state(), rotating: false });
|
||||
const replaceControls = (next: OrbitControls) => {
|
||||
controls.removeEventListener("change", changed);
|
||||
controls = next;
|
||||
controls.addEventListener("change", changed);
|
||||
picker?.close();
|
||||
onControlsChanged?.(next);
|
||||
};
|
||||
const cameraCommands = onControlsChanged ? attachCameraCommands(() => controls, replaceControls, documentId, () => picking?.objects() ?? []) : undefined;
|
||||
const runCameraCommand = (command: string, action: unknown) => {
|
||||
const camera = cameraCommands?.execute(command, action);
|
||||
if (!camera) return;
|
||||
const next = { ...state(), camera };
|
||||
return action === "read" || action === "cancel" ? next : apply({ ...next, rotating: controls.autoRotate });
|
||||
};
|
||||
if (cameraCommands) {
|
||||
const error = document.createElement("span");
|
||||
error.className = "scene-camera-error"; error.setAttribute("role", "alert"); error.hidden = true;
|
||||
const execute = (command: string) => {
|
||||
try { runCameraCommand(command, "apply"); error.hidden = true; error.textContent = ""; }
|
||||
catch (cause) { error.textContent = cause instanceof Error ? cause.message : String(cause); error.hidden = false; }
|
||||
};
|
||||
const views = document.createElement("select");
|
||||
views.setAttribute("aria-label", "标准视图"); views.title = "标准视图";
|
||||
for (const [command, title] of [["", "视图"], ["Std_ViewTop", "顶视图"], ["Std_ViewBottom", "底视图"],
|
||||
["Std_ViewFront", "前视图"], ["Std_ViewRear", "后视图"], ["Std_ViewLeft", "左视图"], ["Std_ViewRight", "右视图"],
|
||||
["Std_ViewIsometric", "等轴测"], ["Std_ViewDimetric", "正二轴测"], ["Std_ViewTrimetric", "正三轴测"]]) {
|
||||
const option = document.createElement("option"); option.value = command; option.textContent = title; views.append(option);
|
||||
}
|
||||
views.onchange = () => { if (views.value) execute(views.value); views.value = ""; };
|
||||
toolbar.append(views);
|
||||
const button = (command: string, title: string, icon: IconNode) => {
|
||||
const element = document.createElement("button"); element.type = "button";
|
||||
element.className = "scene-camera-button"; element.title = title; element.setAttribute("aria-label", title);
|
||||
element.append(createElement(icon, { width: 16, height: 16, "aria-hidden": "true" }));
|
||||
element.onclick = () => execute(command); toolbar.append(element);
|
||||
};
|
||||
button("Std_ViewZoomIn", "放大", ZoomIn); button("Std_ViewZoomOut", "缩小", ZoomOut);
|
||||
button("Std_ViewFitAll", "适配全部", Maximize);
|
||||
button("Std_ViewRotateLeft", "向左旋转视图", RotateCcw); button("Std_ViewRotateRight", "向右旋转视图", RotateCw);
|
||||
button("Std_StoreWorkingView", "存储工作视图", Save); button("Std_RecallWorkingView", "恢复工作视图", History);
|
||||
toolbar.append(error);
|
||||
}
|
||||
const unregister = registerSceneCommandHost({
|
||||
documentId,
|
||||
widgetSurface: container,
|
||||
visible: () => container.isConnected && container.getClientRects().length > 0,
|
||||
execute(command, args) {
|
||||
const action = args.action ?? "apply";
|
||||
if (!["read", "apply", "accept", "cancel"].includes(String(action))) throw new Error("Unknown view action");
|
||||
const next = { ...state() };
|
||||
const cameraResult = runCameraCommand(command, action);
|
||||
if (cameraResult) return cameraResult;
|
||||
if (command === "Std_ClarifySelection") {
|
||||
if (!picker) throw new Error("This view has no object picking provider");
|
||||
if (action === "read") return { ...next, selectionScope: "rendered-object", ...picker.snapshot() };
|
||||
if (action === "cancel") { picker.close(); return { ...next, selectionScope: "rendered-object", selectionPending: false, candidates: [] }; }
|
||||
const point = args.point;
|
||||
if (point !== undefined && (!Array.isArray(point) || point.length !== 2 || point.some(value => typeof value !== "number" || !Number.isFinite(value))))
|
||||
throw new Error("point requires two finite canvas coordinates");
|
||||
const bounds = picking!.canvas.getBoundingClientRect();
|
||||
const candidates = picker.show(Array.isArray(point) ? { x: bounds.left + point[0], y: bounds.top + point[1] } : undefined);
|
||||
return { ...next, selectionScope: "rendered-object", selectionPending: candidates.length > 0, candidates };
|
||||
}
|
||||
if (action === "read") return next;
|
||||
if (command === "Std_AxisCross") {
|
||||
if (args.enabled !== undefined && typeof args.enabled !== "boolean") throw new Error("enabled must be boolean");
|
||||
if (action === "cancel") return next;
|
||||
next.axes = typeof args.enabled === "boolean" ? args.enabled : !next.axes;
|
||||
} else if (command === "Std_DemoMode") {
|
||||
if (args.speed !== undefined && (typeof args.speed !== "number" || !Number.isFinite(args.speed) || Math.abs(args.speed) > 10)) throw new Error("Turntable speed must be between -10 and 10");
|
||||
if (args.play !== undefined && typeof args.play !== "boolean") throw new Error("play must be boolean");
|
||||
next.rotating = action === "cancel" ? false : typeof args.play === "boolean" ? args.play : !next.rotating;
|
||||
if (typeof args.speed === "number") next.speed = args.speed;
|
||||
toolbar.hidden = false;
|
||||
} else throw new Error("This view has no handler for the requested command");
|
||||
return apply(next);
|
||||
},
|
||||
});
|
||||
// A view may switch documents without being remounted.
|
||||
let active = documentId();
|
||||
const changed = () => {
|
||||
if (active === documentId()) return;
|
||||
active = documentId();
|
||||
picker?.close();
|
||||
apply({ ...state(), rotating: false });
|
||||
};
|
||||
controls.addEventListener("change", changed);
|
||||
return { replaceControls, executeCamera: (command: string) => runCameraCommand(command, "apply"), dispose() {
|
||||
disposed = true; unsubscribeNavigation?.();
|
||||
cameraCommands?.dispose();
|
||||
picker?.dispose();
|
||||
unregister(); controls.removeEventListener("change", changed); controls.autoRotate = false;
|
||||
toolbar.remove(); cross.removeFromParent(); cross.geometry.dispose();
|
||||
const materials = Array.isArray(cross.material) ? cross.material : [cross.material];
|
||||
materials.forEach(material => material.dispose());
|
||||
container.style.position = oldPosition;
|
||||
} };
|
||||
}
|
||||
22
web/src/scene-document.ts
Normal file
22
web/src/scene-document.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
export interface SceneDocument {
|
||||
documentId: string;
|
||||
documentToken?: string;
|
||||
action?: string;
|
||||
undoCount?: number;
|
||||
redoCount?: number;
|
||||
selection: string[];
|
||||
created?: string[];
|
||||
removed?: string[];
|
||||
modified?: string[];
|
||||
file?: { name: string; base64: string };
|
||||
objects: Array<{
|
||||
name: string; label: string; typeId: string; dependencies: string[];
|
||||
measurement?: import("./measure-document-adapter.js").DistanceAnnotation;
|
||||
faceCount?: number; edgeCount?: number; visible?: boolean;
|
||||
explodeGroup?: { eligible: boolean; reason: string };
|
||||
color?: number[]; colors?: number[]; opacity?: number; points?: number[][]; facets?: number[][]; lines?: number[][][]; pointMarkers?: number[][];
|
||||
placement?: number[];
|
||||
tolerance?: { vertex: number; edge: number; face: number };
|
||||
base?: string | null;
|
||||
}>;
|
||||
}
|
||||
414
web/src/scene-navigation.ts
Normal file
414
web/src/scene-navigation.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
// Input sequences ported from src/Gui/Navigation/*NavigationStyle.cpp.
|
||||
// Camera motion remains on the scene's existing OrbitControls/camera/target.
|
||||
import * as THREE from "three";
|
||||
import { orbitStyle, rotateOrbit } from "./scene-orbit-model.js";
|
||||
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||
import type { ViewPreferences } from "./view-navigation-preferences.js";
|
||||
|
||||
export const navigationStyles = [
|
||||
["Blender", "Blender", "Shift+middle: pan; middle: rotate; Ctrl+middle: zoom; left+right: pan"],
|
||||
["CAD", "CAD", "Middle: pan; hold middle then left/right: rotate; click and release left/right while holding middle: zoom; Ctrl+right: pan; Shift+right: rotate; Ctrl+Shift+right: zoom"],
|
||||
["Gesture", "Gesture", "Left drag: rotate; right drag or hold left then drag: pan; left+right drag: tilt; one finger: rotate; two fingers: pan/pinch zoom; H or middle: recenter"],
|
||||
["MayaGesture", "MayaGesture", "Alt+left: rotate; Alt+middle: pan; Alt+right: zoom; one finger: rotate; two fingers: pan/pinch zoom/twist"],
|
||||
["OpenCascade", "OpenCascade", "Middle or Ctrl+middle: pan; Ctrl+right: rotate; Ctrl+left horizontal drag: zoom"],
|
||||
["OpenInventor", "Inventor", "Ctrl/Shift+left: select; left: rotate; middle or Ctrl+Shift: pan; left+middle or Ctrl+middle: zoom"],
|
||||
["Revit", "Revit", "Middle or left+right: pan; Shift+middle: rotate; Ctrl+middle: zoom"],
|
||||
["SiemensNX", "SiemensNX", "Middle: rotate; middle+right or Shift+middle: pan; middle+left or Ctrl+middle: zoom; Home: isometric; End: trimetric; F8: top; Ctrl+F: fit"],
|
||||
["SolidWorks", "SolidWorks", "Middle: rotate; Ctrl+middle: pan; Shift+middle: zoom"],
|
||||
["TinkerCAD", "TinkerCAD", "Middle: pan; right: rotate"],
|
||||
["Touchpad", "Touchpad", "Shift and pointer motion: pan; Alt or Shift+left and motion: rotate; Ctrl+Shift and motion: zoom"],
|
||||
].map(([id, native, help]) => ({ id: `Indicator_Navigation${id}`, value: `Gui::${native}NavigationStyle`,
|
||||
label: id === "SiemensNX" ? "Siemens NX" : id, help: `${help}. Left click selects (OpenInventor: Ctrl/Shift+left); Ctrl adds selection. Wheel or PageUp/PageDown: zoom.` }));
|
||||
export const defaultNavigationStyle = "Gui::CADNavigationStyle";
|
||||
type Mode = "idle" | "select" | "pan" | "rotate" | "zoom" | "tilt";
|
||||
type Point = { x: number; y: number };
|
||||
|
||||
export class SceneNavigation {
|
||||
enabled = true;
|
||||
// Set while a transform controller is attached. Left-button presses land on
|
||||
// the gizmo (which paints its own handles); everything else, including
|
||||
// middle-drag orbit and wheel zoom, still belongs to the navigation.
|
||||
gizmoActive = false;
|
||||
gizmoHover = false;
|
||||
private controls: OrbitControls;
|
||||
private style = "CAD";
|
||||
private preferences: ViewPreferences = {};
|
||||
private mode: Mode = "idle";
|
||||
private buttons = 0;
|
||||
private start: Point | null = null;
|
||||
private last: Point | null = null;
|
||||
private started = 0;
|
||||
private chordStarted = 0;
|
||||
private moved = false;
|
||||
private consumed = false;
|
||||
private cancelled = false;
|
||||
private cadZoom = false;
|
||||
private seek = false;
|
||||
private touch = new Map<number, Point>();
|
||||
private captured = new Set<number>();
|
||||
private over = false;
|
||||
private blockContext = false;
|
||||
private gestureMode: Mode | null = null;
|
||||
private readonly originalTouchAction: string;
|
||||
constructor(private canvas: HTMLCanvasElement, controls: OrbitControls,
|
||||
private pick: (point: Point, additive: boolean) => void,
|
||||
private hitPoint: (point: Point) => THREE.Vector3 | undefined,
|
||||
private command: (command: string) => void,
|
||||
private invalidate: () => void,
|
||||
private replaceControls: (controls: OrbitControls) => void) {
|
||||
this.controls = controls;
|
||||
this.originalTouchAction = canvas.style.touchAction;
|
||||
this.bind(controls);
|
||||
canvas.tabIndex = 0;
|
||||
canvas.setAttribute("aria-label", "3D viewport");
|
||||
canvas.addEventListener("pointerdown", this.pointer, true);
|
||||
canvas.addEventListener("pointermove", this.pointer, true);
|
||||
canvas.addEventListener("pointerup", this.pointer, true);
|
||||
canvas.addEventListener("blur", this.cancelEvent);
|
||||
canvas.addEventListener("pointercancel", this.cancelEvent, true);
|
||||
canvas.addEventListener("lostpointercapture", this.lostCapture, true);
|
||||
canvas.addEventListener("pointerenter", this.enter);
|
||||
canvas.addEventListener("pointerleave", this.leave);
|
||||
canvas.addEventListener("wheel", this.wheel, { passive: false, capture: true });
|
||||
canvas.addEventListener("contextmenu", this.context, true);
|
||||
window.addEventListener("keydown", this.key, true);
|
||||
window.addEventListener("keyup", this.key, true);
|
||||
window.addEventListener("blur", this.cancelEvent);
|
||||
document.addEventListener("visibilitychange", this.visibility);
|
||||
}
|
||||
bind(controls: OrbitControls) {
|
||||
this.cancel(); this.controls = controls;
|
||||
// Disconnect only OrbitControls' default input listeners. Its camera,
|
||||
// public motion methods, change events and scene commands are reused.
|
||||
controls.disconnect(); controls.enableDamping = false;
|
||||
this.canvas.style.touchAction = "none";
|
||||
}
|
||||
apply(preferences: ViewPreferences) {
|
||||
this.cancel(); this.preferences = preferences;
|
||||
const value = String(preferences.NavigationStyle || defaultNavigationStyle);
|
||||
this.style = navigationStyles.find(item => item.value === value)?.label.replace(" ", "") ?? "CAD";
|
||||
}
|
||||
cancel() {
|
||||
this.cancelled = true; this.consumed = true; this.seek = false;
|
||||
this.start = null; this.last = null; this.mode = "idle"; this.buttons = 0;
|
||||
this.cadZoom = false; this.gestureMode = null; this.touch.clear();
|
||||
const captured = [...this.captured];
|
||||
this.captured.clear();
|
||||
for (const id of captured) if (this.canvas.hasPointerCapture(id)) this.canvas.releasePointerCapture(id);
|
||||
}
|
||||
private enter = () => { this.over = true; };
|
||||
private leave = () => { this.over = false; if (!this.buttons) this.last = null; };
|
||||
private cancelEvent = () => { this.blockContext = true; this.cancel(); };
|
||||
private lostCapture = (event: PointerEvent) => { if (this.captured.has(event.pointerId)) this.cancelEvent(); };
|
||||
private visibility = () => { if (document.hidden) this.cancelEvent(); };
|
||||
private choose(event: MouseEvent | KeyboardEvent, buttons: number): Mode {
|
||||
const l = !!(buttons & 1), r = !!(buttons & 2), m = !!(buttons & 4);
|
||||
const c = event.ctrlKey, s = event.shiftKey, a = event.altKey;
|
||||
switch (this.style) {
|
||||
case "CAD":
|
||||
if (m && (l || r)) return "rotate";
|
||||
if (m) return this.cadZoom ? "zoom" : "pan";
|
||||
if (r && c && s) return "zoom";
|
||||
if (r && c) return "pan";
|
||||
if (r && s) return "rotate";
|
||||
break;
|
||||
case "Blender":
|
||||
if (l && r) return "pan";
|
||||
if ((m && c) || (r && c && s)) return "zoom";
|
||||
if (m && s) return "pan";
|
||||
if (m) return "rotate";
|
||||
break;
|
||||
case "Revit":
|
||||
if (l && r) return "pan";
|
||||
if ((m && c) || (r && c && s)) return "zoom";
|
||||
if (m && s) return "rotate";
|
||||
if (m) return "pan";
|
||||
break;
|
||||
case "SolidWorks":
|
||||
if (m && c) return "pan";
|
||||
if (m && s) return "zoom";
|
||||
if (m) return "rotate";
|
||||
break;
|
||||
case "SiemensNX":
|
||||
if (m && (r || s)) return "pan";
|
||||
if (m && (l || c)) return "zoom";
|
||||
if (m) return "rotate";
|
||||
break;
|
||||
case "OpenCascade":
|
||||
if (l && c) return "zoom";
|
||||
if (r && c) return "rotate";
|
||||
if (m) return "pan";
|
||||
break;
|
||||
case "OpenInventor":
|
||||
if ((l && m) || (c && m) || (c && s && r)) return "zoom";
|
||||
if (m || (c && s)) return "pan";
|
||||
if (l) return c || s ? "select" : "rotate";
|
||||
break;
|
||||
case "TinkerCAD":
|
||||
if (m) return "pan";
|
||||
if (r) return "rotate";
|
||||
break;
|
||||
case "Touchpad":
|
||||
if (c && s) return "zoom";
|
||||
if (a || (s && l)) return "rotate";
|
||||
if (s) return "pan";
|
||||
break;
|
||||
case "Gesture":
|
||||
if (l && r) return "tilt";
|
||||
if (this.gestureMode && buttons) return this.gestureMode;
|
||||
if (r) return "pan";
|
||||
if (l && !a && !c && !s) return performance.now() - this.started >= this.holdTime() ? "pan" : "rotate";
|
||||
break;
|
||||
case "MayaGesture":
|
||||
if (a && l && r) return "tilt";
|
||||
if (a && m) return "pan";
|
||||
if (a && r) return "zoom";
|
||||
if (a && l) return "rotate";
|
||||
break;
|
||||
}
|
||||
return l ? "select" : "idle";
|
||||
}
|
||||
private holdTime() { return Math.max(1, Number(this.preferences.GestureTapHoldTimeout) || 650); }
|
||||
private threshold() { return Math.max(1, Number(this.preferences.GestureMoveThreshold) || 5); }
|
||||
private isGesture() { return this.style === "Gesture" || this.style === "MayaGesture"; }
|
||||
private pointer = (event: PointerEvent) => {
|
||||
if (!this.enabled) return;
|
||||
if (this.gizmoActive && this.gizmoHover && event.pointerType !== "touch") {
|
||||
const leftDrag = (event.buttons & 1) === 1 && (event.buttons & 6) === 0;
|
||||
const leftRelease = event.type === "pointerup" && event.button === 0 && !event.buttons;
|
||||
if (leftDrag || leftRelease) return;
|
||||
}
|
||||
const point = { x: event.clientX, y: event.clientY };
|
||||
if (event.type === "pointerdown") {
|
||||
this.canvas.focus({ preventScroll: true });
|
||||
if (!this.buttons && !this.touch.size) {
|
||||
this.cancelled = false; this.consumed = false; this.moved = false; this.blockContext = false;
|
||||
this.start = point; this.last = point; this.started = performance.now(); this.gestureMode = null;
|
||||
}
|
||||
this.captured.add(event.pointerId); this.canvas.setPointerCapture(event.pointerId);
|
||||
}
|
||||
if (this.cancelled && event.buttons) return;
|
||||
if (event.pointerType === "touch" && this.isGesture()) {
|
||||
this.touchPointer(event, point); event.preventDefault(); return;
|
||||
}
|
||||
const before = this.buttons;
|
||||
this.buttons = event.buttons;
|
||||
const added = this.buttons & ~before, removed = before & ~this.buttons;
|
||||
// A mouse emits pointermove, not pointerdown/up, for additional buttons.
|
||||
if (this.style === "CAD") {
|
||||
if ((before & 4) && (added & 3)) { this.chordStarted = performance.now(); this.cadZoom = false; }
|
||||
if ((this.buttons & 4) && (removed & 3) && this.mode === "rotate")
|
||||
this.cadZoom = performance.now() - this.chordStarted < 400;
|
||||
if (!(this.buttons & 4)) this.cadZoom = false;
|
||||
}
|
||||
if ((this.buttons & (this.buttons - 1)) !== 0) this.consumed = true;
|
||||
const mode = this.choose(event, this.buttons);
|
||||
if (event.type === "pointermove") {
|
||||
const delta = this.last ? { x: point.x - this.last.x, y: point.y - this.last.y } : { x: 0, y: 0 };
|
||||
if (this.start && Math.hypot(point.x - this.start.x, point.y - this.start.y) > this.threshold()) this.moved = true;
|
||||
if (mode !== "idle" && mode !== "select" && (this.moved || !this.buttons)) {
|
||||
this.consumed = true; this.blockContext = true;
|
||||
if (this.style === "Gesture") this.gestureMode = mode;
|
||||
this.motion(mode, delta, point);
|
||||
}
|
||||
if (this.moved) this.consumed = true;
|
||||
this.last = point;
|
||||
}
|
||||
if (mode !== "idle" && mode !== "select" && !["Gesture"].includes(this.style)) this.consumed = true;
|
||||
if (event.type === "pointerup") {
|
||||
const selectionClick = !this.consumed && !this.moved && this.start && event.button === 0;
|
||||
if (this.seek && event.button === 0) { this.recenter(point); this.seek = false; }
|
||||
else if (selectionClick) {
|
||||
if (this.style === "Gesture" && performance.now() - this.started >= this.holdTime()) this.showContext(point);
|
||||
else this.pick(point, event.ctrlKey || (this.style === "OpenInventor" && event.shiftKey));
|
||||
}
|
||||
if (event.button === 1 && !this.moved && this.start && performance.now() - this.started < 400
|
||||
&& ["CAD", "Blender", "Revit", "SolidWorks", "SiemensNX", "Gesture", "MayaGesture"].includes(this.style)) this.recenter(point);
|
||||
this.captured.delete(event.pointerId);
|
||||
if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId);
|
||||
this.start = null; this.cadZoom = false; this.gestureMode = null;
|
||||
}
|
||||
this.mode = mode;
|
||||
if (event.buttons || event.type === "pointerup") event.preventDefault();
|
||||
};
|
||||
private touchPointer(event: PointerEvent, point: Point) {
|
||||
const before = [...this.touch.values()];
|
||||
if (event.type === "pointerdown") {
|
||||
this.touch.set(event.pointerId, point);
|
||||
if (this.touch.size > 1) { this.consumed = true; this.blockContext = true; }
|
||||
return;
|
||||
}
|
||||
if (!this.touch.has(event.pointerId)) return;
|
||||
if (event.type === "pointerup") {
|
||||
if (this.touch.size === 1 && !this.consumed && !this.moved) {
|
||||
if (performance.now() - this.started >= this.holdTime()) this.showContext(point);
|
||||
else this.pick(point, event.ctrlKey);
|
||||
}
|
||||
this.touch.delete(event.pointerId); this.captured.delete(event.pointerId);
|
||||
if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId);
|
||||
if (!this.touch.size) { this.start = null; this.gestureMode = null; }
|
||||
return;
|
||||
}
|
||||
this.touch.set(event.pointerId, point);
|
||||
const after = [...this.touch.values()];
|
||||
if (after.length >= 2) {
|
||||
const center = (p: Point[]) => ({ x: (p[0].x + p[1].x) / 2, y: (p[0].y + p[1].y) / 2 });
|
||||
const a = center(before), b = center(after);
|
||||
this.motion("pan", { x: b.x - a.x, y: b.y - a.y }, b);
|
||||
const distance = (p: Point[]) => Math.hypot(p[1].x - p[0].x, p[1].y - p[0].y);
|
||||
if (distance(before) > 0 && distance(after) > 0) this.zoom(Math.log(distance(before) / distance(after)), b);
|
||||
if (this.style === "MayaGesture" || this.preferences.DisableTouchTilt === false) {
|
||||
const angle = (p: Point[]) => Math.atan2(p[1].y - p[0].y, p[1].x - p[0].x);
|
||||
this.roll(angle(before) - angle(after));
|
||||
}
|
||||
this.consumed = true; this.moved = true;
|
||||
} else if (this.start && Math.hypot(point.x - this.start.x, point.y - this.start.y) > this.threshold()) {
|
||||
this.moved = true; this.consumed = true; this.blockContext = true;
|
||||
const mode = this.gestureMode ?? (this.style === "Gesture" && performance.now() - this.started >= this.holdTime() ? "pan" : "rotate");
|
||||
this.gestureMode = mode;
|
||||
this.motion(mode, { x: point.x - before[0].x, y: point.y - before[0].y }, point);
|
||||
}
|
||||
}
|
||||
private motion(mode: Mode, delta: Point, point: Point) {
|
||||
const controls = this.controls;
|
||||
controls.autoRotate = false;
|
||||
const height = Math.max(this.canvas.clientHeight, 1), width = Math.max(this.canvas.clientWidth, 1);
|
||||
if (mode === "pan") controls.pan(delta.x, delta.y);
|
||||
if (mode === "rotate") {
|
||||
const bounds = this.canvas.getBoundingClientRect();
|
||||
const normalize = (x: number, y: number) => ({
|
||||
x: 2 * (x - bounds.left) / Math.max(bounds.width - 1, 1) - 1,
|
||||
y: 1 - 2 * (y - bounds.top) / Math.max(bounds.height - 1, 1),
|
||||
});
|
||||
rotateOrbit(controls.object, controls.target, orbitStyle(this.preferences.OrbitStyle),
|
||||
normalize(point.x - delta.x, point.y - delta.y), normalize(point.x, point.y));
|
||||
this.replaceMotionControls();
|
||||
}
|
||||
if (mode === "tilt") this.roll(-2 * Math.PI * delta.x / width);
|
||||
if (mode === "zoom") {
|
||||
const value = this.style === "OpenCascade" ? delta.x / width
|
||||
: this.style === "MayaGesture" ? delta.x / width + delta.y / height : -delta.y / height;
|
||||
this.zoom(value * 10 * (this.preferences.InvertZoom ? -1 : 1), point);
|
||||
}
|
||||
this.invalidate();
|
||||
}
|
||||
private planePoint(point: Point): THREE.Vector3 | undefined {
|
||||
const bounds = this.canvas.getBoundingClientRect();
|
||||
const camera = this.controls.object;
|
||||
camera.updateMatrixWorld();
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1,
|
||||
1 - (point.y - bounds.top) / bounds.height * 2), camera);
|
||||
return ray.ray.intersectPlane(new THREE.Plane().setFromNormalAndCoplanarPoint(
|
||||
camera.getWorldDirection(new THREE.Vector3()), this.controls.target), new THREE.Vector3()) ?? undefined;
|
||||
}
|
||||
private zoom(amount: number, point?: Point) {
|
||||
const controls = this.controls;
|
||||
const anchor = point && this.preferences.ZoomAtCursor !== false ? this.planePoint(point) : undefined;
|
||||
controls.autoRotate = false;
|
||||
controls.dollyIn(Math.exp(Math.max(-2, Math.min(2, amount))));
|
||||
if (anchor && point) {
|
||||
const next = this.planePoint(point);
|
||||
if (next) { const delta = anchor.sub(next); controls.target.add(delta); controls.object.position.add(delta); controls.update(); }
|
||||
}
|
||||
this.invalidate();
|
||||
}
|
||||
private roll(angle: number) {
|
||||
const camera = this.controls.object;
|
||||
const rotation = new THREE.Quaternion().setFromAxisAngle(camera.getWorldDirection(new THREE.Vector3()), angle);
|
||||
camera.up.applyQuaternion(rotation); camera.quaternion.premultiply(rotation);
|
||||
this.replaceMotionControls();
|
||||
}
|
||||
private replaceMotionControls() {
|
||||
const camera = this.controls.object;
|
||||
// OrbitControls caches its up-axis basis at construction, so a rotation must
|
||||
// replace the controls through the same scene owner as camera commands.
|
||||
const old = this.controls;
|
||||
const next = new OrbitControls(camera, this.canvas);
|
||||
next.target.copy(old.target);
|
||||
next.minDistance = old.minDistance; next.maxDistance = old.maxDistance;
|
||||
next.minZoom = old.minZoom; next.maxZoom = old.maxZoom;
|
||||
next.autoRotate = false;
|
||||
old.dispose();
|
||||
// Preserve the in-progress gesture; bind() deliberately cancels gestures
|
||||
// for external camera replacements, but this replacement is part of one.
|
||||
const gesture = { start: this.start, last: this.last, mode: this.mode,
|
||||
buttons: this.buttons, touch: new Map(this.touch), captured: new Set(this.captured),
|
||||
gestureMode: this.gestureMode, consumed: this.consumed, cancelled: this.cancelled };
|
||||
this.captured.clear();
|
||||
this.replaceControls(next);
|
||||
Object.assign(this, gesture);
|
||||
next.update(); this.invalidate();
|
||||
}
|
||||
private recenter(point: Point) {
|
||||
const hit = this.hitPoint(point) ?? this.planePoint(point);
|
||||
if (!hit) return;
|
||||
const delta = hit.clone().sub(this.controls.target);
|
||||
this.controls.object.position.add(delta); this.controls.target.copy(hit);
|
||||
this.controls.update(); this.invalidate();
|
||||
}
|
||||
private showContext(point: Point) {
|
||||
this.blockContext = false;
|
||||
this.canvas.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y }));
|
||||
this.blockContext = true;
|
||||
}
|
||||
private context = (event: MouseEvent) => {
|
||||
if (this.blockContext || this.buttons > 2 || this.touch.size > 1) { event.preventDefault(); event.stopImmediatePropagation(); }
|
||||
};
|
||||
private wheel = (event: WheelEvent) => {
|
||||
if (!this.enabled) return;
|
||||
// TransformControls never listens to wheel, so zoom must always reach the
|
||||
// navigation -- including while the pointer hovers a gizmo handle.
|
||||
event.preventDefault(); event.stopImmediatePropagation(); this.consumed = true;
|
||||
const step = Number(this.preferences.ZoomStep) || 0.2;
|
||||
const amount = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? this.canvas.clientHeight : 1);
|
||||
this.zoom(amount / 100 * step * (this.preferences.InvertZoom ? -1 : 1), { x: event.clientX, y: event.clientY });
|
||||
};
|
||||
private key = (event: KeyboardEvent) => {
|
||||
if (!this.enabled) return;
|
||||
const target = event.target as HTMLElement;
|
||||
if (target !== this.canvas && (!this.over || target?.closest("input,textarea,select,button,[contenteditable=true]"))) return;
|
||||
if (event.key === "Escape") { this.cancelEvent(); return; }
|
||||
if (["Shift", "Control", "Alt"].includes(event.key)) {
|
||||
this.mode = this.choose(event, this.buttons);
|
||||
if (this.style === "Touchpad") { event.preventDefault(); this.last = null; }
|
||||
return;
|
||||
}
|
||||
if (event.type !== "keydown") return;
|
||||
let command = "";
|
||||
if (this.style === "SiemensNX") {
|
||||
if (event.key === "Home") command = "Std_ViewIsometric";
|
||||
if (event.key === "End") command = "Std_ViewTrimetric";
|
||||
if (event.key === "F8") command = "Std_ViewTop";
|
||||
if (event.ctrlKey && event.key.toLowerCase() === "f") command = "Std_ViewFitAll";
|
||||
} else if (event.key === "Home") command = "Std_ViewFitAll";
|
||||
if (command) { event.preventDefault(); this.cancel(); this.command(command); return; }
|
||||
if (event.key === "PageUp" || event.key === "PageDown") {
|
||||
event.preventDefault(); this.zoom((event.key === "PageUp" ? -1 : 1) * (Number(this.preferences.ZoomStep) || 0.2), this.last ?? undefined);
|
||||
} else if (event.key.toLowerCase() === "s") { this.seek = !this.seek; event.preventDefault(); }
|
||||
else if (this.style === "Gesture" && event.key.toLowerCase() === "h" && this.last) { this.recenter(this.last); event.preventDefault(); }
|
||||
else if (event.key.startsWith("Arrow")) {
|
||||
event.preventDefault();
|
||||
this.controls.pan(event.key === "ArrowLeft" ? 10 : event.key === "ArrowRight" ? -10 : 0,
|
||||
event.key === "ArrowUp" ? 10 : event.key === "ArrowDown" ? -10 : 0);
|
||||
this.invalidate();
|
||||
}
|
||||
};
|
||||
dispose() {
|
||||
this.cancel();
|
||||
this.canvas.removeEventListener("pointerdown", this.pointer, true);
|
||||
this.canvas.removeEventListener("pointermove", this.pointer, true);
|
||||
this.canvas.removeEventListener("pointerup", this.pointer, true);
|
||||
this.canvas.removeEventListener("blur", this.cancelEvent);
|
||||
this.canvas.removeEventListener("pointercancel", this.cancelEvent, true);
|
||||
this.canvas.removeEventListener("lostpointercapture", this.lostCapture, true);
|
||||
this.canvas.removeEventListener("pointerenter", this.enter);
|
||||
this.canvas.removeEventListener("pointerleave", this.leave);
|
||||
this.canvas.removeEventListener("wheel", this.wheel, true);
|
||||
this.canvas.removeEventListener("contextmenu", this.context, true);
|
||||
window.removeEventListener("keydown", this.key, true); window.removeEventListener("keyup", this.key, true);
|
||||
window.removeEventListener("blur", this.cancelEvent); document.removeEventListener("visibilitychange", this.visibility);
|
||||
this.canvas.style.touchAction = this.originalTouchAction;
|
||||
}
|
||||
}
|
||||
595
web/src/scene-viewport.tsx
Normal file
595
web/src/scene-viewport.tsx
Normal file
@@ -0,0 +1,595 @@
|
||||
import type { InspectionDisplayAttributes } from "./inspection-result-display.js";
|
||||
import { distanceAnnotation } from "./measure-annotation.js";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
||||
import type { SceneDocument } from "./scene-document.js";
|
||||
import { attachSceneCommands } from "./scene-command-host.js";
|
||||
import { SelectionDecoration } from "./selection-decoration.js";
|
||||
import type { PointsViewState } from "./points-document-facade.js";
|
||||
|
||||
export type ViewPolygon = { polygon: { x: number; y: number }[]; viewProjection: number[] };
|
||||
|
||||
export interface FacetInteraction {
|
||||
mode: "triangle" | "region" | "box" | "navigate";
|
||||
visibleOnly: boolean; frontOnly: boolean;
|
||||
components: Record<string, number[][]>; componentOnClick: boolean;
|
||||
selected: Record<string, number[]>;
|
||||
request?: { id: number; mode: "all" | "small"; maximum: number };
|
||||
onFacets: (facets: Record<string, number[]>, toggle?: boolean) => void;
|
||||
}
|
||||
|
||||
export type InspectionHit = { object: string; index?: number; facet?: number; point: [number, number, number] };
|
||||
|
||||
export function SceneViewport({ viewportHeight = 420, onReady, facetInteraction, polygonMode = false, onPolygon, onCancelPolygon, inspectionMode, onInspect, inspectionAnnotations = [], document, selected, onSelect, onPickMesh, meshInfoMode = false, onHoverMesh, onPickPoint, onPickVertex, onPickLocation, onCancelPick, onViewDirection, ariaLabel = "Geometry viewport", reserveControlsSpace = false, preserveCamera = false, onPickEdge }: {
|
||||
document: SceneDocument & { objects: Array<SceneDocument["objects"][number] & { lineSubelements?: string[]; directionEdges?: string[]; alphas?: number[]; vertices?: number[][]; curvature?: number[]; pointAttributes?: { Color?: number[][]; Normal?: number[][]; Intensity?: number[] }; pointDisplayMode?: string }> }; selected: string[]; onSelect: (name: string) => void; ariaLabel?: string; reserveControlsSpace?: boolean; preserveCamera?: boolean;
|
||||
meshInfoMode?: boolean;
|
||||
onHoverMesh?: (facet: number | null) => void;
|
||||
onPickEdge?: (object: string, subelement: string) => void;
|
||||
onReady?: () => void;
|
||||
viewportHeight?: number;
|
||||
facetInteraction?: FacetInteraction;
|
||||
polygonMode?: boolean;
|
||||
onPolygon?: (capture: ViewPolygon) => void;
|
||||
onCancelPolygon?: () => void;
|
||||
inspectionMode?: "inspect" | "navigate";
|
||||
onInspect?: (hit: InspectionHit) => void;
|
||||
inspectionAnnotations?: Array<{ text: string; point: [number, number, number] }>;
|
||||
onPickMesh?: (pick: { object: string; facet: number; point: [number, number, number]; direction: [number, number, number] }) => void;
|
||||
onPickPoint?: (point: [number, number, number]) => void;
|
||||
onPickVertex?: (point: [number, number, number]) => void;
|
||||
onPickLocation?: (point: [number, number, number], normal?: [number, number, number]) => void;
|
||||
onCancelPick?: () => void;
|
||||
onViewDirection?: (direction: [number, number, number]) => void;
|
||||
}) {
|
||||
const meshInfo = useRef({ active: meshInfoMode, hover: onHoverMesh });
|
||||
meshInfo.current = { active: meshInfoMode, hover: onHoverMesh };
|
||||
const pickEdge = useRef(onPickEdge); pickEdge.current = onPickEdge;
|
||||
const ready = useRef(onReady); ready.current = onReady;
|
||||
const facets = useRef(facetInteraction);
|
||||
facets.current = facetInteraction;
|
||||
const handledFacetRequest = useRef<number>();
|
||||
const polygonCallbacks = useRef({ onPolygon, onCancelPolygon });
|
||||
polygonCallbacks.current = { onPolygon, onCancelPolygon };
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const inspection = useRef({ mode: inspectionMode, pick: onInspect, annotations: inspectionAnnotations });
|
||||
inspection.current = { mode: inspectionMode, pick: onInspect, annotations: inspectionAnnotations };
|
||||
const savedCamera = useRef<{ documentId: string; position: THREE.Vector3; target: THREE.Vector3 }>();
|
||||
const select = useRef(onSelect);
|
||||
select.current = onSelect;
|
||||
const pickMesh = useRef(onPickMesh);
|
||||
pickMesh.current = onPickMesh;
|
||||
const pickPoint = useRef(onPickPoint);
|
||||
pickPoint.current = onPickPoint;
|
||||
const pickVertex = useRef(onPickVertex);
|
||||
pickVertex.current = onPickVertex;
|
||||
const pickLocation = useRef(onPickLocation);
|
||||
pickLocation.current = onPickLocation;
|
||||
const cancelPick = useRef(onCancelPick);
|
||||
cancelPick.current = onCancelPick;
|
||||
const viewDirection = useRef(onViewDirection);
|
||||
viewDirection.current = onViewDirection;
|
||||
useEffect(() => {
|
||||
if (!host.current) return;
|
||||
const container = host.current;
|
||||
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
||||
renderer.setPixelRatio(window.devicePixelRatio);
|
||||
container.appendChild(renderer.domElement);
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(0xf1f3f5);
|
||||
const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000000);
|
||||
camera.up.set(0, 0, 1);
|
||||
let controls: OrbitControls = new OrbitControls(camera, renderer.domElement);
|
||||
const content = new THREE.Group();
|
||||
scene.add(content, new THREE.HemisphereLight(0xffffff, 0x555555, 3));
|
||||
// Shared selection decoration: the local frame is anchored at the selected
|
||||
// object's bounding-box centre rather than at a scene origin.
|
||||
const decoration = new SelectionDecoration(scene);
|
||||
const publishDecoration = (value: SelectionDecoration) => {
|
||||
(window as unknown as { __freecadSceneDecorationState?: unknown }).__freecadSceneDecorationState = value.snapshot();
|
||||
};
|
||||
const sceneCommands = attachSceneCommands(scene, controls, container, () => document.documentId, () => {}, {
|
||||
canvas: renderer.domElement,
|
||||
objects: () => content.children.filter(object => !object.userData.pointsDecoration && object.userData.selectable !== false).map(object => ({
|
||||
id: String(object.userData.name),
|
||||
label: document.objects.find(entry => entry.name === object.userData.name)?.label || String(object.userData.name),
|
||||
object,
|
||||
})),
|
||||
select: id => { if (!meshInfo.current.active && !inspection.current.mode && (!facets.current || facets.current.mode === "navigate")) select.current(id); },
|
||||
}, next => { controls = next; });
|
||||
const geometries: THREE.BufferGeometry[] = [];
|
||||
const materials: THREE.Material[] = [];
|
||||
for (const object of document.objects) {
|
||||
if (object.visible === false) continue;
|
||||
const pointView = object as typeof object & Partial<PointsViewState>;
|
||||
const shapeSelection = selected.includes(object.name) && pointView.selectionStyle !== "Box";
|
||||
const color = shapeSelection ? new THREE.Color(0x16846b)
|
||||
: object.color ? new THREE.Color(object.color[0], object.color[1], object.color[2]) : new THREE.Color(0xa3abb6);
|
||||
if (object.points?.length && object.facets?.length) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(object.points.flat(), 3));
|
||||
geometry.setIndex(object.facets.flat());
|
||||
geometry.computeVertexNormals();
|
||||
const vertexColors = object.colors?.length === object.points.length * 3;
|
||||
const vertexAlphas = vertexColors && object.alphas?.length === object.points.length;
|
||||
if (vertexColors) {
|
||||
const stride = vertexAlphas ? 4 : 3;
|
||||
const values = new Float32Array(object.points.length * stride);
|
||||
const value = new THREE.Color();
|
||||
for (let index = 0; index < object.points.length; ++index) {
|
||||
value.setRGB(object.colors![index * 3], object.colors![index * 3 + 1], object.colors![index * 3 + 2], THREE.SRGBColorSpace).toArray(values, index * stride);
|
||||
if (vertexAlphas) values[index * stride + 3] = object.alphas![index];
|
||||
}
|
||||
geometry.setAttribute("color", new THREE.BufferAttribute(values, stride));
|
||||
}
|
||||
const opacity = object.opacity ?? 1;
|
||||
const transparent = opacity < 1 || Boolean(vertexAlphas && object.alphas!.some(alpha => alpha < 1));
|
||||
const material = new THREE.MeshStandardMaterial({ color: vertexColors ? 0xffffff : color, vertexColors,
|
||||
opacity, transparent, depthWrite: !transparent,
|
||||
emissive: vertexColors && selected.includes(object.name) ? 0x16846b : 0, emissiveIntensity: 0.1, side: THREE.DoubleSide });
|
||||
const mesh = new THREE.Mesh(geometry, material);
|
||||
mesh.userData.name = object.name;
|
||||
content.add(mesh); geometries.push(geometry); materials.push(material);
|
||||
}
|
||||
if (object.pointMarkers?.length) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(object.pointMarkers.flat(), 3));
|
||||
const requestedPointSize = (object as typeof object & InspectionDisplayAttributes).pointSize;
|
||||
const pointSize = typeof requestedPointSize === "number" && Number.isFinite(requestedPointSize)
|
||||
&& requestedPointSize > 0 ? requestedPointSize : 7;
|
||||
const attributes = object.pointAttributes;
|
||||
const mode = object.pointDisplayMode;
|
||||
const count = object.pointMarkers.length;
|
||||
const opacity = object.opacity ?? 1;
|
||||
let material: THREE.Material;
|
||||
if (mode === "Shaded" && attributes?.Normal?.length === count) {
|
||||
geometry.setAttribute("pointNormal", new THREE.Float32BufferAttribute(attributes.Normal.flat(), 3));
|
||||
material = new THREE.ShaderMaterial({
|
||||
transparent: opacity < 1, depthWrite: opacity >= 1,
|
||||
uniforms: { baseColor: { value: color }, opacity: { value: opacity }, pixelRatio: { value: renderer.getPixelRatio() }, pointSize: { value: pointSize } },
|
||||
vertexShader: `attribute vec3 pointNormal; varying float shade; uniform float pixelRatio; uniform float pointSize;
|
||||
void main() { vec3 n = normalMatrix * pointNormal;
|
||||
shade = 0.25 + 0.75 * abs(dot(normalize(n), normalize(vec3(0.3, 0.5, 1.0))));
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); gl_PointSize = pointSize * pixelRatio; }`,
|
||||
fragmentShader: `uniform vec3 baseColor; uniform float opacity; varying float shade;
|
||||
void main() { gl_FragColor = vec4(baseColor * shade, opacity);
|
||||
#include <tonemapping_fragment>
|
||||
#include <colorspace_fragment>
|
||||
}`,
|
||||
});
|
||||
} else {
|
||||
const colors = mode === "Color" && attributes?.Color?.length === count ? attributes.Color : undefined;
|
||||
const intensities = mode === "Intensity" && attributes?.Intensity?.length === count ? attributes.Intensity
|
||||
: mode === "Intensity" && object.curvature?.length === count ? object.curvature : undefined;
|
||||
const alphas = colors && object.alphas?.length === count ? object.alphas : undefined;
|
||||
const stride = alphas ? 4 : 3;
|
||||
if (colors || intensities) {
|
||||
const values = new Float32Array(count * stride);
|
||||
for (let i = 0; i < count; ++i) {
|
||||
const rgb = colors?.[i];
|
||||
const grey = Math.max(0, Math.min(1, intensities?.[i] ?? 0));
|
||||
new THREE.Color().setRGB(rgb?.[0] ?? grey, rgb?.[1] ?? grey, rgb?.[2] ?? grey, THREE.SRGBColorSpace).toArray(values, i * stride);
|
||||
if (alphas) values[i * stride + 3] = alphas[i];
|
||||
}
|
||||
geometry.setAttribute("color", new THREE.BufferAttribute(values, stride));
|
||||
}
|
||||
material = new THREE.PointsMaterial({ color: shapeSelection ? color : colors || intensities ? 0xffffff : color,
|
||||
vertexColors: Boolean(colors || intensities), opacity, transparent: Boolean(alphas) || opacity < 1,
|
||||
depthWrite: !alphas && opacity >= 1, size: pointSize, sizeAttenuation: false });
|
||||
}
|
||||
const points = new THREE.Points(geometry, material);
|
||||
points.userData.name = object.name;
|
||||
points.userData.selectable = pointView.selectable;
|
||||
if (pointView.selectable === false) points.raycast = () => {};
|
||||
content.add(points); geometries.push(geometry); materials.push(material);
|
||||
if (pointView.boundingBox || (pointView.selectionStyle === "Box" && selected.includes(object.name))) {
|
||||
geometry.computeBoundingBox();
|
||||
if (geometry.boundingBox && !geometry.boundingBox.isEmpty()) {
|
||||
const box = new THREE.Box3Helper(geometry.boundingBox, selected.includes(object.name) ? 0x16846b : 0x42484f);
|
||||
box.userData.pointsDecoration = true;
|
||||
box.raycast = () => {};
|
||||
content.add(box); geometries.push(box.geometry); materials.push(box.material as THREE.Material);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (object.measurement) content.add(distanceAnnotation(object.measurement));
|
||||
const segments: number[] = [];
|
||||
const inspectionLines = object as typeof object & {
|
||||
inspectionLineIndices?: number[][];
|
||||
inspectionSampleColors?: number[][];
|
||||
inspectionSampleAlphas?: number[];
|
||||
};
|
||||
const segmentColors: number[] = [];
|
||||
const segmentEdges: Array<string | undefined> = [];
|
||||
for (const [index, line] of (object.lines ?? []).entries()) {
|
||||
const sub = object.lineSubelements?.[index];
|
||||
for (let i = 1; i < line.length; i++) {
|
||||
segments.push(...line[i - 1], ...line[i]);
|
||||
if (inspectionLines.inspectionLineIndices && inspectionLines.inspectionSampleColors) {
|
||||
for (const vertex of [i - 1, i]) {
|
||||
const sample = inspectionLines.inspectionLineIndices[index][vertex];
|
||||
const rgb = inspectionLines.inspectionSampleColors[sample];
|
||||
const color = new THREE.Color().setRGB(rgb[0], rgb[1], rgb[2], THREE.SRGBColorSpace);
|
||||
segmentColors.push(color.r, color.g, color.b, inspectionLines.inspectionSampleAlphas?.[sample] ?? 1);
|
||||
}
|
||||
}
|
||||
segmentEdges.push(sub && object.directionEdges?.includes(sub) ? sub : undefined);
|
||||
}
|
||||
}
|
||||
if (segments.length) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(segments, 3));
|
||||
if (segmentColors.length) geometry.setAttribute("color", new THREE.Float32BufferAttribute(segmentColors, 4));
|
||||
const material = new THREE.LineBasicMaterial({ vertexColors: segmentColors.length > 0,
|
||||
transparent: segmentColors.length > 0, color: segmentColors.length ? 0xffffff : object.typeId === "Part::Section" && object.color
|
||||
? color : selected.includes(object.name) ? 0x16846b : 0x42484f });
|
||||
const lines = new THREE.LineSegments(geometry, material);
|
||||
lines.userData.name = object.name;
|
||||
lines.userData.segmentEdges = segmentEdges;
|
||||
lines.userData.inspectionLineIndices = inspectionLines.inspectionLineIndices;
|
||||
content.add(lines); geometries.push(geometry); materials.push(material);
|
||||
}
|
||||
}
|
||||
const highlight = new THREE.Group(); scene.add(highlight);
|
||||
let previousFacetSelection: Record<string, number[]> | undefined;
|
||||
const updateFacetHighlights = () => {
|
||||
if (previousFacetSelection === facets.current?.selected) return;
|
||||
previousFacetSelection = facets.current?.selected;
|
||||
for (const child of [...highlight.children]) {
|
||||
const mesh = child as THREE.Mesh; mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); highlight.remove(child);
|
||||
}
|
||||
for (const object of document.objects) {
|
||||
if (object.visible === false) continue;
|
||||
const indices = facets.current?.selected[object.name];
|
||||
if (!indices?.length || !object.points || !object.facets) continue;
|
||||
const positions = indices.flatMap(index => (object.facets![index] ?? []).flatMap(vertex => object.points![vertex]));
|
||||
const geometry = new THREE.BufferGeometry(); geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
|
||||
const material = new THREE.MeshBasicMaterial({ color: 0xff8c18, side: THREE.DoubleSide, transparent: true,
|
||||
opacity: 0.72, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 });
|
||||
highlight.add(new THREE.Mesh(geometry, material));
|
||||
}
|
||||
};
|
||||
const bounds = new THREE.Box3().setFromObject(content);
|
||||
const center = bounds.isEmpty() ? new THREE.Vector3() : bounds.getCenter(new THREE.Vector3());
|
||||
const radius = bounds.isEmpty() ? 10 : Math.max(bounds.getSize(new THREE.Vector3()).length(), 0.01);
|
||||
controls.target.copy(center);
|
||||
camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7));
|
||||
if (preserveCamera && savedCamera.current?.documentId === document.documentId) {
|
||||
camera.position.copy(savedCamera.current.position); controls.target.copy(savedCamera.current.target);
|
||||
}
|
||||
camera.near = radius / 10000; camera.far = radius * 100;
|
||||
const toolbar = container.querySelector<HTMLElement>(".scene-display-tools");
|
||||
if (reserveControlsSpace) {
|
||||
renderer.domElement.style.position = "absolute"; renderer.domElement.style.bottom = "0";
|
||||
}
|
||||
const resize = () => {
|
||||
const reserved = reserveControlsSpace && toolbar ? toolbar.offsetTop + toolbar.offsetHeight + 8 : 0;
|
||||
const width = Math.max(container.clientWidth, 1), height = Math.max(container.clientHeight - reserved, 1);
|
||||
renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix();
|
||||
};
|
||||
const observer = new ResizeObserver(resize); observer.observe(container); if (toolbar && reserveControlsSpace) observer.observe(toolbar); resize();
|
||||
const facetMeshes = () => content.children.filter((object): object is THREE.Mesh => object instanceof THREE.Mesh);
|
||||
const eligibleFacet = (mesh: THREE.Mesh, index: number) => {
|
||||
const position = mesh.geometry.getAttribute("position"), indices = mesh.geometry.index!;
|
||||
const a = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3)).applyMatrix4(mesh.matrixWorld);
|
||||
const b = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3 + 1)).applyMatrix4(mesh.matrixWorld);
|
||||
const c = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3 + 2)).applyMatrix4(mesh.matrixWorld);
|
||||
const center = a.clone().add(b).add(c).multiplyScalar(1 / 3);
|
||||
if (facets.current?.frontOnly && b.clone().sub(a).cross(c.clone().sub(a)).dot(camera.position.clone().sub(center)) <= 0) return false;
|
||||
if (facets.current?.visibleOnly) {
|
||||
const samples = [center, a.clone().lerp(center, 0.001), b.clone().lerp(center, 0.001), c.clone().lerp(center, 0.001)];
|
||||
if (!samples.some(point => {
|
||||
const projected = point.project(camera);
|
||||
if (projected.z < -1 || projected.z > 1 || Math.abs(projected.x) > 1 || Math.abs(projected.y) > 1) return false;
|
||||
const ray = new THREE.Raycaster(); ray.setFromCamera(new THREE.Vector2(projected.x, projected.y), camera);
|
||||
const hit = ray.intersectObjects(facetMeshes())[0];
|
||||
return hit?.object === mesh && hit.faceIndex === index;
|
||||
})) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const collectFacets = (polygon?: { x: number; y: number }[]) => {
|
||||
camera.updateMatrixWorld(true); content.updateMatrixWorld(true);
|
||||
const inside = (point: THREE.Vector3) => {
|
||||
if (!polygon) return true;
|
||||
const p = point.project(camera); if (p.z < -1 || p.z > 1) return false;
|
||||
const x = (p.x + 1) / 2, y = (p.y + 1) / 2;
|
||||
let hit = false;
|
||||
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
|
||||
const a = polygon[i], b = polygon[j];
|
||||
if ((a.y > y) !== (b.y > y) && x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x) hit = !hit;
|
||||
}
|
||||
return hit;
|
||||
};
|
||||
const result: Record<string, number[]> = {};
|
||||
for (const mesh of facetMeshes()) {
|
||||
const indices = mesh.geometry.index!, points = mesh.geometry.getAttribute("position");
|
||||
const selected: number[] = [];
|
||||
for (let index = 0; index < indices.count / 3; ++index) {
|
||||
if (!eligibleFacet(mesh, index)) continue;
|
||||
const corners = [0, 1, 2].map(offset => new THREE.Vector3().fromBufferAttribute(points, indices.getX(index * 3 + offset)).applyMatrix4(mesh.matrixWorld));
|
||||
if (corners.some(point => inside(point.clone())) || inside(corners[0].clone().add(corners[1]).add(corners[2]).multiplyScalar(1 / 3))) selected.push(index);
|
||||
}
|
||||
result[String(mesh.userData.name)] = selected;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const polygonLayer = window.document.createElement("div");
|
||||
if (polygonMode || (facetInteraction?.mode === "region" || facetInteraction?.mode === "box")) {
|
||||
controls.enabled = false;
|
||||
polygonLayer.style.cssText = "position:absolute;inset:0;z-index:10;cursor:crosshair;touch-action:none";
|
||||
const svg = window.document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("viewBox", "0 0 1 1"); svg.setAttribute("preserveAspectRatio", "none");
|
||||
svg.style.cssText = "position:absolute;width:100%;height:100%;pointer-events:none";
|
||||
const outline = window.document.createElementNS(svg.namespaceURI, "polygon");
|
||||
outline.setAttribute("fill", "#16846b33"); outline.setAttribute("stroke", "#16846b"); outline.setAttribute("stroke-width", "0.004");
|
||||
svg.appendChild(outline); polygonLayer.appendChild(svg);
|
||||
const vertices: { x: number; y: number }[] = [];
|
||||
const buttons = window.document.createElement("div"); buttons.style.cssText = "position:absolute;top:8px;left:8px";
|
||||
const complete = window.document.createElement("button"); complete.textContent = facetInteraction ? "Select region" : "Complete cut"; complete.disabled = true;
|
||||
const cancel = window.document.createElement("button"); cancel.textContent = "Cancel polygon";
|
||||
buttons.append(complete, cancel); polygonLayer.appendChild(buttons);
|
||||
let drawing = false;
|
||||
const add = (event: PointerEvent) => {
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
|
||||
const y = Math.max(0, Math.min(1, 1 - (event.clientY - rect.top) / rect.height));
|
||||
if (facets.current?.mode === "box" && vertices.length) {
|
||||
const first = vertices[0];
|
||||
vertices.splice(1, vertices.length - 1, { x, y: first.y }, { x, y }, { x: first.x, y });
|
||||
outline.setAttribute("points", vertices.map(p => `${p.x},${1-p.y}`).join(" "));
|
||||
complete.disabled = x === first.x || y === first.y;
|
||||
return;
|
||||
}
|
||||
const last = vertices[vertices.length - 1];
|
||||
if (last && Math.hypot(x - last.x, y - last.y) < 0.003) return;
|
||||
vertices.push({ x, y });
|
||||
outline.setAttribute("points", vertices.map(p => `${p.x},${1-p.y}`).join(" "));
|
||||
const noncollinear = vertices.length >= 3 && vertices.slice(2).some(p => Math.abs((vertices[1].x-vertices[0].x)*(p.y-vertices[0].y) - (vertices[1].y-vertices[0].y)*(p.x-vertices[0].x)) > 1e-10);
|
||||
complete.disabled = !noncollinear;
|
||||
};
|
||||
polygonLayer.onpointerdown = event => {
|
||||
if (buttons.contains(event.target as Node) || event.button !== 0) return;
|
||||
if (facets.current?.mode === "box") vertices.length = 0;
|
||||
drawing = true; polygonLayer.setPointerCapture(event.pointerId); add(event);
|
||||
};
|
||||
polygonLayer.onpointermove = event => { if (drawing) add(event); };
|
||||
polygonLayer.onpointerup = () => { drawing = false; if (facets.current?.mode === "box" && !complete.disabled) facets.current.onFacets(collectFacets(vertices)); };
|
||||
polygonLayer.onpointercancel = () => { drawing = false; };
|
||||
complete.onclick = () => {
|
||||
if (complete.disabled) return;
|
||||
camera.updateMatrixWorld(true);
|
||||
if (facets.current) { facets.current.onFacets(collectFacets(vertices)); return; }
|
||||
polygonCallbacks.current.onPolygon?.({ polygon: vertices, viewProjection: new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).toArray() });
|
||||
};
|
||||
cancel.onclick = () => polygonCallbacks.current.onCancelPolygon?.();
|
||||
polygonLayer.tabIndex = 0;
|
||||
polygonLayer.onkeydown = event => { if (event.key === "Escape") polygonCallbacks.current.onCancelPolygon?.(); };
|
||||
container.appendChild(polygonLayer); polygonLayer.focus();
|
||||
}
|
||||
let downX = 0, downY = 0;
|
||||
const down = (event: PointerEvent) => { downX = event.clientX; downY = event.clientY; };
|
||||
const hover = (event: PointerEvent) => {
|
||||
if (!meshInfo.current.active || event.buttons) return;
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
camera.updateMatrixWorld(true); content.updateMatrixWorld(true);
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.Mesh))[0];
|
||||
meshInfo.current.hover?.(hit?.faceIndex ?? null);
|
||||
};
|
||||
const leave = () => meshInfo.current.hover?.(null);
|
||||
const pick = (event: PointerEvent) => {
|
||||
if (event.button === 2 && !meshInfo.current.active && (pickLocation.current || pickMesh.current)) { cancelPick.current?.(); return; }
|
||||
if (event.button !== 0 || Math.hypot(event.clientX - downX, event.clientY - downY) > 4) return;
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
if (facets.current && facets.current.mode !== "navigate") {
|
||||
if (facets.current.mode !== "triangle") return;
|
||||
camera.updateMatrixWorld(true); content.updateMatrixWorld(true);
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hits = ray.intersectObjects(facetMeshes());
|
||||
const candidates = facets.current.visibleOnly ? hits.slice(0, 1) : hits;
|
||||
const hit = candidates.find(item => item.faceIndex != null && eligibleFacet(item.object as THREE.Mesh, item.faceIndex));
|
||||
if (hit?.faceIndex != null) {
|
||||
const name = String(hit.object.userData.name);
|
||||
const indices = facets.current.componentOnClick
|
||||
? facets.current.components[name]?.find(group => group.includes(hit.faceIndex!)) ?? [hit.faceIndex] : [hit.faceIndex];
|
||||
facets.current.onFacets({ [name]: indices.filter(index => eligibleFacet(hit.object as THREE.Mesh, index)) }, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (inspection.current.mode) {
|
||||
if (inspection.current.mode === "navigate") return;
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.params.Points.threshold = radius / 100;
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hit = ray.intersectObjects(content.children.filter(object =>
|
||||
document.objects.some(item => item.name === object.userData.name && item.typeId === "Inspection::Feature")))[0];
|
||||
if (hit?.object instanceof THREE.Points && hit.index !== undefined) {
|
||||
const point = hit.object.localToWorld(new THREE.Vector3().fromBufferAttribute(hit.object.geometry.getAttribute("position"), hit.index));
|
||||
inspection.current.pick?.({ object: hit.object.userData.name, index: hit.index, point: [point.x,point.y,point.z] });
|
||||
} else if (hit?.faceIndex != null) {
|
||||
inspection.current.pick?.({ object: hit.object.userData.name, facet: hit.faceIndex, point: [hit.point.x,hit.point.y,hit.point.z] });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (pickMesh.current) {
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.Mesh))[0];
|
||||
if (hit && hit.faceIndex != null) {
|
||||
const direction = camera.getWorldDirection(new THREE.Vector3());
|
||||
pickMesh.current({ object: hit.object.userData.name, facet: hit.faceIndex,
|
||||
point: [hit.point.x, hit.point.y, hit.point.z], direction: [direction.x, direction.y, direction.z] });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (pickVertex.current || pickLocation.current) {
|
||||
// Snap to native topology in screen space, independent of tessellation density.
|
||||
let nearest: { point: THREE.Vector3; pixels: number; depth: number; normal?: THREE.Vector3 } | undefined;
|
||||
const occlusion = new THREE.Raycaster();
|
||||
const meshes = content.children.filter(object => object instanceof THREE.Mesh);
|
||||
for (const object of document.objects) {
|
||||
if (object.visible === false) continue;
|
||||
for (const position of object.vertices ?? object.pointMarkers ?? []) {
|
||||
const point = new THREE.Vector3(...position);
|
||||
const projected = point.clone().project(camera);
|
||||
if (projected.z < -1 || projected.z > 1) continue;
|
||||
const pixels = Math.hypot((projected.x + 1) * rect.width / 2 + rect.left - event.clientX,
|
||||
(1 - projected.y) * rect.height / 2 + rect.top - event.clientY);
|
||||
if (pixels > 10) continue;
|
||||
occlusion.setFromCamera(new THREE.Vector2(projected.x, projected.y), camera);
|
||||
const obstruction = occlusion.intersectObjects(meshes)[0];
|
||||
const depth = point.distanceTo(occlusion.ray.origin);
|
||||
if (obstruction && obstruction.distance < depth - radius * 1e-6) continue;
|
||||
if (!nearest || pixels < nearest.pixels - 0.01 || Math.abs(pixels - nearest.pixels) <= 0.01 && depth < nearest.depth) {
|
||||
let normal: THREE.Vector3 | undefined;
|
||||
if (pickLocation.current) {
|
||||
const mesh = meshes.find(item => item.userData.name === object.name);
|
||||
if (mesh instanceof THREE.Mesh) {
|
||||
if (obstruction?.object === mesh && obstruction.face) {
|
||||
normal = obstruction.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld));
|
||||
} else {
|
||||
// A ray through a boundary vertex can miss every triangle by roundoff.
|
||||
// Use that vertex's displayed normal from the same native mesh.
|
||||
const positions = mesh.geometry.getAttribute("position"), normals = mesh.geometry.getAttribute("normal");
|
||||
const vertex = new THREE.Vector3();
|
||||
let facing = -Infinity;
|
||||
for (let index = 0; normals && index < positions.count; ++index) {
|
||||
vertex.fromBufferAttribute(positions, index).applyMatrix4(mesh.matrixWorld);
|
||||
if (vertex.distanceTo(point) > radius * 1e-6) continue;
|
||||
const candidate = new THREE.Vector3().fromBufferAttribute(normals, index)
|
||||
.applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld));
|
||||
const score = -candidate.dot(occlusion.ray.direction);
|
||||
if (score > facing) { normal = candidate; facing = score; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
nearest = { point, pixels, depth, normal };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nearest) {
|
||||
const point: [number, number, number] = [nearest.point.x, nearest.point.y, nearest.point.z];
|
||||
if (pickVertex.current) pickVertex.current(point);
|
||||
else pickLocation.current?.(point, nearest.normal ? [nearest.normal.x, nearest.normal.y, nearest.normal.z] : undefined);
|
||||
return;
|
||||
}
|
||||
if (pickVertex.current) return;
|
||||
}
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.params.Line.threshold = radius / 200;
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
if (pickEdge.current) {
|
||||
const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.LineSegments))
|
||||
.find(hit => hit.index !== undefined && hit.object.userData.segmentEdges?.[Math.floor(hit.index / 2)]);
|
||||
if (hit) pickEdge.current(String(hit.object.userData.name), hit.object.userData.segmentEdges[Math.floor(hit.index! / 2)]);
|
||||
return;
|
||||
}
|
||||
const hit = ray.intersectObjects(content.children)[0];
|
||||
if (pickLocation.current) {
|
||||
if (hit?.face) {
|
||||
const normal = hit.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld));
|
||||
pickLocation.current([hit.point.x, hit.point.y, hit.point.z], [normal.x, normal.y, normal.z]);
|
||||
} else if (hit?.object instanceof THREE.LineSegments) {
|
||||
pickLocation.current([hit.point.x, hit.point.y, hit.point.z]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (hit && pickPoint.current) {
|
||||
// Point raycasts report the closest point on the ray, not the vertex itself.
|
||||
const point = hit.object instanceof THREE.Points && hit.index !== undefined
|
||||
? hit.object.localToWorld(new THREE.Vector3().fromBufferAttribute(hit.object.geometry.getAttribute("position"), hit.index))
|
||||
: hit.point;
|
||||
pickPoint.current([point.x, point.y, point.z]);
|
||||
} else if (hit) select.current(hit.object.userData.name);
|
||||
};
|
||||
renderer.domElement.addEventListener("pointerdown", down);
|
||||
renderer.domElement.addEventListener("pointerup", pick);
|
||||
renderer.domElement.addEventListener("pointermove", hover);
|
||||
renderer.domElement.addEventListener("pointerleave", leave);
|
||||
const labels = window.document.createElement("div");
|
||||
labels.style.cssText = "position:absolute;inset:0;pointer-events:none;overflow:hidden";
|
||||
container.style.position = "relative"; container.appendChild(labels);
|
||||
let previousAnnotations: typeof inspectionAnnotations | undefined;
|
||||
let controlsBeforeInspection: boolean | undefined;
|
||||
const direction = new THREE.Vector3();
|
||||
let announcedReady = false;
|
||||
const syncDecoration = () => {
|
||||
const name = selected[0];
|
||||
const target = name ? content.children.find(child => child.userData.name === name) : undefined;
|
||||
if (!target) { publishDecoration(decoration); decoration.clear(); publishDecoration(decoration); return; }
|
||||
const box = new THREE.Box3().setFromObject(target);
|
||||
if (box.isEmpty()) { decoration.clear(); publishDecoration(decoration); return; }
|
||||
decoration.setTarget(box.getCenter(new THREE.Vector3()).toArray(), new THREE.Quaternion(), target);
|
||||
publishDecoration(decoration);
|
||||
};
|
||||
syncDecoration();
|
||||
renderer.setAnimationLoop(() => {
|
||||
decoration.updateFrame(camera);
|
||||
if (meshInfo.current.active || inspection.current.mode === "inspect") {
|
||||
controlsBeforeInspection ??= controls.enabled;
|
||||
controls.enabled = false; renderer.domElement.style.cursor = "crosshair";
|
||||
} else if (controlsBeforeInspection !== undefined) {
|
||||
controls.enabled = controlsBeforeInspection; controlsBeforeInspection = undefined;
|
||||
renderer.domElement.style.cursor = "";
|
||||
}
|
||||
const annotations = inspection.current.annotations;
|
||||
if (annotations !== previousAnnotations) {
|
||||
labels.replaceChildren(...annotations.map(annotation => {
|
||||
const label = window.document.createElement("span"); label.textContent = annotation.text;
|
||||
label.style.cssText = "position:absolute;background:#55007f;color:#ddd;padding:4px;white-space:nowrap";
|
||||
return label;
|
||||
})); previousAnnotations = annotations;
|
||||
}
|
||||
annotations.forEach((annotation, index) => {
|
||||
const p = new THREE.Vector3(...annotation.point).project(camera);
|
||||
const label = labels.children[index] as HTMLElement;
|
||||
label.style.display = p.z < -1 || p.z > 1 ? "none" : "block";
|
||||
label.style.left = `${(p.x+1)*renderer.domElement.clientWidth/2}px`;
|
||||
label.style.top = `${(1-p.y)*renderer.domElement.clientHeight/2}px`;
|
||||
});
|
||||
controls.update();
|
||||
updateFacetHighlights();
|
||||
const request = facets.current?.request;
|
||||
if (request && request.id !== handledFacetRequest.current) {
|
||||
handledFacetRequest.current = request.id;
|
||||
const picked = collectFacets();
|
||||
if (request.mode === "small") for (const name of Object.keys(picked)) {
|
||||
const small = new Set(facets.current?.components[name]?.filter(group => group.length <= request.maximum).flat() ?? []);
|
||||
picked[name] = picked[name].filter(index => small.has(index));
|
||||
}
|
||||
facets.current?.onFacets(picked);
|
||||
}
|
||||
if (viewDirection.current) {
|
||||
controls.object.getWorldDirection(direction);
|
||||
viewDirection.current([direction.x, direction.y, direction.z]);
|
||||
}
|
||||
renderer.render(scene, camera);
|
||||
if (!announcedReady) { announcedReady = true; ready.current?.(); }
|
||||
});
|
||||
return () => {
|
||||
if (preserveCamera) savedCamera.current = { documentId: document.documentId, position: camera.position.clone(), target: controls.target.clone() };
|
||||
for (const child of highlight.children) {
|
||||
const mesh = child as THREE.Mesh; mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose();
|
||||
}
|
||||
polygonLayer.remove();
|
||||
labels.remove();
|
||||
observer.disconnect(); renderer.setAnimationLoop(null); sceneCommands.dispose(); decoration.dispose(); controls.dispose();
|
||||
renderer.domElement.removeEventListener("pointerdown", down);
|
||||
renderer.domElement.removeEventListener("pointerup", pick);
|
||||
renderer.domElement.removeEventListener("pointermove", hover);
|
||||
renderer.domElement.removeEventListener("pointerleave", leave);
|
||||
geometries.forEach(item => item.dispose()); materials.forEach(item => item.dispose());
|
||||
content.children.forEach(child => child.userData.dispose?.()); renderer.dispose(); renderer.domElement.remove();
|
||||
};
|
||||
}, [document, selected.join("\0"), reserveControlsSpace, polygonMode, facetInteraction?.mode]);
|
||||
return <div ref={host} aria-label={ariaLabel} style={{ width: "100%", height: viewportHeight, maxHeight: "60vh" }} />;
|
||||
}
|
||||
135
web/src/selection-decoration.ts
Normal file
135
web/src/selection-decoration.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
// Shared selection decoration for every three.js scene in the project: an X/Y/Z
|
||||
// triad at the object's local frame plus a wireframe focus box around the picked
|
||||
// shape. Both keep a constant size on screen by scaling against the camera
|
||||
// distance each frame, and both draw above geometry (depthTest off) so the frame
|
||||
// stays legible inside solids. The ImportRenderBridge and the standalone viewers
|
||||
// (standalone test view) all use this one implementation.
|
||||
import * as THREE from "three";
|
||||
|
||||
export type SelectionDecorationSnapshot = {
|
||||
axesVisible: boolean;
|
||||
axesPosition: number[];
|
||||
axesScale: number;
|
||||
focusVisible: boolean;
|
||||
focusMin: number[] | null;
|
||||
focusMax: number[] | null;
|
||||
};
|
||||
|
||||
export class SelectionDecoration {
|
||||
private axes: THREE.Group | null = null;
|
||||
private focus: THREE.Box3Helper | null = null;
|
||||
private origin: THREE.Vector3 | null = null;
|
||||
private readonly quaternion = new THREE.Quaternion();
|
||||
|
||||
constructor(private readonly scene: THREE.Scene) {}
|
||||
|
||||
setTarget(position: number[], quaternion: THREE.Quaternion, object?: THREE.Object3D | null): void {
|
||||
const axes = this.ensureAxes();
|
||||
axes.position.fromArray(position);
|
||||
axes.quaternion.copy(quaternion);
|
||||
axes.visible = true;
|
||||
this.quaternion.copy(quaternion);
|
||||
this.origin = axes.position.clone();
|
||||
this.setFocus(object ?? null);
|
||||
}
|
||||
|
||||
// Called while a gizmo drag is in flight so the triad follows the handle.
|
||||
follow(position: THREE.Vector3, quaternion: THREE.Quaternion): void {
|
||||
if (!this.axes) return;
|
||||
this.axes.position.copy(position);
|
||||
this.axes.quaternion.copy(quaternion);
|
||||
this.origin?.copy(position);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
if (this.axes) this.axes.visible = false;
|
||||
this.origin = null;
|
||||
this.setFocus(null);
|
||||
}
|
||||
|
||||
updateFrame(camera: THREE.Camera): void {
|
||||
const axes = this.axes;
|
||||
if (!axes || !axes.visible || !this.origin) return;
|
||||
camera.updateMatrixWorld();
|
||||
const distance = Math.max(camera.position.distanceTo(this.origin), 1e-4);
|
||||
const scale = camera instanceof THREE.PerspectiveCamera
|
||||
? distance * Math.tan(THREE.MathUtils.degToRad(camera.getEffectiveFOV()) / 2) * 0.18
|
||||
: camera instanceof THREE.OrthographicCamera
|
||||
? ((camera.top - camera.bottom) / Math.max(camera.zoom, 1e-6)) * 0.18
|
||||
: 1;
|
||||
axes.scale.setScalar(Math.max(scale, 1e-4));
|
||||
}
|
||||
|
||||
snapshot(): SelectionDecorationSnapshot {
|
||||
const axes = this.axes;
|
||||
const focus = this.focus;
|
||||
return {
|
||||
axesVisible: Boolean(axes?.visible),
|
||||
axesPosition: axes ? axes.position.toArray().map(value => Math.round(value * 1000) / 1000) : [],
|
||||
axesScale: axes ? Math.round(axes.scale.x * 1000) / 1000 : 0,
|
||||
focusVisible: Boolean(focus?.visible),
|
||||
focusMin: focus ? focus.box.min.toArray().map(value => Math.round(value * 1000) / 1000) : null,
|
||||
focusMax: focus ? focus.box.max.toArray().map(value => Math.round(value * 1000) / 1000) : null,
|
||||
};
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.axes) {
|
||||
this.axes.traverse(child => {
|
||||
const mesh = child as THREE.Mesh;
|
||||
mesh.geometry?.dispose?.();
|
||||
const materials = Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : [];
|
||||
for (const material of materials) material.dispose();
|
||||
});
|
||||
this.scene.remove(this.axes);
|
||||
this.axes = null;
|
||||
}
|
||||
this.setFocus(null);
|
||||
}
|
||||
|
||||
private ensureAxes(): THREE.Group {
|
||||
if (this.axes) return this.axes;
|
||||
const group = new THREE.Group();
|
||||
group.name = "selection-local-axes";
|
||||
const arrows: Array<[number[], number]> = [[[1, 0, 0], 0xd9534f], [[0, 1, 0], 0x5cb85c], [[0, 0, 1], 0x4a90d9]];
|
||||
for (const [direction, color] of arrows) {
|
||||
const arrow = new THREE.ArrowHelper(new THREE.Vector3(direction[0], direction[1], direction[2]).normalize(),
|
||||
new THREE.Vector3(), 1, color, 0.22, 0.09);
|
||||
arrow.userData.selectionHelper = true;
|
||||
arrow.traverse(child => {
|
||||
const material = (child as THREE.Mesh).material as THREE.Material | undefined;
|
||||
if (material) { material.depthTest = false; material.transparent = true; }
|
||||
child.renderOrder = 5;
|
||||
});
|
||||
group.add(arrow);
|
||||
}
|
||||
const origin = new THREE.Mesh(new THREE.SphereGeometry(0.06, 16, 12),
|
||||
new THREE.MeshBasicMaterial({ color: "#ffffff", depthTest: false, transparent: true, opacity: 0.9 }));
|
||||
origin.userData.selectionHelper = true; origin.renderOrder = 5; group.add(origin);
|
||||
group.visible = false;
|
||||
this.scene.add(group);
|
||||
this.axes = group;
|
||||
return group;
|
||||
}
|
||||
|
||||
private setFocus(object: THREE.Object3D | null): void {
|
||||
if (this.focus) {
|
||||
this.scene.remove(this.focus);
|
||||
this.focus.geometry.dispose();
|
||||
(this.focus.material as THREE.Material).dispose();
|
||||
this.focus = null;
|
||||
}
|
||||
if (!object || !object.visible) return;
|
||||
const box = new THREE.Box3().setFromObject(object);
|
||||
if (box.isEmpty()) return;
|
||||
const helper = new THREE.Box3Helper(box, new THREE.Color("#65d9ed"));
|
||||
helper.userData.selectionHelper = true;
|
||||
helper.traverse(child => {
|
||||
const material = (child as THREE.LineSegments).material as THREE.Material | undefined;
|
||||
if (material) { material.depthTest = false; material.transparent = true; material.opacity = 0.75; }
|
||||
child.renderOrder = 4;
|
||||
});
|
||||
this.scene.add(helper);
|
||||
this.focus = helper;
|
||||
}
|
||||
}
|
||||
226
web/src/storage.ts
Normal file
226
web/src/storage.ts
Normal file
@@ -0,0 +1,226 @@
|
||||
const STORE_DIRECTORY = "freecad-1-2";
|
||||
|
||||
interface OpfsFileHandle {
|
||||
createWritable(): Promise<{ write(data: ArrayBuffer): Promise<void>; close(): Promise<void>; abort(): Promise<void> }>;
|
||||
getFile(): Promise<{ arrayBuffer(): Promise<ArrayBuffer> }>;
|
||||
}
|
||||
|
||||
interface OpfsDirectoryHandle {
|
||||
getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<OpfsDirectoryHandle>;
|
||||
getFileHandle(name: string, options?: { create?: boolean }): Promise<OpfsFileHandle>;
|
||||
removeEntry(name: string): Promise<void>;
|
||||
entries(): AsyncIterableIterator<[string, unknown]>;
|
||||
}
|
||||
|
||||
type StorageWithOpfs = StorageManager & {
|
||||
getDirectory?: () => Promise<OpfsDirectoryHandle>;
|
||||
};
|
||||
|
||||
function sanitizeName(name: string): string {
|
||||
const baseName = name.split(/[\\/]/).pop() || "unnamed.step";
|
||||
return baseName.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
|
||||
async function getStore(directory = STORE_DIRECTORY): Promise<OpfsDirectoryHandle> {
|
||||
const storage = navigator.storage as StorageWithOpfs;
|
||||
if (!storage.getDirectory) {
|
||||
throw new Error("当前浏览器不支持 OPFS");
|
||||
}
|
||||
const root = await storage.getDirectory();
|
||||
return root.getDirectoryHandle(directory, { create: true });
|
||||
}
|
||||
|
||||
export function isOpfsSupported(): boolean {
|
||||
return typeof navigator !== "undefined" && typeof (navigator.storage as StorageWithOpfs | undefined)?.getDirectory === "function";
|
||||
}
|
||||
|
||||
export async function writeRawStep(name: string, bytes: ArrayBuffer): Promise<string> {
|
||||
const safeName = sanitizeName(name);
|
||||
const file = await (await getStore()).getFileHandle(safeName, { create: true });
|
||||
const writable = await file.createWritable();
|
||||
await writable.write(bytes);
|
||||
await writable.close();
|
||||
return safeName;
|
||||
}
|
||||
|
||||
export async function readRawStep(name: string): Promise<ArrayBuffer> {
|
||||
const file = await (await getStore()).getFileHandle(sanitizeName(name));
|
||||
return file.getFile().then((value) => value.arrayBuffer());
|
||||
}
|
||||
|
||||
export async function deleteRawStep(name: string): Promise<void> {
|
||||
await (await getStore()).removeEntry(sanitizeName(name));
|
||||
}
|
||||
|
||||
export async function listRawSteps(): Promise<string[]> {
|
||||
const store = await getStore();
|
||||
const names: string[] = [];
|
||||
for await (const [name] of store.entries()) {
|
||||
names.push(name);
|
||||
}
|
||||
return names.sort();
|
||||
}
|
||||
|
||||
const DOCUMENT_DIRECTORY = "freecad-documents";
|
||||
// Exported geometry (STEP/BREP/IGES/STL/...) lives in OPFS. A local download
|
||||
// only happens when the user explicitly asks for one; exports never auto-save.
|
||||
const EXPORT_DIRECTORY = "freecad-exports";
|
||||
function exportFilename(name: string): string {
|
||||
const safeName = sanitizeName(name);
|
||||
if (!/\.[a-z0-9]+$/i.test(safeName)) throw new Error("Export filename needs an extension");
|
||||
return safeName;
|
||||
}
|
||||
export async function writeExportFile(name: string, bytes: ArrayBuffer): Promise<string> {
|
||||
const safeName = exportFilename(name);
|
||||
if (!bytes.byteLength) throw new Error("A nonempty export file is required");
|
||||
const file = await (await getStore(EXPORT_DIRECTORY)).getFileHandle(safeName, { create: true });
|
||||
const writable = await file.createWritable();
|
||||
try {
|
||||
await writable.write(bytes);
|
||||
await writable.close();
|
||||
} catch (error) {
|
||||
await writable.abort().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
return safeName;
|
||||
}
|
||||
export async function listExportFiles(): Promise<string[]> {
|
||||
try {
|
||||
const names: string[] = [];
|
||||
for await (const [name] of (await getStore(EXPORT_DIRECTORY)).entries()) names.push(name);
|
||||
return names.sort();
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "NotFoundError") return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function readExportFile(name: string): Promise<ArrayBuffer> {
|
||||
const file = await (await getStore(EXPORT_DIRECTORY)).getFileHandle(exportFilename(name));
|
||||
return file.getFile().then((value) => value.arrayBuffer());
|
||||
}
|
||||
export async function deleteExportFile(name: string): Promise<void> {
|
||||
await (await getStore(EXPORT_DIRECTORY)).removeEntry(exportFilename(name));
|
||||
}
|
||||
|
||||
// Plot images are independent of editable CAD documents.
|
||||
export async function writePlotSvg(name: string, bytes: ArrayBuffer, signal: AbortSignal, commit: () => void): Promise<string> {
|
||||
const safeName = sanitizeName(name);
|
||||
if (!/\.svg$/i.test(safeName) || !bytes.byteLength) throw new Error("A nonempty SVG image is required");
|
||||
signal.throwIfAborted();
|
||||
const store = await getStore("freecad-plot-images");
|
||||
let created = false;
|
||||
let writable: Awaited<ReturnType<OpfsFileHandle["createWritable"]>> | undefined;
|
||||
try {
|
||||
let file: OpfsFileHandle;
|
||||
try { file = await store.getFileHandle(safeName); }
|
||||
catch (error) {
|
||||
if (!(error instanceof DOMException) || error.name !== "NotFoundError") throw error;
|
||||
signal.throwIfAborted();
|
||||
file = await store.getFileHandle(safeName, { create: true });
|
||||
created = true;
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
writable = await file.createWritable();
|
||||
signal.throwIfAborted();
|
||||
await writable.write(bytes);
|
||||
signal.throwIfAborted();
|
||||
commit();
|
||||
await writable.close();
|
||||
} catch (error) {
|
||||
await writable?.abort().catch(() => undefined);
|
||||
if (created) await store.removeEntry(safeName).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
return safeName;
|
||||
}
|
||||
|
||||
export async function writeDocumentFile(name: string, bytes: ArrayBuffer, signal?: AbortSignal, commit?: () => void): Promise<string> {
|
||||
const safeName = sanitizeName(name);
|
||||
if (!/\.FCStd$/i.test(safeName) || !bytes.byteLength) throw new Error("A nonempty FCStd document is required");
|
||||
signal?.throwIfAborted();
|
||||
const store = await getStore(DOCUMENT_DIRECTORY);
|
||||
let created = false;
|
||||
let writable: Awaited<ReturnType<OpfsFileHandle["createWritable"]>> | undefined;
|
||||
try {
|
||||
let file: OpfsFileHandle;
|
||||
try { file = await store.getFileHandle(safeName); }
|
||||
catch (error) {
|
||||
if (!(error instanceof DOMException) || error.name !== "NotFoundError") throw error;
|
||||
signal?.throwIfAborted();
|
||||
file = await store.getFileHandle(safeName, { create: true });
|
||||
created = true;
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
writable = await file.createWritable();
|
||||
signal?.throwIfAborted();
|
||||
await writable.write(bytes);
|
||||
signal?.throwIfAborted();
|
||||
// Closing commits the complete replacement. Cancellation ends at this boundary.
|
||||
commit?.();
|
||||
await writable.close();
|
||||
} catch (error) {
|
||||
await writable?.abort().catch(() => undefined);
|
||||
if (created) await store.removeEntry(safeName).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
return safeName;
|
||||
}
|
||||
|
||||
export async function readDocumentFile(name: string): Promise<ArrayBuffer> {
|
||||
const legacy = name.startsWith("Test/") ? "Test" : DOCUMENT_DIRECTORY;
|
||||
const file = await (await getStore(legacy)).getFileHandle(sanitizeName(name));
|
||||
return file.getFile().then(value => value.arrayBuffer());
|
||||
}
|
||||
|
||||
// Save review must not create directories or files before acceptance.
|
||||
export async function listSaveDestinations(): Promise<string[]> {
|
||||
const storage = navigator.storage as StorageWithOpfs;
|
||||
if (!storage.getDirectory) throw new Error("当前浏览器不支持 OPFS");
|
||||
try {
|
||||
const store = await (await storage.getDirectory()).getDirectoryHandle(DOCUMENT_DIRECTORY);
|
||||
const names: string[] = [];
|
||||
for await (const [name] of store.entries()) names.push(name);
|
||||
return names;
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "NotFoundError") return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listDocumentFiles(): Promise<string[]> {
|
||||
const names: string[] = [];
|
||||
for await (const [name] of (await getStore(DOCUMENT_DIRECTORY)).entries()) {
|
||||
if (/\.FCStd$/i.test(name)) names.push(name);
|
||||
}
|
||||
for await (const [name] of (await getStore("Test")).entries()) {
|
||||
if (/\.FCStd$/i.test(name)) names.push(`Test/${name}`);
|
||||
}
|
||||
return names.sort();
|
||||
}
|
||||
|
||||
const MACRO_DIRECTORY = "freecad-macros";
|
||||
function macroFilename(name: string): string {
|
||||
if (!name || /[\\/]/.test(name) || !/\.(FCMacro|py)$/i.test(name))
|
||||
throw new Error("Enter a macro filename ending in .FCMacro or .py");
|
||||
return name;
|
||||
}
|
||||
export async function writeMacroFile(name: string, source: string): Promise<void> {
|
||||
const file = await (await getStore(MACRO_DIRECTORY)).getFileHandle(macroFilename(name), { create: true });
|
||||
const writable = await file.createWritable();
|
||||
try { await writable.write(new TextEncoder().encode(source).buffer as ArrayBuffer); await writable.close(); }
|
||||
catch (error) { await writable.abort().catch(() => undefined); throw error; }
|
||||
}
|
||||
export async function readMacroFiles(): Promise<Array<{ filename: string; source: string }>> {
|
||||
const store = await getStore(MACRO_DIRECTORY);
|
||||
const files: Array<{ filename: string; source: string }> = [];
|
||||
for await (const [name] of store.entries()) {
|
||||
if (!/\.(FCMacro|py)$/i.test(name)) continue;
|
||||
const file = await (await store.getFileHandle(name)).getFile();
|
||||
files.push({ filename: name, source: new TextDecoder().decode(await file.arrayBuffer()) });
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function deleteDocumentFile(name: string): Promise<void> {
|
||||
await (await getStore(DOCUMENT_DIRECTORY)).removeEntry(sanitizeName(name));
|
||||
}
|
||||
156
web/src/web-open-adapter.ts
Normal file
156
web/src/web-open-adapter.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { readDocumentFile } from "./storage.js";
|
||||
import { encodeSceneFile } from "./test-scene-session.js";
|
||||
import { createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js";
|
||||
import type { WebModuleRouter } from "./module-router.js";
|
||||
import { viewEndpoint, type DocumentViewResult } from "./part-view-facade.js";
|
||||
import { validOpenResult, type OpenFileEntry, type OpenResult } from "./web-open-contract.js";
|
||||
|
||||
type Directory = FileSystemDirectoryHandle & { entries(): AsyncIterableIterator<[string, FileSystemHandle]> };
|
||||
async function openStore(): Promise<Directory> {
|
||||
if (typeof navigator.storage?.getDirectory !== "function") throw new Error("OPFS is unavailable");
|
||||
return await (await navigator.storage.getDirectory()).getDirectoryHandle("freecad-open-files", { create: true }) as Directory;
|
||||
}
|
||||
async function storedFiles() {
|
||||
const root = await openStore(), files: Array<{ key: string; filename: string }> = [];
|
||||
for await (const [hash, handle] of root.entries()) {
|
||||
if (handle.kind !== "directory" || !/^[a-f0-9]{64}$/.test(hash)) continue;
|
||||
const directory = await root.getDirectoryHandle(hash) as Directory;
|
||||
for await (const [name, item] of directory.entries())
|
||||
if (item.kind === "file") files.push({ key: `${hash}/${name}`, filename: name });
|
||||
}
|
||||
return files.sort((a, b) => a.filename.localeCompare(b.filename) || a.key.localeCompare(b.key));
|
||||
}
|
||||
export function pickFiles(): Promise<File[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const input = document.createElement("input"); input.type = "file"; input.multiple = true; input.accept = ".fcstd,.jt,.step,.stp,.iges,.igs,.brep,.brp,.rle,.stl,.scad,.csg"; input.hidden = true;
|
||||
const finish = (files: File[]) => { input.remove(); resolve(files); };
|
||||
input.onchange = () => finish(Array.from(input.files ?? []));
|
||||
input.addEventListener("cancel", () => finish([]), { once: true });
|
||||
document.body.appendChild(input);
|
||||
try { input.click(); } catch (error) { input.remove(); reject(error); }
|
||||
});
|
||||
}
|
||||
async function prepareFile(file: File | OpenFileEntry): Promise<OpenFileEntry> {
|
||||
const filename = file instanceof File ? file.name : file.filename;
|
||||
if (!filename || filename === "." || filename === ".." || /[\\/]/.test(filename)) throw new Error("Invalid file name");
|
||||
let bytes: Uint8Array<ArrayBuffer>;
|
||||
if (file instanceof File) bytes = new Uint8Array(await file.arrayBuffer());
|
||||
else bytes = Uint8Array.from(atob(file.fileData), char => char.charCodeAt(0));
|
||||
const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map(value => value.toString(16).padStart(2, "0")).join("");
|
||||
const directory = await (await openStore()).getDirectoryHandle(hash, { create: true });
|
||||
const writable = await (await directory.getFileHandle(filename, { create: true })).createWritable();
|
||||
try { await writable.write(bytes); await writable.close(); }
|
||||
catch (error) { await writable.abort().catch(() => {}); throw error; }
|
||||
let binary = "";
|
||||
for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
|
||||
return { filename, fileData: btoa(binary), sha256: hash, ...(!(file instanceof File) && file.module ? { module: file.module } : {}) };
|
||||
}
|
||||
|
||||
function base64Bytes(value: string): ArrayBuffer {
|
||||
const binary = atob(value), bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
async function openPartNativeFile(router: WebModuleRouter, owner: string, documentId: string, file: OpenFileEntry,
|
||||
applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise<OpenResult> {
|
||||
const nativeDocument = documentId.replace(/[^A-Za-z0-9_]/g, "_").replace(/^[^A-Za-z_]/, "_");
|
||||
const extension = file.filename.split(".").pop()?.toLowerCase() ?? "";
|
||||
const command = extension === "step" || extension === "stp" ? "Part_ImportStep"
|
||||
: extension === "iges" || extension === "igs" ? "Import_Iges"
|
||||
: extension === "brep" || extension === "brp" || extension === "rle" ? "Import_ReadBREP" : undefined;
|
||||
// Desktop naming for Std_Open comes from the file stem: Part.insert() creates
|
||||
// the feature with file.fileNamePure() and the native preflight snapshot uses
|
||||
// the same name, so the Web tree must match instead of using a fixed name.
|
||||
const stem = file.filename.replace(/\.[^.]+$/, "");
|
||||
const object = (stem.replace(/[^A-Za-z0-9_]/g, "_").replace(/^[^A-Za-z_]/, "_") || "Imported1");
|
||||
const path = `/tmp/${nativeDocument}_${object}.${extension}`;
|
||||
const schema = "freecad-web-part/document/v1";
|
||||
const request = (action: string, extra: Record<string, unknown> = {}) => router.request("Part", "part.document", {
|
||||
schema, module: "Part", document: nativeDocument, action, object, includeMesh: true, ...extra,
|
||||
}, documentId);
|
||||
const created = await request("create");
|
||||
if (created.kind === "error") throw new Error(created.error.message);
|
||||
const imported = await request("importShape", {
|
||||
label: stem, path, bytes: base64Bytes(file.fileData),
|
||||
...(command ? { desktopImportCommand: command } : {}),
|
||||
});
|
||||
if (imported.kind === "error") throw new Error(imported.error.message);
|
||||
const native = imported.result as { objects?: Array<{ name: string }>; objectCount?: number };
|
||||
const firstObject = native.objects?.[0]?.name;
|
||||
if (!firstObject) throw new Error("Native import produced no document object");
|
||||
applySelection?.(nativeDocument, [{ documentId: nativeDocument, object: firstObject }]);
|
||||
return { command: "Std_Open", documentId, operation: "open", activeDocument: nativeDocument,
|
||||
formats: [], errors: [], opened: [{ filename: file.filename, sha256: file.sha256 ?? "0".repeat(64), reused: false,
|
||||
documents: [{ name: nativeDocument, label: file.filename, filename: file.filename, objectCount: native.objectCount ?? native.objects?.length ?? 0, partialRestore: false, restoreError: false }] }],
|
||||
scene: undefined };
|
||||
}
|
||||
export async function executeOpenDocument(router: WebModuleRouter, args: Record<string, unknown>, documentId: string,
|
||||
applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise<FacadeResponse> {
|
||||
const owner = args.runtimeOwner ?? "PartBox";
|
||||
if (owner !== "PartBox" && owner !== "DocumentProbe") return createFailure("desktop-open", "wrong_document_owner", "Choose the native document runtime");
|
||||
if (args.documentId !== undefined && args.documentId !== documentId)
|
||||
return createFailure("desktop-open", "document_mismatch", "Open request belongs to another document");
|
||||
if (args.activeTask === true) return createFailure("desktop-open", "active_task", "Finish the active task before opening files");
|
||||
if (args.operation !== undefined && args.operation !== "list" && args.operation !== "open")
|
||||
return createFailure("desktop-open", "invalid_request", "Open operation must be list or open");
|
||||
try {
|
||||
const signal = args.signal instanceof AbortSignal ? args.signal : undefined;
|
||||
let inputs: Array<File | OpenFileEntry> = [];
|
||||
if (args.operation === "list") inputs = [];
|
||||
else if (typeof args.storedKey === "string") {
|
||||
const match = /^([a-f0-9]{64})\/([^/\\]+)$/.exec(args.storedKey);
|
||||
if (!match) throw new Error("Invalid stored file key");
|
||||
const directory = await (await openStore()).getDirectoryHandle(match[1]);
|
||||
inputs = [await (await directory.getFileHandle(match[2])).getFile()];
|
||||
} else if (Array.isArray(args.files)) inputs = args.files as Array<File | OpenFileEntry>;
|
||||
else inputs = await pickFiles();
|
||||
if (args.operation !== "list" && !inputs.length) return createFailure("desktop-open", "cancelled", "Open cancelled");
|
||||
const files: OpenFileEntry[] = [];
|
||||
for (const input of inputs) files.push({ ...await prepareFile(input),
|
||||
...(typeof args.module === "string" && args.module ? { module: args.module } : {}) });
|
||||
const nativePart = files.length === 1 && /\.(step|stp|iges|igs|brep|brp|rle|stl)$/i.test(files[0].filename);
|
||||
if (nativePart && args.operation !== "list") {
|
||||
const value = await openPartNativeFile(router, String(owner), documentId, files[0], applySelection);
|
||||
value.storedFiles = await storedFiles();
|
||||
// part.document is routed to the DocumentProbe save worker. Return that
|
||||
// owner so the scene viewer reads the document from the same native runtime.
|
||||
return createSuccess("desktop-open-part-native", { owner: "DocumentProbe", records: [{ name: "Std_Open", status: "success", result: value }] });
|
||||
}
|
||||
// FCStd restore and subsequent part.document snapshots share the
|
||||
// DocumentProbe save worker. Keep the open response and scene on that
|
||||
// owner instead of creating a PartBox-only document the project bridge
|
||||
// cannot edit or save.
|
||||
const nativeFcstd = files.length === 1 && /\.fcstd$/i.test(files[0].filename);
|
||||
const viewOwner = nativeFcstd ? "DocumentProbe" : owner;
|
||||
const response = await router.request("Part", viewEndpoint(viewOwner), {
|
||||
schema: "freecad-web/document-view/v1", owner: viewOwner, document: documentId, command: "Std_Open",
|
||||
parameters: { documentId, operation: args.operation === "list" ? "list" : "open", files, activeTask: args.activeTask },
|
||||
}, documentId);
|
||||
if (response.kind !== "result") return response;
|
||||
const value = response.result;
|
||||
if (!validOpenResult(value, documentId)) return createFailure(response.requestId, "native_protocol_error", "Invalid native open result");
|
||||
value.storedFiles = await storedFiles();
|
||||
const restoredObjectCount = value.opened[0]?.documents?.reduce((sum, document) => sum + document.objectCount, 0) ?? 0;
|
||||
const deferLargeScene = restoredObjectCount > 250;
|
||||
if (deferLargeScene) {
|
||||
value.sceneError = `Initial scene deferred for ${restoredObjectCount} restored objects; use the project workspace scene after the document tree is ready.`;
|
||||
}
|
||||
if (!deferLargeScene && value.opened.length && value.activeDocument) {
|
||||
applySelection?.(value.activeDocument, []);
|
||||
try {
|
||||
const scene = await router.request("Part", viewEndpoint(viewOwner), {
|
||||
schema: "freecad-web/document-view/v1", owner: viewOwner, document: value.activeDocument, command: "Std_DrawStyle",
|
||||
parameters: { documentId: value.activeDocument, action: "read", selection: [] },
|
||||
}, value.activeDocument);
|
||||
if (scene.kind === "error") throw new Error(scene.error.message);
|
||||
if ((scene.result as DocumentViewResult).documentId !== value.activeDocument) throw new Error("Opened document scene identity mismatch");
|
||||
value.scene = scene.result as DocumentViewResult;
|
||||
window.dispatchEvent(new CustomEvent("freecad-document-view", { detail: { owner: viewOwner, documentId: value.activeDocument, value: scene.result } }));
|
||||
} catch (error) { value.sceneError = String(error); }
|
||||
}
|
||||
if (value.errors.length) return createFailure(response.requestId, "file_open_failed",
|
||||
value.errors.map(error => `${error.filename}: ${error.message}`).join("\n"), { openResult: value });
|
||||
return createSuccess(response.requestId, { owner: viewOwner, records: [{ name: "Std_Open", status: "success", result: value }] });
|
||||
} catch (error) { return createFailure("desktop-open", "file_open_failed", String(error)); }
|
||||
}
|
||||
51
web/src/web-open-task.tsx
Normal file
51
web/src/web-open-task.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { useRef, useState } from "react";
|
||||
import type { FacadeResponse } from "./facade-envelope.js";
|
||||
import { validOpenResult, type OpenResult } from "./web-open-contract.js";
|
||||
|
||||
export function WebOpenTask({ response, busy, execute }: {
|
||||
response: FacadeResponse | null; busy: boolean; execute: (args: Record<string, unknown>) => void;
|
||||
}) {
|
||||
const cancellation = useRef<AbortController>();
|
||||
const [owner, setOwner] = useState("PartBox"), [stored, setStored] = useState("");
|
||||
const [module, setModule] = useState("");
|
||||
const batch = response?.kind === "result" ? response.result as { records?: Array<{ name?: string; result?: unknown }> } : undefined;
|
||||
const candidate = response?.kind === "error" ? response.error.diagnostic?.openResult
|
||||
: batch?.records?.find(row => row.name === "Std_Open")?.result;
|
||||
const value = candidate && validOpenResult(candidate, (candidate as OpenResult).documentId) ? candidate : undefined;
|
||||
const run = (args: Record<string, unknown>) => {
|
||||
cancellation.current = new AbortController();
|
||||
execute({ runtimeOwner: owner, module, ...args, signal: cancellation.current.signal });
|
||||
};
|
||||
const handlers = [...new Set(value?.formats.flatMap(format => format.modules) ?? [])].filter(name => name !== "FreeCAD");
|
||||
return <section aria-label="Open documents">
|
||||
<fieldset disabled={busy}>
|
||||
<legend>Open Documents</legend>
|
||||
<label>Document runtime <select value={owner} onChange={event => setOwner(event.target.value)}>
|
||||
<option>PartBox</option><option>DocumentProbe</option></select></label>
|
||||
<label>Import handler <select value={module} onChange={event => setModule(event.target.value)}>
|
||||
<option value="">Automatic</option>{handlers.map(name => <option key={name}>{name}</option>)}
|
||||
</select></label>
|
||||
<button type="button" onClick={() => run({ operation: "open" })}>Choose files</button>
|
||||
<button type="button" onClick={() => run({ operation: "list" })}>Refresh stored files and formats</button>
|
||||
<label>Stored original <select value={stored} onChange={event => setStored(event.target.value)}>
|
||||
<option value="">Select a file</option>{value?.storedFiles?.map(file => <option key={file.key} value={file.key}>
|
||||
{file.filename} ({file.key.slice(0, 8)})
|
||||
</option>)}
|
||||
</select></label>
|
||||
<button type="button" disabled={!stored} onClick={() => run({ storedKey: stored, operation: "open" })}>Open stored file</button>
|
||||
</fieldset>
|
||||
{busy && <button type="button" onClick={() => cancellation.current?.abort()}>Cancel file open before commit</button>}
|
||||
{value && <>
|
||||
<ul>{value.opened.flatMap(file => file.documents.map(doc => <li key={`${file.sha256}:${doc.name}`}>
|
||||
{file.filename}: {doc.label} ({doc.objectCount} objects){file.reused ? " - already open" : ""}
|
||||
{doc.partialRestore && <p role="alert">Document was only partially restored.</p>}
|
||||
{doc.restoreError && <p role="alert">Native document restore reported errors.</p>}
|
||||
</li>))}</ul>
|
||||
{value.errors.map((error, index) => <p role="alert" key={index}>{error.filename}: {error.message}</p>)}
|
||||
{value.sceneError && <p role="alert">{value.sceneError}</p>}
|
||||
<details><summary>Native import formats</summary><ul>{value.formats.map(format => <li key={format.extension}>
|
||||
.{format.extension}: {format.modules.join(", ")}
|
||||
</li>)}</ul></details>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
79
web/src/web-owner-standard-adapter.ts
Normal file
79
web/src/web-owner-standard-adapter.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { FEM_PARAMETER_PATH, isFemParameterPath, requestFemParameters } from "./fem-preferences.js";
|
||||
import { helpPreferences, resolveHelp } from "./help-preferences.js";
|
||||
import { isToolbarParameterPath, requestToolbarParameters } from "./toolbar-preferences.js";
|
||||
import { createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js";
|
||||
import type { WebModuleRouter } from "./module-router.js";
|
||||
import { viewEndpoint, type DocumentViewResult } from "./part-view-facade.js";
|
||||
import { validStandardResult } from "./web-standard-command-contract.js";
|
||||
import routes from "./document-view-routes.json";
|
||||
import { requestOwnerParameters } from "./view-navigation-preferences.js";
|
||||
|
||||
/** Commands with existing native semantics and the mounted standard task. */
|
||||
export function executeOwnerStandard(router: WebModuleRouter, command: string,
|
||||
args: Record<string, unknown>, documentId: string): Promise<FacadeResponse> | undefined {
|
||||
if (!routes.standardCommands.includes(command)) return;
|
||||
if (["Std_DlgParameter", "Std_DlgPreferences"].includes(command)
|
||||
&& (isFemParameterPath(args.path) || args.runtimeOwner === "Fem")) {
|
||||
return requestFemParameters(router, documentId, { ...args, path: args.path ?? FEM_PARAMETER_PATH }, command).then(response => {
|
||||
if (response.kind !== "result") return response;
|
||||
if (!validStandardResult(response.result, command, documentId))
|
||||
return createFailure(response.requestId, "native_protocol_error", "Invalid FEM parameter response");
|
||||
return createSuccess(response.requestId, {
|
||||
schema: "freecad-web/document-view-batch/v1", owner: "Fem", documentId,
|
||||
records: [{ apiId: `Web:desktop:${command}`, name: command, status: "success", native: true, result: response.result }], count: 1,
|
||||
});
|
||||
});
|
||||
}
|
||||
// The standard preferences host keeps its usual owner. Its Material resource
|
||||
// page sends its reads and durable writes directly to the Material worker.
|
||||
const owner = command === "Std_DlgPreferences" && args.runtimeOwner === "Material" ? "PartBox" : args.runtimeOwner ?? "PartBox";
|
||||
if (owner !== "PartBox" && owner !== "DocumentProbe")
|
||||
return Promise.resolve(createFailure("desktop-Web", "wrong_document_owner", "Select the document's native runtime"));
|
||||
if (!documentId.trim() || (args.documentId !== undefined && args.documentId !== documentId))
|
||||
return Promise.resolve(createFailure("desktop-Web", "document_mismatch", "Command document identifiers differ"));
|
||||
const parameterRoot = command === "Std_DlgPreferences" ? "User parameter:BaseApp/Preferences"
|
||||
: command === "Std_DlgCustomize" ? "User parameter:BaseApp/Workbench" : undefined;
|
||||
const request = command === "Std_DlgParameter" && isToolbarParameterPath(args.path)
|
||||
? requestToolbarParameters(router, owner, documentId, args)
|
||||
: ["Std_DlgParameter", "Std_DlgPreferences"].includes(command)
|
||||
? requestOwnerParameters(router, owner, documentId, { ...args, ...(parameterRoot ? { path: args.path ?? parameterRoot } : {}) }, command)
|
||||
: router.request("Part", viewEndpoint(owner), {
|
||||
schema: "freecad-web/document-view/v1", owner, document: documentId, command,
|
||||
parameters: { ...args, ...(parameterRoot ? { path: args.path ?? parameterRoot } : {}), documentId },
|
||||
}, documentId);
|
||||
return request.then(async response => {
|
||||
if (response.kind !== "result") return response;
|
||||
if (!validStandardResult(response.result, command, documentId))
|
||||
return createFailure(response.requestId, "native_protocol_error", "Invalid native standard command response");
|
||||
const value = response.result;
|
||||
if (command === "Std_WhatsThis") {
|
||||
try {
|
||||
const help = resolveHelp(await helpPreferences(router, owner, documentId), value.page);
|
||||
Object.assign(value, { help });
|
||||
} catch (error) {
|
||||
return createFailure(response.requestId, "help_unavailable", String(error));
|
||||
}
|
||||
}
|
||||
if (command === "Std_AnnotationLabel" || command === "Std_TestCmdFuncs") {
|
||||
// Refresh once through the existing read-only display path. A failed
|
||||
// refresh must not invite resubmitting an already committed annotation.
|
||||
try {
|
||||
const refreshed = await router.request("Part", viewEndpoint(owner), {
|
||||
schema: "freecad-web/document-view/v1", owner, document: documentId,
|
||||
command: "Std_DrawStyle", parameters: { documentId, action: "read", selection: args.selection ?? [] },
|
||||
}, documentId);
|
||||
if (refreshed.kind === "result") {
|
||||
const scene = refreshed.result as DocumentViewResult;
|
||||
if (scene.documentId !== documentId || !Array.isArray(scene.meshes)) throw new Error("Invalid native scene response");
|
||||
window.dispatchEvent(new CustomEvent("freecad-document-view", {
|
||||
detail: { owner, documentId, value: scene },
|
||||
}));
|
||||
} else value.sceneError = JSON.stringify(refreshed);
|
||||
} catch (error) { value.sceneError = String(error); }
|
||||
}
|
||||
return createSuccess(response.requestId, {
|
||||
schema: "freecad-web/document-view-batch/v1", owner, documentId,
|
||||
records: [{ apiId: `Web:desktop:${command}`, name: command, status: "success", native: true, result: value }], count: 1,
|
||||
});
|
||||
});
|
||||
}
|
||||
5263
web/src/workbench-shell.tsx
Normal file
5263
web/src/workbench-shell.tsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -51,7 +51,6 @@ export default defineConfig({
|
||||
measure: "measure.html",
|
||||
mesh: "mesh.html",
|
||||
meshpart: "meshpart.html",
|
||||
openscad: "openscad.html",
|
||||
part: "part.html",
|
||||
"part-io": "part-io.html",
|
||||
"part-inspect": "part-inspect.html",
|
||||
|
||||
Reference in New Issue
Block a user