Compare commits
26 Commits
fix/pull-p
...
feat/dag-o
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dd0da3964 | ||
|
|
4921095296 | ||
|
|
3a9fe6aed8 | ||
|
|
9e99b83091 | ||
|
|
fed72676bc | ||
| 91f539a18a | |||
| 2ddfea083a | |||
| be8783bf0a | |||
| 972dc07157 | |||
| 069bb7a552 | |||
| 201e0af450 | |||
| 8a6e5cdffa | |||
| 95c56fa29a | |||
| 33d5eeb76c | |||
| 9e83982c78 | |||
| 52fc9cdd3a | |||
| ae132948d1 | |||
|
|
ab801601c9 | ||
| 32d5f1ea1b | |||
| de80e392f5 | |||
| ba42343577 | |||
| af7eab3a70 | |||
| 6d231e80dd | |||
| a7ef5f195b | |||
|
|
7cf5867a7a | ||
|
|
9a6d1dfbd2 |
@@ -35,9 +35,20 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
FreeCAD.Console.PrintWarning(f"Could not register Silo origin: {e}\n")
|
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",
|
||||||
|
]
|
||||||
|
self.appendToolbar("Silo Origin", self.silo_toolbar_commands, "Unavailable")
|
||||||
|
|
||||||
# Silo menu provides admin/management commands.
|
# 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 = [
|
self.menu_commands = [
|
||||||
"Silo_Info",
|
"Silo_Info",
|
||||||
"Silo_BOM",
|
"Silo_BOM",
|
||||||
@@ -68,6 +79,44 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
|||||||
FreeCADGui.addWorkbench(SiloWorkbench())
|
FreeCADGui.addWorkbench(SiloWorkbench())
|
||||||
FreeCAD.Console.PrintMessage("Silo workbench registered\n")
|
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:
|
||||||
|
FreeCADGui.registerEditingOverlay(
|
||||||
|
"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
|
# Override the Start page with Silo-aware version (must happen before
|
||||||
# the C++ StartLauncher fires at ~100ms after GUI init)
|
# the C++ StartLauncher fires at ~100ms after GUI init)
|
||||||
try:
|
try:
|
||||||
@@ -92,6 +141,4 @@ def _handle_startup_urls():
|
|||||||
handle_kindred_url(arg)
|
handle_kindred_url(arg)
|
||||||
|
|
||||||
|
|
||||||
from PySide import QtCore
|
_QtCore.QTimer.singleShot(500, _handle_startup_urls)
|
||||||
|
|
||||||
QtCore.QTimer.singleShot(500, _handle_startup_urls)
|
|
||||||
|
|||||||
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]))
|
||||||
629
freecad/schema_form.py
Normal file
629
freecad/schema_form.py
Normal file
@@ -0,0 +1,629 @@
|
|||||||
|
"""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 urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
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._load_schema_data()
|
||||||
|
self._build_ui()
|
||||||
|
|
||||||
|
# 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 = []
|
||||||
|
|
||||||
|
def _fetch_properties(self, category: str) -> dict:
|
||||||
|
"""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:
|
||||||
|
resp = urllib.request.urlopen(req, context=_get_ssl_context(), timeout=5)
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
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_api_url, _get_auth_headers, _get_ssl_context
|
||||||
|
|
||||||
|
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:
|
||||||
|
resp = urllib.request.urlopen(req, context=_get_ssl_context(), timeout=5)
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
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)
|
||||||
|
fl.addRow("Type:", self._type_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)
|
||||||
|
|
||||||
|
# -- category change ----------------------------------------------------
|
||||||
|
|
||||||
|
def _on_category_changed(self, category: str):
|
||||||
|
"""Rebuild property groups when category selection changes."""
|
||||||
|
self._create_btn.setEnabled(bool(category))
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
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:
|
||||||
|
result = self._client.create_item(
|
||||||
|
"kindred-rd",
|
||||||
|
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
|
||||||
@@ -26,7 +26,9 @@ from silo_client import (
|
|||||||
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
_PREF_GROUP = "User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
||||||
|
|
||||||
# Configuration - preferences take priority over env vars
|
# Configuration - preferences take priority over env vars
|
||||||
SILO_PROJECTS_DIR = os.environ.get("SILO_PROJECTS_DIR", os.path.expanduser("~/projects"))
|
SILO_PROJECTS_DIR = os.environ.get(
|
||||||
|
"SILO_PROJECTS_DIR", os.path.expanduser("~/projects")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -64,7 +66,9 @@ class FreeCADSiloSettings(SiloSettings):
|
|||||||
param = FreeCAD.ParamGet(_PREF_GROUP)
|
param = FreeCAD.ParamGet(_PREF_GROUP)
|
||||||
return param.GetString("SslCertPath", "")
|
return param.GetString("SslCertPath", "")
|
||||||
|
|
||||||
def save_auth(self, username: str, role: str = "", source: str = "", token: str = ""):
|
def save_auth(
|
||||||
|
self, username: str, role: str = "", source: str = "", token: str = ""
|
||||||
|
):
|
||||||
param = FreeCAD.ParamGet(_PREF_GROUP)
|
param = FreeCAD.ParamGet(_PREF_GROUP)
|
||||||
param.SetString("AuthUsername", username)
|
param.SetString("AuthUsername", username)
|
||||||
param.SetString("AuthRole", role)
|
param.SetString("AuthRole", role)
|
||||||
@@ -122,7 +126,9 @@ def _get_ssl_verify() -> bool:
|
|||||||
def _get_ssl_context():
|
def _get_ssl_context():
|
||||||
from silo_client._ssl import build_ssl_context
|
from silo_client._ssl import build_ssl_context
|
||||||
|
|
||||||
return build_ssl_context(_fc_settings.get_ssl_verify(), _fc_settings.get_ssl_cert_path())
|
return build_ssl_context(
|
||||||
|
_fc_settings.get_ssl_verify(), _fc_settings.get_ssl_cert_path()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _get_auth_headers() -> Dict[str, str]:
|
def _get_auth_headers() -> Dict[str, str]:
|
||||||
@@ -179,7 +185,9 @@ def _fetch_server_mode() -> str:
|
|||||||
# Icon helper
|
# Icon helper
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
_ICON_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "icons")
|
_ICON_DIR = os.path.join(
|
||||||
|
os.path.dirname(os.path.abspath(__file__)), "resources", "icons"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _icon(name):
|
def _icon(name):
|
||||||
@@ -206,41 +214,45 @@ 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}.FCStd
|
Path format: ~/projects/cad/{category_code}_{category_name}/{part_number}_{description}.kc
|
||||||
"""
|
"""
|
||||||
category, _ = parse_part_number(part_number)
|
category, _ = parse_part_number(part_number)
|
||||||
folder_name = get_category_folder_name(category)
|
folder_name = get_category_folder_name(category)
|
||||||
|
|
||||||
if description:
|
if description:
|
||||||
filename = f"{part_number}_{sanitize_filename(description)}.FCStd"
|
filename = f"{part_number}_{sanitize_filename(description)}.kc"
|
||||||
else:
|
else:
|
||||||
filename = f"{part_number}.FCStd"
|
filename = f"{part_number}.kc"
|
||||||
|
|
||||||
return get_projects_dir() / "cad" / folder_name / filename
|
return get_projects_dir() / "cad" / folder_name / 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."""
|
"""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)
|
folder_name = get_category_folder_name(category)
|
||||||
cad_dir = get_projects_dir() / "cad" / folder_name
|
cad_dir = get_projects_dir() / "cad" / folder_name
|
||||||
|
|
||||||
if cad_dir.exists():
|
for search_dir in _search_dirs(cad_dir):
|
||||||
matches = list(cad_dir.glob(f"{part_number}*.FCStd"))
|
for ext in ("*.kc", "*.FCStd"):
|
||||||
if matches:
|
matches = list(search_dir.glob(f"{part_number}{ext[1:]}"))
|
||||||
return matches[0]
|
if matches:
|
||||||
|
return matches[0]
|
||||||
base_cad_dir = get_projects_dir() / "cad"
|
|
||||||
if base_cad_dir.exists():
|
|
||||||
for subdir in base_cad_dir.iterdir():
|
|
||||||
if subdir.is_dir():
|
|
||||||
matches = list(subdir.glob(f"{part_number}*.FCStd"))
|
|
||||||
if matches:
|
|
||||||
return matches[0]
|
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _search_dirs(category_dir: Path):
|
||||||
|
"""Yield the category dir, then all sibling dirs under cad/."""
|
||||||
|
if category_dir.exists():
|
||||||
|
yield category_dir
|
||||||
|
base_cad_dir = category_dir.parent
|
||||||
|
if base_cad_dir.exists():
|
||||||
|
for subdir in base_cad_dir.iterdir():
|
||||||
|
if subdir.is_dir() and subdir != category_dir:
|
||||||
|
yield subdir
|
||||||
|
|
||||||
|
|
||||||
def search_local_files(search_term: str = "", category_filter: str = "") -> list:
|
def search_local_files(search_term: str = "", category_filter: str = "") -> list:
|
||||||
"""Search for CAD files in local cad directory."""
|
"""Search for CAD files in local cad directory."""
|
||||||
results = []
|
results = []
|
||||||
@@ -260,7 +272,9 @@ def search_local_files(search_term: str = "", category_filter: str = "") -> list
|
|||||||
if category_filter and category_code.upper() != category_filter.upper():
|
if category_filter and category_code.upper() != category_filter.upper():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
for fcstd_file in category_dir.glob("*.FCStd"):
|
for fcstd_file in sorted(
|
||||||
|
list(category_dir.glob("*.kc")) + list(category_dir.glob("*.FCStd"))
|
||||||
|
):
|
||||||
filename = fcstd_file.stem
|
filename = fcstd_file.stem
|
||||||
parts = filename.split("_", 1)
|
parts = filename.split("_", 1)
|
||||||
part_number = parts[0]
|
part_number = parts[0]
|
||||||
@@ -574,7 +588,9 @@ def handle_kindred_url(url: str):
|
|||||||
parts = [parsed.netloc] + [p for p in parsed.path.split("/") if p]
|
parts = [parsed.netloc] + [p for p in parsed.path.split("/") if p]
|
||||||
if len(parts) >= 2 and parts[0] == "item":
|
if len(parts) >= 2 and parts[0] == "item":
|
||||||
part_number = parts[1]
|
part_number = parts[1]
|
||||||
FreeCAD.Console.PrintMessage(f"Silo: Opening item {part_number} from kindred:// URL\n")
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Silo: Opening item {part_number} from kindred:// URL\n"
|
||||||
|
)
|
||||||
_sync.open_item(part_number)
|
_sync.open_item(part_number)
|
||||||
|
|
||||||
|
|
||||||
@@ -594,149 +610,44 @@ class Silo_Open:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def Activated(self):
|
def Activated(self):
|
||||||
from PySide import QtCore, QtGui
|
from open_search import OpenItemWidget
|
||||||
|
from PySide import QtGui, QtWidgets
|
||||||
|
|
||||||
dialog = QtGui.QDialog()
|
mw = FreeCADGui.getMainWindow()
|
||||||
dialog.setWindowTitle("Silo - Open Item")
|
mdi = mw.findChild(QtWidgets.QMdiArea)
|
||||||
dialog.setMinimumWidth(700)
|
if not mdi:
|
||||||
dialog.setMinimumHeight(500)
|
return
|
||||||
|
|
||||||
layout = QtGui.QVBoxLayout(dialog)
|
widget = OpenItemWidget(_client, search_local_files)
|
||||||
|
|
||||||
# Search row
|
sw = mdi.addSubWindow(widget)
|
||||||
search_layout = QtGui.QHBoxLayout()
|
sw.setWindowTitle("Open Item")
|
||||||
search_input = QtGui.QLineEdit()
|
sw.setWindowIcon(QtGui.QIcon(_icon("open")))
|
||||||
search_input.setPlaceholderText("Search by part number or description...")
|
sw.show()
|
||||||
search_layout.addWidget(search_input)
|
mdi.setActiveSubWindow(sw)
|
||||||
layout.addLayout(search_layout)
|
|
||||||
|
|
||||||
# Filters
|
def _on_selected(data):
|
||||||
filter_layout = QtGui.QHBoxLayout()
|
sw.close()
|
||||||
db_checkbox = QtGui.QCheckBox("Database")
|
|
||||||
db_checkbox.setChecked(True)
|
|
||||||
local_checkbox = QtGui.QCheckBox("Local Files")
|
|
||||||
local_checkbox.setChecked(True)
|
|
||||||
filter_layout.addWidget(db_checkbox)
|
|
||||||
filter_layout.addWidget(local_checkbox)
|
|
||||||
filter_layout.addStretch()
|
|
||||||
layout.addLayout(filter_layout)
|
|
||||||
|
|
||||||
# Results table
|
|
||||||
results_table = QtGui.QTableWidget()
|
|
||||||
results_table.setColumnCount(5)
|
|
||||||
results_table.setHorizontalHeaderLabels(
|
|
||||||
["Part Number", "Description", "Type", "Source", "Modified"]
|
|
||||||
)
|
|
||||||
results_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
|
|
||||||
results_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
|
|
||||||
results_table.horizontalHeader().setStretchLastSection(True)
|
|
||||||
results_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
|
|
||||||
layout.addWidget(results_table)
|
|
||||||
|
|
||||||
results_data = []
|
|
||||||
|
|
||||||
def do_search():
|
|
||||||
nonlocal results_data
|
|
||||||
search_term = search_input.text().strip()
|
|
||||||
results_data = []
|
|
||||||
results_table.setRowCount(0)
|
|
||||||
|
|
||||||
if db_checkbox.isChecked():
|
|
||||||
try:
|
|
||||||
for item in _client.list_items(search=search_term):
|
|
||||||
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 local_checkbox.isChecked():
|
|
||||||
try:
|
|
||||||
for item in search_local_files(search_term):
|
|
||||||
existing = next(
|
|
||||||
(r for r in results_data if r["part_number"] == item["part_number"]),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
if existing:
|
|
||||||
existing["source"] = "both"
|
|
||||||
existing["path"] = item.get("path")
|
|
||||||
else:
|
|
||||||
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")
|
|
||||||
|
|
||||||
results_table.setRowCount(len(results_data))
|
|
||||||
for row, data in enumerate(results_data):
|
|
||||||
results_table.setItem(row, 0, QtGui.QTableWidgetItem(data["part_number"]))
|
|
||||||
results_table.setItem(row, 1, QtGui.QTableWidgetItem(data["description"]))
|
|
||||||
results_table.setItem(row, 2, QtGui.QTableWidgetItem(data["item_type"]))
|
|
||||||
results_table.setItem(row, 3, QtGui.QTableWidgetItem(data["source"]))
|
|
||||||
results_table.setItem(row, 4, QtGui.QTableWidgetItem(data["modified"]))
|
|
||||||
results_table.resizeColumnsToContents()
|
|
||||||
|
|
||||||
_open_after_close = [None]
|
|
||||||
|
|
||||||
def open_selected():
|
|
||||||
selected = results_table.selectedItems()
|
|
||||||
if not selected:
|
|
||||||
return
|
|
||||||
row = selected[0].row()
|
|
||||||
_open_after_close[0] = dict(results_data[row])
|
|
||||||
dialog.accept()
|
|
||||||
|
|
||||||
search_input.textChanged.connect(lambda: do_search())
|
|
||||||
results_table.doubleClicked.connect(open_selected)
|
|
||||||
|
|
||||||
# Buttons
|
|
||||||
btn_layout = QtGui.QHBoxLayout()
|
|
||||||
open_btn = QtGui.QPushButton("Open")
|
|
||||||
open_btn.clicked.connect(open_selected)
|
|
||||||
cancel_btn = QtGui.QPushButton("Cancel")
|
|
||||||
cancel_btn.clicked.connect(dialog.reject)
|
|
||||||
btn_layout.addStretch()
|
|
||||||
btn_layout.addWidget(open_btn)
|
|
||||||
btn_layout.addWidget(cancel_btn)
|
|
||||||
layout.addLayout(btn_layout)
|
|
||||||
|
|
||||||
do_search()
|
|
||||||
dialog.exec_()
|
|
||||||
|
|
||||||
# Open the document AFTER the dialog has fully closed so that
|
|
||||||
# heavy document loads (especially Assembly files) don't run
|
|
||||||
# inside the dialog's nested event loop, which can cause crashes.
|
|
||||||
data = _open_after_close[0]
|
|
||||||
if data is not None:
|
|
||||||
if data.get("path"):
|
if data.get("path"):
|
||||||
FreeCAD.openDocument(data["path"])
|
FreeCAD.openDocument(data["path"])
|
||||||
else:
|
else:
|
||||||
_sync.open_item(data["part_number"])
|
_sync.open_item(data["part_number"])
|
||||||
|
|
||||||
|
widget.item_selected.connect(_on_selected)
|
||||||
|
widget.cancelled.connect(sw.close)
|
||||||
|
|
||||||
def IsActive(self):
|
def IsActive(self):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
class Silo_New:
|
class Silo_New:
|
||||||
"""Create new item with part number."""
|
"""Create new item with part number.
|
||||||
|
|
||||||
|
Opens a pre-document MDI tab containing the schema-driven creation
|
||||||
|
form. Each invocation opens a new tab so multiple items can be
|
||||||
|
prepared in parallel. On successful creation the tab closes and
|
||||||
|
the real document opens in its place.
|
||||||
|
"""
|
||||||
|
|
||||||
def GetResources(self):
|
def GetResources(self):
|
||||||
return {
|
return {
|
||||||
@@ -746,117 +657,88 @@ class Silo_New:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def Activated(self):
|
def Activated(self):
|
||||||
from PySide import QtGui
|
from PySide import QtGui, QtWidgets
|
||||||
|
from schema_form import SchemaFormWidget
|
||||||
|
|
||||||
sel = FreeCADGui.Selection.getSelection()
|
mw = FreeCADGui.getMainWindow()
|
||||||
|
mdi = mw.findChild(QtWidgets.QMdiArea)
|
||||||
# Category selection
|
if not mdi:
|
||||||
try:
|
|
||||||
schema = _client.get_schema()
|
|
||||||
categories = schema.get("segments", [])
|
|
||||||
cat_segment = next((s for s in categories if s.get("name") == "category"), None)
|
|
||||||
if cat_segment and cat_segment.get("values"):
|
|
||||||
cat_list = [f"{k} - {v}" for k, v in sorted(cat_segment["values"].items())]
|
|
||||||
category_str, ok = QtGui.QInputDialog.getItem(
|
|
||||||
None, "New Item", "Category:", cat_list, 0, False
|
|
||||||
)
|
|
||||||
if not ok:
|
|
||||||
return
|
|
||||||
category = category_str.split(" - ")[0]
|
|
||||||
else:
|
|
||||||
category, ok = QtGui.QInputDialog.getText(None, "New Item", "Category code:")
|
|
||||||
if not ok:
|
|
||||||
return
|
|
||||||
except Exception:
|
|
||||||
category, ok = QtGui.QInputDialog.getText(None, "New Item", "Category code:")
|
|
||||||
if not ok:
|
|
||||||
return
|
|
||||||
|
|
||||||
# Description
|
|
||||||
default_desc = sel[0].Label if sel else ""
|
|
||||||
description, ok = QtGui.QInputDialog.getText(
|
|
||||||
None, "New Item", "Description:", text=default_desc
|
|
||||||
)
|
|
||||||
if not ok:
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# Optional project tagging
|
# Each invocation creates a new pre-document tab
|
||||||
selected_projects = []
|
form = SchemaFormWidget(_client)
|
||||||
try:
|
|
||||||
projects = _client.get_projects()
|
|
||||||
if projects:
|
|
||||||
project_codes = [p.get("code", "") for p in projects if p.get("code")]
|
|
||||||
if project_codes:
|
|
||||||
# Multi-select dialog for projects
|
|
||||||
dialog = QtGui.QDialog()
|
|
||||||
dialog.setWindowTitle("Tag with Projects (Optional)")
|
|
||||||
dialog.setMinimumWidth(300)
|
|
||||||
layout = QtGui.QVBoxLayout(dialog)
|
|
||||||
|
|
||||||
label = QtGui.QLabel("Select projects to tag this item with:")
|
# Pre-fill description from current selection
|
||||||
layout.addWidget(label)
|
sel = FreeCADGui.Selection.getSelection()
|
||||||
|
if sel:
|
||||||
|
form._desc_edit.setText(sel[0].Label)
|
||||||
|
|
||||||
list_widget = QtGui.QListWidget()
|
# Add as MDI subwindow (appears as a tab alongside documents)
|
||||||
list_widget.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
|
sw = mdi.addSubWindow(form)
|
||||||
for code in project_codes:
|
sw.setWindowTitle("New Item")
|
||||||
list_widget.addItem(code)
|
sw.setWindowIcon(QtGui.QIcon(_icon("new")))
|
||||||
layout.addWidget(list_widget)
|
sw.show()
|
||||||
|
mdi.setActiveSubWindow(sw)
|
||||||
|
|
||||||
btn_layout = QtGui.QHBoxLayout()
|
# On creation: process result, close tab, open real document
|
||||||
skip_btn = QtGui.QPushButton("Skip")
|
def _on_created(result):
|
||||||
ok_btn = QtGui.QPushButton("Tag Selected")
|
|
||||||
btn_layout.addWidget(skip_btn)
|
|
||||||
btn_layout.addWidget(ok_btn)
|
|
||||||
layout.addLayout(btn_layout)
|
|
||||||
|
|
||||||
skip_btn.clicked.connect(dialog.reject)
|
|
||||||
ok_btn.clicked.connect(dialog.accept)
|
|
||||||
|
|
||||||
if dialog.exec_() == QtGui.QDialog.Accepted:
|
|
||||||
selected_projects = [item.text() for item in list_widget.selectedItems()]
|
|
||||||
except Exception as e:
|
|
||||||
FreeCAD.Console.PrintWarning(f"Could not fetch projects: {e}\n")
|
|
||||||
|
|
||||||
try:
|
|
||||||
result = _client.create_item(
|
|
||||||
"kindred-rd",
|
|
||||||
category,
|
|
||||||
description,
|
|
||||||
projects=selected_projects if selected_projects else None,
|
|
||||||
)
|
|
||||||
part_number = result["part_number"]
|
part_number = result["part_number"]
|
||||||
|
|
||||||
if sel:
|
try:
|
||||||
# Tag selected object
|
sel_now = FreeCADGui.Selection.getSelection()
|
||||||
obj = sel[0]
|
if sel_now:
|
||||||
set_silo_properties(
|
obj = sel_now[0]
|
||||||
obj,
|
set_silo_properties(
|
||||||
{
|
obj,
|
||||||
"SiloItemId": result.get("id", ""),
|
{
|
||||||
"SiloPartNumber": part_number,
|
"SiloItemId": result.get("id", ""),
|
||||||
"SiloRevision": 1,
|
"SiloPartNumber": part_number,
|
||||||
},
|
"SiloRevision": 1,
|
||||||
)
|
},
|
||||||
obj.Label = part_number
|
)
|
||||||
_sync.save_to_canonical_path(FreeCAD.ActiveDocument, force_rename=True)
|
obj.Label = part_number
|
||||||
else:
|
_sync.save_to_canonical_path(
|
||||||
# Create new document
|
FreeCAD.ActiveDocument, force_rename=True
|
||||||
_sync.create_document_for_item(result, save=True)
|
)
|
||||||
|
else:
|
||||||
|
_sync.create_document_for_item(result, save=True)
|
||||||
|
|
||||||
msg = f"Part number: {part_number}"
|
FreeCAD.Console.PrintMessage(f"Created: {part_number}\n")
|
||||||
if selected_projects:
|
except Exception as e:
|
||||||
msg += f"\nTagged with projects: {', '.join(selected_projects)}"
|
FreeCAD.Console.PrintError(f"Failed to process created item: {e}\n")
|
||||||
|
|
||||||
FreeCAD.Console.PrintMessage(f"Created: {part_number}\n")
|
# Close the pre-document tab
|
||||||
QtGui.QMessageBox.information(None, "Item Created", msg)
|
sw.close()
|
||||||
|
|
||||||
except Exception as e:
|
form.item_created.connect(_on_created)
|
||||||
QtGui.QMessageBox.critical(None, "Error", str(e))
|
form.cancelled.connect(sw.close)
|
||||||
|
|
||||||
def IsActive(self):
|
def IsActive(self):
|
||||||
return _server_mode == "normal"
|
return _server_mode == "normal"
|
||||||
|
|
||||||
|
|
||||||
|
def _push_dag_after_upload(doc, part_number, revision_number):
|
||||||
|
"""Extract and push the feature DAG after a successful upload.
|
||||||
|
|
||||||
|
Failures are logged as warnings -- DAG sync must never block save.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from dag import extract_dag
|
||||||
|
|
||||||
|
nodes, edges = extract_dag(doc)
|
||||||
|
if not nodes:
|
||||||
|
return
|
||||||
|
|
||||||
|
result = _client.push_dag(part_number, revision_number, nodes, edges)
|
||||||
|
node_count = result.get("node_count", len(nodes))
|
||||||
|
edge_count = result.get("edge_count", len(edges))
|
||||||
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"DAG synced: {node_count} nodes, {edge_count} edges\n"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
FreeCAD.Console.PrintWarning(f"DAG sync failed: {e}\n")
|
||||||
|
|
||||||
|
|
||||||
class Silo_Save:
|
class Silo_Save:
|
||||||
"""Save locally and upload to MinIO."""
|
"""Save locally and upload to MinIO."""
|
||||||
|
|
||||||
@@ -920,11 +802,15 @@ class Silo_Save:
|
|||||||
|
|
||||||
# Try to upload to MinIO
|
# Try to upload to MinIO
|
||||||
try:
|
try:
|
||||||
result = _client._upload_file(part_number, str(file_path), properties, "Auto-save")
|
result = _client._upload_file(
|
||||||
|
part_number, str(file_path), properties, "Auto-save"
|
||||||
|
)
|
||||||
|
|
||||||
new_rev = result["revision_number"]
|
new_rev = result["revision_number"]
|
||||||
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)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
FreeCAD.Console.PrintWarning(f"Upload failed: {e}\n")
|
FreeCAD.Console.PrintWarning(f"Upload failed: {e}\n")
|
||||||
FreeCAD.Console.PrintMessage("File saved locally but not uploaded.\n")
|
FreeCAD.Console.PrintMessage("File saved locally but not uploaded.\n")
|
||||||
@@ -953,7 +839,9 @@ class Silo_Commit:
|
|||||||
|
|
||||||
obj = get_tracked_object(doc)
|
obj = get_tracked_object(doc)
|
||||||
if not obj:
|
if not obj:
|
||||||
FreeCAD.Console.PrintError("No tracked object. Use 'New' to register first.\n")
|
FreeCAD.Console.PrintError(
|
||||||
|
"No tracked object. Use 'New' to register first.\n"
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
part_number = obj.SiloPartNumber
|
part_number = obj.SiloPartNumber
|
||||||
@@ -970,11 +858,15 @@ class Silo_Commit:
|
|||||||
if not file_path:
|
if not file_path:
|
||||||
return
|
return
|
||||||
|
|
||||||
result = _client._upload_file(part_number, str(file_path), properties, comment)
|
result = _client._upload_file(
|
||||||
|
part_number, str(file_path), properties, comment
|
||||||
|
)
|
||||||
|
|
||||||
new_rev = result["revision_number"]
|
new_rev = result["revision_number"]
|
||||||
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)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
FreeCAD.Console.PrintError(f"Commit failed: {e}\n")
|
FreeCAD.Console.PrintError(f"Commit failed: {e}\n")
|
||||||
|
|
||||||
@@ -1019,7 +911,9 @@ def _check_pull_conflicts(part_number, local_path, doc=None):
|
|||||||
server_updated = item.get("updated_at", "")
|
server_updated = item.get("updated_at", "")
|
||||||
if server_updated:
|
if server_updated:
|
||||||
# Parse ISO format timestamp
|
# Parse ISO format timestamp
|
||||||
server_dt = datetime.datetime.fromisoformat(server_updated.replace("Z", "+00:00"))
|
server_dt = datetime.datetime.fromisoformat(
|
||||||
|
server_updated.replace("Z", "+00:00")
|
||||||
|
)
|
||||||
if server_dt > local_mtime:
|
if server_dt > local_mtime:
|
||||||
conflicts.append("Server version is newer than local file.")
|
conflicts.append("Server version is newer than local file.")
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -1049,7 +943,9 @@ class SiloPullDialog:
|
|||||||
# Revision table
|
# Revision table
|
||||||
self._table = QtGui.QTableWidget()
|
self._table = QtGui.QTableWidget()
|
||||||
self._table.setColumnCount(5)
|
self._table.setColumnCount(5)
|
||||||
self._table.setHorizontalHeaderLabels(["Rev", "Date", "Comment", "Status", "File"])
|
self._table.setHorizontalHeaderLabels(
|
||||||
|
["Rev", "Date", "Comment", "Status", "File"]
|
||||||
|
)
|
||||||
self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
|
self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
|
||||||
self._table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
|
self._table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
|
||||||
self._table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
|
self._table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
|
||||||
@@ -1121,6 +1017,67 @@ class SiloPullDialog:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _pull_dependencies(part_number, progress_callback=None):
|
||||||
|
"""Recursively pull all BOM children that have files on the server.
|
||||||
|
|
||||||
|
Returns list of (part_number, dest_path) tuples for successfully pulled files.
|
||||||
|
Skips children that already exist locally.
|
||||||
|
"""
|
||||||
|
pulled = []
|
||||||
|
try:
|
||||||
|
bom = _client.get_bom(part_number)
|
||||||
|
except Exception as e:
|
||||||
|
FreeCAD.Console.PrintWarning(f"Could not fetch BOM for {part_number}: {e}\n")
|
||||||
|
return pulled
|
||||||
|
|
||||||
|
for entry in bom:
|
||||||
|
child_pn = entry.get("child_part_number")
|
||||||
|
if not child_pn:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Skip if already exists locally
|
||||||
|
existing = find_file_by_part_number(child_pn)
|
||||||
|
if existing and existing.exists():
|
||||||
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f" {child_pn}: already exists at {existing}\n"
|
||||||
|
)
|
||||||
|
# Still recurse — this child may itself be an assembly with missing deps
|
||||||
|
_pull_dependencies(child_pn, progress_callback)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Check if this child has a file on the server
|
||||||
|
try:
|
||||||
|
latest = _client.latest_file_revision(child_pn)
|
||||||
|
except Exception:
|
||||||
|
latest = None
|
||||||
|
|
||||||
|
if not latest or not latest.get("file_key"):
|
||||||
|
FreeCAD.Console.PrintMessage(f" {child_pn}: no file on server, skipping\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Determine destination path
|
||||||
|
child_desc = entry.get("child_description", "")
|
||||||
|
dest_path = get_cad_file_path(child_pn, child_desc)
|
||||||
|
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
rev_num = latest["revision_number"]
|
||||||
|
FreeCAD.Console.PrintMessage(f" Pulling {child_pn} rev {rev_num}...\n")
|
||||||
|
|
||||||
|
try:
|
||||||
|
ok = _client._download_file(
|
||||||
|
child_pn, rev_num, str(dest_path), progress_callback=progress_callback
|
||||||
|
)
|
||||||
|
if ok:
|
||||||
|
pulled.append((child_pn, dest_path))
|
||||||
|
except Exception as e:
|
||||||
|
FreeCAD.Console.PrintWarning(f" Failed to pull {child_pn}: {e}\n")
|
||||||
|
|
||||||
|
# Recurse into child (it may be a sub-assembly)
|
||||||
|
_pull_dependencies(child_pn, progress_callback)
|
||||||
|
|
||||||
|
return pulled
|
||||||
|
|
||||||
|
|
||||||
class Silo_Pull:
|
class Silo_Pull:
|
||||||
"""Download from MinIO / sync from database."""
|
"""Download from MinIO / sync from database."""
|
||||||
|
|
||||||
@@ -1163,14 +1120,18 @@ class Silo_Pull:
|
|||||||
|
|
||||||
if not has_any_file:
|
if not has_any_file:
|
||||||
if existing_local:
|
if existing_local:
|
||||||
FreeCAD.Console.PrintMessage(f"Opening existing local file: {existing_local}\n")
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Opening existing local file: {existing_local}\n"
|
||||||
|
)
|
||||||
FreeCAD.openDocument(str(existing_local))
|
FreeCAD.openDocument(str(existing_local))
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
item = _client.get_item(part_number)
|
item = _client.get_item(part_number)
|
||||||
new_doc = _sync.create_document_for_item(item, save=True)
|
new_doc = _sync.create_document_for_item(item, save=True)
|
||||||
if new_doc:
|
if new_doc:
|
||||||
FreeCAD.Console.PrintMessage(f"Created local file for {part_number}\n")
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Created local file for {part_number}\n"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
QtGui.QMessageBox.warning(
|
QtGui.QMessageBox.warning(
|
||||||
None,
|
None,
|
||||||
@@ -1248,6 +1209,19 @@ class Silo_Pull:
|
|||||||
|
|
||||||
FreeCAD.Console.PrintMessage(f"Pulled revision {rev_num} of {part_number}\n")
|
FreeCAD.Console.PrintMessage(f"Pulled revision {rev_num} of {part_number}\n")
|
||||||
|
|
||||||
|
# Pull assembly dependencies before opening so links resolve
|
||||||
|
if item.get("item_type") == "assembly":
|
||||||
|
progress.setLabelText(f"Pulling dependencies for {part_number}...")
|
||||||
|
progress.setValue(0)
|
||||||
|
progress.show()
|
||||||
|
dep_pulled = _pull_dependencies(part_number, progress_callback=on_progress)
|
||||||
|
progress.setValue(100)
|
||||||
|
progress.close()
|
||||||
|
if dep_pulled:
|
||||||
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Pulled {len(dep_pulled)} dependency file(s)\n"
|
||||||
|
)
|
||||||
|
|
||||||
# Close existing document if open, then reopen
|
# Close existing document if open, then reopen
|
||||||
if doc and doc.FileName == str(dest_path):
|
if doc and doc.FileName == str(dest_path):
|
||||||
FreeCAD.closeDocument(doc.Name)
|
FreeCAD.closeDocument(doc.Name)
|
||||||
@@ -1301,7 +1275,9 @@ class Silo_Push:
|
|||||||
server_dt = datetime.fromisoformat(
|
server_dt = datetime.fromisoformat(
|
||||||
server_time_str.replace("Z", "+00:00")
|
server_time_str.replace("Z", "+00:00")
|
||||||
)
|
)
|
||||||
local_dt = datetime.fromtimestamp(local_mtime, tz=timezone.utc)
|
local_dt = datetime.fromtimestamp(
|
||||||
|
local_mtime, tz=timezone.utc
|
||||||
|
)
|
||||||
if local_dt > server_dt:
|
if local_dt > server_dt:
|
||||||
unuploaded.append(lf)
|
unuploaded.append(lf)
|
||||||
else:
|
else:
|
||||||
@@ -1314,7 +1290,9 @@ class Silo_Push:
|
|||||||
pass # Not in DB, skip
|
pass # Not in DB, skip
|
||||||
|
|
||||||
if not unuploaded:
|
if not unuploaded:
|
||||||
QtGui.QMessageBox.information(None, "Push", "All local files are already uploaded.")
|
QtGui.QMessageBox.information(
|
||||||
|
None, "Push", "All local files are already uploaded."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
msg = f"Found {len(unuploaded)} files to upload:\n\n"
|
msg = f"Found {len(unuploaded)} files to upload:\n\n"
|
||||||
@@ -1332,7 +1310,9 @@ class Silo_Push:
|
|||||||
|
|
||||||
uploaded = 0
|
uploaded = 0
|
||||||
for item in unuploaded:
|
for item in unuploaded:
|
||||||
result = _sync.upload_file(item["part_number"], item["path"], "Synced from local")
|
result = _sync.upload_file(
|
||||||
|
item["part_number"], item["path"], "Synced from local"
|
||||||
|
)
|
||||||
if result:
|
if result:
|
||||||
uploaded += 1
|
uploaded += 1
|
||||||
|
|
||||||
@@ -1381,9 +1361,7 @@ class Silo_Info:
|
|||||||
msg = f"<h3>{part_number}</h3>"
|
msg = f"<h3>{part_number}</h3>"
|
||||||
msg += f"<p><b>Type:</b> {item.get('item_type', '-')}</p>"
|
msg += f"<p><b>Type:</b> {item.get('item_type', '-')}</p>"
|
||||||
msg += f"<p><b>Description:</b> {item.get('description', '-')}</p>"
|
msg += f"<p><b>Description:</b> {item.get('description', '-')}</p>"
|
||||||
msg += (
|
msg += f"<p><b>Projects:</b> {', '.join(project_codes) if project_codes else 'None'}</p>"
|
||||||
f"<p><b>Projects:</b> {', '.join(project_codes) if project_codes else 'None'}</p>"
|
|
||||||
)
|
|
||||||
msg += f"<p><b>Current Revision:</b> {item.get('current_revision', 1)}</p>"
|
msg += f"<p><b>Current Revision:</b> {item.get('current_revision', 1)}</p>"
|
||||||
msg += f"<p><b>Local Revision:</b> {getattr(obj, 'SiloRevision', '-')}</p>"
|
msg += f"<p><b>Local Revision:</b> {getattr(obj, 'SiloRevision', '-')}</p>"
|
||||||
|
|
||||||
@@ -1449,7 +1427,9 @@ class Silo_TagProjects:
|
|||||||
try:
|
try:
|
||||||
# Get current projects for item
|
# Get current projects for item
|
||||||
current_projects = _client.get_item_projects(part_number)
|
current_projects = _client.get_item_projects(part_number)
|
||||||
current_codes = {p.get("code", "") for p in current_projects if p.get("code")}
|
current_codes = {
|
||||||
|
p.get("code", "") for p in current_projects if p.get("code")
|
||||||
|
}
|
||||||
|
|
||||||
# Get all available projects
|
# Get all available projects
|
||||||
all_projects = _client.get_projects()
|
all_projects = _client.get_projects()
|
||||||
@@ -1560,7 +1540,9 @@ class Silo_Rollback:
|
|||||||
dialog.setMinimumHeight(300)
|
dialog.setMinimumHeight(300)
|
||||||
layout = QtGui.QVBoxLayout(dialog)
|
layout = QtGui.QVBoxLayout(dialog)
|
||||||
|
|
||||||
label = QtGui.QLabel(f"Select a revision to rollback to (current: Rev {current_rev}):")
|
label = QtGui.QLabel(
|
||||||
|
f"Select a revision to rollback to (current: Rev {current_rev}):"
|
||||||
|
)
|
||||||
layout.addWidget(label)
|
layout.addWidget(label)
|
||||||
|
|
||||||
# Revision table
|
# Revision table
|
||||||
@@ -1575,8 +1557,12 @@ class Silo_Rollback:
|
|||||||
for i, rev in enumerate(prev_revisions):
|
for i, rev in enumerate(prev_revisions):
|
||||||
table.setItem(i, 0, QtGui.QTableWidgetItem(str(rev["revision_number"])))
|
table.setItem(i, 0, QtGui.QTableWidgetItem(str(rev["revision_number"])))
|
||||||
table.setItem(i, 1, QtGui.QTableWidgetItem(rev.get("status", "draft")))
|
table.setItem(i, 1, QtGui.QTableWidgetItem(rev.get("status", "draft")))
|
||||||
table.setItem(i, 2, QtGui.QTableWidgetItem(rev.get("created_at", "")[:10]))
|
table.setItem(
|
||||||
table.setItem(i, 3, QtGui.QTableWidgetItem(rev.get("comment", "") or ""))
|
i, 2, QtGui.QTableWidgetItem(rev.get("created_at", "")[:10])
|
||||||
|
)
|
||||||
|
table.setItem(
|
||||||
|
i, 3, QtGui.QTableWidgetItem(rev.get("comment", "") or "")
|
||||||
|
)
|
||||||
|
|
||||||
table.resizeColumnsToContents()
|
table.resizeColumnsToContents()
|
||||||
layout.addWidget(table)
|
layout.addWidget(table)
|
||||||
@@ -1602,7 +1588,9 @@ class Silo_Rollback:
|
|||||||
def on_rollback():
|
def on_rollback():
|
||||||
selected = table.selectedItems()
|
selected = table.selectedItems()
|
||||||
if not selected:
|
if not selected:
|
||||||
QtGui.QMessageBox.warning(dialog, "Rollback", "Please select a revision")
|
QtGui.QMessageBox.warning(
|
||||||
|
dialog, "Rollback", "Please select a revision"
|
||||||
|
)
|
||||||
return
|
return
|
||||||
selected_rev[0] = int(table.item(selected[0].row(), 0).text())
|
selected_rev[0] = int(table.item(selected[0].row(), 0).text())
|
||||||
dialog.accept()
|
dialog.accept()
|
||||||
@@ -1700,7 +1688,9 @@ class Silo_SetStatus:
|
|||||||
# Update status
|
# Update status
|
||||||
_client.update_revision(part_number, rev_num, status=status)
|
_client.update_revision(part_number, rev_num, status=status)
|
||||||
|
|
||||||
FreeCAD.Console.PrintMessage(f"Updated Rev {rev_num} status to '{status}'\n")
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Updated Rev {rev_num} status to '{status}'\n"
|
||||||
|
)
|
||||||
QtGui.QMessageBox.information(
|
QtGui.QMessageBox.information(
|
||||||
None, "Status Updated", f"Revision {rev_num} status set to '{status}'"
|
None, "Status Updated", f"Revision {rev_num} status set to '{status}'"
|
||||||
)
|
)
|
||||||
@@ -1764,7 +1754,9 @@ class Silo_Settings:
|
|||||||
ssl_checkbox.setChecked(param.GetBool("SslVerify", True))
|
ssl_checkbox.setChecked(param.GetBool("SslVerify", True))
|
||||||
layout.addWidget(ssl_checkbox)
|
layout.addWidget(ssl_checkbox)
|
||||||
|
|
||||||
ssl_hint = QtGui.QLabel("Disable only for internal servers with self-signed certificates.")
|
ssl_hint = QtGui.QLabel(
|
||||||
|
"Disable only for internal servers with self-signed certificates."
|
||||||
|
)
|
||||||
ssl_hint.setWordWrap(True)
|
ssl_hint.setWordWrap(True)
|
||||||
ssl_hint.setStyleSheet("color: #888; font-size: 11px;")
|
ssl_hint.setStyleSheet("color: #888; font-size: 11px;")
|
||||||
layout.addWidget(ssl_hint)
|
layout.addWidget(ssl_hint)
|
||||||
@@ -1797,7 +1789,7 @@ class Silo_Settings:
|
|||||||
path, _ = QtGui.QFileDialog.getOpenFileName(
|
path, _ = QtGui.QFileDialog.getOpenFileName(
|
||||||
dialog,
|
dialog,
|
||||||
"Select CA Certificate",
|
"Select CA Certificate",
|
||||||
os.path.dirname(cert_input.text()) or "/etc/ssl/certs",
|
os.path.dirname(cert_input.text()) or os.path.expanduser("~"),
|
||||||
"Certificates (*.pem *.crt *.cer);;All Files (*)",
|
"Certificates (*.pem *.crt *.cer);;All Files (*)",
|
||||||
)
|
)
|
||||||
if path:
|
if path:
|
||||||
@@ -2041,7 +2033,9 @@ class Silo_BOM:
|
|||||||
|
|
||||||
wu_table = QtGui.QTableWidget()
|
wu_table = QtGui.QTableWidget()
|
||||||
wu_table.setColumnCount(5)
|
wu_table.setColumnCount(5)
|
||||||
wu_table.setHorizontalHeaderLabels(["Parent Part Number", "Type", "Qty", "Unit", "Ref Des"])
|
wu_table.setHorizontalHeaderLabels(
|
||||||
|
["Parent Part Number", "Type", "Qty", "Unit", "Ref Des"]
|
||||||
|
)
|
||||||
wu_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
|
wu_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
|
||||||
wu_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
|
wu_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
|
||||||
wu_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
|
wu_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
|
||||||
@@ -2070,12 +2064,16 @@ class Silo_BOM:
|
|||||||
bom_table.setItem(
|
bom_table.setItem(
|
||||||
row, 1, QtGui.QTableWidgetItem(entry.get("child_description", ""))
|
row, 1, QtGui.QTableWidgetItem(entry.get("child_description", ""))
|
||||||
)
|
)
|
||||||
bom_table.setItem(row, 2, QtGui.QTableWidgetItem(entry.get("rel_type", "")))
|
bom_table.setItem(
|
||||||
|
row, 2, QtGui.QTableWidgetItem(entry.get("rel_type", ""))
|
||||||
|
)
|
||||||
qty = entry.get("quantity")
|
qty = entry.get("quantity")
|
||||||
bom_table.setItem(
|
bom_table.setItem(
|
||||||
row, 3, QtGui.QTableWidgetItem(str(qty) if qty is not None else "")
|
row, 3, QtGui.QTableWidgetItem(str(qty) if qty is not None else "")
|
||||||
)
|
)
|
||||||
bom_table.setItem(row, 4, QtGui.QTableWidgetItem(entry.get("unit") or ""))
|
bom_table.setItem(
|
||||||
|
row, 4, QtGui.QTableWidgetItem(entry.get("unit") or "")
|
||||||
|
)
|
||||||
ref_des = entry.get("reference_designators") or []
|
ref_des = entry.get("reference_designators") or []
|
||||||
bom_table.setItem(row, 5, QtGui.QTableWidgetItem(", ".join(ref_des)))
|
bom_table.setItem(row, 5, QtGui.QTableWidgetItem(", ".join(ref_des)))
|
||||||
bom_table.setItem(
|
bom_table.setItem(
|
||||||
@@ -2097,12 +2095,16 @@ class Silo_BOM:
|
|||||||
wu_table.setItem(
|
wu_table.setItem(
|
||||||
row, 0, QtGui.QTableWidgetItem(entry.get("parent_part_number", ""))
|
row, 0, QtGui.QTableWidgetItem(entry.get("parent_part_number", ""))
|
||||||
)
|
)
|
||||||
wu_table.setItem(row, 1, QtGui.QTableWidgetItem(entry.get("rel_type", "")))
|
wu_table.setItem(
|
||||||
|
row, 1, QtGui.QTableWidgetItem(entry.get("rel_type", ""))
|
||||||
|
)
|
||||||
qty = entry.get("quantity")
|
qty = entry.get("quantity")
|
||||||
wu_table.setItem(
|
wu_table.setItem(
|
||||||
row, 2, QtGui.QTableWidgetItem(str(qty) if qty is not None else "")
|
row, 2, QtGui.QTableWidgetItem(str(qty) if qty is not None else "")
|
||||||
)
|
)
|
||||||
wu_table.setItem(row, 3, QtGui.QTableWidgetItem(entry.get("unit") or ""))
|
wu_table.setItem(
|
||||||
|
row, 3, QtGui.QTableWidgetItem(entry.get("unit") or "")
|
||||||
|
)
|
||||||
ref_des = entry.get("reference_designators") or []
|
ref_des = entry.get("reference_designators") or []
|
||||||
wu_table.setItem(row, 4, QtGui.QTableWidgetItem(", ".join(ref_des)))
|
wu_table.setItem(row, 4, QtGui.QTableWidgetItem(", ".join(ref_des)))
|
||||||
wu_table.resizeColumnsToContents()
|
wu_table.resizeColumnsToContents()
|
||||||
@@ -2155,7 +2157,9 @@ class Silo_BOM:
|
|||||||
try:
|
try:
|
||||||
qty = float(qty_text)
|
qty = float(qty_text)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
QtGui.QMessageBox.warning(dialog, "BOM", "Quantity must be a number.")
|
QtGui.QMessageBox.warning(
|
||||||
|
dialog, "BOM", "Quantity must be a number."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
unit = unit_input.text().strip() or None
|
unit = unit_input.text().strip() or None
|
||||||
@@ -2234,7 +2238,9 @@ class Silo_BOM:
|
|||||||
try:
|
try:
|
||||||
new_qty = float(qty_text)
|
new_qty = float(qty_text)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
QtGui.QMessageBox.warning(dialog, "BOM", "Quantity must be a number.")
|
QtGui.QMessageBox.warning(
|
||||||
|
dialog, "BOM", "Quantity must be a number."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
new_unit = unit_input.text().strip() or None
|
new_unit = unit_input.text().strip() or None
|
||||||
@@ -2258,7 +2264,9 @@ class Silo_BOM:
|
|||||||
)
|
)
|
||||||
load_bom()
|
load_bom()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
QtGui.QMessageBox.warning(dialog, "BOM", f"Failed to update entry:\n{exc}")
|
QtGui.QMessageBox.warning(
|
||||||
|
dialog, "BOM", f"Failed to update entry:\n{exc}"
|
||||||
|
)
|
||||||
|
|
||||||
def on_remove():
|
def on_remove():
|
||||||
selected = bom_table.selectedItems()
|
selected = bom_table.selectedItems()
|
||||||
@@ -2284,7 +2292,9 @@ class Silo_BOM:
|
|||||||
_client.delete_bom_entry(part_number, child_pn)
|
_client.delete_bom_entry(part_number, child_pn)
|
||||||
load_bom()
|
load_bom()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
QtGui.QMessageBox.warning(dialog, "BOM", f"Failed to remove entry:\n{exc}")
|
QtGui.QMessageBox.warning(
|
||||||
|
dialog, "BOM", f"Failed to remove entry:\n{exc}"
|
||||||
|
)
|
||||||
|
|
||||||
add_btn.clicked.connect(on_add)
|
add_btn.clicked.connect(on_add)
|
||||||
edit_btn.clicked.connect(on_edit)
|
edit_btn.clicked.connect(on_edit)
|
||||||
@@ -2323,7 +2333,9 @@ class SiloEventListener(QtCore.QThread):
|
|||||||
|
|
||||||
item_updated = QtCore.Signal(str) # part_number
|
item_updated = QtCore.Signal(str) # part_number
|
||||||
revision_created = QtCore.Signal(str, int) # part_number, revision
|
revision_created = QtCore.Signal(str, int) # part_number, revision
|
||||||
connection_status = QtCore.Signal(str, int, str) # (status, retry_count, error_message)
|
connection_status = QtCore.Signal(
|
||||||
|
str, int, str
|
||||||
|
) # (status, retry_count, error_message)
|
||||||
server_mode_changed = QtCore.Signal(str) # "normal" / "read-only" / "degraded"
|
server_mode_changed = QtCore.Signal(str) # "normal" / "read-only" / "degraded"
|
||||||
|
|
||||||
_MAX_RETRIES = 10
|
_MAX_RETRIES = 10
|
||||||
@@ -2350,23 +2362,30 @@ class SiloEventListener(QtCore.QThread):
|
|||||||
# -- thread entry -------------------------------------------------------
|
# -- thread entry -------------------------------------------------------
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
|
import time
|
||||||
|
|
||||||
retries = 0
|
retries = 0
|
||||||
last_error = ""
|
last_error = ""
|
||||||
while not self._stop_flag:
|
while not self._stop_flag:
|
||||||
|
t0 = time.monotonic()
|
||||||
try:
|
try:
|
||||||
self._listen()
|
self._listen()
|
||||||
# _listen returns normally only on clean EOF / stop
|
# _listen returns normally only on clean EOF / stop
|
||||||
if self._stop_flag:
|
if self._stop_flag:
|
||||||
return
|
return
|
||||||
retries += 1
|
|
||||||
last_error = "connection closed"
|
last_error = "connection closed"
|
||||||
except _SSEUnsupported:
|
except _SSEUnsupported:
|
||||||
self.connection_status.emit("unsupported", 0, "")
|
self.connection_status.emit("unsupported", 0, "")
|
||||||
return
|
return
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
retries += 1
|
|
||||||
last_error = str(exc) or "unknown error"
|
last_error = str(exc) or "unknown error"
|
||||||
|
|
||||||
|
# Reset retries if the connection was up for a while
|
||||||
|
elapsed = time.monotonic() - t0
|
||||||
|
if elapsed > 30:
|
||||||
|
retries = 0
|
||||||
|
retries += 1
|
||||||
|
|
||||||
if retries > self._MAX_RETRIES:
|
if retries > self._MAX_RETRIES:
|
||||||
self.connection_status.emit("gave_up", retries - 1, last_error)
|
self.connection_status.emit("gave_up", retries - 1, last_error)
|
||||||
return
|
return
|
||||||
@@ -2390,7 +2409,9 @@ class SiloEventListener(QtCore.QThread):
|
|||||||
req = urllib.request.Request(url, headers=headers, method="GET")
|
req = urllib.request.Request(url, headers=headers, method="GET")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self._response = urllib.request.urlopen(req, context=_get_ssl_context(), timeout=90)
|
self._response = urllib.request.urlopen(
|
||||||
|
req, context=_get_ssl_context(), timeout=90
|
||||||
|
)
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
if e.code in (404, 501):
|
if e.code in (404, 501):
|
||||||
raise _SSEUnsupported()
|
raise _SSEUnsupported()
|
||||||
@@ -2671,7 +2692,9 @@ class SiloAuthDockWidget:
|
|||||||
self._sse_label.setToolTip("")
|
self._sse_label.setToolTip("")
|
||||||
FreeCAD.Console.PrintMessage("Silo: SSE connected\n")
|
FreeCAD.Console.PrintMessage("Silo: SSE connected\n")
|
||||||
elif status == "disconnected":
|
elif status == "disconnected":
|
||||||
self._sse_label.setText(f"Reconnecting ({retry}/{SiloEventListener._MAX_RETRIES})...")
|
self._sse_label.setText(
|
||||||
|
f"Reconnecting ({retry}/{SiloEventListener._MAX_RETRIES})..."
|
||||||
|
)
|
||||||
self._sse_label.setStyleSheet("font-size: 11px; color: #FF9800;")
|
self._sse_label.setStyleSheet("font-size: 11px; color: #FF9800;")
|
||||||
self._sse_label.setToolTip(error or "Connection lost")
|
self._sse_label.setToolTip(error or "Connection lost")
|
||||||
FreeCAD.Console.PrintWarning(
|
FreeCAD.Console.PrintWarning(
|
||||||
@@ -2681,7 +2704,9 @@ class SiloAuthDockWidget:
|
|||||||
self._sse_label.setText("Disconnected")
|
self._sse_label.setText("Disconnected")
|
||||||
self._sse_label.setStyleSheet("font-size: 11px; color: #F44336;")
|
self._sse_label.setStyleSheet("font-size: 11px; color: #F44336;")
|
||||||
self._sse_label.setToolTip(error or "Max retries reached")
|
self._sse_label.setToolTip(error or "Max retries reached")
|
||||||
FreeCAD.Console.PrintError(f"Silo: SSE gave up after {retry} retries: {error}\n")
|
FreeCAD.Console.PrintError(
|
||||||
|
f"Silo: SSE gave up after {retry} retries: {error}\n"
|
||||||
|
)
|
||||||
elif status == "unsupported":
|
elif status == "unsupported":
|
||||||
self._sse_label.setText("Not available")
|
self._sse_label.setText("Not available")
|
||||||
self._sse_label.setStyleSheet("font-size: 11px; color: #888;")
|
self._sse_label.setStyleSheet("font-size: 11px; color: #888;")
|
||||||
@@ -2723,10 +2748,14 @@ class SiloAuthDockWidget:
|
|||||||
self._refresh_activity_panel()
|
self._refresh_activity_panel()
|
||||||
|
|
||||||
def _on_remote_revision(self, part_number, revision):
|
def _on_remote_revision(self, part_number, revision):
|
||||||
FreeCAD.Console.PrintMessage(f"Silo: New revision {revision} for {part_number}\n")
|
FreeCAD.Console.PrintMessage(
|
||||||
|
f"Silo: New revision {revision} for {part_number}\n"
|
||||||
|
)
|
||||||
mw = FreeCADGui.getMainWindow()
|
mw = FreeCADGui.getMainWindow()
|
||||||
if mw is not None:
|
if mw is not None:
|
||||||
mw.statusBar().showMessage(f"Silo: {part_number} rev {revision} available", 5000)
|
mw.statusBar().showMessage(
|
||||||
|
f"Silo: {part_number} rev {revision} available", 5000
|
||||||
|
)
|
||||||
self._refresh_activity_panel()
|
self._refresh_activity_panel()
|
||||||
|
|
||||||
def _refresh_activity_panel(self):
|
def _refresh_activity_panel(self):
|
||||||
@@ -2792,7 +2821,9 @@ class SiloAuthDockWidget:
|
|||||||
rev_part = f" \u2013 Rev {rev_num}" if rev_num else ""
|
rev_part = f" \u2013 Rev {rev_num}" if rev_num else ""
|
||||||
date_part = f" \u2013 {updated}" if updated else ""
|
date_part = f" \u2013 {updated}" if updated else ""
|
||||||
local_badge = " \u25cf local" if pn in local_pns else ""
|
local_badge = " \u25cf local" if pn in local_pns else ""
|
||||||
line1 = f"{pn} \u2013 {desc_display}{rev_part}{date_part}{local_badge}"
|
line1 = (
|
||||||
|
f"{pn} \u2013 {desc_display}{rev_part}{date_part}{local_badge}"
|
||||||
|
)
|
||||||
|
|
||||||
if comment:
|
if comment:
|
||||||
line1 += f'\n "{comment}"'
|
line1 += f'\n "{comment}"'
|
||||||
@@ -3248,7 +3279,9 @@ class Silo_StartPanel:
|
|||||||
dock = QtGui.QDockWidget("Silo", mw)
|
dock = QtGui.QDockWidget("Silo", mw)
|
||||||
dock.setObjectName("SiloStartPanel")
|
dock.setObjectName("SiloStartPanel")
|
||||||
dock.setWidget(content.widget)
|
dock.setWidget(content.widget)
|
||||||
dock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
|
dock.setAllowedAreas(
|
||||||
|
QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea
|
||||||
|
)
|
||||||
mw.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
|
mw.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
|
||||||
|
|
||||||
def IsActive(self):
|
def IsActive(self):
|
||||||
@@ -3282,7 +3315,9 @@ class _DiagWorker(QtCore.QThread):
|
|||||||
self.result.emit("DNS", False, "no hostname in URL")
|
self.result.emit("DNS", False, "no hostname in URL")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
addrs = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
|
addrs = socket.getaddrinfo(
|
||||||
|
hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM
|
||||||
|
)
|
||||||
first_ip = addrs[0][4][0] if addrs else "?"
|
first_ip = addrs[0][4][0] if addrs else "?"
|
||||||
self.result.emit("DNS", True, f"{hostname} -> {first_ip}")
|
self.result.emit("DNS", True, f"{hostname} -> {first_ip}")
|
||||||
except socket.gaierror as e:
|
except socket.gaierror as e:
|
||||||
|
|||||||
@@ -392,12 +392,17 @@ class SiloOrigin:
|
|||||||
obj.SiloPartNumber, str(file_path), properties, comment=""
|
obj.SiloPartNumber, str(file_path), properties, comment=""
|
||||||
)
|
)
|
||||||
|
|
||||||
# Clear modified flag
|
# Clear modified flag (Modified is on Gui.Document, not App.Document)
|
||||||
doc.Modified = False
|
gui_doc = FreeCADGui.getDocument(doc.Name)
|
||||||
|
if gui_doc:
|
||||||
|
gui_doc.Modified = False
|
||||||
|
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
|
||||||
FreeCAD.Console.PrintError(f"Silo save failed: {e}\n")
|
FreeCAD.Console.PrintError(f"Silo save failed: {e}\n")
|
||||||
|
FreeCAD.Console.PrintError(traceback.format_exc())
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def saveDocumentAs(self, doc, newIdentity: str) -> bool:
|
def saveDocumentAs(self, doc, newIdentity: str) -> bool:
|
||||||
|
|||||||
Submodule silo-client updated: 68a4139251...fb658c5a24
Reference in New Issue
Block a user