Compare commits
72 Commits
fix/sse-re
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6222a5181 | ||
|
|
9187622239 | ||
| 63a6da8b6c | |||
|
|
a88e104d94 | ||
|
|
7dc157894f | ||
| 43e905c00a | |||
|
|
f67d9a0422 | ||
| af98994a53 | |||
|
|
d266bfb653 | ||
| a92174e0b9 | |||
|
|
edbaf65923 | ||
| 80f8ec27a0 | |||
|
|
6b3e8b7518 | ||
| b3fe98c696 | |||
|
|
c537e2f08f | ||
| 29b1f32fd9 | |||
| dca6380199 | |||
| 27f0cc0f34 | |||
| a5eff534b5 | |||
|
|
1001424b16 | ||
| 7e3127498a | |||
| 82d8741059 | |||
|
|
3fe43710fa | ||
|
|
8cbd872e5c | ||
|
|
e31321ac95 | ||
|
|
dc64a66f0f | ||
|
|
3d38e4b4c3 | ||
|
|
da2a360c56 | ||
|
|
3dd0da3964 | ||
|
|
4921095296 | ||
|
|
3a9fe6aed8 | ||
|
|
9e99b83091 | ||
| 0f407360ed | |||
| fa4f3145c6 | |||
|
|
fed72676bc | ||
| d3e27010d8 | |||
|
|
d7c6066030 | ||
| 91f539a18a | |||
| 2ddfea083a | |||
| be8783bf0a | |||
| 972dc07157 | |||
| 069bb7a552 | |||
| 201e0af450 | |||
| 8a6e5cdffa | |||
| 95c56fa29a | |||
| 33d5eeb76c | |||
| 9e83982c78 | |||
| e83769090b | |||
| 52fc9cdd3a | |||
| ae132948d1 | |||
|
|
ab801601c9 | ||
| 32d5f1ea1b | |||
| de80e392f5 | |||
| ba42343577 | |||
| af7eab3a70 | |||
| 6c9789fdf3 | |||
| 85bfb17854 | |||
| 6d231e80dd | |||
| a7ef5f195b | |||
|
|
7cf5867a7a | ||
|
|
9a6d1dfbd2 | ||
| 8937cb5e8b | |||
| a53cd52c73 | |||
|
|
c6e187a75c | ||
|
|
2e9bf52082 | ||
|
|
383eefce9c | ||
|
|
1676b3e1a0 | ||
|
|
06cd30e88d | ||
| f9924d35f7 | |||
| 373f3aaa79 | |||
| 66b2baf510 | |||
|
|
d26bb6da2d |
7
.mailmap
Normal file
7
.mailmap
Normal file
@@ -0,0 +1,7 @@
|
||||
forbes <contact@kindred-systems.com> forbes <joseph.forbes@kindred-systems.com>
|
||||
forbes <contact@kindred-systems.com> forbes <zoe.forbes@kindred-systems.com>
|
||||
forbes <contact@kindred-systems.com> forbes-0023 <joseph.forbes@kindred-systems.com>
|
||||
forbes <contact@kindred-systems.com> forbes-0023 <zoe.forbes@kindred-systems.com>
|
||||
forbes <contact@kindred-systems.com> josephforbes23 <joseph.forbes@kindred-systems.com>
|
||||
forbes <contact@kindred-systems.com> Zoe Forbes <forbes@copernicus-9.kindred.internal>
|
||||
forbes <contact@kindred-systems.com> admin <admin@kindred-systems.com>
|
||||
13
Init.py
Normal file
13
Init.py
Normal file
@@ -0,0 +1,13 @@
|
||||
"""Silo addon — console initialization.
|
||||
|
||||
Adds the shared silo-client package to sys.path so that
|
||||
``import silo_client`` works from silo_commands.py and other modules.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
_mod_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
_client_dir = os.path.join(_mod_dir, "silo-client")
|
||||
if os.path.isdir(_client_dir) and _client_dir not in sys.path:
|
||||
sys.path.insert(0, _client_dir)
|
||||
265
InitGui.py
Normal file
265
InitGui.py
Normal file
@@ -0,0 +1,265 @@
|
||||
"""Kindred Silo addon — GUI initialization.
|
||||
|
||||
Registers the SiloWorkbench, Silo file origin, overlay context,
|
||||
dock panels (auth + activity), document observer, and start page override.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import FreeCAD
|
||||
import FreeCADGui
|
||||
|
||||
FreeCAD.Console.PrintMessage("Kindred Silo InitGui.py loading...\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Workbench
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SiloWorkbench(FreeCADGui.Workbench):
|
||||
"""Kindred Silo workbench for item database integration."""
|
||||
|
||||
MenuText = "Kindred Silo"
|
||||
ToolTip = "Item database and part management for Kindred Create"
|
||||
Icon = ""
|
||||
|
||||
def __init__(self):
|
||||
icon_path = os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
"freecad",
|
||||
"resources",
|
||||
"icons",
|
||||
"silo.svg",
|
||||
)
|
||||
if os.path.exists(icon_path):
|
||||
self.__class__.Icon = icon_path
|
||||
|
||||
def Initialize(self):
|
||||
"""Called when workbench is first activated."""
|
||||
import silo_commands
|
||||
|
||||
# Register Silo as a file origin in the unified origin system
|
||||
try:
|
||||
import silo_origin
|
||||
|
||||
silo_origin.register_silo_origin()
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Could not register Silo origin: {e}\n")
|
||||
|
||||
# Silo origin toolbar — shown as an overlay on any context when the
|
||||
# active document is Silo-tracked. Registered as Unavailable so
|
||||
# EditingContextResolver controls visibility via the overlay system.
|
||||
self.silo_toolbar_commands = [
|
||||
"Silo_Commit",
|
||||
"Silo_Pull",
|
||||
"Silo_Push",
|
||||
"Separator",
|
||||
"Silo_Info",
|
||||
"Silo_BOM",
|
||||
"Silo_Jobs",
|
||||
]
|
||||
self.appendToolbar("Silo Origin", self.silo_toolbar_commands, "Unavailable")
|
||||
|
||||
# Silo menu provides admin/management commands.
|
||||
self.menu_commands = [
|
||||
"Silo_Info",
|
||||
"Silo_BOM",
|
||||
"Silo_Jobs",
|
||||
"Silo_TagProjects",
|
||||
"Silo_SetStatus",
|
||||
"Silo_Rollback",
|
||||
"Silo_SaveAsTemplate",
|
||||
"Separator",
|
||||
"Silo_Settings",
|
||||
"Silo_Auth",
|
||||
"Silo_Runners",
|
||||
"Silo_StartPanel",
|
||||
"Silo_Diag",
|
||||
]
|
||||
|
||||
self.appendMenu("Silo", self.menu_commands)
|
||||
|
||||
def Activated(self):
|
||||
"""Called when workbench is activated."""
|
||||
FreeCAD.Console.PrintMessage("Kindred Silo workbench activated\n")
|
||||
FreeCADGui.runCommand("Silo_StartPanel", 0)
|
||||
|
||||
def Deactivated(self):
|
||||
pass
|
||||
|
||||
def GetClassName(self):
|
||||
return "Gui::PythonWorkbench"
|
||||
|
||||
|
||||
FreeCADGui.addWorkbench(SiloWorkbench())
|
||||
FreeCAD.Console.PrintMessage("Silo workbench registered\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Silo overlay context — adds "Silo Origin" toolbar to any active context
|
||||
# when the current document is Silo-tracked.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _register_silo_overlay():
|
||||
"""Register the Silo overlay after the Silo workbench has initialised."""
|
||||
|
||||
def _silo_overlay_match():
|
||||
"""Return True if the active document is Silo-tracked."""
|
||||
try:
|
||||
doc = FreeCAD.ActiveDocument
|
||||
if not doc:
|
||||
return False
|
||||
from silo_origin import get_silo_origin
|
||||
|
||||
origin = get_silo_origin()
|
||||
return origin.ownsDocument(doc)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
try:
|
||||
from kindred_sdk import register_overlay
|
||||
|
||||
register_overlay(
|
||||
"silo", # overlay id
|
||||
["Silo Origin"], # toolbar names to append
|
||||
_silo_overlay_match, # match function
|
||||
)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Silo overlay registration failed: {e}\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Document observer — builds the Silo metadata tree when .kc files open.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _register_silo_document_observer():
|
||||
"""Register the Silo document observer for .kc tree building."""
|
||||
try:
|
||||
import silo_document
|
||||
|
||||
silo_document.register()
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintLog(f"Silo: document observer registration skipped: {e}\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dock panels — auth and activity widgets via SDK
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _setup_silo_auth_panel():
|
||||
"""Dock the Silo authentication panel in the right-hand side panel."""
|
||||
try:
|
||||
from kindred_sdk import register_dock_panel
|
||||
|
||||
def _factory():
|
||||
import silo_commands
|
||||
|
||||
auth = silo_commands.SiloAuthDockWidget()
|
||||
# Prevent GC of the auth timer by stashing on the widget
|
||||
auth.widget._auth = auth
|
||||
return auth.widget
|
||||
|
||||
register_dock_panel("SiloDatabaseAuth", "Database Auth", _factory)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintLog(f"Silo: auth panel skipped: {e}\n")
|
||||
|
||||
|
||||
def _setup_silo_activity_panel():
|
||||
"""Show a dock widget with recent Silo database activity."""
|
||||
try:
|
||||
from kindred_sdk import register_dock_panel
|
||||
|
||||
def _factory():
|
||||
from PySide import QtWidgets
|
||||
|
||||
widget = QtWidgets.QWidget()
|
||||
layout = QtWidgets.QVBoxLayout(widget)
|
||||
activity_list = QtWidgets.QListWidget()
|
||||
layout.addWidget(activity_list)
|
||||
|
||||
try:
|
||||
import silo_commands
|
||||
|
||||
items = silo_commands._client.list_items()
|
||||
if isinstance(items, list):
|
||||
for item in items[:20]:
|
||||
pn = item.get("part_number", "")
|
||||
desc = item.get("description", "")
|
||||
updated = item.get("updated_at", "")
|
||||
if updated:
|
||||
updated = updated[:10]
|
||||
activity_list.addItem(f"{pn} - {desc} - {updated}")
|
||||
if activity_list.count() == 0:
|
||||
activity_list.addItem("(No items in database)")
|
||||
except Exception:
|
||||
activity_list.addItem("(Unable to connect to Silo database)")
|
||||
|
||||
return widget
|
||||
|
||||
register_dock_panel("SiloDatabaseActivity", "Database Activity", _factory)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintLog(f"Silo: activity panel skipped: {e}\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# First-start check
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _check_silo_first_start():
|
||||
"""Show Silo settings dialog on first startup if not yet configured."""
|
||||
try:
|
||||
param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/KindredSilo")
|
||||
if not param.GetBool("FirstStartChecked", False):
|
||||
param.SetBool("FirstStartChecked", True)
|
||||
if not param.GetString("ApiUrl", ""):
|
||||
FreeCADGui.runCommand("Silo_Settings")
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintLog(f"Silo: first-start check skipped: {e}\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Start page override — must happen before the C++ StartLauncher fires
|
||||
# at ~100ms after GUI init.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
try:
|
||||
import silo_start
|
||||
|
||||
silo_start.register()
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Silo Start page override failed: {e}\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Handle kindred:// URLs passed as command-line arguments on cold start.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _handle_startup_urls():
|
||||
"""Process any kindred:// URLs passed as command-line arguments."""
|
||||
import sys
|
||||
|
||||
from silo_commands import handle_kindred_url
|
||||
|
||||
for arg in sys.argv[1:]:
|
||||
if arg.startswith("kindred://"):
|
||||
handle_kindred_url(arg)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deferred setup — staggered timers for non-blocking startup
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
from PySide import QtCore as _QtCore
|
||||
|
||||
_QtCore.QTimer.singleShot(500, _handle_startup_urls)
|
||||
_QtCore.QTimer.singleShot(600, _register_silo_document_observer)
|
||||
_QtCore.QTimer.singleShot(2000, _setup_silo_auth_panel)
|
||||
_QtCore.QTimer.singleShot(2500, _register_silo_overlay)
|
||||
_QtCore.QTimer.singleShot(3000, _check_silo_first_start)
|
||||
_QtCore.QTimer.singleShot(4000, _setup_silo_activity_panel)
|
||||
@@ -35,18 +35,33 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Could not register Silo origin: {e}\n")
|
||||
|
||||
# Silo origin toolbar — shown as an overlay on any context when the
|
||||
# active document is Silo-tracked. Registered as Unavailable so
|
||||
# EditingContextResolver controls visibility via the overlay system.
|
||||
self.silo_toolbar_commands = [
|
||||
"Silo_Commit",
|
||||
"Silo_Pull",
|
||||
"Silo_Push",
|
||||
"Separator",
|
||||
"Silo_Info",
|
||||
"Silo_BOM",
|
||||
"Silo_Jobs",
|
||||
]
|
||||
self.appendToolbar("Silo Origin", self.silo_toolbar_commands, "Unavailable")
|
||||
|
||||
# Silo menu provides admin/management commands.
|
||||
# File operations (New/Open/Save) are handled by the standard File
|
||||
# toolbar via the origin system -- no separate Silo toolbar needed.
|
||||
self.menu_commands = [
|
||||
"Silo_Info",
|
||||
"Silo_BOM",
|
||||
"Silo_Jobs",
|
||||
"Silo_TagProjects",
|
||||
"Silo_SetStatus",
|
||||
"Silo_Rollback",
|
||||
"Silo_SaveAsTemplate",
|
||||
"Separator",
|
||||
"Silo_Settings",
|
||||
"Silo_Auth",
|
||||
"Silo_Runners",
|
||||
"Silo_StartPanel",
|
||||
"Silo_Diag",
|
||||
]
|
||||
@@ -67,3 +82,69 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
||||
|
||||
FreeCADGui.addWorkbench(SiloWorkbench())
|
||||
FreeCAD.Console.PrintMessage("Silo workbench registered\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Silo overlay context — adds "Silo Origin" toolbar to any active context
|
||||
# when the current document is Silo-tracked.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _register_silo_overlay():
|
||||
"""Register the Silo overlay after the Silo workbench has initialised."""
|
||||
|
||||
def _silo_overlay_match():
|
||||
"""Return True if the active document is Silo-tracked."""
|
||||
try:
|
||||
doc = FreeCAD.ActiveDocument
|
||||
if not doc:
|
||||
return False
|
||||
from silo_origin import get_silo_origin
|
||||
|
||||
origin = get_silo_origin()
|
||||
return origin.ownsDocument(doc)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
try:
|
||||
from kindred_sdk import register_overlay
|
||||
|
||||
register_overlay(
|
||||
"silo", # overlay id
|
||||
["Silo Origin"], # toolbar names to append
|
||||
_silo_overlay_match, # match function
|
||||
)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Silo overlay registration failed: {e}\n")
|
||||
|
||||
|
||||
from PySide import QtCore as _QtCore
|
||||
|
||||
_QtCore.QTimer.singleShot(2500, _register_silo_overlay)
|
||||
|
||||
|
||||
# Override the Start page with Silo-aware version (must happen before
|
||||
# the C++ StartLauncher fires at ~100ms after GUI init)
|
||||
try:
|
||||
import silo_start
|
||||
|
||||
silo_start.register()
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Silo Start page override failed: {e}\n")
|
||||
|
||||
|
||||
# Handle kindred:// URLs passed as command-line arguments on cold start.
|
||||
# Delayed to run after the GUI is fully initialised and the Silo addon has
|
||||
# loaded its client/sync objects.
|
||||
def _handle_startup_urls():
|
||||
"""Process any kindred:// URLs passed as command-line arguments."""
|
||||
import sys
|
||||
|
||||
from silo_commands import handle_kindred_url
|
||||
|
||||
for arg in sys.argv[1:]:
|
||||
if arg.startswith("kindred://"):
|
||||
handle_kindred_url(arg)
|
||||
|
||||
|
||||
_QtCore.QTimer.singleShot(500, _handle_startup_urls)
|
||||
|
||||
BIN
freecad/__pycache__/silo_commands.cpython-313.pyc
Normal file
BIN
freecad/__pycache__/silo_commands.cpython-313.pyc
Normal file
Binary file not shown.
BIN
freecad/__pycache__/silo_origin.cpython-313.pyc
Normal file
BIN
freecad/__pycache__/silo_origin.cpython-313.pyc
Normal file
Binary file not shown.
BIN
freecad/__pycache__/silo_start.cpython-313.pyc
Normal file
BIN
freecad/__pycache__/silo_start.cpython-313.pyc
Normal file
Binary file not shown.
317
freecad/bom_sync.py
Normal file
317
freecad/bom_sync.py
Normal file
@@ -0,0 +1,317 @@
|
||||
"""BOM extraction engine for FreeCAD Assembly documents.
|
||||
|
||||
Extracts cross-document ``App::Link`` components from an Assembly,
|
||||
resolves Silo UUIDs to part numbers, diffs against the server BOM,
|
||||
and applies adds/quantity updates via individual API calls.
|
||||
|
||||
No GUI dependencies -- usable in both desktop and headless mode.
|
||||
|
||||
Public API
|
||||
----------
|
||||
extract_bom_entries(doc) -> List[BomEntry]
|
||||
resolve_entries(entries, client) -> (resolved, unresolved)
|
||||
diff_bom(local_entries, remote_entries) -> BomDiff
|
||||
apply_bom_diff(diff, parent_pn, client) -> BomResult
|
||||
sync_bom_after_upload(doc, part_number, client) -> Optional[BomResult]
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import FreeCAD
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data structures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class BomEntry:
|
||||
"""A single BOM line extracted from an Assembly."""
|
||||
|
||||
silo_item_id: Optional[str] # UUID from SiloItemId property
|
||||
part_number: Optional[str] # resolved via get_item_by_uuid()
|
||||
label: str # FreeCAD Label of the linked object
|
||||
doc_path: str # FileName of the linked document
|
||||
quantity: int # summed from ElementCount + individual links
|
||||
consolidation_warning: bool = False # multiple individual links to same source
|
||||
|
||||
|
||||
@dataclass
|
||||
class BomDiff:
|
||||
"""Result of diffing local assembly BOM against server BOM."""
|
||||
|
||||
added: List[Dict[str, Any]] = field(default_factory=list)
|
||||
removed: List[Dict[str, Any]] = field(default_factory=list)
|
||||
quantity_changed: List[Dict[str, Any]] = field(default_factory=list)
|
||||
unchanged: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BomResult:
|
||||
"""Summary of a BOM sync operation."""
|
||||
|
||||
added_count: int = 0
|
||||
updated_count: int = 0
|
||||
unreferenced_count: int = 0
|
||||
unresolved_count: int = 0
|
||||
errors: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Assembly detection helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _find_assembly(doc):
|
||||
"""Return the first ``Assembly::AssemblyObject`` in *doc*, or ``None``."""
|
||||
for obj in doc.Objects:
|
||||
if obj.isDerivedFrom("Assembly::AssemblyObject"):
|
||||
return obj
|
||||
return None
|
||||
|
||||
|
||||
def _get_silo_item_id(doc):
|
||||
"""Read ``SiloItemId`` from the tracked object in *doc*.
|
||||
|
||||
Returns ``None`` if the document has no tracked object or no UUID.
|
||||
"""
|
||||
for obj in doc.Objects:
|
||||
if hasattr(obj, "SiloItemId") and obj.SiloItemId:
|
||||
return obj.SiloItemId
|
||||
return None
|
||||
|
||||
|
||||
def _link_count(link_obj) -> int:
|
||||
"""Return the instance count for an ``App::Link``.
|
||||
|
||||
``ElementCount > 0`` means link array; otherwise single link (qty 1).
|
||||
"""
|
||||
element_count = getattr(link_obj, "ElementCount", 0)
|
||||
return element_count if element_count > 0 else 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Extraction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def extract_bom_entries(doc) -> List[BomEntry]:
|
||||
"""Walk the Assembly in *doc* and collect cross-document link entries.
|
||||
|
||||
Returns an empty list if the document has no Assembly or no
|
||||
cross-document links. Only first-level children are extracted;
|
||||
sub-assemblies commit their own BOMs separately.
|
||||
"""
|
||||
assembly = _find_assembly(doc)
|
||||
if assembly is None:
|
||||
return []
|
||||
|
||||
# Key by linked document path to merge duplicates.
|
||||
entries: Dict[str, BomEntry] = {}
|
||||
|
||||
for obj in assembly.Group:
|
||||
# Accept App::Link (single or array) and App::LinkElement.
|
||||
if not (
|
||||
obj.isDerivedFrom("App::Link") or obj.isDerivedFrom("App::LinkElement")
|
||||
):
|
||||
continue
|
||||
|
||||
linked = obj.getLinkedObject()
|
||||
if linked is None:
|
||||
continue
|
||||
|
||||
# Skip in-document links (construction / layout geometry).
|
||||
if linked.Document == doc:
|
||||
continue
|
||||
|
||||
linked_doc = linked.Document
|
||||
doc_path = linked_doc.FileName or linked_doc.Name
|
||||
|
||||
qty = _link_count(obj)
|
||||
|
||||
if doc_path in entries:
|
||||
entries[doc_path].quantity += qty
|
||||
entries[doc_path].consolidation_warning = True
|
||||
else:
|
||||
entries[doc_path] = BomEntry(
|
||||
silo_item_id=_get_silo_item_id(linked_doc),
|
||||
part_number=None,
|
||||
label=linked.Label,
|
||||
doc_path=doc_path,
|
||||
quantity=qty,
|
||||
)
|
||||
|
||||
return list(entries.values())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Resolution
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def resolve_entries(
|
||||
entries: List[BomEntry], client
|
||||
) -> Tuple[List[BomEntry], List[BomEntry]]:
|
||||
"""Resolve ``SiloItemId`` UUIDs to part numbers via the API.
|
||||
|
||||
Returns ``(resolved, unresolved)``. Unresolved entries have no
|
||||
``SiloItemId`` or the UUID lookup failed.
|
||||
"""
|
||||
resolved: List[BomEntry] = []
|
||||
unresolved: List[BomEntry] = []
|
||||
|
||||
for entry in entries:
|
||||
if not entry.silo_item_id:
|
||||
unresolved.append(entry)
|
||||
continue
|
||||
|
||||
try:
|
||||
item = client.get_item_by_uuid(entry.silo_item_id)
|
||||
entry.part_number = item["part_number"]
|
||||
resolved.append(entry)
|
||||
except Exception:
|
||||
unresolved.append(entry)
|
||||
|
||||
return resolved, unresolved
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Diff
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def diff_bom(
|
||||
local_entries: List[BomEntry],
|
||||
remote_entries: List[Dict[str, Any]],
|
||||
) -> BomDiff:
|
||||
"""Diff local assembly BOM against server BOM.
|
||||
|
||||
*local_entries*: resolved ``BomEntry`` list.
|
||||
*remote_entries*: raw dicts from ``client.get_bom()`` with keys
|
||||
``child_part_number`` and ``quantity``.
|
||||
"""
|
||||
local_map = {e.part_number: e.quantity for e in local_entries}
|
||||
remote_map = {e["child_part_number"]: e.get("quantity", 1) for e in remote_entries}
|
||||
|
||||
diff = BomDiff()
|
||||
|
||||
for pn, qty in local_map.items():
|
||||
if pn not in remote_map:
|
||||
diff.added.append({"part_number": pn, "quantity": qty})
|
||||
elif remote_map[pn] != qty:
|
||||
diff.quantity_changed.append(
|
||||
{
|
||||
"part_number": pn,
|
||||
"local_quantity": qty,
|
||||
"remote_quantity": remote_map[pn],
|
||||
}
|
||||
)
|
||||
else:
|
||||
diff.unchanged.append({"part_number": pn, "quantity": qty})
|
||||
|
||||
for pn, qty in remote_map.items():
|
||||
if pn not in local_map:
|
||||
diff.removed.append({"part_number": pn, "quantity": qty})
|
||||
|
||||
return diff
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Apply
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def apply_bom_diff(diff: BomDiff, parent_pn: str, client) -> BomResult:
|
||||
"""Apply adds and quantity updates to the server BOM.
|
||||
|
||||
Uses individual CRUD calls (Phase 1 fallback). Phase 2 replaces
|
||||
this with a single ``POST /items/{pn}/bom/merge`` call.
|
||||
|
||||
Removed entries are NEVER deleted -- only warned about.
|
||||
Each call is individually wrapped so one failure does not block others.
|
||||
"""
|
||||
result = BomResult()
|
||||
|
||||
for entry in diff.added:
|
||||
try:
|
||||
client.add_bom_entry(
|
||||
parent_pn,
|
||||
entry["part_number"],
|
||||
quantity=entry["quantity"],
|
||||
rel_type="component",
|
||||
)
|
||||
result.added_count += 1
|
||||
except Exception as e:
|
||||
result.errors.append(f"add {entry['part_number']}: {e}")
|
||||
|
||||
for entry in diff.quantity_changed:
|
||||
try:
|
||||
client.update_bom_entry(
|
||||
parent_pn,
|
||||
entry["part_number"],
|
||||
quantity=entry["local_quantity"],
|
||||
)
|
||||
result.updated_count += 1
|
||||
except Exception as e:
|
||||
result.errors.append(f"update {entry['part_number']}: {e}")
|
||||
|
||||
result.unreferenced_count = len(diff.removed)
|
||||
if diff.removed:
|
||||
pns = ", ".join(e["part_number"] for e in diff.removed)
|
||||
FreeCAD.Console.PrintWarning(
|
||||
f"BOM sync: {result.unreferenced_count} server entries "
|
||||
f"not in assembly (not deleted): {pns}\n"
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Top-level orchestrator
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def sync_bom_after_upload(doc, part_number: str, client) -> Optional[BomResult]:
|
||||
"""Full BOM sync pipeline: extract, resolve, diff, apply.
|
||||
|
||||
Returns ``None`` if *doc* is not an assembly or has no cross-document
|
||||
links. Returns a ``BomResult`` with summary counts otherwise.
|
||||
"""
|
||||
entries = extract_bom_entries(doc)
|
||||
if not entries:
|
||||
return None
|
||||
|
||||
resolved, unresolved = resolve_entries(entries, client)
|
||||
|
||||
# Log consolidation warnings.
|
||||
for entry in entries:
|
||||
if entry.consolidation_warning:
|
||||
FreeCAD.Console.PrintWarning(
|
||||
f"BOM sync: {entry.label} ({entry.doc_path}) has multiple "
|
||||
f"individual links. Consider using a link array "
|
||||
f"(ElementCount) for cleaner assembly management.\n"
|
||||
)
|
||||
|
||||
# Log unresolved components.
|
||||
for entry in unresolved:
|
||||
FreeCAD.Console.PrintWarning(
|
||||
f"BOM sync: {entry.label} ({entry.doc_path}) has no Silo "
|
||||
f"part number -- excluded from BOM.\n"
|
||||
)
|
||||
|
||||
if not resolved:
|
||||
result = BomResult()
|
||||
result.unresolved_count = len(unresolved)
|
||||
return result
|
||||
|
||||
# Fetch current server BOM.
|
||||
try:
|
||||
remote = client.get_bom(part_number)
|
||||
except Exception:
|
||||
remote = []
|
||||
|
||||
diff = diff_bom(resolved, remote)
|
||||
result = apply_bom_diff(diff, part_number, client)
|
||||
result.unresolved_count = len(unresolved)
|
||||
return result
|
||||
463
freecad/dag.py
Normal file
463
freecad/dag.py
Normal file
@@ -0,0 +1,463 @@
|
||||
"""DAG extraction engine for FreeCAD documents.
|
||||
|
||||
Extracts the feature tree from a FreeCAD document as nodes and edges
|
||||
for syncing to the Silo server. No GUI dependencies -- usable in both
|
||||
desktop and headless (``--console``) mode.
|
||||
|
||||
Public API
|
||||
----------
|
||||
classify_type(type_id) -> Optional[str]
|
||||
compute_properties_hash(obj) -> str
|
||||
extract_dag(doc) -> (nodes, edges)
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TypeId -> DAG node type mapping
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_TYPE_MAP: Dict[str, str] = {
|
||||
# Sketch
|
||||
"Sketcher::SketchObject": "sketch",
|
||||
# Sketch-based additive
|
||||
"PartDesign::Pad": "pad",
|
||||
"PartDesign::Revolution": "pad",
|
||||
"PartDesign::AdditivePipe": "pad",
|
||||
"PartDesign::AdditiveLoft": "pad",
|
||||
"PartDesign::AdditiveHelix": "pad",
|
||||
# Sketch-based subtractive
|
||||
"PartDesign::Pocket": "pocket",
|
||||
"PartDesign::Groove": "pocket",
|
||||
"PartDesign::Hole": "pocket",
|
||||
"PartDesign::SubtractivePipe": "pocket",
|
||||
"PartDesign::SubtractiveLoft": "pocket",
|
||||
"PartDesign::SubtractiveHelix": "pocket",
|
||||
# Dress-up
|
||||
"PartDesign::Fillet": "fillet",
|
||||
"PartDesign::Chamfer": "chamfer",
|
||||
"PartDesign::Draft": "chamfer",
|
||||
"PartDesign::Thickness": "chamfer",
|
||||
# Transformations
|
||||
"PartDesign::Mirrored": "pad",
|
||||
"PartDesign::LinearPattern": "pad",
|
||||
"PartDesign::PolarPattern": "pad",
|
||||
"PartDesign::Scaled": "pad",
|
||||
"PartDesign::MultiTransform": "pad",
|
||||
# Boolean
|
||||
"PartDesign::Boolean": "pad",
|
||||
# Additive primitives
|
||||
"PartDesign::AdditiveBox": "pad",
|
||||
"PartDesign::AdditiveCylinder": "pad",
|
||||
"PartDesign::AdditiveSphere": "pad",
|
||||
"PartDesign::AdditiveCone": "pad",
|
||||
"PartDesign::AdditiveEllipsoid": "pad",
|
||||
"PartDesign::AdditiveTorus": "pad",
|
||||
"PartDesign::AdditivePrism": "pad",
|
||||
"PartDesign::AdditiveWedge": "pad",
|
||||
# Subtractive primitives
|
||||
"PartDesign::SubtractiveBox": "pocket",
|
||||
"PartDesign::SubtractiveCylinder": "pocket",
|
||||
"PartDesign::SubtractiveSphere": "pocket",
|
||||
"PartDesign::SubtractiveCone": "pocket",
|
||||
"PartDesign::SubtractiveEllipsoid": "pocket",
|
||||
"PartDesign::SubtractiveTorus": "pocket",
|
||||
"PartDesign::SubtractivePrism": "pocket",
|
||||
"PartDesign::SubtractiveWedge": "pocket",
|
||||
# Containers
|
||||
"PartDesign::Body": "body",
|
||||
"App::Part": "part",
|
||||
"Part::Feature": "part",
|
||||
# Datum / reference
|
||||
"PartDesign::Point": "datum",
|
||||
"PartDesign::Line": "datum",
|
||||
"PartDesign::Plane": "datum",
|
||||
"PartDesign::CoordinateSystem": "datum",
|
||||
"PartDesign::ShapeBinder": "datum",
|
||||
"PartDesign::SubShapeBinder": "datum",
|
||||
}
|
||||
|
||||
|
||||
def classify_type(type_id: str) -> Optional[str]:
|
||||
"""Map a FreeCAD TypeId string to a DAG node type.
|
||||
|
||||
Returns one of ``sketch``, ``pad``, ``pocket``, ``fillet``,
|
||||
``chamfer``, ``body``, ``part``, ``datum``, or ``None`` if the
|
||||
TypeId is not a recognized feature.
|
||||
"""
|
||||
return _TYPE_MAP.get(type_id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Properties hash
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _safe_float(val: Any) -> Any:
|
||||
"""Convert a float to a JSON-safe value, replacing NaN/Infinity with 0."""
|
||||
if isinstance(val, float) and (math.isnan(val) or math.isinf(val)):
|
||||
return 0.0
|
||||
return val
|
||||
|
||||
|
||||
def _prop_value(obj: Any, name: str) -> Any:
|
||||
"""Safely read ``obj.<name>.Value``, returning *None* on failure."""
|
||||
try:
|
||||
return _safe_float(getattr(obj, name).Value)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _prop_raw(obj: Any, name: str) -> Any:
|
||||
"""Safely read ``obj.<name>``, returning *None* on failure."""
|
||||
try:
|
||||
return getattr(obj, name)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _link_name(obj: Any, name: str) -> Optional[str]:
|
||||
"""Return the ``.Name`` of a linked object property, or *None*."""
|
||||
try:
|
||||
link = getattr(obj, name)
|
||||
if isinstance(link, (list, tuple)):
|
||||
link = link[0]
|
||||
return link.Name if link is not None else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _collect_inputs(obj: Any) -> Dict[str, Any]:
|
||||
"""Extract the parametric inputs that affect *obj*'s geometry.
|
||||
|
||||
The returned dict is JSON-serialized and hashed to produce the
|
||||
``properties_hash`` for the DAG node.
|
||||
"""
|
||||
tid = obj.TypeId
|
||||
inputs: Dict[str, Any] = {"_type": tid}
|
||||
|
||||
# --- Sketch ---
|
||||
if tid == "Sketcher::SketchObject":
|
||||
inputs["geometry_count"] = _prop_raw(obj, "GeometryCount")
|
||||
inputs["constraint_count"] = _prop_raw(obj, "ConstraintCount")
|
||||
try:
|
||||
inputs["geometry"] = obj.Shape.exportBrepToString()
|
||||
except Exception:
|
||||
pass
|
||||
return inputs
|
||||
|
||||
# --- Extrude (Pad / Pocket) ---
|
||||
if tid in ("PartDesign::Pad", "PartDesign::Pocket"):
|
||||
inputs["length"] = _prop_value(obj, "Length")
|
||||
inputs["type"] = str(_prop_raw(obj, "Type") or "")
|
||||
inputs["reversed"] = _prop_raw(obj, "Reversed")
|
||||
inputs["sketch"] = _link_name(obj, "Profile")
|
||||
return inputs
|
||||
|
||||
# --- Revolution / Groove ---
|
||||
if tid in ("PartDesign::Revolution", "PartDesign::Groove"):
|
||||
inputs["angle"] = _prop_value(obj, "Angle")
|
||||
inputs["type"] = str(_prop_raw(obj, "Type") or "")
|
||||
inputs["reversed"] = _prop_raw(obj, "Reversed")
|
||||
inputs["sketch"] = _link_name(obj, "Profile")
|
||||
return inputs
|
||||
|
||||
# --- Hole ---
|
||||
if tid == "PartDesign::Hole":
|
||||
inputs["diameter"] = _prop_value(obj, "Diameter")
|
||||
inputs["depth"] = _prop_value(obj, "Depth")
|
||||
inputs["threaded"] = _prop_raw(obj, "Threaded")
|
||||
inputs["thread_type"] = str(_prop_raw(obj, "ThreadType") or "")
|
||||
inputs["depth_type"] = str(_prop_raw(obj, "DepthType") or "")
|
||||
inputs["sketch"] = _link_name(obj, "Profile")
|
||||
return inputs
|
||||
|
||||
# --- Pipe / Loft / Helix (additive + subtractive) ---
|
||||
if tid in (
|
||||
"PartDesign::AdditivePipe",
|
||||
"PartDesign::SubtractivePipe",
|
||||
"PartDesign::AdditiveLoft",
|
||||
"PartDesign::SubtractiveLoft",
|
||||
"PartDesign::AdditiveHelix",
|
||||
"PartDesign::SubtractiveHelix",
|
||||
):
|
||||
inputs["sketch"] = _link_name(obj, "Profile")
|
||||
inputs["spine"] = _link_name(obj, "Spine")
|
||||
return inputs
|
||||
|
||||
# --- Fillet ---
|
||||
if tid == "PartDesign::Fillet":
|
||||
inputs["radius"] = _prop_value(obj, "Radius")
|
||||
return inputs
|
||||
|
||||
# --- Chamfer ---
|
||||
if tid == "PartDesign::Chamfer":
|
||||
inputs["chamfer_type"] = str(_prop_raw(obj, "ChamferType") or "")
|
||||
inputs["size"] = _prop_value(obj, "Size")
|
||||
inputs["size2"] = _prop_value(obj, "Size2")
|
||||
inputs["angle"] = _prop_value(obj, "Angle")
|
||||
return inputs
|
||||
|
||||
# --- Draft ---
|
||||
if tid == "PartDesign::Draft":
|
||||
inputs["angle"] = _prop_value(obj, "Angle")
|
||||
inputs["reversed"] = _prop_raw(obj, "Reversed")
|
||||
return inputs
|
||||
|
||||
# --- Thickness ---
|
||||
if tid == "PartDesign::Thickness":
|
||||
inputs["value"] = _prop_value(obj, "Value")
|
||||
inputs["reversed"] = _prop_raw(obj, "Reversed")
|
||||
inputs["mode"] = str(_prop_raw(obj, "Mode") or "")
|
||||
inputs["join"] = str(_prop_raw(obj, "Join") or "")
|
||||
return inputs
|
||||
|
||||
# --- Mirrored ---
|
||||
if tid == "PartDesign::Mirrored":
|
||||
inputs["mirror_plane"] = _link_name(obj, "MirrorPlane")
|
||||
return inputs
|
||||
|
||||
# --- LinearPattern ---
|
||||
if tid == "PartDesign::LinearPattern":
|
||||
inputs["direction"] = _link_name(obj, "Direction")
|
||||
inputs["reversed"] = _prop_raw(obj, "Reversed")
|
||||
inputs["length"] = _prop_value(obj, "Length")
|
||||
inputs["occurrences"] = _prop_value(obj, "Occurrences")
|
||||
return inputs
|
||||
|
||||
# --- PolarPattern ---
|
||||
if tid == "PartDesign::PolarPattern":
|
||||
inputs["axis"] = _link_name(obj, "Axis")
|
||||
inputs["reversed"] = _prop_raw(obj, "Reversed")
|
||||
inputs["angle"] = _prop_value(obj, "Angle")
|
||||
inputs["occurrences"] = _prop_value(obj, "Occurrences")
|
||||
return inputs
|
||||
|
||||
# --- Scaled ---
|
||||
if tid == "PartDesign::Scaled":
|
||||
inputs["factor"] = _prop_value(obj, "Factor")
|
||||
inputs["occurrences"] = _prop_value(obj, "Occurrences")
|
||||
return inputs
|
||||
|
||||
# --- MultiTransform ---
|
||||
if tid == "PartDesign::MultiTransform":
|
||||
try:
|
||||
inputs["transform_count"] = len(obj.Transformations)
|
||||
except Exception:
|
||||
pass
|
||||
return inputs
|
||||
|
||||
# --- Boolean ---
|
||||
if tid == "PartDesign::Boolean":
|
||||
inputs["type"] = str(_prop_raw(obj, "Type") or "")
|
||||
return inputs
|
||||
|
||||
# --- Primitives (additive) ---
|
||||
if tid in (
|
||||
"PartDesign::AdditiveBox",
|
||||
"PartDesign::SubtractiveBox",
|
||||
):
|
||||
inputs["length"] = _prop_value(obj, "Length")
|
||||
inputs["width"] = _prop_value(obj, "Width")
|
||||
inputs["height"] = _prop_value(obj, "Height")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditiveCylinder",
|
||||
"PartDesign::SubtractiveCylinder",
|
||||
):
|
||||
inputs["radius"] = _prop_value(obj, "Radius")
|
||||
inputs["height"] = _prop_value(obj, "Height")
|
||||
inputs["angle"] = _prop_value(obj, "Angle")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditiveSphere",
|
||||
"PartDesign::SubtractiveSphere",
|
||||
):
|
||||
inputs["radius"] = _prop_value(obj, "Radius")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditiveCone",
|
||||
"PartDesign::SubtractiveCone",
|
||||
):
|
||||
inputs["radius1"] = _prop_value(obj, "Radius1")
|
||||
inputs["radius2"] = _prop_value(obj, "Radius2")
|
||||
inputs["height"] = _prop_value(obj, "Height")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditiveEllipsoid",
|
||||
"PartDesign::SubtractiveEllipsoid",
|
||||
):
|
||||
inputs["radius1"] = _prop_value(obj, "Radius1")
|
||||
inputs["radius2"] = _prop_value(obj, "Radius2")
|
||||
inputs["radius3"] = _prop_value(obj, "Radius3")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditiveTorus",
|
||||
"PartDesign::SubtractiveTorus",
|
||||
):
|
||||
inputs["radius1"] = _prop_value(obj, "Radius1")
|
||||
inputs["radius2"] = _prop_value(obj, "Radius2")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditivePrism",
|
||||
"PartDesign::SubtractivePrism",
|
||||
):
|
||||
inputs["polygon"] = _prop_raw(obj, "Polygon")
|
||||
inputs["circumradius"] = _prop_value(obj, "Circumradius")
|
||||
inputs["height"] = _prop_value(obj, "Height")
|
||||
return inputs
|
||||
|
||||
if tid in (
|
||||
"PartDesign::AdditiveWedge",
|
||||
"PartDesign::SubtractiveWedge",
|
||||
):
|
||||
for dim in (
|
||||
"Xmin",
|
||||
"Ymin",
|
||||
"Zmin",
|
||||
"X2min",
|
||||
"Z2min",
|
||||
"Xmax",
|
||||
"Ymax",
|
||||
"Zmax",
|
||||
"X2max",
|
||||
"Z2max",
|
||||
):
|
||||
inputs[dim.lower()] = _prop_value(obj, dim)
|
||||
return inputs
|
||||
|
||||
# --- Datum / ShapeBinder ---
|
||||
if tid in (
|
||||
"PartDesign::Point",
|
||||
"PartDesign::Line",
|
||||
"PartDesign::Plane",
|
||||
"PartDesign::CoordinateSystem",
|
||||
"PartDesign::ShapeBinder",
|
||||
"PartDesign::SubShapeBinder",
|
||||
):
|
||||
try:
|
||||
p = obj.Placement
|
||||
inputs["position"] = {
|
||||
"x": _safe_float(p.Base.x),
|
||||
"y": _safe_float(p.Base.y),
|
||||
"z": _safe_float(p.Base.z),
|
||||
}
|
||||
inputs["rotation"] = {
|
||||
"axis_x": _safe_float(p.Rotation.Axis.x),
|
||||
"axis_y": _safe_float(p.Rotation.Axis.y),
|
||||
"axis_z": _safe_float(p.Rotation.Axis.z),
|
||||
"angle": _safe_float(p.Rotation.Angle),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
return inputs
|
||||
|
||||
# --- Body / Part (containers) ---
|
||||
if tid in ("PartDesign::Body", "App::Part", "Part::Feature"):
|
||||
try:
|
||||
inputs["child_count"] = len(obj.Group)
|
||||
except Exception:
|
||||
inputs["child_count"] = 0
|
||||
return inputs
|
||||
|
||||
# --- Fallback ---
|
||||
inputs["label"] = obj.Label
|
||||
return inputs
|
||||
|
||||
|
||||
def compute_properties_hash(obj: Any) -> str:
|
||||
"""Return a SHA-256 hex digest of *obj*'s parametric inputs.
|
||||
|
||||
The hash is used for memoization -- if a node's inputs haven't
|
||||
changed since the last validation run, re-validation can be skipped.
|
||||
"""
|
||||
inputs = _collect_inputs(obj)
|
||||
canonical = json.dumps(inputs, sort_keys=True, default=str)
|
||||
return hashlib.sha256(canonical.encode()).hexdigest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DAG extraction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def extract_dag(
|
||||
doc: Any,
|
||||
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
||||
"""Walk a FreeCAD document and return ``(nodes, edges)``.
|
||||
|
||||
*nodes* is a list of dicts matching the Silo ``PUT /dag`` payload
|
||||
schema. *edges* connects dependencies (source) to dependents
|
||||
(target).
|
||||
|
||||
Only objects whose TypeId is recognized by :func:`classify_type`
|
||||
are included. Edges are limited to pairs where **both** endpoints
|
||||
are included, preventing dangling references to internal objects
|
||||
such as ``App::Origin``.
|
||||
"""
|
||||
# Pass 1 -- identify included objects
|
||||
included: Set[str] = set()
|
||||
classified: Dict[str, str] = {} # obj.Name -> node_type
|
||||
|
||||
for obj in doc.Objects:
|
||||
if not hasattr(obj, "TypeId"):
|
||||
continue
|
||||
node_type = classify_type(obj.TypeId)
|
||||
if node_type is not None:
|
||||
included.add(obj.Name)
|
||||
classified[obj.Name] = node_type
|
||||
|
||||
# Pass 2 -- build nodes and edges
|
||||
nodes: List[Dict[str, Any]] = []
|
||||
edges: List[Dict[str, Any]] = []
|
||||
seen_edges: Set[Tuple[str, str]] = set()
|
||||
|
||||
for obj in doc.Objects:
|
||||
if obj.Name not in included:
|
||||
continue
|
||||
|
||||
nodes.append(
|
||||
{
|
||||
"node_key": obj.Name,
|
||||
"node_type": classified[obj.Name],
|
||||
"properties_hash": compute_properties_hash(obj),
|
||||
"metadata": {
|
||||
"label": obj.Label,
|
||||
"type_id": obj.TypeId,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
# Walk dependencies: OutList contains objects this one depends on
|
||||
try:
|
||||
out_list = obj.OutList
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for dep in out_list:
|
||||
if not hasattr(dep, "Name"):
|
||||
continue
|
||||
if dep.Name not in included:
|
||||
continue
|
||||
edge_key = (dep.Name, obj.Name)
|
||||
if edge_key in seen_edges:
|
||||
continue
|
||||
seen_edges.add(edge_key)
|
||||
edges.append(
|
||||
{
|
||||
"source_key": dep.Name,
|
||||
"target_key": obj.Name,
|
||||
"edge_type": "depends_on",
|
||||
}
|
||||
)
|
||||
|
||||
return nodes, edges
|
||||
191
freecad/open_search.py
Normal file
191
freecad/open_search.py
Normal file
@@ -0,0 +1,191 @@
|
||||
"""Search-and-open widget for Kindred Create.
|
||||
|
||||
Provides :class:`OpenItemWidget`, a plain ``QWidget`` that can be
|
||||
embedded in an MDI sub-window. Searches both the Silo database and
|
||||
local CAD files, presenting results in a unified table. Emits
|
||||
``item_selected`` when the user picks an item and ``cancelled`` when
|
||||
the user clicks Cancel.
|
||||
"""
|
||||
|
||||
import FreeCAD
|
||||
from PySide import QtCore, QtWidgets
|
||||
|
||||
|
||||
class OpenItemWidget(QtWidgets.QWidget):
|
||||
"""Search-and-open widget for embedding in an MDI subwindow.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
client : SiloClient
|
||||
Authenticated Silo API client instance.
|
||||
search_local_fn : callable
|
||||
Function that accepts a search term string and returns an
|
||||
iterable of dicts with keys ``part_number``, ``description``,
|
||||
``path``, ``modified``.
|
||||
parent : QWidget, optional
|
||||
Parent widget.
|
||||
|
||||
Signals
|
||||
-------
|
||||
item_selected(dict)
|
||||
Emitted when the user selects an item. The dict contains
|
||||
keys: *part_number*, *description*, *item_type*, *source*
|
||||
(``"database"``, ``"local"``, or ``"both"``), *modified*,
|
||||
and *path* (str or ``None``).
|
||||
cancelled()
|
||||
Emitted when the user clicks Cancel.
|
||||
"""
|
||||
|
||||
item_selected = QtCore.Signal(dict)
|
||||
cancelled = QtCore.Signal()
|
||||
|
||||
def __init__(self, client, search_local_fn, parent=None):
|
||||
super().__init__(parent)
|
||||
self._client = client
|
||||
self._search_local = search_local_fn
|
||||
self._results_data = []
|
||||
|
||||
self.setMinimumWidth(700)
|
||||
self.setMinimumHeight(500)
|
||||
|
||||
self._build_ui()
|
||||
|
||||
# Debounced search timer (500 ms)
|
||||
self._search_timer = QtCore.QTimer(self)
|
||||
self._search_timer.setSingleShot(True)
|
||||
self._search_timer.setInterval(500)
|
||||
self._search_timer.timeout.connect(self._do_search)
|
||||
|
||||
# Populate on first display
|
||||
QtCore.QTimer.singleShot(0, self._do_search)
|
||||
|
||||
# ---- UI construction ---------------------------------------------------
|
||||
|
||||
def _build_ui(self):
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.setSpacing(8)
|
||||
|
||||
# Search row
|
||||
self._search_input = QtWidgets.QLineEdit()
|
||||
self._search_input.setPlaceholderText("Search by part number or description...")
|
||||
self._search_input.textChanged.connect(self._on_search_changed)
|
||||
layout.addWidget(self._search_input)
|
||||
|
||||
# Filter checkboxes
|
||||
filter_layout = QtWidgets.QHBoxLayout()
|
||||
self._db_checkbox = QtWidgets.QCheckBox("Database")
|
||||
self._db_checkbox.setChecked(True)
|
||||
self._local_checkbox = QtWidgets.QCheckBox("Local Files")
|
||||
self._local_checkbox.setChecked(True)
|
||||
self._db_checkbox.toggled.connect(self._on_filter_changed)
|
||||
self._local_checkbox.toggled.connect(self._on_filter_changed)
|
||||
filter_layout.addWidget(self._db_checkbox)
|
||||
filter_layout.addWidget(self._local_checkbox)
|
||||
filter_layout.addStretch()
|
||||
layout.addLayout(filter_layout)
|
||||
|
||||
# Results table
|
||||
self._results_table = QtWidgets.QTableWidget()
|
||||
self._results_table.setColumnCount(5)
|
||||
self._results_table.setHorizontalHeaderLabels(
|
||||
["Part Number", "Description", "Type", "Source", "Modified"]
|
||||
)
|
||||
self._results_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
|
||||
self._results_table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
|
||||
self._results_table.horizontalHeader().setStretchLastSection(True)
|
||||
self._results_table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
|
||||
self._results_table.doubleClicked.connect(self._open_selected)
|
||||
layout.addWidget(self._results_table, 1)
|
||||
|
||||
# Buttons
|
||||
btn_layout = QtWidgets.QHBoxLayout()
|
||||
btn_layout.addStretch()
|
||||
open_btn = QtWidgets.QPushButton("Open")
|
||||
open_btn.clicked.connect(self._open_selected)
|
||||
cancel_btn = QtWidgets.QPushButton("Cancel")
|
||||
cancel_btn.clicked.connect(self.cancelled.emit)
|
||||
btn_layout.addWidget(open_btn)
|
||||
btn_layout.addWidget(cancel_btn)
|
||||
layout.addLayout(btn_layout)
|
||||
|
||||
# ---- Search logic ------------------------------------------------------
|
||||
|
||||
def _on_search_changed(self, _text):
|
||||
"""Restart debounce timer on each keystroke."""
|
||||
self._search_timer.start()
|
||||
|
||||
def _on_filter_changed(self, _checked):
|
||||
"""Re-run search immediately when filter checkboxes change."""
|
||||
self._do_search()
|
||||
|
||||
def _do_search(self):
|
||||
"""Execute search against database and/or local files."""
|
||||
search_term = self._search_input.text().strip()
|
||||
self._results_data = []
|
||||
|
||||
if self._db_checkbox.isChecked():
|
||||
try:
|
||||
for item in self._client.list_items(search=search_term):
|
||||
self._results_data.append(
|
||||
{
|
||||
"part_number": item.get("part_number", ""),
|
||||
"description": item.get("description", ""),
|
||||
"item_type": item.get("item_type", ""),
|
||||
"source": "database",
|
||||
"modified": item.get("updated_at", "")[:10]
|
||||
if item.get("updated_at")
|
||||
else "",
|
||||
"path": None,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"DB search failed: {e}\n")
|
||||
|
||||
if self._local_checkbox.isChecked():
|
||||
try:
|
||||
for item in self._search_local(search_term):
|
||||
existing = next(
|
||||
(r for r in self._results_data if r["part_number"] == item["part_number"]),
|
||||
None,
|
||||
)
|
||||
if existing:
|
||||
existing["source"] = "both"
|
||||
existing["path"] = item.get("path")
|
||||
else:
|
||||
self._results_data.append(
|
||||
{
|
||||
"part_number": item.get("part_number", ""),
|
||||
"description": item.get("description", ""),
|
||||
"item_type": "",
|
||||
"source": "local",
|
||||
"modified": item.get("modified", "")[:10]
|
||||
if item.get("modified")
|
||||
else "",
|
||||
"path": item.get("path"),
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Local search failed: {e}\n")
|
||||
|
||||
self._populate_table()
|
||||
|
||||
def _populate_table(self):
|
||||
"""Refresh the results table from ``_results_data``."""
|
||||
self._results_table.setRowCount(len(self._results_data))
|
||||
for row, data in enumerate(self._results_data):
|
||||
self._results_table.setItem(row, 0, QtWidgets.QTableWidgetItem(data["part_number"]))
|
||||
self._results_table.setItem(row, 1, QtWidgets.QTableWidgetItem(data["description"]))
|
||||
self._results_table.setItem(row, 2, QtWidgets.QTableWidgetItem(data["item_type"]))
|
||||
self._results_table.setItem(row, 3, QtWidgets.QTableWidgetItem(data["source"]))
|
||||
self._results_table.setItem(row, 4, QtWidgets.QTableWidgetItem(data["modified"]))
|
||||
self._results_table.resizeColumnsToContents()
|
||||
|
||||
# ---- Selection ---------------------------------------------------------
|
||||
|
||||
def _open_selected(self):
|
||||
"""Emit ``item_selected`` with the data from the selected row."""
|
||||
selected = self._results_table.selectedItems()
|
||||
if not selected:
|
||||
return
|
||||
row = selected[0].row()
|
||||
self.item_selected.emit(dict(self._results_data[row]))
|
||||
@@ -12,4 +12,17 @@
|
||||
<subdirectory>./</subdirectory>
|
||||
</workbench>
|
||||
</content>
|
||||
|
||||
<!-- Kindred Create extensions -->
|
||||
<kindred>
|
||||
<min_create_version>0.1.0</min_create_version>
|
||||
<load_priority>60</load_priority>
|
||||
<pure_python>true</pure_python>
|
||||
<dependencies>
|
||||
<dependency>sdk</dependency>
|
||||
</dependencies>
|
||||
<contexts>
|
||||
<context id="*" action="overlay"/>
|
||||
</contexts>
|
||||
</kindred>
|
||||
</package>
|
||||
|
||||
8
freecad/resources/icons/silo-rollback.svg
Normal file
8
freecad/resources/icons/silo-rollback.svg
Normal file
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#cba6f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Counter-clockwise arrow -->
|
||||
<polyline points="1 4 1 10 7 10" stroke="#f38ba8"/>
|
||||
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" stroke="#cba6f7"/>
|
||||
<!-- Clock hands -->
|
||||
<line x1="12" y1="7" x2="12" y2="12" stroke="#89dceb" stroke-width="1.5"/>
|
||||
<line x1="12" y1="12" x2="15" y2="14" stroke="#89dceb" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 493 B |
7
freecad/resources/icons/silo-status.svg
Normal file
7
freecad/resources/icons/silo-status.svg
Normal file
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#cba6f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Shield shape -->
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" fill="#313244"/>
|
||||
<!-- Status bars -->
|
||||
<line x1="8" y1="10" x2="16" y2="10" stroke="#a6e3a1" stroke-width="1.5"/>
|
||||
<line x1="8" y1="14" x2="13" y2="14" stroke="#89dceb" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 435 B |
6
freecad/resources/icons/silo-tag.svg
Normal file
6
freecad/resources/icons/silo-tag.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#cba6f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Tag shape -->
|
||||
<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" fill="#313244"/>
|
||||
<!-- Tag hole -->
|
||||
<circle cx="7" cy="7" r="1.5" fill="#cba6f7" stroke="none"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 373 B |
156
freecad/runner.py
Normal file
156
freecad/runner.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""Headless runner entry points for silorunner compute jobs.
|
||||
|
||||
These functions are invoked via ``create --console -e`` by the
|
||||
silorunner binary. They must work without a display server.
|
||||
|
||||
Entry Points
|
||||
------------
|
||||
dag_extract(input_path, output_path)
|
||||
Extract feature DAG and write JSON.
|
||||
validate(input_path, output_path)
|
||||
Rebuild all features and report pass/fail per node.
|
||||
export(input_path, output_path, format='step')
|
||||
Export geometry to STEP, IGES, STL, or OBJ.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import FreeCAD
|
||||
|
||||
|
||||
def dag_extract(input_path, output_path):
|
||||
"""Extract the feature DAG from a Create file.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_path : str
|
||||
Path to the ``.kc`` or ``.FCStd`` file.
|
||||
output_path : str
|
||||
Path to write the JSON output.
|
||||
|
||||
Output JSON::
|
||||
|
||||
{"nodes": [...], "edges": [...]}
|
||||
"""
|
||||
from dag import extract_dag
|
||||
|
||||
doc = FreeCAD.openDocument(input_path)
|
||||
try:
|
||||
nodes, edges = extract_dag(doc)
|
||||
with open(output_path, "w") as f:
|
||||
json.dump({"nodes": nodes, "edges": edges}, f)
|
||||
FreeCAD.Console.PrintMessage(
|
||||
f"DAG extracted: {len(nodes)} nodes, {len(edges)} edges -> {output_path}\n"
|
||||
)
|
||||
finally:
|
||||
FreeCAD.closeDocument(doc.Name)
|
||||
|
||||
|
||||
def validate(input_path, output_path):
|
||||
"""Validate a Create file by rebuilding all features.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_path : str
|
||||
Path to the ``.kc`` or ``.FCStd`` file.
|
||||
output_path : str
|
||||
Path to write the JSON output.
|
||||
|
||||
Output JSON::
|
||||
|
||||
{
|
||||
"valid": true/false,
|
||||
"nodes": [
|
||||
{"node_key": "Pad001", "state": "clean", "message": null, "properties_hash": "..."},
|
||||
...
|
||||
]
|
||||
}
|
||||
"""
|
||||
from dag import classify_type, compute_properties_hash
|
||||
|
||||
doc = FreeCAD.openDocument(input_path)
|
||||
try:
|
||||
doc.recompute()
|
||||
|
||||
results = []
|
||||
all_valid = True
|
||||
|
||||
for obj in doc.Objects:
|
||||
if not hasattr(obj, "TypeId"):
|
||||
continue
|
||||
node_type = classify_type(obj.TypeId)
|
||||
if node_type is None:
|
||||
continue
|
||||
|
||||
state = "clean"
|
||||
message = None
|
||||
if hasattr(obj, "isValid") and not obj.isValid():
|
||||
state = "failed"
|
||||
message = f"Feature {obj.Label} failed to recompute"
|
||||
all_valid = False
|
||||
|
||||
results.append(
|
||||
{
|
||||
"node_key": obj.Name,
|
||||
"state": state,
|
||||
"message": message,
|
||||
"properties_hash": compute_properties_hash(obj),
|
||||
}
|
||||
)
|
||||
|
||||
with open(output_path, "w") as f:
|
||||
json.dump({"valid": all_valid, "nodes": results}, f)
|
||||
|
||||
status = "PASS" if all_valid else "FAIL"
|
||||
FreeCAD.Console.PrintMessage(
|
||||
f"Validation {status}: {len(results)} nodes -> {output_path}\n"
|
||||
)
|
||||
finally:
|
||||
FreeCAD.closeDocument(doc.Name)
|
||||
|
||||
|
||||
def export(input_path, output_path, format="step"):
|
||||
"""Export a Create file to an external geometry format.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_path : str
|
||||
Path to the ``.kc`` or ``.FCStd`` file.
|
||||
output_path : str
|
||||
Path to write the exported file.
|
||||
format : str
|
||||
One of ``step``, ``iges``, ``stl``, ``obj``.
|
||||
"""
|
||||
import Part
|
||||
|
||||
doc = FreeCAD.openDocument(input_path)
|
||||
try:
|
||||
shapes = [
|
||||
obj.Shape for obj in doc.Objects if hasattr(obj, "Shape") and obj.Shape
|
||||
]
|
||||
if not shapes:
|
||||
raise ValueError("No geometry found in document")
|
||||
|
||||
compound = Part.makeCompound(shapes)
|
||||
|
||||
format_lower = format.lower()
|
||||
if format_lower == "step":
|
||||
compound.exportStep(output_path)
|
||||
elif format_lower == "iges":
|
||||
compound.exportIges(output_path)
|
||||
elif format_lower == "stl":
|
||||
import Mesh
|
||||
|
||||
Mesh.export([compound], output_path)
|
||||
elif format_lower == "obj":
|
||||
import Mesh
|
||||
|
||||
Mesh.export([compound], output_path)
|
||||
else:
|
||||
raise ValueError(f"Unsupported format: {format}")
|
||||
|
||||
FreeCAD.Console.PrintMessage(
|
||||
f"Exported {format_lower.upper()} -> {output_path}\n"
|
||||
)
|
||||
finally:
|
||||
FreeCAD.closeDocument(doc.Name)
|
||||
648
freecad/schema_form.py
Normal file
648
freecad/schema_form.py
Normal file
@@ -0,0 +1,648 @@
|
||||
"""Schema-driven new-item form for Kindred Create.
|
||||
|
||||
Fetches schema data from the Silo REST API and builds a dynamic Qt form
|
||||
that mirrors the React ``CreateItemPane`` — category picker, property
|
||||
fields grouped by domain, live part number preview, and project tagging.
|
||||
|
||||
The primary widget is :class:`SchemaFormWidget` (a plain ``QWidget``)
|
||||
which can be embedded in an MDI tab, dock panel, or wrapped in the
|
||||
backward-compatible :class:`SchemaFormDialog` modal.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import FreeCAD
|
||||
from PySide import QtCore, QtGui, QtWidgets
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Domain labels derived from the first character of category codes.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DOMAIN_LABELS = {
|
||||
"F": "Fasteners",
|
||||
"C": "Fluid Fittings",
|
||||
"R": "Motion Components",
|
||||
"S": "Structural",
|
||||
"E": "Electrical",
|
||||
"M": "Mechanical",
|
||||
"T": "Tooling",
|
||||
"A": "Assemblies",
|
||||
"P": "Purchased",
|
||||
"X": "Custom Fabricated",
|
||||
}
|
||||
|
||||
_ITEM_TYPES = ["part", "assembly", "consumable", "tool"]
|
||||
_SOURCING_TYPES = ["manufactured", "purchased"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Collapsible group box
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _CollapsibleGroup(QtWidgets.QGroupBox):
|
||||
"""A QGroupBox that can be collapsed by clicking its title."""
|
||||
|
||||
def __init__(self, title: str, parent=None, collapsed=False):
|
||||
super().__init__(title, parent)
|
||||
self.setCheckable(True)
|
||||
self.setChecked(not collapsed)
|
||||
self.toggled.connect(self._on_toggled)
|
||||
self._content = QtWidgets.QWidget()
|
||||
self._layout = QtWidgets.QFormLayout(self._content)
|
||||
self._layout.setContentsMargins(8, 4, 8, 4)
|
||||
self._layout.setSpacing(6)
|
||||
|
||||
outer = QtWidgets.QVBoxLayout(self)
|
||||
outer.setContentsMargins(0, 4, 0, 0)
|
||||
outer.addWidget(self._content)
|
||||
|
||||
if collapsed:
|
||||
self._content.hide()
|
||||
|
||||
def form_layout(self) -> QtWidgets.QFormLayout:
|
||||
return self._layout
|
||||
|
||||
def _on_toggled(self, checked: bool):
|
||||
self._content.setVisible(checked)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Category picker (domain combo → subcategory combo)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _CategoryPicker(QtWidgets.QWidget):
|
||||
"""Two chained combo boxes: domain group → subcategory within that group."""
|
||||
|
||||
category_changed = QtCore.Signal(str) # emits full code e.g. "F01"
|
||||
|
||||
def __init__(self, categories: dict, parent=None):
|
||||
super().__init__(parent)
|
||||
self._categories = categories # {code: description, ...}
|
||||
|
||||
# Group by first character
|
||||
self._groups = {} # {prefix: [(code, desc), ...]}
|
||||
for code, desc in sorted(categories.items()):
|
||||
prefix = code[0] if code else "?"
|
||||
self._groups.setdefault(prefix, []).append((code, desc))
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(8)
|
||||
|
||||
self._domain_combo = QtWidgets.QComboBox()
|
||||
self._domain_combo.addItem("-- Select domain --", "")
|
||||
for prefix in sorted(self._groups.keys()):
|
||||
label = _DOMAIN_LABELS.get(prefix, prefix)
|
||||
count = len(self._groups[prefix])
|
||||
self._domain_combo.addItem(f"{prefix} \u2014 {label} ({count})", prefix)
|
||||
self._domain_combo.currentIndexChanged.connect(self._on_domain_changed)
|
||||
layout.addWidget(self._domain_combo, 1)
|
||||
|
||||
self._sub_combo = QtWidgets.QComboBox()
|
||||
self._sub_combo.setEnabled(False)
|
||||
self._sub_combo.currentIndexChanged.connect(self._on_sub_changed)
|
||||
layout.addWidget(self._sub_combo, 1)
|
||||
|
||||
def selected_category(self) -> str:
|
||||
return self._sub_combo.currentData() or ""
|
||||
|
||||
def _on_domain_changed(self, _index: int):
|
||||
prefix = self._domain_combo.currentData()
|
||||
self._sub_combo.clear()
|
||||
if not prefix:
|
||||
self._sub_combo.setEnabled(False)
|
||||
self.category_changed.emit("")
|
||||
return
|
||||
|
||||
self._sub_combo.setEnabled(True)
|
||||
self._sub_combo.addItem("-- Select subcategory --", "")
|
||||
for code, desc in self._groups.get(prefix, []):
|
||||
self._sub_combo.addItem(f"{code} \u2014 {desc}", code)
|
||||
|
||||
def _on_sub_changed(self, _index: int):
|
||||
code = self._sub_combo.currentData() or ""
|
||||
self.category_changed.emit(code)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Property field factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_field(prop_def: dict) -> QtWidgets.QWidget:
|
||||
"""Create a Qt widget for a property definition.
|
||||
|
||||
``prop_def`` has keys: type, default, unit, description, required.
|
||||
"""
|
||||
ptype = prop_def.get("type", "string")
|
||||
|
||||
if ptype == "boolean":
|
||||
cb = QtWidgets.QCheckBox()
|
||||
default = prop_def.get("default")
|
||||
if default is True:
|
||||
cb.setChecked(True)
|
||||
if prop_def.get("description"):
|
||||
cb.setToolTip(prop_def["description"])
|
||||
return cb
|
||||
|
||||
if ptype == "number":
|
||||
container = QtWidgets.QWidget()
|
||||
h = QtWidgets.QHBoxLayout(container)
|
||||
h.setContentsMargins(0, 0, 0, 0)
|
||||
h.setSpacing(4)
|
||||
|
||||
spin = QtWidgets.QDoubleSpinBox()
|
||||
spin.setDecimals(4)
|
||||
spin.setRange(-1e9, 1e9)
|
||||
spin.setSpecialValueText("") # show empty when at minimum
|
||||
default = prop_def.get("default")
|
||||
if default is not None and default != "":
|
||||
try:
|
||||
spin.setValue(float(default))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
else:
|
||||
spin.clear()
|
||||
if prop_def.get("description"):
|
||||
spin.setToolTip(prop_def["description"])
|
||||
h.addWidget(spin, 1)
|
||||
|
||||
unit = prop_def.get("unit", "")
|
||||
if unit:
|
||||
unit_label = QtWidgets.QLabel(unit)
|
||||
unit_label.setFixedWidth(40)
|
||||
h.addWidget(unit_label)
|
||||
|
||||
return container
|
||||
|
||||
# Default: string
|
||||
le = QtWidgets.QLineEdit()
|
||||
default = prop_def.get("default")
|
||||
if default and isinstance(default, str):
|
||||
le.setText(default)
|
||||
if prop_def.get("description"):
|
||||
le.setPlaceholderText(prop_def["description"])
|
||||
le.setToolTip(prop_def["description"])
|
||||
return le
|
||||
|
||||
|
||||
def _read_field(widget: QtWidgets.QWidget, prop_def: dict):
|
||||
"""Extract the value from a property widget, type-converted."""
|
||||
ptype = prop_def.get("type", "string")
|
||||
|
||||
if ptype == "boolean":
|
||||
return widget.isChecked()
|
||||
|
||||
if ptype == "number":
|
||||
spin = widget.findChild(QtWidgets.QDoubleSpinBox)
|
||||
if spin is None:
|
||||
return None
|
||||
text = spin.text().strip()
|
||||
if not text:
|
||||
return None
|
||||
return spin.value()
|
||||
|
||||
# string
|
||||
if isinstance(widget, QtWidgets.QLineEdit):
|
||||
val = widget.text().strip()
|
||||
return val if val else None
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Embeddable form widget
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SchemaFormWidget(QtWidgets.QWidget):
|
||||
"""Schema-driven new-item form widget.
|
||||
|
||||
A plain ``QWidget`` that can be embedded in an MDI subwindow, dock
|
||||
panel, or dialog. Emits :pyqt:`item_created` on successful creation
|
||||
and :pyqt:`cancelled` when the user clicks Cancel.
|
||||
"""
|
||||
|
||||
item_created = QtCore.Signal(dict)
|
||||
cancelled = QtCore.Signal()
|
||||
|
||||
def __init__(self, client, parent=None):
|
||||
super().__init__(parent)
|
||||
self._client = client
|
||||
self._prop_widgets = {} # {key: (widget, prop_def)}
|
||||
self._prop_groups = [] # list of _CollapsibleGroup to clear on category change
|
||||
self._categories = {}
|
||||
self._projects = []
|
||||
self._templates = [] # List[TemplateInfo]
|
||||
|
||||
self._load_schema_data()
|
||||
self._build_ui()
|
||||
self._update_template_combo()
|
||||
|
||||
# Part number preview debounce timer
|
||||
self._pn_timer = QtCore.QTimer(self)
|
||||
self._pn_timer.setSingleShot(True)
|
||||
self._pn_timer.setInterval(500)
|
||||
self._pn_timer.timeout.connect(self._update_pn_preview)
|
||||
|
||||
# -- data loading -------------------------------------------------------
|
||||
|
||||
def _load_schema_data(self):
|
||||
"""Fetch categories and projects from the API."""
|
||||
try:
|
||||
schema = self._client.get_schema()
|
||||
segments = schema.get("segments", [])
|
||||
cat_segment = next(
|
||||
(s for s in segments if s.get("name") == "category"), None
|
||||
)
|
||||
if cat_segment and cat_segment.get("values"):
|
||||
self._categories = cat_segment["values"]
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Schema form: failed to fetch schema: {e}\n")
|
||||
|
||||
try:
|
||||
self._projects = self._client.get_projects() or []
|
||||
except Exception:
|
||||
self._projects = []
|
||||
|
||||
try:
|
||||
from templates import discover_templates, get_search_paths
|
||||
|
||||
self._templates = discover_templates(get_search_paths())
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(
|
||||
f"Schema form: failed to discover templates: {e}\n"
|
||||
)
|
||||
self._templates = []
|
||||
|
||||
def _fetch_properties(self, category: str) -> dict:
|
||||
"""Fetch merged property definitions for a category."""
|
||||
try:
|
||||
data = self._client.get_property_schema(category=category)
|
||||
return data.get("properties", data)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(
|
||||
f"Schema form: failed to fetch properties for {category}: {e}\n"
|
||||
)
|
||||
return {}
|
||||
|
||||
def _generate_pn_preview(self, category: str) -> str:
|
||||
"""Call the server to preview the next part number."""
|
||||
from silo_commands import _get_schema_name
|
||||
|
||||
try:
|
||||
data = self._client.generate_part_number(_get_schema_name(), category)
|
||||
return data.get("part_number", "")
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
# -- UI construction ----------------------------------------------------
|
||||
|
||||
def _build_ui(self):
|
||||
root = QtWidgets.QVBoxLayout(self)
|
||||
root.setSpacing(8)
|
||||
|
||||
# Inline error label (hidden by default)
|
||||
self._error_label = QtWidgets.QLabel()
|
||||
self._error_label.setStyleSheet(
|
||||
"background-color: #f38ba8; color: #1e1e2e; "
|
||||
"padding: 8px; border-radius: 4px; font-weight: bold;"
|
||||
)
|
||||
self._error_label.setAlignment(QtCore.Qt.AlignCenter)
|
||||
self._error_label.hide()
|
||||
root.addWidget(self._error_label)
|
||||
|
||||
# Part number preview banner
|
||||
self._pn_label = QtWidgets.QLabel("Part Number: \u2014")
|
||||
self._pn_label.setStyleSheet(
|
||||
"font-size: 16px; font-weight: bold; padding: 8px;"
|
||||
)
|
||||
self._pn_label.setAlignment(QtCore.Qt.AlignCenter)
|
||||
root.addWidget(self._pn_label)
|
||||
|
||||
# Scroll area for form content
|
||||
scroll = QtWidgets.QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
|
||||
scroll_content = QtWidgets.QWidget()
|
||||
self._form_layout = QtWidgets.QVBoxLayout(scroll_content)
|
||||
self._form_layout.setSpacing(8)
|
||||
self._form_layout.setContentsMargins(8, 4, 8, 4)
|
||||
scroll.setWidget(scroll_content)
|
||||
root.addWidget(scroll, 1)
|
||||
|
||||
# --- Identity section ---
|
||||
identity = _CollapsibleGroup("Identity")
|
||||
fl = identity.form_layout()
|
||||
|
||||
self._type_combo = QtWidgets.QComboBox()
|
||||
for t in _ITEM_TYPES:
|
||||
self._type_combo.addItem(t.capitalize(), t)
|
||||
self._type_combo.currentIndexChanged.connect(
|
||||
lambda _: self._update_template_combo()
|
||||
)
|
||||
fl.addRow("Type:", self._type_combo)
|
||||
|
||||
self._template_combo = QtWidgets.QComboBox()
|
||||
self._template_combo.addItem("(No template)", None)
|
||||
fl.addRow("Template:", self._template_combo)
|
||||
|
||||
self._desc_edit = QtWidgets.QLineEdit()
|
||||
self._desc_edit.setPlaceholderText("Item description")
|
||||
fl.addRow("Description:", self._desc_edit)
|
||||
|
||||
self._cat_picker = _CategoryPicker(self._categories)
|
||||
self._cat_picker.category_changed.connect(self._on_category_changed)
|
||||
fl.addRow("Category:", self._cat_picker)
|
||||
|
||||
self._form_layout.addWidget(identity)
|
||||
|
||||
# --- Sourcing section ---
|
||||
sourcing = _CollapsibleGroup("Sourcing", collapsed=True)
|
||||
fl = sourcing.form_layout()
|
||||
|
||||
self._sourcing_combo = QtWidgets.QComboBox()
|
||||
for s in _SOURCING_TYPES:
|
||||
self._sourcing_combo.addItem(s.capitalize(), s)
|
||||
fl.addRow("Sourcing:", self._sourcing_combo)
|
||||
|
||||
self._cost_spin = QtWidgets.QDoubleSpinBox()
|
||||
self._cost_spin.setDecimals(2)
|
||||
self._cost_spin.setRange(0, 1e9)
|
||||
self._cost_spin.setPrefix("$ ")
|
||||
self._cost_spin.setSpecialValueText("")
|
||||
fl.addRow("Standard Cost:", self._cost_spin)
|
||||
|
||||
self._sourcing_url = QtWidgets.QLineEdit()
|
||||
self._sourcing_url.setPlaceholderText("https://...")
|
||||
fl.addRow("Sourcing URL:", self._sourcing_url)
|
||||
|
||||
self._form_layout.addWidget(sourcing)
|
||||
|
||||
# --- Details section ---
|
||||
details = _CollapsibleGroup("Details", collapsed=True)
|
||||
fl = details.form_layout()
|
||||
|
||||
self._long_desc = QtWidgets.QTextEdit()
|
||||
self._long_desc.setMaximumHeight(80)
|
||||
self._long_desc.setPlaceholderText("Detailed description...")
|
||||
fl.addRow("Long Description:", self._long_desc)
|
||||
|
||||
# Project selection
|
||||
self._project_list = QtWidgets.QListWidget()
|
||||
self._project_list.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
|
||||
self._project_list.setMaximumHeight(100)
|
||||
for proj in self._projects:
|
||||
code = proj.get("code", "")
|
||||
name = proj.get("name", "")
|
||||
label = f"{code} \u2014 {name}" if name else code
|
||||
item = QtWidgets.QListWidgetItem(label)
|
||||
item.setData(QtCore.Qt.UserRole, code)
|
||||
self._project_list.addItem(item)
|
||||
if self._projects:
|
||||
fl.addRow("Projects:", self._project_list)
|
||||
|
||||
self._form_layout.addWidget(details)
|
||||
|
||||
# --- Dynamic property groups (inserted here on category change) ---
|
||||
self._prop_insert_index = self._form_layout.count()
|
||||
|
||||
# Spacer
|
||||
self._form_layout.addStretch()
|
||||
|
||||
# --- Buttons ---
|
||||
btn_layout = QtWidgets.QHBoxLayout()
|
||||
btn_layout.addStretch()
|
||||
|
||||
self._cancel_btn = QtWidgets.QPushButton("Cancel")
|
||||
self._cancel_btn.clicked.connect(self.cancelled.emit)
|
||||
btn_layout.addWidget(self._cancel_btn)
|
||||
|
||||
self._create_btn = QtWidgets.QPushButton("Create")
|
||||
self._create_btn.setEnabled(False)
|
||||
self._create_btn.setDefault(True)
|
||||
self._create_btn.clicked.connect(self._on_create)
|
||||
btn_layout.addWidget(self._create_btn)
|
||||
|
||||
root.addLayout(btn_layout)
|
||||
|
||||
# -- template filtering -------------------------------------------------
|
||||
|
||||
def _update_template_combo(self):
|
||||
"""Repopulate the template combo based on current type and category."""
|
||||
from templates import filter_templates
|
||||
|
||||
self._template_combo.clear()
|
||||
self._template_combo.addItem("(No template)", None)
|
||||
item_type = self._type_combo.currentData() or ""
|
||||
category = self._cat_picker.selected_category() or ""
|
||||
for t in filter_templates(self._templates, item_type, category):
|
||||
self._template_combo.addItem(t.name, t.path)
|
||||
|
||||
# -- category change ----------------------------------------------------
|
||||
|
||||
def _on_category_changed(self, category: str):
|
||||
"""Rebuild property groups when category selection changes."""
|
||||
self._create_btn.setEnabled(bool(category))
|
||||
self._update_template_combo()
|
||||
|
||||
# Remove old property groups
|
||||
for group in self._prop_groups:
|
||||
self._form_layout.removeWidget(group)
|
||||
group.deleteLater()
|
||||
self._prop_groups.clear()
|
||||
self._prop_widgets.clear()
|
||||
|
||||
if not category:
|
||||
self._pn_label.setText("Part Number: \u2014")
|
||||
return
|
||||
|
||||
# Trigger part number preview
|
||||
self._pn_timer.start()
|
||||
|
||||
# Fetch properties
|
||||
all_props = self._fetch_properties(category)
|
||||
if not all_props:
|
||||
return
|
||||
|
||||
# Separate into category-specific and common (default) properties.
|
||||
# The server merges them but we can identify category-specific ones
|
||||
# by checking what the schema defines for this category prefix.
|
||||
prefix = category[0]
|
||||
domain_label = _DOMAIN_LABELS.get(prefix, prefix)
|
||||
|
||||
# We fetch the raw schema to determine which keys are category-specific.
|
||||
# For now, use a heuristic: keys that are NOT in the well-known defaults
|
||||
# list are category-specific.
|
||||
_KNOWN_DEFAULTS = {
|
||||
"manufacturer",
|
||||
"manufacturer_pn",
|
||||
"supplier",
|
||||
"supplier_pn",
|
||||
"sourcing_link",
|
||||
"standard_cost",
|
||||
"lead_time_days",
|
||||
"minimum_order_qty",
|
||||
"lifecycle_status",
|
||||
"rohs_compliant",
|
||||
"country_of_origin",
|
||||
"notes",
|
||||
}
|
||||
|
||||
cat_specific = {}
|
||||
common = {}
|
||||
for key, pdef in sorted(all_props.items()):
|
||||
if key in _KNOWN_DEFAULTS:
|
||||
common[key] = pdef
|
||||
else:
|
||||
cat_specific[key] = pdef
|
||||
|
||||
insert_pos = self._prop_insert_index
|
||||
|
||||
# Category-specific properties group
|
||||
if cat_specific:
|
||||
group = _CollapsibleGroup(f"{domain_label} Properties")
|
||||
fl = group.form_layout()
|
||||
for key, pdef in cat_specific.items():
|
||||
label = key.replace("_", " ").title()
|
||||
widget = _make_field(pdef)
|
||||
fl.addRow(f"{label}:", widget)
|
||||
self._prop_widgets[key] = (widget, pdef)
|
||||
self._form_layout.insertWidget(insert_pos, group)
|
||||
self._prop_groups.append(group)
|
||||
insert_pos += 1
|
||||
|
||||
# Common properties group (collapsed by default)
|
||||
if common:
|
||||
group = _CollapsibleGroup("Common Properties", collapsed=True)
|
||||
fl = group.form_layout()
|
||||
for key, pdef in common.items():
|
||||
label = key.replace("_", " ").title()
|
||||
widget = _make_field(pdef)
|
||||
fl.addRow(f"{label}:", widget)
|
||||
self._prop_widgets[key] = (widget, pdef)
|
||||
self._form_layout.insertWidget(insert_pos, group)
|
||||
self._prop_groups.append(group)
|
||||
|
||||
def _update_pn_preview(self):
|
||||
"""Fetch and display the next part number preview."""
|
||||
category = self._cat_picker.selected_category()
|
||||
if not category:
|
||||
self._pn_label.setText("Part Number: \u2014")
|
||||
return
|
||||
|
||||
pn = self._generate_pn_preview(category)
|
||||
if pn:
|
||||
self._pn_label.setText(f"Part Number: {pn}")
|
||||
self.setWindowTitle(f"New: {pn}")
|
||||
else:
|
||||
self._pn_label.setText(f"Part Number: {category}-????")
|
||||
self.setWindowTitle(f"New: {category}-????")
|
||||
|
||||
# -- submission ---------------------------------------------------------
|
||||
|
||||
def _collect_form_data(self) -> dict:
|
||||
"""Collect all form values into a dict suitable for create_item."""
|
||||
category = self._cat_picker.selected_category()
|
||||
description = self._desc_edit.text().strip()
|
||||
item_type = self._type_combo.currentData()
|
||||
sourcing_type = self._sourcing_combo.currentData()
|
||||
cost_text = self._cost_spin.text().strip().lstrip("$ ")
|
||||
standard_cost = float(cost_text) if cost_text else None
|
||||
sourcing_link = self._sourcing_url.text().strip() or None
|
||||
long_description = self._long_desc.toPlainText().strip() or None
|
||||
|
||||
# Projects
|
||||
selected_projects = []
|
||||
for item in self._project_list.selectedItems():
|
||||
code = item.data(QtCore.Qt.UserRole)
|
||||
if code:
|
||||
selected_projects.append(code)
|
||||
|
||||
# Properties
|
||||
properties = {}
|
||||
for key, (widget, pdef) in self._prop_widgets.items():
|
||||
val = _read_field(widget, pdef)
|
||||
if val is not None and val != "":
|
||||
properties[key] = val
|
||||
|
||||
return {
|
||||
"category": category,
|
||||
"description": description,
|
||||
"item_type": item_type,
|
||||
"sourcing_type": sourcing_type,
|
||||
"standard_cost": standard_cost,
|
||||
"sourcing_link": sourcing_link,
|
||||
"long_description": long_description,
|
||||
"projects": selected_projects if selected_projects else None,
|
||||
"properties": properties if properties else None,
|
||||
"template_path": self._template_combo.currentData(),
|
||||
}
|
||||
|
||||
def _on_create(self):
|
||||
"""Validate and submit the form."""
|
||||
self._error_label.hide()
|
||||
data = self._collect_form_data()
|
||||
|
||||
if not data["category"]:
|
||||
self._error_label.setText("Category is required.")
|
||||
self._error_label.show()
|
||||
return
|
||||
|
||||
try:
|
||||
from silo_commands import _get_schema_name
|
||||
|
||||
result = self._client.create_item(
|
||||
_get_schema_name(),
|
||||
data["category"],
|
||||
data["description"],
|
||||
projects=data["projects"],
|
||||
)
|
||||
result["_form_data"] = data
|
||||
self.item_created.emit(result)
|
||||
except Exception as e:
|
||||
self._error_label.setText(f"Failed to create item: {e}")
|
||||
self._error_label.show()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Modal dialog wrapper (backward compatibility)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SchemaFormDialog(QtWidgets.QDialog):
|
||||
"""Modal dialog wrapper around :class:`SchemaFormWidget`.
|
||||
|
||||
Provides the same ``exec_and_create()`` API as the original
|
||||
implementation for callers that still need blocking modal behavior.
|
||||
"""
|
||||
|
||||
def __init__(self, client, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("New Item")
|
||||
self.setMinimumSize(600, 500)
|
||||
self.resize(680, 700)
|
||||
self._result = None
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._form = SchemaFormWidget(client, parent=self)
|
||||
self._form.item_created.connect(self._on_created)
|
||||
self._form.cancelled.connect(self.reject)
|
||||
layout.addWidget(self._form)
|
||||
|
||||
@property
|
||||
def _desc_edit(self):
|
||||
"""Expose description field for pre-fill by callers."""
|
||||
return self._form._desc_edit
|
||||
|
||||
def _on_created(self, result):
|
||||
self._result = result
|
||||
self.accept()
|
||||
|
||||
def exec_and_create(self):
|
||||
"""Show dialog and return the creation result, or None if cancelled."""
|
||||
if self.exec_() == QtWidgets.QDialog.Accepted:
|
||||
return self._result
|
||||
return None
|
||||
File diff suppressed because it is too large
Load Diff
@@ -30,7 +30,7 @@ class SiloOrigin:
|
||||
Key behaviors:
|
||||
- Documents are always stored locally (hybrid local-remote model)
|
||||
- Database tracks metadata, part numbers, and revision history
|
||||
- MinIO stores revision snapshots for sync/backup
|
||||
- Server stores revision files for sync/backup
|
||||
- Identity is tracked by UUID (SiloItemId), displayed as part number
|
||||
"""
|
||||
|
||||
@@ -299,9 +299,7 @@ class SiloOrigin:
|
||||
Created App.Document or None
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_New")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
FreeCADGui.runCommand("Silo_New")
|
||||
return FreeCAD.ActiveDocument
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo new document failed: {e}\n")
|
||||
@@ -322,9 +320,7 @@ class SiloOrigin:
|
||||
if not identity:
|
||||
# No identity - show search dialog
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_Open")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
FreeCADGui.runCommand("Silo_Open")
|
||||
return FreeCAD.ActiveDocument
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo open failed: {e}\n")
|
||||
@@ -354,9 +350,7 @@ class SiloOrigin:
|
||||
Opened App.Document or None
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_Open")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
FreeCADGui.runCommand("Silo_Open")
|
||||
return FreeCAD.ActiveDocument
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo open failed: {e}\n")
|
||||
@@ -394,16 +388,19 @@ class SiloOrigin:
|
||||
|
||||
# Upload to Silo
|
||||
properties = collect_document_properties(doc)
|
||||
_client._upload_file(
|
||||
obj.SiloPartNumber, str(file_path), properties, comment=""
|
||||
)
|
||||
_client._upload_file(obj.SiloPartNumber, str(file_path), properties, comment="")
|
||||
|
||||
# Clear modified flag
|
||||
doc.Modified = False
|
||||
# Clear modified flag (Modified is on Gui.Document, not App.Document)
|
||||
gui_doc = FreeCADGui.getDocument(doc.Name)
|
||||
if gui_doc:
|
||||
gui_doc.Modified = False
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
FreeCAD.Console.PrintError(f"Silo save failed: {e}\n")
|
||||
FreeCAD.Console.PrintError(traceback.format_exc())
|
||||
return False
|
||||
|
||||
def saveDocumentAs(self, doc, newIdentity: str) -> bool:
|
||||
@@ -473,10 +470,8 @@ class SiloOrigin:
|
||||
True if command was executed
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_Commit")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
return True
|
||||
FreeCADGui.runCommand("Silo_Commit")
|
||||
return True
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo commit failed: {e}\n")
|
||||
return False
|
||||
@@ -493,10 +488,8 @@ class SiloOrigin:
|
||||
True if command was executed
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_Pull")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
return True
|
||||
FreeCADGui.runCommand("Silo_Pull")
|
||||
return True
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo pull failed: {e}\n")
|
||||
return False
|
||||
@@ -513,10 +506,8 @@ class SiloOrigin:
|
||||
True if command was executed
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_Push")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
return True
|
||||
FreeCADGui.runCommand("Silo_Push")
|
||||
return True
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo push failed: {e}\n")
|
||||
return False
|
||||
@@ -530,9 +521,7 @@ class SiloOrigin:
|
||||
doc: FreeCAD App.Document
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_Info")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
FreeCADGui.runCommand("Silo_Info")
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo info failed: {e}\n")
|
||||
|
||||
@@ -545,9 +534,7 @@ class SiloOrigin:
|
||||
doc: FreeCAD App.Document
|
||||
"""
|
||||
try:
|
||||
cmd = FreeCADGui.Command.get("Silo_BOM")
|
||||
if cmd:
|
||||
cmd.Activated()
|
||||
FreeCADGui.runCommand("Silo_BOM")
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo BOM failed: {e}\n")
|
||||
|
||||
@@ -578,12 +565,9 @@ def register_silo_origin():
|
||||
This should be called during workbench initialization to make
|
||||
Silo available as a file origin.
|
||||
"""
|
||||
origin = get_silo_origin()
|
||||
try:
|
||||
FreeCADGui.addOrigin(origin)
|
||||
FreeCAD.Console.PrintLog("Registered Silo origin\n")
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Could not register Silo origin: {e}\n")
|
||||
from kindred_sdk import register_origin
|
||||
|
||||
register_origin(get_silo_origin())
|
||||
|
||||
|
||||
def unregister_silo_origin():
|
||||
@@ -593,9 +577,7 @@ def unregister_silo_origin():
|
||||
"""
|
||||
global _silo_origin
|
||||
if _silo_origin:
|
||||
try:
|
||||
FreeCADGui.removeOrigin(_silo_origin)
|
||||
FreeCAD.Console.PrintLog("Unregistered Silo origin\n")
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Could not unregister Silo origin: {e}\n")
|
||||
from kindred_sdk import unregister_origin
|
||||
|
||||
unregister_origin(_silo_origin)
|
||||
_silo_origin = None
|
||||
|
||||
654
freecad/silo_start.py
Normal file
654
freecad/silo_start.py
Normal file
@@ -0,0 +1,654 @@
|
||||
"""Silo Start Page — native Qt start view for Kindred Create.
|
||||
|
||||
Replaces the default Start page with a rich native panel that fetches data
|
||||
from the Silo REST API, shows real-time activity via SSE, and provides quick
|
||||
access to database items and recent local files.
|
||||
|
||||
The command override is activated by calling ``register()`` at module level
|
||||
from InitGui.py, which overwrites the C++ ``Start_Start`` command.
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import FreeCAD
|
||||
import FreeCADGui
|
||||
from PySide import QtCore, QtGui, QtWidgets
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Catppuccin Mocha palette
|
||||
# ---------------------------------------------------------------------------
|
||||
# Catppuccin Mocha palette — sourced from kindred-addon-sdk
|
||||
from kindred_sdk.theme import get_theme_tokens
|
||||
|
||||
_MOCHA = get_theme_tokens()
|
||||
|
||||
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _get_silo_base_url() -> str:
|
||||
"""Return the Silo web UI root URL (without /api)."""
|
||||
param = FreeCAD.ParamGet(_PREF_GROUP)
|
||||
url = param.GetString("ApiUrl", "")
|
||||
if not url:
|
||||
url = os.environ.get("SILO_API_URL", "http://localhost:8080/api")
|
||||
url = url.rstrip("/")
|
||||
if url.endswith("/api"):
|
||||
url = url[:-4]
|
||||
return url
|
||||
|
||||
|
||||
def _get_recent_files() -> list:
|
||||
"""Read recent files from FreeCAD preferences."""
|
||||
group = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/RecentFiles")
|
||||
count = group.GetInt("RecentFiles", 0)
|
||||
files = []
|
||||
for i in range(count):
|
||||
path = group.GetString(f"MRU{i}", "")
|
||||
if path and os.path.exists(path):
|
||||
p = Path(path)
|
||||
mtime = datetime.fromtimestamp(p.stat().st_mtime)
|
||||
files.append({"path": str(p), "name": p.name, "modified": mtime})
|
||||
return files
|
||||
|
||||
|
||||
def _relative_time(dt: datetime) -> str:
|
||||
"""Format a datetime as a human-friendly relative string."""
|
||||
now = datetime.now()
|
||||
diff = now - dt
|
||||
seconds = int(diff.total_seconds())
|
||||
if seconds < 60:
|
||||
return "just now"
|
||||
minutes = seconds // 60
|
||||
if minutes < 60:
|
||||
return f"{minutes}m ago"
|
||||
hours = minutes // 60
|
||||
if hours < 24:
|
||||
return f"{hours}h ago"
|
||||
days = hours // 24
|
||||
if days < 30:
|
||||
return f"{days}d ago"
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stylesheet
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_STYLESHEET = f"""
|
||||
SiloStartView {{
|
||||
background-color: {_MOCHA["base"]};
|
||||
}}
|
||||
|
||||
/* --- Status banner --- */
|
||||
#SiloStatusBanner {{
|
||||
background-color: {_MOCHA["surface0"]};
|
||||
border-radius: 8px;
|
||||
}}
|
||||
#SiloStatusBanner QLabel {{
|
||||
color: {_MOCHA["text"]};
|
||||
font-size: 13px;
|
||||
}}
|
||||
#SiloStatusBanner QPushButton {{
|
||||
background-color: {_MOCHA["blue"]};
|
||||
color: {_MOCHA["crust"]};
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
padding: 6px 12px;
|
||||
font-weight: bold;
|
||||
font-size: 12px;
|
||||
}}
|
||||
#SiloStatusBanner QPushButton:hover {{
|
||||
background-color: {_MOCHA["lavender"]};
|
||||
}}
|
||||
|
||||
/* --- Section headers --- */
|
||||
.SiloSectionHeader {{
|
||||
color: {_MOCHA["text"]};
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
}}
|
||||
|
||||
/* --- Search field --- */
|
||||
#SiloSearchField {{
|
||||
background-color: {_MOCHA["surface0"]};
|
||||
border: 1px solid {_MOCHA["surface1"]};
|
||||
border-radius: 4px;
|
||||
padding: 6px 10px;
|
||||
color: {_MOCHA["text"]};
|
||||
font-size: 13px;
|
||||
}}
|
||||
#SiloSearchField:focus {{
|
||||
border-color: {_MOCHA["blue"]};
|
||||
}}
|
||||
|
||||
/* --- List widgets --- */
|
||||
.SiloList {{
|
||||
background-color: {_MOCHA["mantle"]};
|
||||
border: 1px solid {_MOCHA["surface0"]};
|
||||
border-radius: 6px;
|
||||
padding: 4px;
|
||||
}}
|
||||
.SiloList::item {{
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid {_MOCHA["surface0"]};
|
||||
color: {_MOCHA["text"]};
|
||||
}}
|
||||
.SiloList::item:last {{
|
||||
border-bottom: none;
|
||||
}}
|
||||
.SiloList::item:hover {{
|
||||
background-color: {_MOCHA["surface0"]};
|
||||
}}
|
||||
.SiloList::item:selected {{
|
||||
background-color: {_MOCHA["surface1"]};
|
||||
}}
|
||||
|
||||
/* --- Activity feed --- */
|
||||
#SiloActivityFeed {{
|
||||
background-color: {_MOCHA["mantle"]};
|
||||
border: 1px solid {_MOCHA["surface0"]};
|
||||
border-radius: 6px;
|
||||
padding: 4px;
|
||||
}}
|
||||
#SiloActivityFeed::item {{
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid {_MOCHA["surface0"]};
|
||||
color: {_MOCHA["subtext0"]};
|
||||
font-size: 12px;
|
||||
}}
|
||||
#SiloActivityFeed::item:last {{
|
||||
border-bottom: none;
|
||||
}}
|
||||
|
||||
/* --- Footer checkbox --- */
|
||||
QCheckBox {{
|
||||
color: {_MOCHA["subtext0"]};
|
||||
font-size: 12px;
|
||||
}}
|
||||
QCheckBox::indicator {{
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main start view
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SiloStartView(QtWidgets.QWidget):
|
||||
"""Native Qt start page with Silo database items, recent files, and
|
||||
real-time activity feed."""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setObjectName("SiloStartView")
|
||||
|
||||
self._silo_url = _get_silo_base_url()
|
||||
self._connected = False
|
||||
self._event_listener = None
|
||||
self._activity_events = [] # list of (datetime, text) tuples
|
||||
self._silo_imported = False
|
||||
self._silo_cmds = None # lazy ref to silo_commands module
|
||||
|
||||
self._build_ui()
|
||||
self.setStyleSheet(_STYLESHEET)
|
||||
|
||||
# Debounce timer for search
|
||||
self._search_timer = QtCore.QTimer(self)
|
||||
self._search_timer.setSingleShot(True)
|
||||
self._search_timer.setInterval(300)
|
||||
self._search_timer.timeout.connect(self._refresh_items)
|
||||
|
||||
# Periodic refresh
|
||||
self._poll_timer = QtCore.QTimer(self)
|
||||
self._poll_timer.setInterval(30000)
|
||||
self._poll_timer.timeout.connect(self._periodic_refresh)
|
||||
self._poll_timer.start()
|
||||
|
||||
# Initial load after event loop starts
|
||||
QtCore.QTimer.singleShot(100, self._initial_load)
|
||||
|
||||
# -- lazy import --------------------------------------------------------
|
||||
|
||||
def _silo(self):
|
||||
"""Lazy-import silo_commands to avoid circular import at module load."""
|
||||
if not self._silo_imported:
|
||||
try:
|
||||
import silo_commands
|
||||
|
||||
self._silo_cmds = silo_commands
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Silo Start: cannot import silo_commands: {e}\n")
|
||||
self._silo_cmds = None
|
||||
self._silo_imported = True
|
||||
return self._silo_cmds
|
||||
|
||||
# -- UI construction ----------------------------------------------------
|
||||
|
||||
def _build_ui(self):
|
||||
root = QtWidgets.QVBoxLayout(self)
|
||||
root.setContentsMargins(32, 24, 32, 16)
|
||||
root.setSpacing(0)
|
||||
|
||||
# --- Status banner ---
|
||||
banner = QtWidgets.QFrame()
|
||||
banner.setObjectName("SiloStatusBanner")
|
||||
banner_layout = QtWidgets.QHBoxLayout(banner)
|
||||
banner_layout.setContentsMargins(16, 10, 16, 10)
|
||||
|
||||
self._status_icon = QtWidgets.QLabel()
|
||||
self._status_icon.setFixedSize(12, 12)
|
||||
banner_layout.addWidget(self._status_icon)
|
||||
|
||||
self._status_label = QtWidgets.QLabel("Checking Silo connection...")
|
||||
self._status_label.setWordWrap(True)
|
||||
banner_layout.addWidget(self._status_label, 1)
|
||||
|
||||
self._browser_btn = QtWidgets.QPushButton("Open in Browser")
|
||||
self._browser_btn.setFixedWidth(130)
|
||||
self._browser_btn.setCursor(QtCore.Qt.PointingHandCursor)
|
||||
self._browser_btn.clicked.connect(self._open_in_browser)
|
||||
banner_layout.addWidget(self._browser_btn)
|
||||
|
||||
self._retry_btn = QtWidgets.QPushButton("Retry")
|
||||
self._retry_btn.setFixedWidth(70)
|
||||
self._retry_btn.setCursor(QtCore.Qt.PointingHandCursor)
|
||||
self._retry_btn.clicked.connect(self._initial_load)
|
||||
self._retry_btn.hide()
|
||||
banner_layout.addWidget(self._retry_btn)
|
||||
|
||||
root.addWidget(banner)
|
||||
root.addSpacing(20)
|
||||
|
||||
# --- Main content: items (left) + recent files (right) ---
|
||||
content_splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
|
||||
content_splitter.setHandleWidth(12)
|
||||
content_splitter.setStyleSheet(
|
||||
f"QSplitter::handle {{ background-color: {_MOCHA['base']}; }}"
|
||||
)
|
||||
|
||||
# Left: Database Items
|
||||
left = QtWidgets.QWidget()
|
||||
left_layout = QtWidgets.QVBoxLayout(left)
|
||||
left_layout.setContentsMargins(0, 0, 0, 0)
|
||||
left_layout.setSpacing(8)
|
||||
|
||||
items_header = QtWidgets.QLabel("Database Items")
|
||||
items_header.setProperty("class", "SiloSectionHeader")
|
||||
left_layout.addWidget(items_header)
|
||||
|
||||
self._search_field = QtWidgets.QLineEdit()
|
||||
self._search_field.setObjectName("SiloSearchField")
|
||||
self._search_field.setPlaceholderText("Search items...")
|
||||
self._search_field.textChanged.connect(self._on_search_changed)
|
||||
left_layout.addWidget(self._search_field)
|
||||
|
||||
self._items_list = QtWidgets.QListWidget()
|
||||
self._items_list.setProperty("class", "SiloList")
|
||||
self._items_list.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
|
||||
self._items_list.itemDoubleClicked.connect(self._on_item_double_clicked)
|
||||
self._items_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
|
||||
self._items_list.customContextMenuRequested.connect(self._on_item_context_menu)
|
||||
left_layout.addWidget(self._items_list, 1)
|
||||
|
||||
content_splitter.addWidget(left)
|
||||
|
||||
# Right: Recent Files
|
||||
right = QtWidgets.QWidget()
|
||||
right_layout = QtWidgets.QVBoxLayout(right)
|
||||
right_layout.setContentsMargins(0, 0, 0, 0)
|
||||
right_layout.setSpacing(8)
|
||||
|
||||
recent_header = QtWidgets.QLabel("Recent Files")
|
||||
recent_header.setProperty("class", "SiloSectionHeader")
|
||||
right_layout.addWidget(recent_header)
|
||||
|
||||
self._file_list = QtWidgets.QListWidget()
|
||||
self._file_list.setProperty("class", "SiloList")
|
||||
self._file_list.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
|
||||
self._file_list.itemDoubleClicked.connect(self._on_file_clicked)
|
||||
right_layout.addWidget(self._file_list, 1)
|
||||
|
||||
content_splitter.addWidget(right)
|
||||
content_splitter.setStretchFactor(0, 3)
|
||||
content_splitter.setStretchFactor(1, 2)
|
||||
|
||||
root.addWidget(content_splitter, 1)
|
||||
root.addSpacing(12)
|
||||
|
||||
# --- Activity Feed (bottom) ---
|
||||
activity_header = QtWidgets.QLabel("Activity")
|
||||
activity_header.setProperty("class", "SiloSectionHeader")
|
||||
root.addWidget(activity_header)
|
||||
root.addSpacing(6)
|
||||
|
||||
self._activity_list = QtWidgets.QListWidget()
|
||||
self._activity_list.setObjectName("SiloActivityFeed")
|
||||
self._activity_list.setMaximumHeight(140)
|
||||
self._activity_list.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
|
||||
root.addWidget(self._activity_list)
|
||||
root.addSpacing(12)
|
||||
|
||||
# --- Footer ---
|
||||
footer = QtWidgets.QHBoxLayout()
|
||||
footer.addStretch()
|
||||
self._startup_cb = QtWidgets.QCheckBox("Don't show this page on startup")
|
||||
start_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start")
|
||||
show = start_prefs.GetBool("ShowOnStartup", True)
|
||||
self._startup_cb.setChecked(not show)
|
||||
self._startup_cb.toggled.connect(self._on_startup_toggled)
|
||||
footer.addWidget(self._startup_cb)
|
||||
root.addLayout(footer)
|
||||
|
||||
# -- data loading -------------------------------------------------------
|
||||
|
||||
def _initial_load(self):
|
||||
"""First-time data load and SSE connection."""
|
||||
self._refresh_status()
|
||||
self._refresh_items()
|
||||
self._refresh_recent_files()
|
||||
self._start_sse()
|
||||
|
||||
def _periodic_refresh(self):
|
||||
"""Periodic refresh of items and connection status."""
|
||||
self._refresh_status()
|
||||
self._refresh_items()
|
||||
self._refresh_recent_files()
|
||||
|
||||
def _refresh_status(self):
|
||||
"""Update the connection status banner."""
|
||||
sc = self._silo()
|
||||
if sc is None:
|
||||
self._set_status(False, "Silo addon not available")
|
||||
return
|
||||
|
||||
try:
|
||||
reachable, _ = sc._client.check_connection()
|
||||
except Exception:
|
||||
reachable = False
|
||||
|
||||
self._silo_url = _get_silo_base_url()
|
||||
if reachable:
|
||||
self._set_status(True, f"Connected to {self._silo_url}")
|
||||
else:
|
||||
self._set_status(False, f"Cannot reach {self._silo_url}")
|
||||
|
||||
def _set_status(self, connected: bool, message: str):
|
||||
self._connected = connected
|
||||
if connected:
|
||||
self._status_icon.setStyleSheet(
|
||||
f"background-color: {_MOCHA['green']}; border-radius: 6px;"
|
||||
)
|
||||
self._retry_btn.hide()
|
||||
self._browser_btn.show()
|
||||
else:
|
||||
self._status_icon.setStyleSheet(
|
||||
f"background-color: {_MOCHA['red']}; border-radius: 6px;"
|
||||
)
|
||||
self._retry_btn.show()
|
||||
self._browser_btn.hide()
|
||||
self._status_label.setText(message)
|
||||
|
||||
def _refresh_items(self):
|
||||
"""Fetch items from Silo API and populate the items list."""
|
||||
sc = self._silo()
|
||||
if sc is None:
|
||||
return
|
||||
|
||||
self._items_list.clear()
|
||||
search = self._search_field.text().strip()
|
||||
|
||||
try:
|
||||
if search:
|
||||
items = sc._client.list_items(search=search)
|
||||
else:
|
||||
items = sc._client.list_items()
|
||||
except Exception:
|
||||
item = QtWidgets.QListWidgetItem("(Unable to fetch items)")
|
||||
item.setFlags(QtCore.Qt.NoItemFlags)
|
||||
self._items_list.addItem(item)
|
||||
return
|
||||
|
||||
if not isinstance(items, list) or not items:
|
||||
item = QtWidgets.QListWidgetItem("(No items found)")
|
||||
item.setFlags(QtCore.Qt.NoItemFlags)
|
||||
self._items_list.addItem(item)
|
||||
return
|
||||
|
||||
# Collect local part numbers for badge
|
||||
local_pns = set()
|
||||
try:
|
||||
for lf in sc.search_local_files():
|
||||
local_pns.add(lf.get("part_number", ""))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for entry in items[:30]:
|
||||
pn = entry.get("part_number", "")
|
||||
desc = entry.get("description", "")
|
||||
rev = entry.get("current_revision", "")
|
||||
|
||||
desc_display = desc
|
||||
if len(desc_display) > 50:
|
||||
desc_display = desc_display[:47] + "..."
|
||||
|
||||
local_badge = " [local]" if pn in local_pns else ""
|
||||
rev_part = f" Rev {rev}" if rev else ""
|
||||
label = f"{pn} \u2014 {desc_display}{rev_part}{local_badge}"
|
||||
|
||||
list_item = QtWidgets.QListWidgetItem(label)
|
||||
list_item.setData(QtCore.Qt.UserRole, pn)
|
||||
if desc and len(desc) > 50:
|
||||
list_item.setToolTip(desc)
|
||||
if pn in local_pns:
|
||||
list_item.setForeground(QtGui.QColor(_MOCHA["green"]))
|
||||
self._items_list.addItem(list_item)
|
||||
|
||||
def _refresh_recent_files(self):
|
||||
"""Populate the recent files list."""
|
||||
self._file_list.clear()
|
||||
files = _get_recent_files()
|
||||
if not files:
|
||||
item = QtWidgets.QListWidgetItem("(No recent files)")
|
||||
item.setFlags(QtCore.Qt.NoItemFlags)
|
||||
self._file_list.addItem(item)
|
||||
return
|
||||
for f in files:
|
||||
label = f"{f['name']}\n{_relative_time(f['modified'])}"
|
||||
item = QtWidgets.QListWidgetItem(label)
|
||||
item.setData(QtCore.Qt.UserRole, f["path"])
|
||||
item.setToolTip(f["path"])
|
||||
self._file_list.addItem(item)
|
||||
|
||||
# -- SSE ----------------------------------------------------------------
|
||||
|
||||
def _start_sse(self):
|
||||
"""Connect to SSE for live activity updates."""
|
||||
sc = self._silo()
|
||||
if sc is None:
|
||||
return
|
||||
|
||||
if self._event_listener is not None:
|
||||
return # already running
|
||||
|
||||
try:
|
||||
self._event_listener = sc.SiloEventListener()
|
||||
self._event_listener.item_updated.connect(self._on_sse_item_updated)
|
||||
self._event_listener.revision_created.connect(self._on_sse_revision_created)
|
||||
self._event_listener.connection_status.connect(self._on_sse_status)
|
||||
self._event_listener.start()
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintLog(f"Silo Start: SSE listener failed to start: {e}\n")
|
||||
|
||||
def _stop_sse(self):
|
||||
"""Stop SSE listener when the view is destroyed."""
|
||||
if self._event_listener is not None:
|
||||
self._event_listener.stop()
|
||||
self._event_listener = None
|
||||
|
||||
def _on_sse_item_updated(self, part_number: str):
|
||||
self._add_activity_event(f"{part_number} updated")
|
||||
self._refresh_items()
|
||||
|
||||
def _on_sse_revision_created(self, part_number: str, revision: int):
|
||||
self._add_activity_event(f"{part_number} Rev {revision} created")
|
||||
self._refresh_items()
|
||||
|
||||
def _on_sse_status(self, status: str, retry: int, error: str):
|
||||
if status == "connected":
|
||||
FreeCAD.Console.PrintLog("Silo Start: SSE connected\n")
|
||||
elif status == "disconnected":
|
||||
FreeCAD.Console.PrintLog(f"Silo Start: SSE disconnected (retry {retry}): {error}\n")
|
||||
|
||||
def _add_activity_event(self, text: str):
|
||||
"""Add an event to the activity feed."""
|
||||
now = datetime.now()
|
||||
self._activity_events.insert(0, (now, text))
|
||||
self._activity_events = self._activity_events[:20]
|
||||
self._rebuild_activity_feed()
|
||||
|
||||
def _rebuild_activity_feed(self):
|
||||
"""Rebuild the activity list widget from stored events."""
|
||||
self._activity_list.clear()
|
||||
if not self._activity_events:
|
||||
item = QtWidgets.QListWidgetItem("(No recent activity)")
|
||||
item.setFlags(QtCore.Qt.NoItemFlags)
|
||||
self._activity_list.addItem(item)
|
||||
return
|
||||
for ts, text in self._activity_events:
|
||||
label = f"{text} \u00b7 {_relative_time(ts)}"
|
||||
self._activity_list.addItem(label)
|
||||
|
||||
# -- interaction --------------------------------------------------------
|
||||
|
||||
def _on_search_changed(self, _text: str):
|
||||
"""Debounce search input."""
|
||||
self._search_timer.start()
|
||||
|
||||
def _on_item_double_clicked(self, item: QtWidgets.QListWidgetItem):
|
||||
pn = item.data(QtCore.Qt.UserRole)
|
||||
if not pn:
|
||||
return
|
||||
sc = self._silo()
|
||||
if sc is None:
|
||||
return
|
||||
local_path = sc.find_file_by_part_number(pn)
|
||||
if local_path and local_path.exists():
|
||||
FreeCAD.openDocument(str(local_path))
|
||||
else:
|
||||
sc._sync.open_item(pn)
|
||||
|
||||
def _on_item_context_menu(self, pos):
|
||||
item = self._items_list.itemAt(pos)
|
||||
if item is None:
|
||||
return
|
||||
pn = item.data(QtCore.Qt.UserRole)
|
||||
if not pn:
|
||||
return
|
||||
|
||||
menu = QtWidgets.QMenu()
|
||||
open_action = menu.addAction("Open in Create")
|
||||
browser_action = menu.addAction("Open in Browser")
|
||||
copy_action = menu.addAction("Copy Part Number")
|
||||
|
||||
action = menu.exec_(self._items_list.mapToGlobal(pos))
|
||||
sc = self._silo()
|
||||
if action == open_action:
|
||||
if sc:
|
||||
local_path = sc.find_file_by_part_number(pn)
|
||||
if local_path and local_path.exists():
|
||||
FreeCAD.openDocument(str(local_path))
|
||||
else:
|
||||
sc._sync.open_item(pn)
|
||||
elif action == browser_action:
|
||||
url = f"{_get_silo_base_url()}/items/{pn}"
|
||||
QtGui.QDesktopServices.openUrl(QtCore.QUrl(url))
|
||||
elif action == copy_action:
|
||||
QtWidgets.QApplication.clipboard().setText(pn)
|
||||
|
||||
def _on_file_clicked(self, item: QtWidgets.QListWidgetItem):
|
||||
path = item.data(QtCore.Qt.UserRole)
|
||||
if path:
|
||||
try:
|
||||
FreeCADGui.open(path)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintError(f"Silo Start: failed to open {path}: {e}\n")
|
||||
|
||||
def _open_in_browser(self):
|
||||
"""Open Silo web UI in the system browser."""
|
||||
url = _get_silo_base_url()
|
||||
QtGui.QDesktopServices.openUrl(QtCore.QUrl(url))
|
||||
|
||||
@staticmethod
|
||||
def _on_startup_toggled(checked: bool):
|
||||
prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start")
|
||||
prefs.SetBool("ShowOnStartup", not checked)
|
||||
|
||||
# -- cleanup ------------------------------------------------------------
|
||||
|
||||
def closeEvent(self, event):
|
||||
self._stop_sse()
|
||||
self._poll_timer.stop()
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Command override
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _SiloStartCommand:
|
||||
"""Replacement for the C++ Start_Start command."""
|
||||
|
||||
def Activated(self):
|
||||
mw = FreeCADGui.getMainWindow()
|
||||
mdi = mw.findChild(QtWidgets.QMdiArea)
|
||||
if not mdi:
|
||||
return
|
||||
|
||||
# Reuse existing view if open
|
||||
for sw in mdi.subWindowList():
|
||||
if sw.widget() and sw.widget().objectName() == "SiloStartView":
|
||||
mdi.setActiveSubWindow(sw)
|
||||
sw.show()
|
||||
return
|
||||
|
||||
# Create new view as MDI subwindow
|
||||
view = SiloStartView()
|
||||
sw = mdi.addSubWindow(view)
|
||||
sw.setWindowTitle("Start")
|
||||
sw.setWindowIcon(QtGui.QIcon(":/icons/StartCommandIcon.svg"))
|
||||
sw.show()
|
||||
mdi.setActiveSubWindow(sw)
|
||||
|
||||
def GetResources(self):
|
||||
return {
|
||||
"MenuText": "&Start Page",
|
||||
"ToolTip": "Displays the start page",
|
||||
"Pixmap": "StartCommandIcon",
|
||||
}
|
||||
|
||||
def IsActive(self):
|
||||
return True
|
||||
|
||||
|
||||
def register():
|
||||
"""Override the Start_Start command with the Silo start page.
|
||||
|
||||
Call this from InitGui.py at module level so the override is in
|
||||
place before the C++ StartLauncher fires (100ms after GUI init).
|
||||
"""
|
||||
try:
|
||||
FreeCADGui.addCommand("Start_Start", _SiloStartCommand())
|
||||
FreeCAD.Console.PrintMessage("Silo Start: registered start page override\n")
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Silo Start: failed to register override: {e}\n")
|
||||
167
freecad/templates.py
Normal file
167
freecad/templates.py
Normal file
@@ -0,0 +1,167 @@
|
||||
"""Template discovery and metadata for Kindred Create .kc templates.
|
||||
|
||||
A template is a normal ``.kc`` file that contains a ``silo/template.json``
|
||||
descriptor inside the ZIP archive. This module scans known directories for
|
||||
template files, parses their descriptors, and provides filtering helpers
|
||||
used by the schema form UI.
|
||||
|
||||
Search paths (checked in order, later shadows earlier by name):
|
||||
1. ``{silo_addon}/templates/`` — system templates shipped with the addon
|
||||
2. ``{userAppData}/Templates/`` — personal templates (sister to Macro/)
|
||||
3. ``~/projects/templates/`` — org-shared project templates
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import zipfile
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class TemplateInfo:
|
||||
"""Parsed template descriptor from ``silo/template.json``."""
|
||||
|
||||
path: str # Absolute path to the .kc file
|
||||
name: str = ""
|
||||
description: str = ""
|
||||
item_types: List[str] = field(default_factory=list)
|
||||
categories: List[str] = field(default_factory=list)
|
||||
icon: str = ""
|
||||
author: str = ""
|
||||
tags: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def read_template_info(kc_path: str) -> Optional[TemplateInfo]:
|
||||
"""Read ``silo/template.json`` from a ``.kc`` file.
|
||||
|
||||
Returns a :class:`TemplateInfo` if the file is a valid template,
|
||||
or ``None`` if the file does not contain a template descriptor.
|
||||
"""
|
||||
try:
|
||||
with zipfile.ZipFile(kc_path, "r") as zf:
|
||||
if "silo/template.json" not in zf.namelist():
|
||||
return None
|
||||
raw = zf.read("silo/template.json")
|
||||
data = json.loads(raw)
|
||||
return TemplateInfo(
|
||||
path=str(kc_path),
|
||||
name=data.get("name", Path(kc_path).stem),
|
||||
description=data.get("description", ""),
|
||||
item_types=data.get("item_types", []),
|
||||
categories=data.get("categories", []),
|
||||
icon=data.get("icon", ""),
|
||||
author=data.get("author", ""),
|
||||
tags=data.get("tags", []),
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def inject_template_json(kc_path: str, template_info: dict) -> bool:
|
||||
"""Inject ``silo/template.json`` into a ``.kc`` (ZIP) file.
|
||||
|
||||
Rewrites the ZIP to avoid duplicate entries. Returns ``True`` on
|
||||
success, raises on I/O errors.
|
||||
"""
|
||||
if not os.path.isfile(kc_path):
|
||||
return False
|
||||
|
||||
payload = json.dumps(template_info, indent=2).encode("utf-8")
|
||||
|
||||
tmp_fd, tmp_path = tempfile.mkstemp(suffix=".kc")
|
||||
os.close(tmp_fd)
|
||||
try:
|
||||
with zipfile.ZipFile(kc_path, "r") as zin:
|
||||
with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zout:
|
||||
for item in zin.infolist():
|
||||
if item.filename == "silo/template.json":
|
||||
continue
|
||||
zout.writestr(item, zin.read(item.filename))
|
||||
zout.writestr("silo/template.json", payload)
|
||||
shutil.move(tmp_path, kc_path)
|
||||
return True
|
||||
except Exception:
|
||||
if os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
raise
|
||||
|
||||
|
||||
def get_default_template_dir() -> str:
|
||||
"""Return the user templates directory, creating it if needed.
|
||||
|
||||
Located at ``{userAppData}/Templates/``, a sister to ``Macro/``.
|
||||
"""
|
||||
import FreeCAD
|
||||
|
||||
d = os.path.join(FreeCAD.getUserAppDataDir(), "Templates")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def discover_templates(search_paths: List[str]) -> List[TemplateInfo]:
|
||||
"""Scan search paths for ``.kc`` files containing ``silo/template.json``.
|
||||
|
||||
Later paths shadow earlier paths by template name.
|
||||
"""
|
||||
by_name = {}
|
||||
for search_dir in search_paths:
|
||||
if not os.path.isdir(search_dir):
|
||||
continue
|
||||
for filename in sorted(os.listdir(search_dir)):
|
||||
if not filename.lower().endswith(".kc"):
|
||||
continue
|
||||
full_path = os.path.join(search_dir, filename)
|
||||
info = read_template_info(full_path)
|
||||
if info is not None:
|
||||
by_name[info.name] = info
|
||||
return sorted(by_name.values(), key=lambda t: t.name)
|
||||
|
||||
|
||||
def get_search_paths() -> List[str]:
|
||||
"""Return the ordered list of template search directories."""
|
||||
paths = []
|
||||
|
||||
# 1. System templates (shipped with the silo addon)
|
||||
system_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
|
||||
paths.append(system_dir)
|
||||
|
||||
# 2. User app-data templates (personal, sister to Macro/)
|
||||
try:
|
||||
import FreeCAD
|
||||
|
||||
user_app_templates = os.path.join(FreeCAD.getUserAppDataDir(), "Templates")
|
||||
paths.append(user_app_templates)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3. Shared project templates
|
||||
try:
|
||||
from silo_commands import get_projects_dir
|
||||
|
||||
user_dir = str(get_projects_dir() / "templates")
|
||||
paths.append(user_dir)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return paths
|
||||
|
||||
|
||||
def filter_templates(
|
||||
templates: List[TemplateInfo],
|
||||
item_type: str = "",
|
||||
category: str = "",
|
||||
) -> List[TemplateInfo]:
|
||||
"""Filter templates by item type and category prefix."""
|
||||
result = []
|
||||
for t in templates:
|
||||
if item_type and t.item_types and item_type not in t.item_types:
|
||||
continue
|
||||
if category and t.categories:
|
||||
if not any(category.startswith(prefix) for prefix in t.categories):
|
||||
continue
|
||||
result.append(t)
|
||||
return result
|
||||
78
freecad/templates/inject_template.py
Normal file
78
freecad/templates/inject_template.py
Normal file
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject silo/template.json into a .kc file to make it a template.
|
||||
|
||||
Usage:
|
||||
python inject_template.py <kc_file> <name> [--type part|assembly] [--description "..."]
|
||||
|
||||
Examples:
|
||||
python inject_template.py part.kc "Part (Generic)" --type part
|
||||
python inject_template.py sheet-metal-part.kc "Sheet Metal Part" --type part \
|
||||
--description "Body with SheetMetal base feature and laser-cut job"
|
||||
python inject_template.py assembly.kc "Assembly" --type assembly
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Allow importing from the parent freecad/ directory when run standalone
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from templates import inject_template_json
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Inject template metadata into a .kc file"
|
||||
)
|
||||
parser.add_argument("kc_file", help="Path to the .kc file")
|
||||
parser.add_argument("name", help="Template display name")
|
||||
parser.add_argument(
|
||||
"--type",
|
||||
dest="item_types",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Item type filter (part, assembly). Can be repeated.",
|
||||
)
|
||||
parser.add_argument("--description", default="", help="Template description")
|
||||
parser.add_argument("--icon", default="", help="Icon identifier")
|
||||
parser.add_argument("--author", default="Kindred Systems", help="Author name")
|
||||
parser.add_argument(
|
||||
"--category",
|
||||
dest="categories",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Category prefix filter. Can be repeated. Empty = all.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tag",
|
||||
dest="tags",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Searchable tags. Can be repeated.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.item_types:
|
||||
args.item_types = ["part"]
|
||||
|
||||
template_info = {
|
||||
"template_version": "1.0",
|
||||
"name": args.name,
|
||||
"description": args.description,
|
||||
"item_types": args.item_types,
|
||||
"categories": args.categories,
|
||||
"icon": args.icon,
|
||||
"author": args.author,
|
||||
"tags": args.tags,
|
||||
}
|
||||
|
||||
if inject_template_json(args.kc_file, template_info):
|
||||
print(f"Injected silo/template.json into {args.kc_file}")
|
||||
print(json.dumps(template_info, indent=2))
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
25
package.xml
Normal file
25
package.xml
Normal file
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<package format="1" xmlns="https://wiki.freecad.org/Package_Metadata">
|
||||
<name>silo</name>
|
||||
<description>PLM workbench for Kindred Create</description>
|
||||
<version>0.1.0</version>
|
||||
<maintainer email="development@kindred-systems.com">Kindred Systems</maintainer>
|
||||
<license file="LICENSE">MIT</license>
|
||||
<url type="repository">https://git.kindred-systems.com/kindred/silo-mod</url>
|
||||
|
||||
<content>
|
||||
<workbench>
|
||||
<classname>SiloWorkbench</classname>
|
||||
<subdirectory>freecad</subdirectory>
|
||||
</workbench>
|
||||
</content>
|
||||
|
||||
<kindred>
|
||||
<min_create_version>0.1.0</min_create_version>
|
||||
<load_priority>60</load_priority>
|
||||
<pure_python>true</pure_python>
|
||||
<dependencies>
|
||||
<dependency>sdk</dependency>
|
||||
</dependencies>
|
||||
</kindred>
|
||||
</package>
|
||||
Submodule silo-client updated: a6ac3d4d06...5dfb567bac
Reference in New Issue
Block a user