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:
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
Reference in New Issue
Block a user