Files
FreeCADWasmDev/tools/parity/extract-desktop-gui.mjs
2026-11-13 15:01:14 +08:00

300 lines
14 KiB
JavaScript

#!/usr/bin/env node
// Extracts desktop FreeCAD workbench menus/toolbars/docks/command metadata and
// joins them with the Web command matrix. Outputs:
// - web/public/api/desktop-gui-manifest.json
// - web/docs/current/desktop-parity-matrix.json
// - web/public/api/gui-command-gap-report.json
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../..");
const webRoot = path.join(repoRoot, "web");
const sourceRoot = path.join(repoRoot, "freecad-source");
const srcRoot = path.join(sourceRoot, "src");
const args = process.argv.slice(2);
const check = args.includes("--check");
const matrixPath = path.join(webRoot, "public/api/workbench-command-matrix.json");
const routesPath = path.join(webRoot, "public/api/desktop-command-routes.json");
const matrix = JSON.parse(fs.readFileSync(matrixPath, "utf8"));
const routes = JSON.parse(fs.readFileSync(routesPath, "utf8"));
const moduleIds = [...new Set((matrix.records ?? []).map(item => item.module))].sort();
const read = file => (fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "");
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const quote = value => String(value ?? "").replace(/^&/, "").trim();
const parseCppMenus = text => {
const section = text.slice(text.indexOf("setupMenuBar"), text.indexOf("setupToolBars") > 0
? text.indexOf("setupToolBars") : undefined);
const menus = new Map();
const declarations = [...section.matchAll(/Gui::MenuItem\*\s+(\w+)\s*=\s*new\s+Gui::MenuItem[^;]*;/g)];
for (let index = 0; index < declarations.length; index++) {
const match = declarations[index];
const start = match.index;
const end = declarations[index + 1]?.index ?? section.length;
const block = section.slice(start, end);
const label = /setCommand\("([^"]*)"\)/.exec(block)?.[1];
if (!label) continue;
const items = [];
for (const token of block.split("<<").slice(1)) {
const value = token.split(";")[0].trim();
const command = /^"([^"]+)"$/.exec(value)?.[1];
const child = /^(\w+)$/.exec(value)?.[1];
if (command) items.push({ type: command === "Separator" ? "separator" : "command", id: command });
else if (child && child !== match[1]) items.push({ type: "submenu", ref: child });
}
menus.set(match[1], { label: quote(label), items });
}
for (const menu of menus.values()) {
menu.items = menu.items.map(item => item.type === "submenu" && menus.has(item.ref)
? { type: "submenu", label: menus.get(item.ref).label, items: menus.get(item.ref).items }
: item);
}
return [...menus.values()].filter(menu => menu.label && menu.items.length > 0 && !/^&?(File|Edit|View|Tools|Macro|Windows|Help)$/i.test(menu.label));
};
const parseCppToolBars = text => {
const start = text.indexOf("setupToolBars");
const section = text.slice(start, text.indexOf("setupCommandBars") > start ? text.indexOf("setupCommandBars") : undefined);
const bars = [];
for (const match of section.matchAll(/Gui::ToolBarItem\*\s+(\w+)\s*=\s*new\s+Gui::ToolBarItem\([^)]*\);/g)) {
const block = section.slice(match.index).split(/\n\s*\}/)[0];
const name = /setCommand\("([^"]*)"\)/.exec(block)?.[1];
if (!name) continue;
const items = [...block.matchAll(/<<\s*"([^"]+)"/g)].map(item => item[1]).filter(item => item !== "Separator");
bars.push({ name: quote(name), items });
}
return bars;
};
const pythonCalls = (text, name) => {
const calls = [];
let index = 0;
while ((index = text.indexOf(`${name}(`, index)) >= 0) {
let cursor = index + name.length + 1;
let depth = 1; let quote = "";
for (; cursor < text.length; cursor++) {
const char = text[cursor];
if (quote) { if (char === quote && text[cursor - 1] !== "\\") quote = ""; continue; }
if (char === '"' || char === "'") { quote = char; continue; }
if (char === "(" || char === "[") depth++;
if (char === ")" || char === "]") depth--;
if (depth === 0) break;
}
calls.push(text.slice(index + name.length + 1, cursor));
index = cursor + 1;
}
return calls;
};
const splitPythonArgs = value => {
const parts = []; let depth = 0; let quote = ""; let start = 0;
for (let index = 0; index < value.length; index++) {
const char = value[index];
if (quote) { if (char === quote && value[index - 1] !== "\\") quote = ""; continue; }
if (char === '"' || char === "'") { quote = char; continue; }
if (char === "(" || char === "[") depth++;
if (char === ")" || char === "]") depth--;
if (char === "," && depth === 0) { parts.push(value.slice(start, index)); start = index + 1; }
}
parts.push(value.slice(start));
return parts.map(part => part.trim()).filter(Boolean);
};
const parsePythonGui = text => {
const vars = new Map();
for (const match of text.matchAll(/^\s*(?:self\.)?(\w+)\s*=\s*\[([\s\S]*?)\]\s*$/gm)) {
vars.set(match[1], { type: "list", value: [...match[2].matchAll(/["']([^"']+)["']/g)].map(item => item[1]) });
}
for (const match of text.matchAll(/^\s*(?:self\.)?(\w+)\s*=\s*QT_TRANSLATE_NOOP\([^,]+,\s*"([^"]*)"\)/gm)) {
vars.set(match[1], { type: "label", value: match[2] });
}
const resolve = expr => {
const value = expr.trim();
if (vars.has(value)) return vars.get(value);
if (/^\[/.test(value)) return { type: "list", value: [...value.matchAll(/["']([^"']+)["']/g)].map(item => item[1]) };
const translated = /QT_TRANSLATE_NOOP\([^,]+,\s*"([^"]*)"\)/.exec(value);
if (translated) return { type: "label", value: translated[1] };
const quoted = /^["']([^"']+)["']$/.exec(value);
if (quoted) return { type: "label", value: quoted[1] };
return null;
};
const resolveList = expr => {
if (expr.includes("+")) return splitPythonArgs(expr.replace(/\+/g, ",")).flatMap(resolveList);
const resolved = resolve(expr);
if (!resolved) return [];
return resolved.type === "list" ? resolved.value : [resolved.value];
};
const menus = [];
for (const body of pythonCalls(text, "appendMenu")) {
const args = splitPythonArgs(body);
if (args.length < 2) continue;
const labels = resolveList(args[0]);
const items = resolveList(args.at(-1));
for (const label of labels) menus.push({ label: label.replace(/^&/, ""), items: items.map(id =>
({ type: id === "Separator" ? "separator" : "command", id })) });
}
const toolbars = [];
for (const body of pythonCalls(text, "appendToolbar")) {
const args = splitPythonArgs(body);
if (args.length < 2) continue;
const names = resolveList(args[0]);
const items = resolveList(args[1]);
for (const name of names) toolbars.push({ name: name.replace(/^&/, ""), items });
}
return { menus, toolbars };
};
const parseCommandMetadata = text => {
const metadata = {};
const field = (block, name) => new RegExp(`${name}\\s*=\\s*(?:QT_TR_NOOP\\(|QT_TRANSLATE_NOOP\\([^,]+,\\s*)?"([^"]*)"`).exec(block)?.[1];
const record = (id, block) => {
const menuText = field(block, "sMenuText");
const toolTip = field(block, "sToolTipText");
const icon = field(block, "sPixmap");
const accel = field(block, "sAccel");
if (menuText || toolTip || icon || accel)
metadata[id] = { menuText: menuText ?? "", toolTip: toolTip ?? "", icon: icon ?? "", accel: accel ?? "" };
};
for (const match of text.matchAll(/Command\("([^"]+)"\)/g))
record(match[1], text.slice(match.index, match.index + 1400));
for (const match of text.matchAll(/sName\s*=\s*"([^"]+)"/g))
record(match[1], text.slice(match.index, match.index + 1400));
return metadata;
};
const guiSourceFor = module => {
const candidates = [
path.join(srcRoot, "Mod", module, "Gui", "Workbench.cpp"),
path.join(srcRoot, "Mod", module, "Gui", "Workbench.py"),
path.join(srcRoot, "Mod", module, "InitGui.py"),
];
return candidates.find(file => fs.existsSync(file)) ?? null;
};
const workbenches = [];
const commandMetadata = {};
const presentModules = [];
for (const module of moduleIds) {
const file = guiSourceFor(module);
if (!file) continue;
presentModules.push(module);
const text = read(file);
const isPython = file.endsWith(".py");
const menus = isPython ? parsePythonGui(text).menus : parseCppMenus(text);
const toolbars = isPython ? parsePythonGui(text).toolbars : parseCppToolBars(text);
const docks = [...text.matchAll(/(?:addDockWidget|registerDockWindow)\(\s*"([^"]+)"/g)].map(match => match[1]);
if (!isPython) for (const [id, meta] of Object.entries(parseCommandMetadata(text))) commandMetadata[id] = meta;
const seenMenus = new Set();
const cleanMenus = menus.filter(menu => menu.label && menu.label !== "Workbench"
&& menu.items.some(item => item.type !== "separator"))
.filter(menu => { if (seenMenus.has(menu.label)) return false; seenMenus.add(menu.label); return true; });
const seenToolbars = new Set();
const cleanToolbars = toolbars.filter(toolbar => toolbar.name && toolbar.name !== "Workbench"
&& toolbar.items.length).filter(toolbar => { if (seenToolbars.has(toolbar.name)) return false; seenToolbars.add(toolbar.name); return true; });
workbenches.push({ id: module, source: path.relative(repoRoot, file), menus: cleanMenus,
toolbars: cleanToolbars, docks });
}
const commandDir = path.join(srcRoot, "Gui");
for (const name of fs.existsSync(commandDir) ? fs.readdirSync(commandDir) : []) {
if (!/^Command.*\.cpp$/.test(name)) continue;
Object.assign(commandMetadata, parseCommandMetadata(read(path.join(commandDir, name))));
}
for (const module of presentModules) {
const dir = path.join(srcRoot, "Mod", module, "Gui");
if (!fs.existsSync(dir)) continue;
for (const name of fs.readdirSync(dir)) {
if (!/^Command.*\.cpp$/.test(name)) continue;
Object.assign(commandMetadata, parseCommandMetadata(read(path.join(dir, name))));
}
}
const menuCommandIds = new Set();
const toolbarCommandIds = new Set();
const flatten = items => {
for (const item of items ?? []) {
if (item.type === "command" && item.id) menuCommandIds.add(item.id);
if (item.type === "submenu") flatten(item.items);
}
};
for (const workbench of workbenches) {
for (const menu of workbench.menus) flatten(menu.items);
for (const toolbar of workbench.toolbars) for (const id of toolbar.items) toolbarCommandIds.add(id);
}
const routeByCommand = new Map((routes.records ?? []).map(item => [`${item.appearanceModule ?? item.module}:${item.desktopCommand ?? item.command}`, item]));
const boundaryCommands = new Set(["TechDraw_PageDefault", "FEM_ResultShow", "CAM_Adaptive", "Import_Gltf"]);
const records = (matrix.records ?? []).map(item => {
const key = `${item.module}:${item.command}`;
const route = routeByCommand.get(key) ?? null;
let status = "gui-missing";
if (boundaryCommands.has(item.command)) status = "boundary";
else if (item.disposition === "implemented") status = "implemented";
else if (item.disposition === "native_handler") status = "native-ui-check";
else if (menuCommandIds.has(item.command) || toolbarCommandIds.has(item.command)) status = "gui-route-missing";
return {
id: item.id ?? key, module: item.module, command: item.command,
disposition: item.disposition ?? "unknown", route: item.route ?? route?.route ?? null,
inMenu: menuCommandIds.has(item.command), inToolbar: toolbarCommandIds.has(item.command),
metadata: commandMetadata[item.command] ?? null, status,
sourcePath: item.sourcePath ?? null, sourceLine: item.sourceLine ?? null,
};
});
const manifest = {
schema: "freecad-web-desktop-gui-manifest/v1",
generatedAt: new Date().toISOString(),
sourceRevision: { matrix: sha256(matrixPath), routes: sha256(routesPath) },
workbenchCount: workbenches.length,
workbenches,
commandMetadata,
commandCount: records.length,
menuCommandCount: menuCommandIds.size,
toolbarCommandCount: toolbarCommandIds.size,
};
const matrixOut = {
schema: "freecad-web-desktop-parity-matrix/v1",
generatedAt: manifest.generatedAt,
stats: {
workbenches: workbenches.length,
commands: records.length,
menuCommands: menuCommandIds.size,
toolbarCommands: toolbarCommandIds.size,
implemented: records.filter(item => item.status === "implemented").length,
nativeUiCheck: records.filter(item => item.status === "native-ui-check").length,
guiRouteMissing: records.filter(item => item.status === "gui-route-missing").length,
guiMissing: records.filter(item => item.status === "gui-missing").length,
boundary: records.filter(item => item.status === "boundary").length,
},
records,
};
const gapReport = {
schema: "freecad-web-desktop-gui-gap-report/v1",
generatedAt: manifest.generatedAt,
byStatus: matrixOut.stats,
records: records.filter(item => item.status !== "implemented").map(item => ({
id: item.id, module: item.module, command: item.command, status: item.status,
inMenu: item.inMenu, inToolbar: item.inToolbar, route: item.route,
source: item.sourcePath ? `${item.sourcePath}:${item.sourceLine ?? ""}` : null,
})),
};
if (check) {
// Plot/Show/Web are utility modules without a desktop workbench source.
const noGuiWorkbench = new Set(["Plot", "Show", "Web"]);
const missing = moduleIds.filter(module => !presentModules.includes(module) && !noGuiWorkbench.has(module));
if (missing.length) throw new Error(`no desktop GUI source for modules: ${missing.join(", ")}`);
if (workbenches.length < 29) throw new Error(`expected at least 29 GUI workbenches, got ${workbenches.length}`);
}
fs.mkdirSync(path.join(webRoot, "public/api"), { recursive: true });
fs.mkdirSync(path.join(webRoot, "docs/current"), { recursive: true });
fs.writeFileSync(path.join(webRoot, "public/api/desktop-gui-manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
fs.writeFileSync(path.join(webRoot, "docs/current/desktop-parity-matrix.json"), `${JSON.stringify(matrixOut, null, 2)}\n`);
fs.writeFileSync(path.join(webRoot, "public/api/gui-command-gap-report.json"), `${JSON.stringify(gapReport, null, 2)}\n`);
console.log(JSON.stringify({ ok: true, workbenches: workbenches.length, commands: records.length,
menuCommands: menuCommandIds.size, stats: matrixOut.stats }));