Compare commits
21 Commits
fix/auth-p
...
9187622239
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9187622239 | ||
| 63a6da8b6c | |||
|
|
a88e104d94 | ||
|
|
7dc157894f | ||
| 43e905c00a | |||
|
|
f67d9a0422 | ||
| af98994a53 | |||
|
|
d266bfb653 | ||
| a92174e0b9 | |||
|
|
edbaf65923 | ||
| 80f8ec27a0 | |||
|
|
6b3e8b7518 | ||
| b3fe98c696 | |||
|
|
c537e2f08f | ||
| 29b1f32fd9 | |||
| dca6380199 | |||
| 27f0cc0f34 | |||
| a5eff534b5 | |||
|
|
1001424b16 | ||
| 7e3127498a | |||
| 82d8741059 |
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)
|
||||||
@@ -57,6 +57,7 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
|||||||
"Silo_TagProjects",
|
"Silo_TagProjects",
|
||||||
"Silo_SetStatus",
|
"Silo_SetStatus",
|
||||||
"Silo_Rollback",
|
"Silo_Rollback",
|
||||||
|
"Silo_SaveAsTemplate",
|
||||||
"Separator",
|
"Separator",
|
||||||
"Silo_Settings",
|
"Silo_Settings",
|
||||||
"Silo_Auth",
|
"Silo_Auth",
|
||||||
@@ -106,7 +107,9 @@ def _register_silo_overlay():
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
FreeCADGui.registerEditingOverlay(
|
from kindred_sdk import register_overlay
|
||||||
|
|
||||||
|
register_overlay(
|
||||||
"silo", # overlay id
|
"silo", # overlay id
|
||||||
["Silo Origin"], # toolbar names to append
|
["Silo Origin"], # toolbar names to append
|
||||||
_silo_overlay_match, # match function
|
_silo_overlay_match, # match function
|
||||||
|
|||||||
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
|
||||||
@@ -12,4 +12,17 @@
|
|||||||
<subdirectory>./</subdirectory>
|
<subdirectory>./</subdirectory>
|
||||||
</workbench>
|
</workbench>
|
||||||
</content>
|
</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>
|
</package>
|
||||||
|
|||||||
@@ -10,9 +10,6 @@ backward-compatible :class:`SchemaFormDialog` modal.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import urllib.error
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
import FreeCAD
|
import FreeCAD
|
||||||
from PySide import QtCore, QtGui, QtWidgets
|
from PySide import QtCore, QtGui, QtWidgets
|
||||||
@@ -237,9 +234,11 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
self._prop_groups = [] # list of _CollapsibleGroup to clear on category change
|
self._prop_groups = [] # list of _CollapsibleGroup to clear on category change
|
||||||
self._categories = {}
|
self._categories = {}
|
||||||
self._projects = []
|
self._projects = []
|
||||||
|
self._templates = [] # List[TemplateInfo]
|
||||||
|
|
||||||
self._load_schema_data()
|
self._load_schema_data()
|
||||||
self._build_ui()
|
self._build_ui()
|
||||||
|
self._update_template_combo()
|
||||||
|
|
||||||
# Part number preview debounce timer
|
# Part number preview debounce timer
|
||||||
self._pn_timer = QtCore.QTimer(self)
|
self._pn_timer = QtCore.QTimer(self)
|
||||||
@@ -254,7 +253,9 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
try:
|
try:
|
||||||
schema = self._client.get_schema()
|
schema = self._client.get_schema()
|
||||||
segments = schema.get("segments", [])
|
segments = schema.get("segments", [])
|
||||||
cat_segment = next((s for s in segments if s.get("name") == "category"), None)
|
cat_segment = next(
|
||||||
|
(s for s in segments if s.get("name") == "category"), None
|
||||||
|
)
|
||||||
if cat_segment and cat_segment.get("values"):
|
if cat_segment and cat_segment.get("values"):
|
||||||
self._categories = cat_segment["values"]
|
self._categories = cat_segment["values"]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -265,19 +266,20 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
except Exception:
|
except Exception:
|
||||||
self._projects = []
|
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:
|
def _fetch_properties(self, category: str) -> dict:
|
||||||
"""Fetch merged property definitions for a category."""
|
"""Fetch merged property definitions for a category."""
|
||||||
from silo_commands import _get_api_url, _get_auth_headers, _get_ssl_context
|
|
||||||
|
|
||||||
api_url = _get_api_url().rstrip("/")
|
|
||||||
url = f"{api_url}/schemas/kindred-rd/properties?category={urllib.parse.quote(category)}"
|
|
||||||
req = urllib.request.Request(url, method="GET")
|
|
||||||
req.add_header("Accept", "application/json")
|
|
||||||
for k, v in _get_auth_headers().items():
|
|
||||||
req.add_header(k, v)
|
|
||||||
try:
|
try:
|
||||||
resp = urllib.request.urlopen(req, context=_get_ssl_context(), timeout=5)
|
data = self._client.get_property_schema(category=category)
|
||||||
data = json.loads(resp.read().decode("utf-8"))
|
|
||||||
return data.get("properties", data)
|
return data.get("properties", data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
FreeCAD.Console.PrintWarning(
|
FreeCAD.Console.PrintWarning(
|
||||||
@@ -287,19 +289,10 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
|
|
||||||
def _generate_pn_preview(self, category: str) -> str:
|
def _generate_pn_preview(self, category: str) -> str:
|
||||||
"""Call the server to preview the next part number."""
|
"""Call the server to preview the next part number."""
|
||||||
from silo_commands import _get_api_url, _get_auth_headers, _get_ssl_context
|
from silo_commands import _get_schema_name
|
||||||
|
|
||||||
api_url = _get_api_url().rstrip("/")
|
|
||||||
url = f"{api_url}/generate-part-number"
|
|
||||||
payload = json.dumps({"schema": "kindred-rd", "category": category}).encode()
|
|
||||||
req = urllib.request.Request(url, data=payload, method="POST")
|
|
||||||
req.add_header("Content-Type", "application/json")
|
|
||||||
req.add_header("Accept", "application/json")
|
|
||||||
for k, v in _get_auth_headers().items():
|
|
||||||
req.add_header(k, v)
|
|
||||||
try:
|
try:
|
||||||
resp = urllib.request.urlopen(req, context=_get_ssl_context(), timeout=5)
|
data = self._client.generate_part_number(_get_schema_name(), category)
|
||||||
data = json.loads(resp.read().decode("utf-8"))
|
|
||||||
return data.get("part_number", "")
|
return data.get("part_number", "")
|
||||||
except Exception:
|
except Exception:
|
||||||
return ""
|
return ""
|
||||||
@@ -322,7 +315,9 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
|
|
||||||
# Part number preview banner
|
# Part number preview banner
|
||||||
self._pn_label = QtWidgets.QLabel("Part Number: \u2014")
|
self._pn_label = QtWidgets.QLabel("Part Number: \u2014")
|
||||||
self._pn_label.setStyleSheet("font-size: 16px; font-weight: bold; padding: 8px;")
|
self._pn_label.setStyleSheet(
|
||||||
|
"font-size: 16px; font-weight: bold; padding: 8px;"
|
||||||
|
)
|
||||||
self._pn_label.setAlignment(QtCore.Qt.AlignCenter)
|
self._pn_label.setAlignment(QtCore.Qt.AlignCenter)
|
||||||
root.addWidget(self._pn_label)
|
root.addWidget(self._pn_label)
|
||||||
|
|
||||||
@@ -344,8 +339,15 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
self._type_combo = QtWidgets.QComboBox()
|
self._type_combo = QtWidgets.QComboBox()
|
||||||
for t in _ITEM_TYPES:
|
for t in _ITEM_TYPES:
|
||||||
self._type_combo.addItem(t.capitalize(), t)
|
self._type_combo.addItem(t.capitalize(), t)
|
||||||
|
self._type_combo.currentIndexChanged.connect(
|
||||||
|
lambda _: self._update_template_combo()
|
||||||
|
)
|
||||||
fl.addRow("Type:", self._type_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 = QtWidgets.QLineEdit()
|
||||||
self._desc_edit.setPlaceholderText("Item description")
|
self._desc_edit.setPlaceholderText("Item description")
|
||||||
fl.addRow("Description:", self._desc_edit)
|
fl.addRow("Description:", self._desc_edit)
|
||||||
@@ -425,11 +427,25 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
|
|
||||||
root.addLayout(btn_layout)
|
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 ----------------------------------------------------
|
# -- category change ----------------------------------------------------
|
||||||
|
|
||||||
def _on_category_changed(self, category: str):
|
def _on_category_changed(self, category: str):
|
||||||
"""Rebuild property groups when category selection changes."""
|
"""Rebuild property groups when category selection changes."""
|
||||||
self._create_btn.setEnabled(bool(category))
|
self._create_btn.setEnabled(bool(category))
|
||||||
|
self._update_template_combo()
|
||||||
|
|
||||||
# Remove old property groups
|
# Remove old property groups
|
||||||
for group in self._prop_groups:
|
for group in self._prop_groups:
|
||||||
@@ -561,6 +577,7 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
"long_description": long_description,
|
"long_description": long_description,
|
||||||
"projects": selected_projects if selected_projects else None,
|
"projects": selected_projects if selected_projects else None,
|
||||||
"properties": properties if properties else None,
|
"properties": properties if properties else None,
|
||||||
|
"template_path": self._template_combo.currentData(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def _on_create(self):
|
def _on_create(self):
|
||||||
@@ -574,8 +591,10 @@ class SchemaFormWidget(QtWidgets.QWidget):
|
|||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
from silo_commands import _get_schema_name
|
||||||
|
|
||||||
result = self._client.create_item(
|
result = self._client.create_item(
|
||||||
"kindred-rd",
|
_get_schema_name(),
|
||||||
data["category"],
|
data["category"],
|
||||||
data["description"],
|
data["description"],
|
||||||
projects=data["projects"],
|
projects=data["projects"],
|
||||||
|
|||||||
@@ -14,14 +14,7 @@ from typing import Any, Dict, List, Optional, Tuple
|
|||||||
import FreeCAD
|
import FreeCAD
|
||||||
import FreeCADGui
|
import FreeCADGui
|
||||||
from PySide import QtCore
|
from PySide import QtCore
|
||||||
from silo_client import (
|
from silo_client import SiloClient, SiloSettings
|
||||||
CATEGORY_NAMES,
|
|
||||||
SiloClient,
|
|
||||||
SiloSettings,
|
|
||||||
get_category_folder_name,
|
|
||||||
parse_part_number,
|
|
||||||
sanitize_filename,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Preference group for Kindred Silo settings
|
# Preference group for Kindred Silo settings
|
||||||
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
||||||
@@ -32,6 +25,27 @@ SILO_PROJECTS_DIR = os.environ.get(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Local utility helpers (previously in silo_client, now server-driven)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_part_number(part_number: str) -> Tuple[str, str]:
|
||||||
|
"""Parse part number into ``(category, sequence)``. E.g. ``"F01-0001"`` -> ``("F01", "0001")``."""
|
||||||
|
parts = part_number.split("-")
|
||||||
|
if len(parts) >= 2:
|
||||||
|
return parts[0], parts[1]
|
||||||
|
return part_number, ""
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_filename(name: str) -> str:
|
||||||
|
"""Sanitize a string for use in filenames."""
|
||||||
|
sanitized = re.sub(r'[<>:"/\\|?*]', "_", name)
|
||||||
|
sanitized = re.sub(r"[\s_]+", "_", sanitized)
|
||||||
|
sanitized = sanitized.strip("_ ")
|
||||||
|
return sanitized[:50]
|
||||||
|
|
||||||
|
|
||||||
def _relative_time(dt):
|
def _relative_time(dt):
|
||||||
"""Format a datetime as a human-friendly relative string."""
|
"""Format a datetime as a human-friendly relative string."""
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
@@ -96,6 +110,13 @@ class FreeCADSiloSettings(SiloSettings):
|
|||||||
if token:
|
if token:
|
||||||
param.SetString("ApiToken", token)
|
param.SetString("ApiToken", token)
|
||||||
|
|
||||||
|
def get_schema_name(self) -> str:
|
||||||
|
param = FreeCAD.ParamGet(_PREF_GROUP)
|
||||||
|
name = param.GetString("SchemaName", "")
|
||||||
|
if not name:
|
||||||
|
name = os.environ.get("SILO_SCHEMA", "kindred-rd")
|
||||||
|
return name
|
||||||
|
|
||||||
def clear_auth(self):
|
def clear_auth(self):
|
||||||
param = FreeCAD.ParamGet(_PREF_GROUP)
|
param = FreeCAD.ParamGet(_PREF_GROUP)
|
||||||
param.SetString("ApiToken", "")
|
param.SetString("ApiToken", "")
|
||||||
@@ -139,6 +160,10 @@ def _get_api_url() -> str:
|
|||||||
return _fc_settings.get_api_url()
|
return _fc_settings.get_api_url()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_schema_name() -> str:
|
||||||
|
return _fc_settings.get_schema_name()
|
||||||
|
|
||||||
|
|
||||||
def _get_ssl_verify() -> bool:
|
def _get_ssl_verify() -> bool:
|
||||||
return _fc_settings.get_ssl_verify()
|
return _fc_settings.get_ssl_verify()
|
||||||
|
|
||||||
@@ -172,13 +197,13 @@ def _clear_auth():
|
|||||||
# Server mode tracking
|
# Server mode tracking
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
_server_mode = "offline" # "normal" | "read-only" | "degraded" | "offline"
|
_server_mode = "offline" # "normal" | "read-only" | "offline"
|
||||||
|
|
||||||
|
|
||||||
def _fetch_server_mode() -> str:
|
def _fetch_server_mode() -> str:
|
||||||
"""Fetch server mode from the /ready endpoint.
|
"""Fetch server mode from the /ready endpoint.
|
||||||
|
|
||||||
Returns one of: "normal", "read-only", "degraded", "offline".
|
Returns one of: "normal", "read-only", "offline".
|
||||||
"""
|
"""
|
||||||
api_url = _get_api_url().rstrip("/")
|
api_url = _get_api_url().rstrip("/")
|
||||||
base_url = api_url[:-4] if api_url.endswith("/api") else api_url
|
base_url = api_url[:-4] if api_url.endswith("/api") else api_url
|
||||||
@@ -193,8 +218,6 @@ def _fetch_server_mode() -> str:
|
|||||||
return "normal"
|
return "normal"
|
||||||
if status in ("read-only", "read_only", "readonly"):
|
if status in ("read-only", "read_only", "readonly"):
|
||||||
return "read-only"
|
return "read-only"
|
||||||
if status in ("degraded",):
|
|
||||||
return "degraded"
|
|
||||||
# Unknown status but server responded — treat as normal
|
# Unknown status but server responded — treat as normal
|
||||||
return "normal"
|
return "normal"
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -234,24 +257,22 @@ def get_projects_dir() -> Path:
|
|||||||
def get_cad_file_path(part_number: str, description: str = "") -> Path:
|
def get_cad_file_path(part_number: str, description: str = "") -> Path:
|
||||||
"""Generate canonical file path for a CAD file.
|
"""Generate canonical file path for a CAD file.
|
||||||
|
|
||||||
Path format: ~/projects/cad/{category_code}_{category_name}/{part_number}_{description}.kc
|
Path format: ~/projects/cad/{category_code}/{part_number}_{description}.kc
|
||||||
"""
|
"""
|
||||||
category, _ = parse_part_number(part_number)
|
category, _ = _parse_part_number(part_number)
|
||||||
folder_name = get_category_folder_name(category)
|
|
||||||
|
|
||||||
if description:
|
if description:
|
||||||
filename = f"{part_number}_{sanitize_filename(description)}.kc"
|
filename = f"{part_number}_{_sanitize_filename(description)}.kc"
|
||||||
else:
|
else:
|
||||||
filename = f"{part_number}.kc"
|
filename = f"{part_number}.kc"
|
||||||
|
|
||||||
return get_projects_dir() / "cad" / folder_name / filename
|
return get_projects_dir() / "cad" / category / filename
|
||||||
|
|
||||||
|
|
||||||
def find_file_by_part_number(part_number: str) -> Optional[Path]:
|
def find_file_by_part_number(part_number: str) -> Optional[Path]:
|
||||||
"""Find existing CAD file for a part number. Prefers .kc over .FCStd."""
|
"""Find existing CAD file for a part number. Prefers .kc over .FCStd."""
|
||||||
category, _ = parse_part_number(part_number)
|
category, _ = _parse_part_number(part_number)
|
||||||
folder_name = get_category_folder_name(category)
|
cad_dir = get_projects_dir() / "cad" / category
|
||||||
cad_dir = get_projects_dir() / "cad" / folder_name
|
|
||||||
|
|
||||||
for search_dir in _search_dirs(cad_dir):
|
for search_dir in _search_dirs(cad_dir):
|
||||||
for ext in ("*.kc", "*.FCStd"):
|
for ext in ("*.kc", "*.FCStd"):
|
||||||
@@ -516,7 +537,7 @@ class SiloSync:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Add a Body for parts (not assemblies)
|
# Add a Body for parts (not assemblies)
|
||||||
body_label = sanitize_filename(description) if description else "Body"
|
body_label = _sanitize_filename(description) if description else "Body"
|
||||||
body = doc.addObject("PartDesign::Body", "_" + body_label)
|
body = doc.addObject("PartDesign::Body", "_" + body_label)
|
||||||
body.Label = body_label
|
body.Label = body_label
|
||||||
part_obj.addObject(body)
|
part_obj.addObject(body)
|
||||||
@@ -530,6 +551,86 @@ class SiloSync:
|
|||||||
|
|
||||||
return doc
|
return doc
|
||||||
|
|
||||||
|
def create_document_from_template(
|
||||||
|
self, item: Dict[str, Any], template_path: str, save: bool = True
|
||||||
|
):
|
||||||
|
"""Create a new document by copying a template .kc and stamping Silo properties.
|
||||||
|
|
||||||
|
Falls back to :meth:`create_document_for_item` if *template_path*
|
||||||
|
is missing or invalid.
|
||||||
|
"""
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
part_number = item.get("part_number", "")
|
||||||
|
description = item.get("description", "")
|
||||||
|
item_type = item.get("item_type", "part")
|
||||||
|
|
||||||
|
if not part_number or not os.path.isfile(template_path):
|
||||||
|
return self.create_document_for_item(item, save=save)
|
||||||
|
|
||||||
|
dest_path = get_cad_file_path(part_number, description)
|
||||||
|
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
shutil.copy2(template_path, str(dest_path))
|
||||||
|
self._clean_template_zip(str(dest_path))
|
||||||
|
|
||||||
|
doc = FreeCAD.openDocument(str(dest_path))
|
||||||
|
if not doc:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Find the root container (first App::Part or Assembly)
|
||||||
|
root_obj = None
|
||||||
|
for obj in doc.Objects:
|
||||||
|
if obj.TypeId in ("App::Part", "Assembly::AssemblyObject"):
|
||||||
|
root_obj = obj
|
||||||
|
break
|
||||||
|
if root_obj is None and doc.Objects:
|
||||||
|
root_obj = doc.Objects[0]
|
||||||
|
|
||||||
|
if root_obj:
|
||||||
|
root_obj.Label = part_number
|
||||||
|
set_silo_properties(
|
||||||
|
root_obj,
|
||||||
|
{
|
||||||
|
"SiloItemId": item.get("id", ""),
|
||||||
|
"SiloPartNumber": part_number,
|
||||||
|
"SiloRevision": item.get("current_revision", 1),
|
||||||
|
"SiloItemType": item_type,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.recompute()
|
||||||
|
|
||||||
|
if save:
|
||||||
|
doc.save()
|
||||||
|
|
||||||
|
return doc
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _clean_template_zip(filepath: str):
|
||||||
|
"""Strip ``silo/template.json`` and ``silo/manifest.json`` from a copied template.
|
||||||
|
|
||||||
|
The manifest is auto-recreated by ``kc_format.py`` on next save.
|
||||||
|
"""
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
tmp_path = filepath + ".tmp"
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(filepath, "r") as zf_in:
|
||||||
|
with zipfile.ZipFile(tmp_path, "w") as zf_out:
|
||||||
|
for entry in zf_in.infolist():
|
||||||
|
if entry.filename in (
|
||||||
|
"silo/template.json",
|
||||||
|
"silo/manifest.json",
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
zf_out.writestr(entry, zf_in.read(entry.filename))
|
||||||
|
os.replace(tmp_path, filepath)
|
||||||
|
except Exception as exc:
|
||||||
|
if os.path.exists(tmp_path):
|
||||||
|
os.unlink(tmp_path)
|
||||||
|
FreeCAD.Console.PrintWarning(f"Failed to clean template ZIP: {exc}\n")
|
||||||
|
|
||||||
def open_item(self, part_number: str):
|
def open_item(self, part_number: str):
|
||||||
"""Open or create item document."""
|
"""Open or create item document."""
|
||||||
existing_path = find_file_by_part_number(part_number)
|
existing_path = find_file_by_part_number(part_number)
|
||||||
@@ -547,7 +648,7 @@ class SiloSync:
|
|||||||
def upload_file(
|
def upload_file(
|
||||||
self, part_number: str, file_path: str, comment: str = "Auto-save"
|
self, part_number: str, file_path: str, comment: str = "Auto-save"
|
||||||
) -> Optional[Dict]:
|
) -> Optional[Dict]:
|
||||||
"""Upload file to MinIO."""
|
"""Upload file to the server."""
|
||||||
try:
|
try:
|
||||||
doc = FreeCAD.openDocument(file_path)
|
doc = FreeCAD.openDocument(file_path)
|
||||||
if not doc:
|
if not doc:
|
||||||
@@ -561,7 +662,7 @@ class SiloSync:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def download_file(self, part_number: str) -> Optional[Path]:
|
def download_file(self, part_number: str) -> Optional[Path]:
|
||||||
"""Download latest file from MinIO."""
|
"""Download the latest revision file from the server."""
|
||||||
try:
|
try:
|
||||||
item = self.client.get_item(part_number)
|
item = self.client.get_item(part_number)
|
||||||
file_path = get_cad_file_path(part_number, item.get("description", ""))
|
file_path = get_cad_file_path(part_number, item.get("description", ""))
|
||||||
@@ -721,7 +822,13 @@ class Silo_New:
|
|||||||
FreeCAD.ActiveDocument, force_rename=True
|
FreeCAD.ActiveDocument, force_rename=True
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
_sync.create_document_for_item(result, save=True)
|
template_path = result.get("_form_data", {}).get("template_path")
|
||||||
|
if template_path:
|
||||||
|
_sync.create_document_from_template(
|
||||||
|
result, template_path, save=True
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
_sync.create_document_for_item(result, save=True)
|
||||||
|
|
||||||
FreeCAD.Console.PrintMessage(f"Created: {part_number}\n")
|
FreeCAD.Console.PrintMessage(f"Created: {part_number}\n")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -759,13 +866,67 @@ def _push_dag_after_upload(doc, part_number, revision_number):
|
|||||||
FreeCAD.Console.PrintWarning(f"DAG sync failed: {e}\n")
|
FreeCAD.Console.PrintWarning(f"DAG sync failed: {e}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def _update_manifest_revision(file_path, revision_number):
|
||||||
|
"""Write revision_hash into the .kc manifest after a successful upload.
|
||||||
|
|
||||||
|
Failures are logged as warnings -- must never block save.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from kc_format import update_manifest_fields
|
||||||
|
|
||||||
|
update_manifest_fields(
|
||||||
|
file_path,
|
||||||
|
{
|
||||||
|
"revision_hash": str(revision_number),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
FreeCAD.Console.PrintWarning(f"Manifest revision update failed: {e}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def _push_bom_after_upload(doc, part_number, revision_number):
|
||||||
|
"""Extract and sync Assembly BOM after a successful upload.
|
||||||
|
|
||||||
|
Only runs for Assembly documents with cross-document links.
|
||||||
|
Failures are logged as warnings -- BOM sync must never block save.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from bom_sync import sync_bom_after_upload
|
||||||
|
|
||||||
|
result = sync_bom_after_upload(doc, part_number, _client)
|
||||||
|
if result is None:
|
||||||
|
return # Not an assembly or no cross-doc links
|
||||||
|
|
||||||
|
parts = []
|
||||||
|
if result.added_count:
|
||||||
|
parts.append(f"+{result.added_count} added")
|
||||||
|
if result.updated_count:
|
||||||
|
parts.append(f"~{result.updated_count} qty updated")
|
||||||
|
if result.unreferenced_count:
|
||||||
|
parts.append(f"!{result.unreferenced_count} unreferenced")
|
||||||
|
if result.unresolved_count:
|
||||||
|
FreeCAD.Console.PrintWarning(
|
||||||
|
f"BOM sync: {result.unresolved_count} components "
|
||||||
|
f"have no Silo part number\n"
|
||||||
|
)
|
||||||
|
if parts:
|
||||||
|
FreeCAD.Console.PrintMessage(f"BOM synced: {', '.join(parts)}\n")
|
||||||
|
else:
|
||||||
|
FreeCAD.Console.PrintMessage("BOM synced: no changes\n")
|
||||||
|
|
||||||
|
for err in result.errors:
|
||||||
|
FreeCAD.Console.PrintWarning(f"BOM sync error: {err}\n")
|
||||||
|
except Exception as e:
|
||||||
|
FreeCAD.Console.PrintWarning(f"BOM sync failed: {e}\n")
|
||||||
|
|
||||||
|
|
||||||
class Silo_Save:
|
class Silo_Save:
|
||||||
"""Save locally and upload to MinIO."""
|
"""Save locally and upload to the server."""
|
||||||
|
|
||||||
def GetResources(self):
|
def GetResources(self):
|
||||||
return {
|
return {
|
||||||
"MenuText": "Save",
|
"MenuText": "Save",
|
||||||
"ToolTip": "Save locally and upload to MinIO (Ctrl+S)",
|
"ToolTip": "Save locally and upload to server (Ctrl+S)",
|
||||||
"Pixmap": _icon("save"),
|
"Pixmap": _icon("save"),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -820,7 +981,7 @@ class Silo_Save:
|
|||||||
|
|
||||||
FreeCAD.Console.PrintMessage(f"Saved: {file_path}\n")
|
FreeCAD.Console.PrintMessage(f"Saved: {file_path}\n")
|
||||||
|
|
||||||
# Try to upload to MinIO
|
# Try to upload to server
|
||||||
try:
|
try:
|
||||||
result = _client._upload_file(
|
result = _client._upload_file(
|
||||||
part_number, str(file_path), properties, "Auto-save"
|
part_number, str(file_path), properties, "Auto-save"
|
||||||
@@ -830,6 +991,8 @@ class Silo_Save:
|
|||||||
FreeCAD.Console.PrintMessage(f"Uploaded as revision {new_rev}\n")
|
FreeCAD.Console.PrintMessage(f"Uploaded as revision {new_rev}\n")
|
||||||
|
|
||||||
_push_dag_after_upload(doc, part_number, new_rev)
|
_push_dag_after_upload(doc, part_number, new_rev)
|
||||||
|
_push_bom_after_upload(doc, part_number, new_rev)
|
||||||
|
_update_manifest_revision(str(file_path), new_rev)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
FreeCAD.Console.PrintWarning(f"Upload failed: {e}\n")
|
FreeCAD.Console.PrintWarning(f"Upload failed: {e}\n")
|
||||||
@@ -886,6 +1049,8 @@ class Silo_Commit:
|
|||||||
FreeCAD.Console.PrintMessage(f"Committed revision {new_rev}: {comment}\n")
|
FreeCAD.Console.PrintMessage(f"Committed revision {new_rev}: {comment}\n")
|
||||||
|
|
||||||
_push_dag_after_upload(doc, part_number, new_rev)
|
_push_dag_after_upload(doc, part_number, new_rev)
|
||||||
|
_push_bom_after_upload(doc, part_number, new_rev)
|
||||||
|
_update_manifest_revision(str(file_path), new_rev)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
FreeCAD.Console.PrintError(f"Commit failed: {e}\n")
|
FreeCAD.Console.PrintError(f"Commit failed: {e}\n")
|
||||||
@@ -1099,12 +1264,12 @@ def _pull_dependencies(part_number, progress_callback=None):
|
|||||||
|
|
||||||
|
|
||||||
class Silo_Pull:
|
class Silo_Pull:
|
||||||
"""Download from MinIO / sync from database."""
|
"""Download revision file from the server."""
|
||||||
|
|
||||||
def GetResources(self):
|
def GetResources(self):
|
||||||
return {
|
return {
|
||||||
"MenuText": "Pull",
|
"MenuText": "Pull",
|
||||||
"ToolTip": "Download from MinIO with revision selection",
|
"ToolTip": "Download file with revision selection",
|
||||||
"Pixmap": _icon("pull"),
|
"Pixmap": _icon("pull"),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1260,12 +1425,12 @@ class Silo_Pull:
|
|||||||
|
|
||||||
|
|
||||||
class Silo_Push:
|
class Silo_Push:
|
||||||
"""Upload local files to MinIO."""
|
"""Upload local files to the server."""
|
||||||
|
|
||||||
def GetResources(self):
|
def GetResources(self):
|
||||||
return {
|
return {
|
||||||
"MenuText": "Push",
|
"MenuText": "Push",
|
||||||
"ToolTip": "Upload local files that aren't in MinIO",
|
"ToolTip": "Upload local files that aren't on the server",
|
||||||
"Pixmap": _icon("push"),
|
"Pixmap": _icon("push"),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1386,7 +1551,7 @@ class Silo_Info:
|
|||||||
msg += f"<p><b>Local Revision:</b> {getattr(obj, 'SiloRevision', '-')}</p>"
|
msg += f"<p><b>Local Revision:</b> {getattr(obj, 'SiloRevision', '-')}</p>"
|
||||||
|
|
||||||
has_file, _ = _client.has_file(part_number)
|
has_file, _ = _client.has_file(part_number)
|
||||||
msg += f"<p><b>File in MinIO:</b> {'Yes' if has_file else 'No'}</p>"
|
msg += f"<p><b>File on Server:</b> {'Yes' if has_file else 'No'}</p>"
|
||||||
|
|
||||||
# Show current revision status
|
# Show current revision status
|
||||||
if revisions:
|
if revisions:
|
||||||
@@ -1769,6 +1934,31 @@ class Silo_Settings:
|
|||||||
|
|
||||||
layout.addSpacing(10)
|
layout.addSpacing(10)
|
||||||
|
|
||||||
|
# Schema name
|
||||||
|
schema_label = QtGui.QLabel("Schema Name:")
|
||||||
|
layout.addWidget(schema_label)
|
||||||
|
|
||||||
|
schema_input = QtGui.QLineEdit()
|
||||||
|
schema_input.setPlaceholderText("kindred-rd")
|
||||||
|
current_schema = param.GetString("SchemaName", "")
|
||||||
|
if current_schema:
|
||||||
|
schema_input.setText(current_schema)
|
||||||
|
else:
|
||||||
|
env_schema = os.environ.get("SILO_SCHEMA", "")
|
||||||
|
if env_schema:
|
||||||
|
schema_input.setText(env_schema)
|
||||||
|
layout.addWidget(schema_input)
|
||||||
|
|
||||||
|
schema_hint = QtGui.QLabel(
|
||||||
|
"The part-numbering schema to use. Leave empty for "
|
||||||
|
"SILO_SCHEMA env var or default (kindred-rd)."
|
||||||
|
)
|
||||||
|
schema_hint.setWordWrap(True)
|
||||||
|
schema_hint.setStyleSheet("color: #888; font-size: 11px;")
|
||||||
|
layout.addWidget(schema_hint)
|
||||||
|
|
||||||
|
layout.addSpacing(10)
|
||||||
|
|
||||||
# SSL
|
# SSL
|
||||||
ssl_checkbox = QtGui.QCheckBox("Verify SSL certificates")
|
ssl_checkbox = QtGui.QCheckBox("Verify SSL certificates")
|
||||||
ssl_checkbox.setChecked(param.GetBool("SslVerify", True))
|
ssl_checkbox.setChecked(param.GetBool("SslVerify", True))
|
||||||
@@ -1911,6 +2101,7 @@ class Silo_Settings:
|
|||||||
auth_display = "not configured"
|
auth_display = "not configured"
|
||||||
status_label = QtGui.QLabel(
|
status_label = QtGui.QLabel(
|
||||||
f"<b>Active URL:</b> {_get_api_url()}<br>"
|
f"<b>Active URL:</b> {_get_api_url()}<br>"
|
||||||
|
f"<b>Schema:</b> {_get_schema_name()}<br>"
|
||||||
f"<b>SSL verification:</b> {'enabled' if _get_ssl_verify() else 'disabled'}<br>"
|
f"<b>SSL verification:</b> {'enabled' if _get_ssl_verify() else 'disabled'}<br>"
|
||||||
f"<b>CA certificate:</b> {cert_display}<br>"
|
f"<b>CA certificate:</b> {cert_display}<br>"
|
||||||
f"<b>Authentication:</b> {auth_display}"
|
f"<b>Authentication:</b> {auth_display}"
|
||||||
@@ -1932,6 +2123,7 @@ class Silo_Settings:
|
|||||||
def on_save():
|
def on_save():
|
||||||
url = url_input.text().strip()
|
url = url_input.text().strip()
|
||||||
param.SetString("ApiUrl", url)
|
param.SetString("ApiUrl", url)
|
||||||
|
param.SetString("SchemaName", schema_input.text().strip())
|
||||||
param.SetBool("SslVerify", ssl_checkbox.isChecked())
|
param.SetBool("SslVerify", ssl_checkbox.isChecked())
|
||||||
cert_path = cert_input.text().strip()
|
cert_path = cert_input.text().strip()
|
||||||
param.SetString("SslCertPath", cert_path)
|
param.SetString("SslCertPath", cert_path)
|
||||||
@@ -2356,12 +2548,15 @@ class SiloEventListener(QtCore.QThread):
|
|||||||
connection_status = QtCore.Signal(
|
connection_status = QtCore.Signal(
|
||||||
str, int, str
|
str, int, str
|
||||||
) # (status, retry_count, error_message)
|
) # (status, retry_count, error_message)
|
||||||
server_mode_changed = QtCore.Signal(str) # "normal" / "read-only" / "degraded"
|
server_mode_changed = QtCore.Signal(str) # "normal" / "read-only" / "offline"
|
||||||
|
|
||||||
# DAG events
|
# DAG events
|
||||||
dag_updated = QtCore.Signal(str, int, int) # part_number, node_count, edge_count
|
dag_updated = QtCore.Signal(str, int, int) # part_number, node_count, edge_count
|
||||||
dag_validated = QtCore.Signal(str, bool, int) # part_number, valid, failed_count
|
dag_validated = QtCore.Signal(str, bool, int) # part_number, valid, failed_count
|
||||||
|
|
||||||
|
# BOM events
|
||||||
|
bom_merged = QtCore.Signal(str, int, int, int) # pn, added, updated, unreferenced
|
||||||
|
|
||||||
# Job lifecycle events
|
# Job lifecycle events
|
||||||
job_created = QtCore.Signal(str, str, str) # job_id, definition_name, part_number
|
job_created = QtCore.Signal(str, str, str) # job_id, definition_name, part_number
|
||||||
job_claimed = QtCore.Signal(str, str) # job_id, runner_id
|
job_claimed = QtCore.Signal(str, str) # job_id, runner_id
|
||||||
@@ -2536,6 +2731,13 @@ class SiloEventListener(QtCore.QThread):
|
|||||||
bool(payload.get("valid", False)),
|
bool(payload.get("valid", False)),
|
||||||
int(payload.get("failed_count", 0)),
|
int(payload.get("failed_count", 0)),
|
||||||
)
|
)
|
||||||
|
elif event_type == "bom.merged":
|
||||||
|
self.bom_merged.emit(
|
||||||
|
pn,
|
||||||
|
int(payload.get("added", 0)),
|
||||||
|
int(payload.get("updated", 0)),
|
||||||
|
int(payload.get("unreferenced", 0)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class _SSEUnsupported(Exception):
|
class _SSEUnsupported(Exception):
|
||||||
@@ -2765,6 +2967,7 @@ class SiloAuthDockWidget:
|
|||||||
self._event_listener.server_mode_changed.connect(self._on_server_mode)
|
self._event_listener.server_mode_changed.connect(self._on_server_mode)
|
||||||
self._event_listener.dag_updated.connect(self._on_dag_updated)
|
self._event_listener.dag_updated.connect(self._on_dag_updated)
|
||||||
self._event_listener.dag_validated.connect(self._on_dag_validated)
|
self._event_listener.dag_validated.connect(self._on_dag_validated)
|
||||||
|
self._event_listener.bom_merged.connect(self._on_bom_merged)
|
||||||
self._event_listener.job_created.connect(self._on_job_created)
|
self._event_listener.job_created.connect(self._on_job_created)
|
||||||
self._event_listener.job_claimed.connect(self._on_job_claimed)
|
self._event_listener.job_claimed.connect(self._on_job_claimed)
|
||||||
self._event_listener.job_progress.connect(self._on_job_progress)
|
self._event_listener.job_progress.connect(self._on_job_progress)
|
||||||
@@ -2819,11 +3022,6 @@ class SiloAuthDockWidget:
|
|||||||
"background: #FFC107; color: #000; padding: 4px; font-size: 11px;",
|
"background: #FFC107; color: #000; padding: 4px; font-size: 11px;",
|
||||||
True,
|
True,
|
||||||
),
|
),
|
||||||
"degraded": (
|
|
||||||
"MinIO unavailable \u2014 file ops limited",
|
|
||||||
"background: #FF9800; color: #000; padding: 4px; font-size: 11px;",
|
|
||||||
True,
|
|
||||||
),
|
|
||||||
"offline": (
|
"offline": (
|
||||||
"Disconnected from silo",
|
"Disconnected from silo",
|
||||||
"background: #F44336; color: #fff; padding: 4px; font-size: 11px;",
|
"background: #F44336; color: #fff; padding: 4px; font-size: 11px;",
|
||||||
@@ -2929,12 +3127,10 @@ class SiloAuthDockWidget:
|
|||||||
|
|
||||||
def _on_dag_updated(self, part_number, node_count, edge_count):
|
def _on_dag_updated(self, part_number, node_count, edge_count):
|
||||||
FreeCAD.Console.PrintMessage(
|
FreeCAD.Console.PrintMessage(
|
||||||
f"Silo: DAG updated for {part_number}"
|
f"Silo: DAG updated for {part_number} ({node_count} nodes, {edge_count} edges)\n"
|
||||||
f" ({node_count} nodes, {edge_count} edges)\n"
|
|
||||||
)
|
)
|
||||||
self._append_activity_event(
|
self._append_activity_event(
|
||||||
f"\u25b6 {part_number} \u2013 DAG synced"
|
f"\u25b6 {part_number} \u2013 DAG synced ({node_count} nodes, {edge_count} edges)",
|
||||||
f" ({node_count} nodes, {edge_count} edges)",
|
|
||||||
part_number,
|
part_number,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -2945,11 +3141,27 @@ class SiloAuthDockWidget:
|
|||||||
else:
|
else:
|
||||||
status = f"\u2717 FAIL ({failed_count} failed)"
|
status = f"\u2717 FAIL ({failed_count} failed)"
|
||||||
FreeCAD.Console.PrintWarning(
|
FreeCAD.Console.PrintWarning(
|
||||||
f"Silo: Validation failed for {part_number}"
|
f"Silo: Validation failed for {part_number} ({failed_count} features failed)\n"
|
||||||
f" ({failed_count} features failed)\n"
|
|
||||||
)
|
)
|
||||||
self._append_activity_event(f"{status} \u2013 {part_number}", part_number)
|
self._append_activity_event(f"{status} \u2013 {part_number}", part_number)
|
||||||
|
|
||||||
|
def _on_bom_merged(self, part_number, added, updated, unreferenced):
|
||||||
|
parts = []
|
||||||
|
if added:
|
||||||
|
parts.append(f"+{added} added")
|
||||||
|
if updated:
|
||||||
|
parts.append(f"~{updated} qty changed")
|
||||||
|
if unreferenced:
|
||||||
|
parts.append(f"!{unreferenced} unreferenced")
|
||||||
|
summary = ", ".join(parts) if parts else "no changes"
|
||||||
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Silo: BOM merged for {part_number} ({summary})\n"
|
||||||
|
)
|
||||||
|
self._append_activity_event(
|
||||||
|
f"\u2630 {part_number} \u2013 BOM synced ({summary})",
|
||||||
|
part_number,
|
||||||
|
)
|
||||||
|
|
||||||
def _on_job_created(self, job_id, definition_name, part_number):
|
def _on_job_created(self, job_id, definition_name, part_number):
|
||||||
FreeCAD.Console.PrintMessage(
|
FreeCAD.Console.PrintMessage(
|
||||||
f"Silo: Job {definition_name} created for {part_number}\n"
|
f"Silo: Job {definition_name} created for {part_number}\n"
|
||||||
@@ -3377,8 +3589,7 @@ class JobMonitorDialog:
|
|||||||
reply = QtGui.QMessageBox.question(
|
reply = QtGui.QMessageBox.question(
|
||||||
self.dialog,
|
self.dialog,
|
||||||
"Cancel Job",
|
"Cancel Job",
|
||||||
f"Cancel job {job.get('definition_name', '')} for "
|
f"Cancel job {job.get('definition_name', '')} for {job.get('part_number', '')}?",
|
||||||
f"{job.get('part_number', '')}?",
|
|
||||||
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
|
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
|
||||||
)
|
)
|
||||||
if reply != QtGui.QMessageBox.Yes:
|
if reply != QtGui.QMessageBox.Yes:
|
||||||
@@ -3891,6 +4102,218 @@ class Silo_StartPanel:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class SaveAsTemplateDialog:
|
||||||
|
"""Dialog to capture template metadata for Save as Template."""
|
||||||
|
|
||||||
|
_ITEM_TYPES = ["part", "assembly", "consumable", "tool"]
|
||||||
|
|
||||||
|
def __init__(self, doc, parent=None):
|
||||||
|
self._doc = doc
|
||||||
|
self._parent = parent
|
||||||
|
|
||||||
|
def exec_(self):
|
||||||
|
"""Show dialog. Returns template_info dict or None if cancelled."""
|
||||||
|
from PySide import QtGui, QtWidgets
|
||||||
|
|
||||||
|
dlg = QtWidgets.QDialog(self._parent)
|
||||||
|
dlg.setWindowTitle("Save as Template")
|
||||||
|
dlg.setMinimumWidth(420)
|
||||||
|
|
||||||
|
layout = QtWidgets.QVBoxLayout(dlg)
|
||||||
|
|
||||||
|
form = QtWidgets.QFormLayout()
|
||||||
|
form.setSpacing(6)
|
||||||
|
|
||||||
|
# Pre-populate defaults from document state
|
||||||
|
default_name = self._doc.Label or Path(self._doc.FileName).stem
|
||||||
|
obj = get_tracked_object(self._doc)
|
||||||
|
|
||||||
|
default_author = _get_auth_username() or os.environ.get("USER", "")
|
||||||
|
default_item_type = ""
|
||||||
|
default_category = ""
|
||||||
|
if obj:
|
||||||
|
if hasattr(obj, "SiloItemType"):
|
||||||
|
default_item_type = getattr(obj, "SiloItemType", "")
|
||||||
|
if hasattr(obj, "SiloPartNumber") and obj.SiloPartNumber:
|
||||||
|
default_category, _ = _parse_part_number(obj.SiloPartNumber)
|
||||||
|
|
||||||
|
# Name (required)
|
||||||
|
name_edit = QtWidgets.QLineEdit(default_name)
|
||||||
|
name_edit.setPlaceholderText("Template display name")
|
||||||
|
form.addRow("Name:", name_edit)
|
||||||
|
|
||||||
|
# Description
|
||||||
|
desc_edit = QtWidgets.QLineEdit()
|
||||||
|
desc_edit.setPlaceholderText("What this template is for")
|
||||||
|
form.addRow("Description:", desc_edit)
|
||||||
|
|
||||||
|
# Item Types (multi-select)
|
||||||
|
type_list = QtWidgets.QListWidget()
|
||||||
|
type_list.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
|
||||||
|
type_list.setMaximumHeight(80)
|
||||||
|
for t in self._ITEM_TYPES:
|
||||||
|
item = QtWidgets.QListWidgetItem(t.capitalize())
|
||||||
|
item.setData(QtCore.Qt.UserRole, t)
|
||||||
|
type_list.addItem(item)
|
||||||
|
if t == default_item_type:
|
||||||
|
item.setSelected(True)
|
||||||
|
form.addRow("Item Types:", type_list)
|
||||||
|
|
||||||
|
# Categories (comma-separated prefixes)
|
||||||
|
cat_edit = QtWidgets.QLineEdit(default_category)
|
||||||
|
cat_edit.setPlaceholderText("e.g. F, M01 (empty = all)")
|
||||||
|
form.addRow("Categories:", cat_edit)
|
||||||
|
|
||||||
|
# Author
|
||||||
|
author_edit = QtWidgets.QLineEdit(default_author)
|
||||||
|
form.addRow("Author:", author_edit)
|
||||||
|
|
||||||
|
# Tags (comma-separated)
|
||||||
|
tags_edit = QtWidgets.QLineEdit()
|
||||||
|
tags_edit.setPlaceholderText("e.g. sheet metal, fabrication")
|
||||||
|
form.addRow("Tags:", tags_edit)
|
||||||
|
|
||||||
|
layout.addLayout(form)
|
||||||
|
|
||||||
|
# Buttons
|
||||||
|
btn_layout = QtWidgets.QHBoxLayout()
|
||||||
|
btn_layout.addStretch()
|
||||||
|
cancel_btn = QtWidgets.QPushButton("Cancel")
|
||||||
|
cancel_btn.clicked.connect(dlg.reject)
|
||||||
|
btn_layout.addWidget(cancel_btn)
|
||||||
|
save_btn = QtWidgets.QPushButton("Save Template")
|
||||||
|
save_btn.setDefault(True)
|
||||||
|
save_btn.clicked.connect(dlg.accept)
|
||||||
|
btn_layout.addWidget(save_btn)
|
||||||
|
layout.addLayout(btn_layout)
|
||||||
|
|
||||||
|
if dlg.exec_() != QtWidgets.QDialog.Accepted:
|
||||||
|
return None
|
||||||
|
|
||||||
|
name = name_edit.text().strip()
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
|
||||||
|
selected_types = []
|
||||||
|
for i in range(type_list.count()):
|
||||||
|
item = type_list.item(i)
|
||||||
|
if item.isSelected():
|
||||||
|
selected_types.append(item.data(QtCore.Qt.UserRole))
|
||||||
|
|
||||||
|
categories = [c.strip() for c in cat_edit.text().split(",") if c.strip()]
|
||||||
|
tags = [t.strip() for t in tags_edit.text().split(",") if t.strip()]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"template_version": "1.0",
|
||||||
|
"name": name,
|
||||||
|
"description": desc_edit.text().strip(),
|
||||||
|
"item_types": selected_types,
|
||||||
|
"categories": categories,
|
||||||
|
"icon": "",
|
||||||
|
"author": author_edit.text().strip(),
|
||||||
|
"tags": tags,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Silo_SaveAsTemplate:
|
||||||
|
"""Save a copy of the current document as a reusable template."""
|
||||||
|
|
||||||
|
def GetResources(self):
|
||||||
|
return {
|
||||||
|
"MenuText": "Save as Template",
|
||||||
|
"ToolTip": "Save a copy of this document as a reusable template",
|
||||||
|
"Pixmap": _icon("new"),
|
||||||
|
}
|
||||||
|
|
||||||
|
def Activated(self):
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
from PySide import QtGui
|
||||||
|
from templates import get_default_template_dir, inject_template_json
|
||||||
|
|
||||||
|
doc = FreeCAD.ActiveDocument
|
||||||
|
if not doc:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not doc.FileName:
|
||||||
|
QtGui.QMessageBox.warning(
|
||||||
|
None,
|
||||||
|
"Save as Template",
|
||||||
|
"Please save the document first.",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Capture template metadata from user
|
||||||
|
dialog = SaveAsTemplateDialog(doc)
|
||||||
|
template_info = dialog.exec_()
|
||||||
|
if not template_info:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Determine destination
|
||||||
|
dest_dir = get_default_template_dir()
|
||||||
|
filename = _sanitize_filename(template_info["name"]) + ".kc"
|
||||||
|
dest = os.path.join(dest_dir, filename)
|
||||||
|
|
||||||
|
# Check for overwrite
|
||||||
|
if os.path.exists(dest):
|
||||||
|
reply = QtGui.QMessageBox.question(
|
||||||
|
None,
|
||||||
|
"Save as Template",
|
||||||
|
f"Template '{filename}' already exists. Overwrite?",
|
||||||
|
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
|
||||||
|
)
|
||||||
|
if reply != QtGui.QMessageBox.Yes:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Save current state, then copy
|
||||||
|
doc.save()
|
||||||
|
shutil.copy2(doc.FileName, dest)
|
||||||
|
|
||||||
|
# Strip Silo identity and inject template descriptor
|
||||||
|
_sync._clean_template_zip(dest)
|
||||||
|
inject_template_json(dest, template_info)
|
||||||
|
|
||||||
|
FreeCAD.Console.PrintMessage(f"Template saved: {dest}\n")
|
||||||
|
|
||||||
|
# Offer Silo upload if connected
|
||||||
|
if _server_mode == "normal":
|
||||||
|
reply = QtGui.QMessageBox.question(
|
||||||
|
None,
|
||||||
|
"Save as Template",
|
||||||
|
"Upload template to Silo for team sharing?",
|
||||||
|
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
|
||||||
|
)
|
||||||
|
if reply == QtGui.QMessageBox.Yes:
|
||||||
|
self._upload_to_silo(dest, template_info)
|
||||||
|
|
||||||
|
QtGui.QMessageBox.information(
|
||||||
|
None,
|
||||||
|
"Save as Template",
|
||||||
|
f"Template '{template_info['name']}' saved.",
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _upload_to_silo(file_path, template_info):
|
||||||
|
"""Upload template to Silo as a shared item. Non-blocking on failure."""
|
||||||
|
try:
|
||||||
|
schema = _get_schema_name()
|
||||||
|
result = _client.create_item(
|
||||||
|
schema, "T00", template_info.get("name", "Template")
|
||||||
|
)
|
||||||
|
part_number = result["part_number"]
|
||||||
|
_client._upload_file(part_number, file_path, {}, "Template upload")
|
||||||
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Template uploaded to Silo as {part_number}\n"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
FreeCAD.Console.PrintWarning(
|
||||||
|
f"Template upload to Silo failed (saved locally): {e}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def IsActive(self):
|
||||||
|
return FreeCAD.ActiveDocument is not None
|
||||||
|
|
||||||
|
|
||||||
class _DiagWorker(QtCore.QThread):
|
class _DiagWorker(QtCore.QThread):
|
||||||
"""Background worker that runs connectivity diagnostics."""
|
"""Background worker that runs connectivity diagnostics."""
|
||||||
|
|
||||||
@@ -4043,3 +4466,4 @@ FreeCADGui.addCommand("Silo_StartPanel", Silo_StartPanel())
|
|||||||
FreeCADGui.addCommand("Silo_Diag", Silo_Diag())
|
FreeCADGui.addCommand("Silo_Diag", Silo_Diag())
|
||||||
FreeCADGui.addCommand("Silo_Jobs", Silo_Jobs())
|
FreeCADGui.addCommand("Silo_Jobs", Silo_Jobs())
|
||||||
FreeCADGui.addCommand("Silo_Runners", Silo_Runners())
|
FreeCADGui.addCommand("Silo_Runners", Silo_Runners())
|
||||||
|
FreeCADGui.addCommand("Silo_SaveAsTemplate", Silo_SaveAsTemplate())
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ class SiloOrigin:
|
|||||||
Key behaviors:
|
Key behaviors:
|
||||||
- Documents are always stored locally (hybrid local-remote model)
|
- Documents are always stored locally (hybrid local-remote model)
|
||||||
- Database tracks metadata, part numbers, and revision history
|
- 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
|
- Identity is tracked by UUID (SiloItemId), displayed as part number
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -388,9 +388,7 @@ class SiloOrigin:
|
|||||||
|
|
||||||
# Upload to Silo
|
# Upload to Silo
|
||||||
properties = collect_document_properties(doc)
|
properties = collect_document_properties(doc)
|
||||||
_client._upload_file(
|
_client._upload_file(obj.SiloPartNumber, str(file_path), properties, comment="")
|
||||||
obj.SiloPartNumber, str(file_path), properties, comment=""
|
|
||||||
)
|
|
||||||
|
|
||||||
# Clear modified flag (Modified is on Gui.Document, not App.Document)
|
# Clear modified flag (Modified is on Gui.Document, not App.Document)
|
||||||
gui_doc = FreeCADGui.getDocument(doc.Name)
|
gui_doc = FreeCADGui.getDocument(doc.Name)
|
||||||
@@ -567,12 +565,9 @@ def register_silo_origin():
|
|||||||
This should be called during workbench initialization to make
|
This should be called during workbench initialization to make
|
||||||
Silo available as a file origin.
|
Silo available as a file origin.
|
||||||
"""
|
"""
|
||||||
origin = get_silo_origin()
|
from kindred_sdk import register_origin
|
||||||
try:
|
|
||||||
FreeCADGui.addOrigin(origin)
|
register_origin(get_silo_origin())
|
||||||
FreeCAD.Console.PrintLog("Registered Silo origin\n")
|
|
||||||
except Exception as e:
|
|
||||||
FreeCAD.Console.PrintWarning(f"Could not register Silo origin: {e}\n")
|
|
||||||
|
|
||||||
|
|
||||||
def unregister_silo_origin():
|
def unregister_silo_origin():
|
||||||
@@ -582,9 +577,7 @@ def unregister_silo_origin():
|
|||||||
"""
|
"""
|
||||||
global _silo_origin
|
global _silo_origin
|
||||||
if _silo_origin:
|
if _silo_origin:
|
||||||
try:
|
from kindred_sdk import unregister_origin
|
||||||
FreeCADGui.removeOrigin(_silo_origin)
|
|
||||||
FreeCAD.Console.PrintLog("Unregistered Silo origin\n")
|
unregister_origin(_silo_origin)
|
||||||
except Exception as e:
|
|
||||||
FreeCAD.Console.PrintWarning(f"Could not unregister Silo origin: {e}\n")
|
|
||||||
_silo_origin = None
|
_silo_origin = None
|
||||||
|
|||||||
@@ -19,23 +19,10 @@ from PySide import QtCore, QtGui, QtWidgets
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Catppuccin Mocha palette
|
# Catppuccin Mocha palette
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
_MOCHA = {
|
# Catppuccin Mocha palette — sourced from kindred-addon-sdk
|
||||||
"base": "#1e1e2e",
|
from kindred_sdk.theme import get_theme_tokens
|
||||||
"mantle": "#181825",
|
|
||||||
"crust": "#11111b",
|
_MOCHA = get_theme_tokens()
|
||||||
"surface0": "#313244",
|
|
||||||
"surface1": "#45475a",
|
|
||||||
"surface2": "#585b70",
|
|
||||||
"text": "#cdd6f4",
|
|
||||||
"subtext0": "#a6adc8",
|
|
||||||
"subtext1": "#bac2de",
|
|
||||||
"blue": "#89b4fa",
|
|
||||||
"green": "#a6e3a1",
|
|
||||||
"red": "#f38ba8",
|
|
||||||
"peach": "#fab387",
|
|
||||||
"lavender": "#b4befe",
|
|
||||||
"overlay0": "#6c7086",
|
|
||||||
}
|
|
||||||
|
|
||||||
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
||||||
|
|
||||||
|
|||||||
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: 9b71cf0375...5dfb567bac
Reference in New Issue
Block a user