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 { 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 { 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 { const filename = file instanceof File ? file.name : file.filename; if (!filename || filename === "." || filename === ".." || /[\\/]/.test(filename)) throw new Error("Invalid file name"); let bytes: Uint8Array; 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 { 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 = {}) => 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, documentId: string, applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise { 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 = []; 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; 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)); } }