Add desktop GUI manifest, parity matrix and Web baseline audit

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-11-13 14:08:35 +08:00
parent 579d6d20c8
commit aff9b6464a
9 changed files with 48403 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
#!/usr/bin/env node
// Baseline Web GUI audit for one workbench: menus/toolbars/docks/status, page
// errors and overflow, compared with desktop-gui-manifest.json.
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
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 require = createRequire(path.join(webRoot, "package.json"));
const { chromium } = require("playwright");
const args = process.argv.slice(2);
const option = (name, fallback) => {
const index = args.indexOf(name);
return index < 0 ? fallback : args[index + 1] ?? fallback;
};
const workbench = option("--workbench", "Part");
const origin = option("--origin", "http://127.0.0.1:5181");
const manifest = JSON.parse(fs.readFileSync(path.join(webRoot, "public/api/desktop-gui-manifest.json"), "utf8"));
const desktop = manifest.workbenches.find(item => item.id === workbench);
if (!desktop) throw new Error(`manifest has no workbench ${workbench}`);
const outDir = path.join(webRoot, "docs/current/desktop-parity-evidence");
fs.mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const errors = []; const failed = [];
page.on("pageerror", error => errors.push(String(error)));
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
const url = `${origin}/project.html?workbench=${encodeURIComponent(workbench)}`;
const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 120000 });
await page.waitForSelector('select[aria-label="Workbench"]', { timeout: 120000 }).catch(() => {});
await page.waitForTimeout(1500);
const metrics = await page.evaluate(() => ({
menus: [...document.querySelectorAll('nav[aria-label="Application menus"] details > summary')]
.map(node => node.textContent.trim()),
toolbarButtons: document.querySelectorAll('[role="toolbar"] button, .part-tool-button, .toolbar-workspace button').length,
docks: [...document.querySelectorAll('aside[aria-label], section[aria-label], [role="region"]')]
.map(node => node.getAttribute("aria-label")).filter(Boolean),
hasTree: Boolean(document.querySelector('.fc-tree, aside[aria-label="Model tree"]')),
hasProperties: Boolean(document.querySelector('aside.properties')),
hasTask: Boolean(document.querySelector('[role="region"]')),
status: document.querySelector('footer [role="status"]')?.textContent?.trim() ?? "",
workbenchValue: document.querySelector('select[aria-label="Workbench"]')?.value ?? "",
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
}));
const expectedMenus = desktop.menus.map(menu => menu.label);
const missingMenus = expectedMenus.filter(label => !metrics.menus.includes(label));
const shot = path.join(outDir, `${workbench}-web.png`);
await page.screenshot({ path: shot, fullPage: false });
const report = {
schema: "freecad-web-desktop-parity/web-gui-audit/v1",
generatedAt: new Date().toISOString(), workbench, url,
desktop: { menus: expectedMenus, toolbars: desktop.toolbars.map(bar => bar.name),
menuCommandCount: desktop.menus.reduce((sum, menu) => sum + menu.items.length, 0) },
web: metrics, missingMenus,
status: response?.status(), errors, failed,
ok: response?.status() === 200 && errors.length === 0 && failed.length === 0 && metrics.overflow === 0,
};
fs.writeFileSync(path.join(outDir, `${workbench}-web-audit.json`), `${JSON.stringify(report, null, 2)}\n`);
console.log(JSON.stringify(report));
await browser.close();
process.exitCode = report.ok ? 0 : 1;

View File

@@ -0,0 +1,251 @@
#!/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 && !/^&?(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 parsePythonLists = text => {
const lists = new Map();
for (const match of text.matchAll(/(\w+)\s*=\s*\[([^\]]*)\]/gs)) {
const items = [...match[2].matchAll(/["']([^"']+)["']/g)].map(item => item[1]);
if (items.length) lists.set(match[1], items);
}
return lists;
};
const pythonArgStrings = value => [...value.matchAll(/["']([^"']+)["']/g)].map(match => match[1]);
const resolvePythonItems = (value, lists) => {
const trimmed = value.trim();
if (lists.has(trimmed)) return lists.get(trimmed);
const bracket = /\[([\s\S]*)\]/.exec(trimmed);
if (bracket) return pythonArgStrings(bracket[1]);
return [];
};
const parsePythonGui = text => {
const lists = parsePythonLists(text);
const menus = [];
for (const match of text.matchAll(/appendMenu\(([\s\S]*?)\)\s*$/gm)) {
const value = match[1];
const strings = pythonArgStrings(value);
const label = strings.at(-1);
const items = resolvePythonItems(value.split(",").slice(0, -1).join(","), lists);
if (label) menus.push({ label, items: items.map(id => ({ type: "command", id })) });
}
const toolbars = [];
for (const match of text.matchAll(/appendToolbar\(([\s\S]*?)\)\s*$/gm)) {
const value = match[1];
const parts = value.split(",");
const name = pythonArgStrings(parts[0]).at(-1) ?? parts[0].trim();
const items = resolvePythonItems(parts.slice(1).join(","), lists);
if (name) toolbars.push({ name, 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;
workbenches.push({ id: module, source: path.relative(repoRoot, file), menus, toolbars, 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 }));