#!/usr/bin/env python3 """Inventory desktop UI surfaces and group Web parity work by shared owners. This is a source inventory, not a validation or acceptance check. It records the existing desktop GUI anchors, Web mounted surfaces, policy gap counts and the native build targets that can own a package. The output is deliberately separate from module-batch-manifest.json, whose status and selection belong to the outer scheduler planner. """ from __future__ import annotations import json import re from datetime import datetime, timezone from pathlib import Path from policy_io import atomic_write ROOT = Path(__file__).resolve().parents[1] DOCS = ROOT / "docs/current" SOURCE = ROOT / "freecad-source/src/Mod" WEB = ROOT / "web/src" POLICY = DOCS / "execution-policy.json" OUT_JSON = DOCS / "desktop-ui-parity-inventory.json" OUT_MD = DOCS / "DESKTOP_UI_PARITY_PACKAGE_PLAN_20260922.md" MODULES = [ "Part", "PartDesign", "Sketcher", "Spreadsheet", "TechDraw", "Surface", "Draft", "Mesh", "MeshPart", "BIM", "Fem", "CAM", "Assembly", "Measure", "Material", "Points", "Robot", "ReverseEngineering", "Inspection", "Import", "Cloud", "JtReader", "Start", "Help", "Plot", "Show", "Sandbox", "TemplatePyMod", "Test", "Tux", "Web", ] TARGET_RE = re.compile(r"FreeCADWeb[A-Za-z0-9_]+Probe") COMMAND_RE = re.compile(r"\b(?:Cmd|Command)[A-Za-z0-9_]+") def read(path: Path) -> str: try: return path.read_text(encoding="utf-8", errors="replace") except OSError: return "" def files(directory: Path, suffix: str | None = None) -> list[str]: if not directory.is_dir(): return [] values = [str(p.relative_to(ROOT)) for p in directory.rglob("*") if p.is_file()] if suffix: values = [value for value in values if value.endswith(suffix)] return sorted(values) def web_files(module: str) -> list[str]: aliases = { "PartDesign": "partdesign-", "TechDraw": "techdraw-", "MeshPart": "meshpart-", "ReverseEngineering": "reverseengineering-", "TemplatePyMod": "templatepymod-", } prefix = aliases.get(module, module.lower() + "-") return sorted(str(path.relative_to(ROOT)) for path in WEB.glob(f"{prefix}*") if path.is_file()) def command_source(module: str) -> list[str]: return desktop_sources(module)["commandSources"] def desktop_sources(module: str) -> dict: # Python workbenches put panels/commands outside Gui; Web also owns the # application-wide C++ GUI. A missing Gui directory is not missing UI. roots = [SOURCE / module] if module == "Web": roots.append(ROOT / "freecad-source/src/Gui") paths = sorted({name for root in roots for name in files(root) if Path(name).suffix in {".cpp", ".h", ".py", ".ui"} and not any(part.lower() in {"tests", "test", "resources", "__pycache__"} for part in Path(name).parts[5:-1])}) # Designer UI files intentionally include Resources/panels/preferences. ui_files = sorted({name for root in roots for name in files(root, ".ui")}) commands, workbenches, panels, properties, preferences = [], [], [], [], [] for name in paths: path = Path(name) lower = path.name.lower() if path.suffix == ".py": text = read(ROOT / name) if re.search(r"\b(?:addCommand|addWorkbench|appendMenu|appendToolbar|appendContextMenu)\s*\(", text): commands.append(name) if lower == "initgui.py" or re.search(r"\b(?:appendMenu|appendToolbar)\s*\(", text): workbenches.append(name) if "task" in lower or "panel" in lower or re.search(r"\b(?:showDialog|QDialog)\s*\(", text): panels.append(name) if "viewprovider" in lower or "property" in lower: properties.append(name) if "pref" in lower or re.search(r"\baddPreferencePage\s*\(", text): preferences.append(name) elif path.suffix in {".cpp", ".h"} and ("Gui" in path.parts or module == "Web"): if lower.startswith("command") or lower.endswith("workbench.cpp"): commands.append(name) if lower.endswith("workbench.cpp"): workbenches.append(name) if lower.startswith(("task", "dlg")) or "dialog" in lower: panels.append(name) if lower.startswith(("property", "viewprovider")): properties.append(name) if "settings" in lower or "pref" in lower: preferences.append(name) return {"sourceRoots": [str(root.relative_to(ROOT)) for root in roots if root.is_dir()], "commandSources": commands, "workbenchSources": workbenches, "taskAndDialogUi": ui_files, "taskAndDialogSources": panels, "propertyAndViewSources": properties, "preferenceSources": preferences} def native_targets(module: str, cmake_text: str) -> list[str]: if module == "Web": return sorted(set(TARGET_RE.findall(cmake_text)) & { "FreeCADWebWebRuntimeProbe", "FreeCADWebDocumentProbe", "FreeCADWebWorkbenchCommandProbe"}) if module == "Part": return sorted(name for name in set(TARGET_RE.findall(cmake_text)) if re.fullmatch(r"FreeCADWeb(?:Part(?:Box|DesktopCommand|GeometryFamily|Io)|Document)Probe", name)) aliases = {"Fem": "Fem", "PartDesign": "PartDesign", "MeshPart": "MeshPart", "TechDraw": "TechDraw", "ReverseEngineering": "ReverseEngineering", "Assembly": "Assembly"} needle = aliases.get(module, module) return sorted({name for name in TARGET_RE.findall(cmake_text) if needle.lower() in name.lower()}) def package_for(module: str) -> str: if module in {"Part", "PartDesign", "Sketcher"}: return "ui-primary-modeling-workspace" if module in {"Spreadsheet", "TechDraw"}: return "ui-document-editors-output" if module in {"Mesh", "MeshPart", "Surface", "Draft"}: return "ui-geometry-workbench-tasks" if module in {"BIM", "Fem", "CAM", "Assembly"}: return "ui-domain-workbench-tasks" if module in {"Material", "Measure", "Points", "Robot", "ReverseEngineering", "Inspection"}: return "ui-analysis-and-inspection-tasks" return "ui-shell-preferences-and-utility" def main() -> int: cmake = read(ROOT / "freecad-source/src/WebAssembly/FreeCADCoreProbe/CMakeLists.txt") try: policy = json.loads(POLICY.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): policy = {} gaps = policy.get("confirmedGapRepairs", []) if isinstance(policy, dict) else [] gap_counts: dict[str, dict[str, int]] = {} for row in gaps: if not isinstance(row, dict): continue module = str(row.get("module") or "") if not module: continue status = str(row.get("status") or "open") gap_counts.setdefault(module, {})[status] = gap_counts.setdefault(module, {}).get(status, 0) + 1 shared_sources = [ "web/src/project-shell.tsx", "web/src/workbench-shell.tsx", "web/src/desktop-command-dispatcher.ts", "web/src/persistent-toolbar-workspace.tsx", "web/src/web-desktop-adapter.ts", "web/src/css.ts", ] inventory = [] for module in MODULES: gui = SOURCE / module / "Gui" desktop = desktop_sources(module) ui_files = desktop["taskAndDialogUi"] command_files = desktop["commandSources"] command_text = "\n".join(read(ROOT / path) for path in command_files) web_owned = web_files(module) task_files = [path for path in web_owned if path.endswith("-task.tsx") or path.endswith("-task.ts")] adapter_files = [path for path in web_owned if "adapter" in Path(path).name or "facade" in Path(path).name] imports = [] for host in ("web/src/project-shell.tsx", "web/src/workbench-shell.tsx", "web/src/partdesign-workspace-component.tsx"): for line, text in enumerate(read(ROOT / host).splitlines(), 1): if "import" in text and any(Path(name).stem in text for name in web_owned if name.endswith(".tsx")): imports.append({"path": host, "line": line, "source": text.strip()}) inventory.append({ "module": module, "package": package_for(module), "desktop": { **desktop, "guiDirectory": str(gui.relative_to(ROOT)), "guiDirectoryExists": gui.is_dir(), "commandSymbolCount": len(set(COMMAND_RE.findall(command_text))), "countMeaning": "Source search symbols only; not command coverage or completion", }, "web": { "ownedFiles": web_owned, "taskPanels": task_files, "adaptersAndFacades": adapter_files, "candidateSharedShells": [path for path in shared_sources if (ROOT / path).is_file()], "componentImportAnchors": imports, "importMeaning": "Imports locate code; imports do not prove mounted or usable routes", }, "nativeBuildTargets": native_targets(module, cmake), "gapStatusCounts": gap_counts.get(module, {}), "uiCoverage": {area: "source_indexed_not_compared" for area in ( "menus", "toolbars_buttons", "tasks_control_panels", "properties", "dialogs_preferences", "context_menus", "status_feedback", "shortcuts_focus_styles")}, "retainedGapKeys": [row.get("key") for row in gaps if row.get("module") == module], "registration": { "sourceGapLedger": "docs/current/execution-policy.json:confirmedGapRepairs[]", "discoveryRecords": "docs/current/operator-gap-discovery/run-*.json", "implementationRecord": "docs/current/operator-gap--implementation.json or README.md", "statusRule": "implemented_unvalidated; validation remains disabled", }, }) packages = [ { "id": "ui-shell-preferences-and-utility", "modules": [m["module"] for m in inventory if m["package"] == "ui-shell-preferences-and-utility"], "sharedFrontendOwners": ["project-shell.tsx", "workbench-shell.tsx", "persistent-toolbar-workspace.tsx", "web-desktop-adapter.ts"], "nativeTargets": ["FreeCADWebDocumentProbe", "FreeCADWebWorkbenchCommandProbe"], "surfaceScope": ["application menus", "workbench selector", "toolbar layout", "status/error feedback", "preferences/dialog host", "context menu host"], "buildScope": "frontend Vite bundle once; native target only when shared owner or command registry changes", }, { "id": "ui-primary-modeling-workspace", "modules": ["Part", "PartDesign", "Sketcher"], "sharedFrontendOwners": ["project-shell.tsx", "partdesign-workspace-component.tsx", "workbench-shell.tsx", "desktop-command-dispatcher.ts"], "nativeTargets": ["FreeCADWebDocumentProbe", "FreeCADWebPartBoxProbe", "FreeCADWebPartDesignRuntimeProbe", "FreeCADWebSketcherProbe", "FreeCADWebPartDesktopCommandProbe"], "surfaceScope": ["modeling menus/toolbars", "shared task panels", "tree/property pages", "selection and viewport handoff", "accept/cancel/history"], "buildScope": "group changed native owners by configured tree; one -j8 build per affected tree, then one frontend build", }, { "id": "ui-document-editors-output", "modules": ["Spreadsheet", "TechDraw"], "sharedFrontendOwners": ["spreadsheet-sheet-editor.tsx", "project-shell.tsx", "workbench-shell.tsx", "web-print-adapter.ts"], "nativeTargets": ["FreeCADWebSpreadsheetRuntimeProbe", "FreeCADWebTechDrawRuntimeProbe", "FreeCADWebDocumentProbe"], "surfaceScope": ["sheet/page menus", "table/page task panels", "cell/page property dialogs", "print/export/preview", "context actions"], "buildScope": "reuse current retained owners; build only changed Spreadsheet/TechDraw targets and one frontend bundle", }, { "id": "ui-geometry-workbench-tasks", "modules": ["Mesh", "MeshPart", "Surface", "Draft"], "sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"], "nativeTargets": ["FreeCADWebMeshRuntimeProbe", "FreeCADWebMeshPartRuntimeProbe", "FreeCADWebSurfaceRuntimeProbe", "FreeCADWebDraftRuntimeProbe"], "surfaceScope": ["workbench menus/toolbars", "geometry task dialogs", "property editors", "selection filters", "preview/apply/cancel feedback"], "buildScope": "one target build per changed native owner; shared Web route and frontend build once", }, { "id": "ui-domain-workbench-tasks", "modules": ["BIM", "Fem", "CAM", "Assembly"], "sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"], "nativeTargets": ["FreeCADWebBimRuntimeProbe", "FreeCADWebFemGenericFamilyProbe", "FreeCADWebCAMProbe", "FreeCADWebAssemblyProbe", "FreeCADWebAssemblyKernelProbe"], "surfaceScope": ["domain menus/toolbars", "task panels", "property/preferences dialogs", "context menus", "job/progress/status feedback"], "buildScope": "group native changes by actual configured owner target; no unrelated module rebuild", }, { "id": "ui-analysis-and-inspection-tasks", "modules": ["Material", "Measure", "Points", "Robot", "ReverseEngineering", "Inspection"], "sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"], "nativeTargets": ["FreeCADWebMaterialRuntimeProbe", "FreeCADWebMeasureRuntimeProbe", "FreeCADWebPointsRuntimeProbe", "FreeCADWebRobotRuntimeProbe", "FreeCADWebReverseEngineeringRuntimeProbe", "FreeCADWebInspectionRuntimeProbe"], "surfaceScope": ["command menus", "selection/property dialogs", "task panels", "result/status presentation", "cancel/recovery semantics"], "buildScope": "shared frontend bundle; build only native targets whose source owner changed", }, ] result = { "schema": "freecad-web-desktop-ui-parity-inventory/v1", "generatedAt": datetime.now(timezone.utc).isoformat(), "mode": "source-inventory-no-validation", "coverageMeaning": "Source index only. Eight UI surfaces per module remain explicitly unassessed by this index. Reuse keyed implementation records; do not re-open completed work solely for missing comparisons.", "buildTargetMeaning": "Candidate targets only, never a build list. Resolve changed file consumers and published build trees in web/tools/sync-assets.mjs before necessary native -j8 builds.", "objective": "Desktop UI parity packages grouped by shared workbench owners and native build targets", "registration": { "policy": "docs/current/execution-policy.json", "confirmedGapKey": "operator-gap-", "packageRecord": "docs/current/desktop-ui-parity-package-records.json", "implementationStatus": "implemented_unvalidated", }, "sharedFrontendOwners": shared_sources, "packages": packages, "modules": inventory, } atomic_write(OUT_JSON, result) lines = [ "# 桌面 UI 对标包计划(2026-09-22)", "", "本文件是源码盘点和分包基线,不是验证报告。调度器继续保持单一实例;`module-batch-manifest.json` 的状态、选择和批次 ID 仍由外层规划器维护。", "主线:桌面 FreeCAD UI → Web FreeCAD UI 完全功能与样式对标。覆盖 C++ GUI、Python InitGui/命令/任务面板、Designer .ui 和应用公共 GUI。文件存在、import、命令符号和构建成功均不代表入口已挂载或整模块已对标。", "每模块保留菜单、工具栏按钮、任务/控制面板、属性页、对话框/偏好、右键菜单、状态反馈、快捷键/焦点/样式八类覆盖状态;未比较项不自动制造缺口,只沿具体源码路由查缺。六个大类是索引目录,实际实施包仍按共享文档所有者/适配器/构建目标聚合。", "", "## 统一路由骨架", "", "每个包都沿用:桌面 `Workbench.cpp/Command.cpp` 注册 → Web `project-shell.tsx` 或 `workbench-shell.tsx` 菜单/工具栏 → React 任务面板、属性页或对话框 → `DesktopCommandDispatcher` 与模块 adapter/facade → 原生 Document owner/WASM → 树、视口、状态栏和历史反馈。", "", "共享前端所有者:`project-shell.tsx`、`workbench-shell.tsx`、`persistent-toolbar-workspace.tsx`、`desktop-command-dispatcher.ts`、`web-desktop-adapter.ts`。", "", "## 分包", "", ] for package in packages: lines.extend([ f"### `{package['id']}`", f"模块:{', '.join(package['modules'])}", f"构建目标:{', '.join(package['nativeTargets'])}", f"对标面:{ '、'.join(package['surfaceScope']) }。", f"接续规则:{package['buildScope']}。", "", ]) lines.extend([ "## 缺口登记方式", "", "具体缺口仍登记在 `docs/current/execution-policy.json` 的 `confirmedGapRepairs[]`,每条必须有桌面源码锚点、Web 路由入口、原生 owner、对标范围、具体剩余限制和实现记录。多个同一工作台/构建目标的缺口使用同一个 `functionalPackage`,在一个回合集中修改;不要为单个按钮单独创建包。", "", "状态只使用 `open`、`implemented_unvalidated` 或真实阻塞状态;不运行测试、烟测、浏览器检查、截图、验收或独立类型检查。必要构建仅使用受影响目标和原生 `-j8`,前端使用现有 Vite 配置。", "", "详细机器可读盘点见 [`desktop-ui-parity-inventory.json`](desktop-ui-parity-inventory.json)。包状态见 [`desktop-ui-parity-package-records.json`](desktop-ui-parity-package-records.json)。", ]) OUT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8") print(json.dumps({"inventory": str(OUT_JSON.relative_to(ROOT)), "plan": str(OUT_MD.relative_to(ROOT)), "modules": len(inventory), "packages": len(packages)}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())