Compare commits
19 Commits
fix/silo-w
...
fix/bom-re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
383eefce9c | ||
|
|
1676b3e1a0 | ||
|
|
06cd30e88d | ||
| f9924d35f7 | |||
| 373f3aaa79 | |||
| 66b2baf510 | |||
| 35f33f2079 | |||
|
|
d26bb6da2d | ||
|
|
e5126c913d | ||
| 76973aaae0 | |||
|
|
4ddbf26af7 | ||
| 516116ae9d | |||
|
|
6fa60af5e0 | ||
| fd3c97ff97 | |||
| fb9e1d3188 | |||
|
|
026ed0cb8a | ||
|
|
45e803402d | ||
|
|
fcb0a214e2 | ||
| 3228ef5f79 |
@@ -35,19 +35,9 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning(f"Could not register Silo origin: {e}\n")
|
||||
|
||||
self.toolbar_commands = [
|
||||
"Silo_ToggleMode",
|
||||
"Separator",
|
||||
"Silo_Open",
|
||||
"Silo_New",
|
||||
"Silo_Save",
|
||||
"Silo_Commit",
|
||||
"Silo_Pull",
|
||||
"Silo_Push",
|
||||
]
|
||||
|
||||
# Menu has management/admin commands (file commands are in File menu
|
||||
# via the Create module's SiloMenuManipulator)
|
||||
# Silo menu provides admin/management commands.
|
||||
# File operations (New/Open/Save) are handled by the standard File
|
||||
# toolbar via the origin system -- no separate Silo toolbar needed.
|
||||
self.menu_commands = [
|
||||
"Silo_Info",
|
||||
"Silo_BOM",
|
||||
@@ -57,15 +47,16 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
||||
"Separator",
|
||||
"Silo_Settings",
|
||||
"Silo_Auth",
|
||||
"Silo_StartPanel",
|
||||
"Silo_Diag",
|
||||
]
|
||||
|
||||
self.appendToolbar("Silo", self.toolbar_commands)
|
||||
self.appendMenu("Silo", self.menu_commands)
|
||||
|
||||
def Activated(self):
|
||||
"""Called when workbench is activated."""
|
||||
FreeCAD.Console.PrintMessage("Kindred Silo workbench activated\n")
|
||||
self._show_shortcut_recommendations()
|
||||
FreeCADGui.runCommand("Silo_StartPanel", 0)
|
||||
|
||||
def Deactivated(self):
|
||||
pass
|
||||
@@ -73,41 +64,6 @@ class SiloWorkbench(FreeCADGui.Workbench):
|
||||
def GetClassName(self):
|
||||
return "Gui::PythonWorkbench"
|
||||
|
||||
def _show_shortcut_recommendations(self):
|
||||
"""Show keyboard shortcut recommendations dialog on first activation."""
|
||||
try:
|
||||
param_group = FreeCAD.ParamGet(
|
||||
"User parameter:BaseApp/Preferences/Mod/KindredSilo"
|
||||
)
|
||||
if param_group.GetBool("ShortcutsShown", False):
|
||||
return
|
||||
param_group.SetBool("ShortcutsShown", True)
|
||||
|
||||
from PySide import QtGui
|
||||
|
||||
msg = """<h3>Welcome to Kindred Silo!</h3>
|
||||
<p>For the best experience, set up these keyboard shortcuts:</p>
|
||||
<table style="margin: 10px 0;">
|
||||
<tr><td><b>Ctrl+O</b></td><td> - </td><td>Silo_Open (Search & Open)</td></tr>
|
||||
<tr><td><b>Ctrl+N</b></td><td> - </td><td>Silo_New (Register new item)</td></tr>
|
||||
<tr><td><b>Ctrl+S</b></td><td> - </td><td>Silo_Save (Save & upload)</td></tr>
|
||||
<tr><td><b>Ctrl+Shift+S</b></td><td> - </td><td>Silo_Commit (Save with comment)</td></tr>
|
||||
</table>
|
||||
<p><b>To set shortcuts:</b> Tools > Customize > Keyboard</p>
|
||||
<p style="color: #888;">This message appears once.</p>"""
|
||||
|
||||
dialog = QtGui.QMessageBox()
|
||||
dialog.setWindowTitle("Silo Keyboard Shortcuts")
|
||||
dialog.setTextFormat(QtGui.Qt.RichText)
|
||||
dialog.setText(msg)
|
||||
dialog.setIcon(QtGui.QMessageBox.Information)
|
||||
dialog.addButton("Set Up Now", QtGui.QMessageBox.AcceptRole)
|
||||
dialog.addButton("Later", QtGui.QMessageBox.RejectRole)
|
||||
if dialog.exec_() == 0:
|
||||
FreeCADGui.runCommand("Std_DlgCustomize", 0)
|
||||
except Exception as e:
|
||||
FreeCAD.Console.PrintWarning("Silo shortcuts dialog: " + str(e) + "\n")
|
||||
|
||||
|
||||
FreeCADGui.addWorkbench(SiloWorkbench())
|
||||
FreeCAD.Console.PrintMessage("Silo workbench registered\n")
|
||||
|
||||
8
freecad/resources/icons/silo-rollback.svg
Normal file
8
freecad/resources/icons/silo-rollback.svg
Normal file
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#cba6f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Counter-clockwise arrow -->
|
||||
<polyline points="1 4 1 10 7 10" stroke="#f38ba8"/>
|
||||
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" stroke="#cba6f7"/>
|
||||
<!-- Clock hands -->
|
||||
<line x1="12" y1="7" x2="12" y2="12" stroke="#89dceb" stroke-width="1.5"/>
|
||||
<line x1="12" y1="12" x2="15" y2="14" stroke="#89dceb" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 493 B |
7
freecad/resources/icons/silo-status.svg
Normal file
7
freecad/resources/icons/silo-status.svg
Normal file
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#cba6f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Shield shape -->
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" fill="#313244"/>
|
||||
<!-- Status bars -->
|
||||
<line x1="8" y1="10" x2="16" y2="10" stroke="#a6e3a1" stroke-width="1.5"/>
|
||||
<line x1="8" y1="14" x2="13" y2="14" stroke="#89dceb" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 435 B |
6
freecad/resources/icons/silo-tag.svg
Normal file
6
freecad/resources/icons/silo-tag.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#cba6f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Tag shape -->
|
||||
<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" fill="#313244"/>
|
||||
<!-- Tag hole -->
|
||||
<circle cx="7" cy="7" r="1.5" fill="#cba6f7" stroke="none"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 373 B |
@@ -3,6 +3,7 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@@ -147,6 +148,39 @@ def _clear_auth():
|
||||
_fc_settings.clear_auth()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Server mode tracking
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_server_mode = "offline" # "normal" | "read-only" | "degraded" | "offline"
|
||||
|
||||
|
||||
def _fetch_server_mode() -> str:
|
||||
"""Fetch server mode from the /ready endpoint.
|
||||
|
||||
Returns one of: "normal", "read-only", "degraded", "offline".
|
||||
"""
|
||||
api_url = _get_api_url().rstrip("/")
|
||||
base_url = api_url[:-4] if api_url.endswith("/api") else api_url
|
||||
url = f"{base_url}/ready"
|
||||
try:
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
resp = urllib.request.urlopen(req, context=_get_ssl_context(), timeout=10)
|
||||
body = resp.read(4096).decode("utf-8", errors="replace")
|
||||
data = json.loads(body)
|
||||
status = data.get("status", "")
|
||||
if status in ("ok", "ready"):
|
||||
return "normal"
|
||||
if status in ("read-only", "read_only", "readonly"):
|
||||
return "read-only"
|
||||
if status in ("degraded",):
|
||||
return "degraded"
|
||||
# Unknown status but server responded — treat as normal
|
||||
return "normal"
|
||||
except Exception:
|
||||
return "offline"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Icon helper
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -817,7 +851,7 @@ class Silo_New:
|
||||
QtGui.QMessageBox.critical(None, "Error", str(e))
|
||||
|
||||
def IsActive(self):
|
||||
return True
|
||||
return _server_mode == "normal"
|
||||
|
||||
|
||||
class Silo_Save:
|
||||
@@ -895,7 +929,7 @@ class Silo_Save:
|
||||
FreeCAD.Console.PrintMessage("File saved locally but not uploaded.\n")
|
||||
|
||||
def IsActive(self):
|
||||
return FreeCAD.ActiveDocument is not None
|
||||
return FreeCAD.ActiveDocument is not None and _server_mode == "normal"
|
||||
|
||||
|
||||
class Silo_Commit:
|
||||
@@ -948,7 +982,7 @@ class Silo_Commit:
|
||||
FreeCAD.Console.PrintError(f"Commit failed: {e}\n")
|
||||
|
||||
def IsActive(self):
|
||||
return FreeCAD.ActiveDocument is not None
|
||||
return FreeCAD.ActiveDocument is not None and _server_mode == "normal"
|
||||
|
||||
|
||||
def _check_pull_conflicts(part_number, local_path, doc=None):
|
||||
@@ -1320,7 +1354,7 @@ class Silo_Push:
|
||||
QtGui.QMessageBox.information(None, "Push", f"Uploaded {uploaded} files.")
|
||||
|
||||
def IsActive(self):
|
||||
return True
|
||||
return _server_mode == "normal"
|
||||
|
||||
|
||||
class Silo_Info:
|
||||
@@ -1964,15 +1998,18 @@ class Silo_BOM:
|
||||
|
||||
obj = get_tracked_object(doc)
|
||||
if not obj:
|
||||
FreeCAD.Console.PrintError("No tracked Silo item in active document.\n")
|
||||
from PySide import QtGui as _qg
|
||||
|
||||
_qg.QMessageBox.warning(
|
||||
reply = QtGui.QMessageBox.question(
|
||||
None,
|
||||
"BOM",
|
||||
"This document is not registered with Silo.\nUse Silo > New to register it first.",
|
||||
"This document is not registered with Silo.\n\nRegister it now?",
|
||||
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
|
||||
)
|
||||
return
|
||||
if reply != QtGui.QMessageBox.Yes:
|
||||
return
|
||||
FreeCADGui.runCommand("Silo_New")
|
||||
obj = get_tracked_object(doc)
|
||||
if not obj:
|
||||
return
|
||||
|
||||
part_number = obj.SiloPartNumber
|
||||
|
||||
@@ -2316,85 +2353,6 @@ class Silo_BOM:
|
||||
return FreeCAD.ActiveDocument is not None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Silo Mode toggle - swap Ctrl+O/S/N between standard and Silo commands
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Stored original shortcuts so they can be restored on toggle-off
|
||||
_original_shortcuts: Dict[str, Any] = {}
|
||||
|
||||
|
||||
def _swap_shortcuts(mapping, enable_silo):
|
||||
"""Swap keyboard shortcuts between standard and Silo commands.
|
||||
|
||||
mapping: list of (std_cmd, silo_cmd, shortcut) tuples
|
||||
enable_silo: True to assign shortcuts to Silo commands, False to restore.
|
||||
"""
|
||||
from PySide import QtGui
|
||||
|
||||
mw = FreeCADGui.getMainWindow()
|
||||
if mw is None:
|
||||
return
|
||||
|
||||
for std_cmd, silo_cmd, shortcut in mapping:
|
||||
if enable_silo:
|
||||
# Save and clear the standard command's shortcut
|
||||
std_action = mw.findChild(QtGui.QAction, std_cmd)
|
||||
if std_action:
|
||||
_original_shortcuts[std_cmd] = std_action.shortcut().toString()
|
||||
std_action.setShortcut("")
|
||||
# Assign the shortcut to the Silo command
|
||||
silo_action = mw.findChild(QtGui.QAction, silo_cmd)
|
||||
if silo_action:
|
||||
silo_action.setShortcut(shortcut)
|
||||
else:
|
||||
# Clear the Silo command's shortcut
|
||||
silo_action = mw.findChild(QtGui.QAction, silo_cmd)
|
||||
if silo_action:
|
||||
silo_action.setShortcut("")
|
||||
# Restore the standard command's original shortcut
|
||||
std_action = mw.findChild(QtGui.QAction, std_cmd)
|
||||
if std_action and std_cmd in _original_shortcuts:
|
||||
std_action.setShortcut(_original_shortcuts.pop(std_cmd))
|
||||
|
||||
|
||||
_SHORTCUT_MAP = [
|
||||
("Std_Open", "Silo_Open", "Ctrl+O"),
|
||||
("Std_Save", "Silo_Save", "Ctrl+S"),
|
||||
("Std_New", "Silo_New", "Ctrl+N"),
|
||||
]
|
||||
|
||||
|
||||
class Silo_ToggleMode:
|
||||
"""Toggle between standard file operations and Silo equivalents."""
|
||||
|
||||
def GetResources(self):
|
||||
return {
|
||||
"MenuText": "Silo Mode",
|
||||
"ToolTip": (
|
||||
"Toggle between standard file operations and Silo equivalents.\n"
|
||||
"When ON: Ctrl+O/S/N use Silo Open/Save/New.\n"
|
||||
"When OFF: Standard FreeCAD file operations."
|
||||
),
|
||||
"Pixmap": _icon("silo"),
|
||||
"Checkable": True,
|
||||
}
|
||||
|
||||
def Activated(self, checked):
|
||||
param = FreeCAD.ParamGet(_PREF_GROUP)
|
||||
if checked:
|
||||
_swap_shortcuts(_SHORTCUT_MAP, enable_silo=True)
|
||||
param.SetBool("SiloMode", True)
|
||||
FreeCAD.Console.PrintMessage("Silo mode enabled\n")
|
||||
else:
|
||||
_swap_shortcuts(_SHORTCUT_MAP, enable_silo=False)
|
||||
param.SetBool("SiloMode", False)
|
||||
FreeCAD.Console.PrintMessage("Silo mode disabled\n")
|
||||
|
||||
def IsActive(self):
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SSE live-update listener
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -2411,12 +2369,13 @@ class SiloEventListener(QtCore.QThread):
|
||||
item_updated = QtCore.Signal(str) # part_number
|
||||
revision_created = QtCore.Signal(str, int) # part_number, revision
|
||||
connection_status = QtCore.Signal(
|
||||
str
|
||||
) # "connected" / "disconnected" / "unsupported"
|
||||
str, int, str
|
||||
) # (status, retry_count, error_message)
|
||||
server_mode_changed = QtCore.Signal(str) # "normal" / "read-only" / "degraded"
|
||||
|
||||
_MAX_FAST_RETRIES = 3
|
||||
_FAST_RETRY_SECS = 5
|
||||
_SLOW_RETRY_SECS = 30
|
||||
_MAX_RETRIES = 10
|
||||
_BASE_DELAY = 1 # seconds, doubles each retry
|
||||
_MAX_DELAY = 60 # seconds, backoff cap
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
@@ -2439,6 +2398,7 @@ class SiloEventListener(QtCore.QThread):
|
||||
|
||||
def run(self):
|
||||
retries = 0
|
||||
last_error = ""
|
||||
while not self._stop_flag:
|
||||
try:
|
||||
self._listen()
|
||||
@@ -2446,21 +2406,24 @@ class SiloEventListener(QtCore.QThread):
|
||||
if self._stop_flag:
|
||||
return
|
||||
retries += 1
|
||||
last_error = "connection closed"
|
||||
except _SSEUnsupported:
|
||||
self.connection_status.emit("unsupported")
|
||||
self.connection_status.emit("unsupported", 0, "")
|
||||
return
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
retries += 1
|
||||
last_error = str(exc) or "unknown error"
|
||||
|
||||
self.connection_status.emit("disconnected")
|
||||
if retries > self._MAX_RETRIES:
|
||||
self.connection_status.emit("gave_up", retries - 1, last_error)
|
||||
return
|
||||
|
||||
if retries <= self._MAX_FAST_RETRIES:
|
||||
delay = self._FAST_RETRY_SECS
|
||||
else:
|
||||
delay = self._SLOW_RETRY_SECS
|
||||
self.connection_status.emit("disconnected", retries, last_error)
|
||||
|
||||
delay = min(self._BASE_DELAY * (2 ** (retries - 1)), self._MAX_DELAY)
|
||||
|
||||
# Interruptible sleep
|
||||
for _ in range(delay):
|
||||
for _ in range(int(delay)):
|
||||
if self._stop_flag:
|
||||
return
|
||||
self.msleep(1000)
|
||||
@@ -2484,7 +2447,7 @@ class SiloEventListener(QtCore.QThread):
|
||||
except urllib.error.URLError:
|
||||
raise
|
||||
|
||||
self.connection_status.emit("connected")
|
||||
self.connection_status.emit("connected", 0, "")
|
||||
|
||||
event_type = ""
|
||||
data_buf = ""
|
||||
@@ -2513,6 +2476,12 @@ class SiloEventListener(QtCore.QThread):
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return
|
||||
|
||||
if event_type == "server.state":
|
||||
mode = payload.get("mode", "")
|
||||
if mode:
|
||||
self.server_mode_changed.emit(mode)
|
||||
return
|
||||
|
||||
pn = payload.get("part_number", "")
|
||||
if not pn:
|
||||
return
|
||||
@@ -2620,6 +2589,13 @@ class SiloAuthDockWidget:
|
||||
sse_row.addStretch()
|
||||
layout.addLayout(sse_row)
|
||||
|
||||
# Server mode banner (hidden when normal)
|
||||
self._mode_banner = QtGui.QLabel("")
|
||||
self._mode_banner.setWordWrap(True)
|
||||
self._mode_banner.setContentsMargins(6, 4, 6, 4)
|
||||
self._mode_banner.setVisible(False)
|
||||
layout.addWidget(self._mode_banner)
|
||||
|
||||
layout.addSpacing(4)
|
||||
|
||||
# Buttons
|
||||
@@ -2709,6 +2685,14 @@ class SiloAuthDockWidget:
|
||||
self._login_btn.setText("Login")
|
||||
self._login_btn.clicked.connect(self._on_login_clicked)
|
||||
|
||||
# Fetch and display server mode
|
||||
global _server_mode
|
||||
if reachable:
|
||||
_server_mode = _fetch_server_mode()
|
||||
else:
|
||||
_server_mode = "offline"
|
||||
self._update_mode_banner()
|
||||
|
||||
# Manage SSE listener based on auth state
|
||||
self._sync_event_listener(authed)
|
||||
|
||||
@@ -2722,23 +2706,68 @@ class SiloAuthDockWidget:
|
||||
self._event_listener.item_updated.connect(self._on_remote_change)
|
||||
self._event_listener.revision_created.connect(self._on_remote_revision)
|
||||
self._event_listener.connection_status.connect(self._on_sse_status)
|
||||
self._event_listener.server_mode_changed.connect(self._on_server_mode)
|
||||
self._event_listener.start()
|
||||
else:
|
||||
if self._event_listener is not None and self._event_listener.isRunning():
|
||||
self._event_listener.stop()
|
||||
self._sse_label.setText("")
|
||||
|
||||
def _on_sse_status(self, status):
|
||||
def _on_sse_status(self, status, retry, error):
|
||||
if status == "connected":
|
||||
self._sse_label.setText("Listening")
|
||||
self._sse_label.setStyleSheet("font-size: 11px; color: #4CAF50;")
|
||||
self._sse_label.setToolTip("")
|
||||
FreeCAD.Console.PrintMessage("Silo: SSE connected\n")
|
||||
elif status == "disconnected":
|
||||
self._sse_label.setText("Reconnecting...")
|
||||
self._sse_label.setText(
|
||||
f"Reconnecting ({retry}/{SiloEventListener._MAX_RETRIES})..."
|
||||
)
|
||||
self._sse_label.setStyleSheet("font-size: 11px; color: #FF9800;")
|
||||
self._sse_label.setToolTip(error or "Connection lost")
|
||||
FreeCAD.Console.PrintWarning(
|
||||
f"Silo: SSE reconnecting ({retry}/{SiloEventListener._MAX_RETRIES}): {error}\n"
|
||||
)
|
||||
elif status == "gave_up":
|
||||
self._sse_label.setText("Disconnected")
|
||||
self._sse_label.setStyleSheet("font-size: 11px; color: #F44336;")
|
||||
self._sse_label.setToolTip(error or "Max retries reached")
|
||||
FreeCAD.Console.PrintError(
|
||||
f"Silo: SSE gave up after {retry} retries: {error}\n"
|
||||
)
|
||||
elif status == "unsupported":
|
||||
self._sse_label.setText("Not available")
|
||||
self._sse_label.setStyleSheet("font-size: 11px; color: #888;")
|
||||
|
||||
def _on_server_mode(self, mode):
|
||||
global _server_mode
|
||||
_server_mode = mode
|
||||
self._update_mode_banner()
|
||||
|
||||
def _update_mode_banner(self):
|
||||
_MODE_BANNERS = {
|
||||
"normal": ("", "", False),
|
||||
"read-only": (
|
||||
"Server is in read-only mode",
|
||||
"background: #FFC107; color: #000; padding: 4px; font-size: 11px;",
|
||||
True,
|
||||
),
|
||||
"degraded": (
|
||||
"MinIO unavailable \u2014 file ops limited",
|
||||
"background: #FF9800; color: #000; padding: 4px; font-size: 11px;",
|
||||
True,
|
||||
),
|
||||
"offline": (
|
||||
"Disconnected from silo",
|
||||
"background: #F44336; color: #fff; padding: 4px; font-size: 11px;",
|
||||
True,
|
||||
),
|
||||
}
|
||||
text, style, visible = _MODE_BANNERS.get(_server_mode, _MODE_BANNERS["offline"])
|
||||
self._mode_banner.setText(text)
|
||||
self._mode_banner.setStyleSheet(style)
|
||||
self._mode_banner.setVisible(visible)
|
||||
|
||||
def _on_remote_change(self, part_number):
|
||||
FreeCAD.Console.PrintMessage(f"Silo: Part {part_number} updated on server\n")
|
||||
mw = FreeCADGui.getMainWindow()
|
||||
@@ -2759,7 +2788,7 @@ class SiloAuthDockWidget:
|
||||
|
||||
def _refresh_activity_panel(self):
|
||||
"""Refresh the Database Activity panel if it exists."""
|
||||
from PySide import QtWidgets
|
||||
from PySide import QtCore, QtGui, QtWidgets
|
||||
|
||||
mw = FreeCADGui.getMainWindow()
|
||||
if mw is None:
|
||||
@@ -2771,6 +2800,24 @@ class SiloAuthDockWidget:
|
||||
if activity_list is None:
|
||||
return
|
||||
activity_list.clear()
|
||||
|
||||
# Connect interaction signals (once)
|
||||
if not getattr(activity_list, "_silo_connected", False):
|
||||
activity_list.itemDoubleClicked.connect(self._on_activity_double_click)
|
||||
activity_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
|
||||
activity_list.customContextMenuRequested.connect(
|
||||
lambda pos: self._on_activity_context_menu(activity_list, pos)
|
||||
)
|
||||
activity_list._silo_connected = True
|
||||
|
||||
# Collect local part numbers for badge
|
||||
local_pns = set()
|
||||
try:
|
||||
for lf in search_local_files():
|
||||
local_pns.add(lf.get("part_number", ""))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
items = _client.list_items()
|
||||
if isinstance(items, list):
|
||||
@@ -2780,12 +2827,96 @@ class SiloAuthDockWidget:
|
||||
updated = item.get("updated_at", "")
|
||||
if updated:
|
||||
updated = updated[:10]
|
||||
activity_list.addItem(f"{pn} - {desc} - {updated}")
|
||||
|
||||
# Fetch latest revision info
|
||||
rev_num = ""
|
||||
comment = ""
|
||||
try:
|
||||
revs = _client.get_revisions(pn)
|
||||
if revs:
|
||||
latest = revs[0] if isinstance(revs, list) else revs
|
||||
rev_num = str(latest.get("revision_number", ""))
|
||||
comment = latest.get("comment", "") or ""
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Truncate long descriptions
|
||||
desc_display = desc
|
||||
if len(desc_display) > 40:
|
||||
desc_display = desc_display[:37] + "..."
|
||||
|
||||
# Build display text
|
||||
rev_part = f" \u2013 Rev {rev_num}" if rev_num else ""
|
||||
date_part = f" \u2013 {updated}" if updated else ""
|
||||
local_badge = " \u25cf local" if pn in local_pns else ""
|
||||
line1 = (
|
||||
f"{pn} \u2013 {desc_display}{rev_part}{date_part}{local_badge}"
|
||||
)
|
||||
|
||||
if comment:
|
||||
line1 += f'\n "{comment}"'
|
||||
else:
|
||||
line1 += "\n (no comment)"
|
||||
|
||||
list_item = QtWidgets.QListWidgetItem(line1)
|
||||
list_item.setData(QtCore.Qt.UserRole, pn)
|
||||
if desc and len(desc) > 40:
|
||||
list_item.setToolTip(desc)
|
||||
if pn in local_pns:
|
||||
list_item.setForeground(QtGui.QColor("#4CAF50"))
|
||||
activity_list.addItem(list_item)
|
||||
|
||||
if activity_list.count() == 0:
|
||||
activity_list.addItem("(No items in database)")
|
||||
except Exception:
|
||||
activity_list.addItem("(Unable to refresh activity)")
|
||||
|
||||
def _on_activity_double_click(self, item):
|
||||
"""Open/checkout item from activity pane."""
|
||||
pn = item.data(256) # Qt.UserRole
|
||||
if not pn:
|
||||
return
|
||||
local_path = find_file_by_part_number(pn)
|
||||
if local_path and local_path.exists():
|
||||
FreeCAD.openDocument(str(local_path))
|
||||
else:
|
||||
_sync.open_item(pn)
|
||||
|
||||
def _on_activity_context_menu(self, activity_list, pos):
|
||||
"""Show context menu for activity pane items."""
|
||||
from PySide import QtCore, QtGui
|
||||
|
||||
item = activity_list.itemAt(pos)
|
||||
if item is None:
|
||||
return
|
||||
pn = item.data(QtCore.Qt.UserRole)
|
||||
if not pn:
|
||||
return
|
||||
|
||||
menu = QtGui.QMenu()
|
||||
open_action = menu.addAction("Open in Create")
|
||||
browser_action = menu.addAction("Open in Browser")
|
||||
copy_action = menu.addAction("Copy Part Number")
|
||||
revisions_action = menu.addAction("View Revisions")
|
||||
|
||||
action = menu.exec_(activity_list.mapToGlobal(pos))
|
||||
if action == open_action:
|
||||
local_path = find_file_by_part_number(pn)
|
||||
if local_path and local_path.exists():
|
||||
FreeCAD.openDocument(str(local_path))
|
||||
else:
|
||||
_sync.open_item(pn)
|
||||
elif action == browser_action:
|
||||
import webbrowser
|
||||
|
||||
api_url = _get_api_url().rstrip("/")
|
||||
base_url = api_url[:-4] if api_url.endswith("/api") else api_url
|
||||
webbrowser.open(f"{base_url}/items/{pn}")
|
||||
elif action == copy_action:
|
||||
QtGui.QApplication.clipboard().setText(pn)
|
||||
elif action == revisions_action:
|
||||
FreeCADGui.runCommand("Silo_Info", 0)
|
||||
|
||||
# -- Actions ------------------------------------------------------------
|
||||
|
||||
def _on_login_clicked(self):
|
||||
@@ -2934,6 +3065,390 @@ class Silo_Auth:
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Start panel
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SiloStartPanel:
|
||||
"""Content widget for the Silo Start Panel dock."""
|
||||
|
||||
def __init__(self):
|
||||
from PySide import QtCore, QtGui
|
||||
|
||||
self.widget = QtGui.QWidget()
|
||||
self._build_ui()
|
||||
self._refresh()
|
||||
|
||||
self._timer = QtCore.QTimer(self.widget)
|
||||
self._timer.timeout.connect(self._refresh)
|
||||
self._timer.start(60000) # Refresh every 60 seconds
|
||||
|
||||
def _build_ui(self):
|
||||
from PySide import QtCore, QtGui
|
||||
|
||||
layout = QtGui.QVBoxLayout(self.widget)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.setSpacing(6)
|
||||
|
||||
# Connection status badge
|
||||
status_row = QtGui.QHBoxLayout()
|
||||
status_row.setSpacing(6)
|
||||
self._conn_dot = QtGui.QLabel("\u2b24")
|
||||
self._conn_dot.setFixedWidth(16)
|
||||
self._conn_dot.setAlignment(QtCore.Qt.AlignCenter)
|
||||
self._conn_label = QtGui.QLabel("Checking...")
|
||||
self._conn_label.setStyleSheet("font-weight: bold;")
|
||||
status_row.addWidget(self._conn_dot)
|
||||
status_row.addWidget(self._conn_label)
|
||||
status_row.addStretch()
|
||||
layout.addLayout(status_row)
|
||||
|
||||
layout.addSpacing(8)
|
||||
|
||||
# My Checkouts section
|
||||
checkout_header = QtGui.QLabel("My Checkouts")
|
||||
checkout_header.setStyleSheet("font-weight: bold; font-size: 12px;")
|
||||
layout.addWidget(checkout_header)
|
||||
|
||||
self._checkout_list = QtGui.QListWidget()
|
||||
self._checkout_list.setMaximumHeight(160)
|
||||
self._checkout_list.setAlternatingRowColors(True)
|
||||
self._checkout_list.itemDoubleClicked.connect(self._on_checkout_clicked)
|
||||
layout.addWidget(self._checkout_list)
|
||||
|
||||
layout.addSpacing(8)
|
||||
|
||||
# Recent Silo Activity section
|
||||
activity_header = QtGui.QLabel("Recent Silo Activity")
|
||||
activity_header.setStyleSheet("font-weight: bold; font-size: 12px;")
|
||||
layout.addWidget(activity_header)
|
||||
|
||||
self._activity_list = QtGui.QListWidget()
|
||||
self._activity_list.setMaximumHeight(200)
|
||||
self._activity_list.setAlternatingRowColors(True)
|
||||
self._activity_list.itemDoubleClicked.connect(self._on_activity_clicked)
|
||||
layout.addWidget(self._activity_list)
|
||||
|
||||
layout.addSpacing(8)
|
||||
|
||||
# Local Recent Files section
|
||||
local_header = QtGui.QLabel("Local Recent Files")
|
||||
local_header.setStyleSheet("font-weight: bold; font-size: 12px;")
|
||||
layout.addWidget(local_header)
|
||||
|
||||
self._local_list = QtGui.QListWidget()
|
||||
self._local_list.setMaximumHeight(160)
|
||||
self._local_list.setAlternatingRowColors(True)
|
||||
self._local_list.itemDoubleClicked.connect(self._on_local_clicked)
|
||||
layout.addWidget(self._local_list)
|
||||
|
||||
layout.addStretch()
|
||||
|
||||
def _refresh(self):
|
||||
self._refresh_connection()
|
||||
self._refresh_checkouts()
|
||||
self._refresh_activity()
|
||||
self._refresh_local()
|
||||
|
||||
def _refresh_connection(self):
|
||||
try:
|
||||
reachable, _ = _client.check_connection()
|
||||
except Exception:
|
||||
reachable = False
|
||||
|
||||
if reachable:
|
||||
api_url = _get_api_url()
|
||||
parsed = urllib.parse.urlparse(api_url)
|
||||
hostname = parsed.hostname or api_url
|
||||
self._conn_dot.setStyleSheet("color: #4CAF50; font-size: 10px;")
|
||||
self._conn_label.setText(f"Connected to {hostname}")
|
||||
else:
|
||||
self._conn_dot.setStyleSheet("color: #888; font-size: 10px;")
|
||||
self._conn_label.setText("Disconnected")
|
||||
|
||||
def _refresh_checkouts(self):
|
||||
self._checkout_list.clear()
|
||||
try:
|
||||
local_files = search_local_files()
|
||||
for item in local_files[:15]:
|
||||
pn = item.get("part_number", "")
|
||||
desc = item.get("description", "")
|
||||
modified = (item.get("modified") or "")[:10]
|
||||
label = f"{pn} {desc}"
|
||||
if modified:
|
||||
label += f" ({modified})"
|
||||
list_item = self._checkout_list.addItem(label)
|
||||
except Exception:
|
||||
self._checkout_list.addItem("(Unable to scan local files)")
|
||||
|
||||
if self._checkout_list.count() == 0:
|
||||
self._checkout_list.addItem("(No local checkouts)")
|
||||
|
||||
def _refresh_activity(self):
|
||||
self._activity_list.clear()
|
||||
try:
|
||||
reachable, _ = _client.check_connection()
|
||||
except Exception:
|
||||
reachable = False
|
||||
|
||||
if not reachable:
|
||||
self._activity_list.addItem("(Not connected)")
|
||||
return
|
||||
|
||||
try:
|
||||
items = _client.list_items()
|
||||
if isinstance(items, list):
|
||||
# Collect local part numbers for badge comparison
|
||||
local_pns = set()
|
||||
try:
|
||||
for lf in search_local_files():
|
||||
local_pns.add(lf.get("part_number", ""))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for item in items[:10]:
|
||||
pn = item.get("part_number", "")
|
||||
desc = item.get("description", "")
|
||||
updated = (item.get("updated_at") or "")[:10]
|
||||
badge = "\u2713 " if pn in local_pns else ""
|
||||
label = f"{badge}{pn} {desc}"
|
||||
if updated:
|
||||
label += f" ({updated})"
|
||||
self._activity_list.addItem(label)
|
||||
|
||||
if self._activity_list.count() == 0:
|
||||
self._activity_list.addItem("(No items in database)")
|
||||
except Exception:
|
||||
self._activity_list.addItem("(Unable to fetch activity)")
|
||||
|
||||
def _refresh_local(self):
|
||||
from PySide import QtGui
|
||||
|
||||
self._local_list.clear()
|
||||
try:
|
||||
param = FreeCAD.ParamGet("User parameter:BaseApp/RecentFiles")
|
||||
count = param.GetInt("RecentFiles", 0)
|
||||
for i in range(min(count, 10)):
|
||||
path = param.GetString(f"MRU{i}", "")
|
||||
if path:
|
||||
name = Path(path).name
|
||||
item = QtGui.QListWidgetItem(name)
|
||||
item.setToolTip(path)
|
||||
item.setData(256, path) # Qt.UserRole = 256
|
||||
self._local_list.addItem(item)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if self._local_list.count() == 0:
|
||||
self._local_list.addItem("(No recent files)")
|
||||
|
||||
def _on_checkout_clicked(self, item):
|
||||
"""Open a local checkout file."""
|
||||
text = item.text()
|
||||
if text.startswith("("):
|
||||
return
|
||||
pn = text.split()[0] if text else ""
|
||||
if not pn:
|
||||
return
|
||||
local_path = find_file_by_part_number(pn)
|
||||
if local_path and local_path.exists():
|
||||
FreeCAD.openDocument(str(local_path))
|
||||
|
||||
def _on_activity_clicked(self, item):
|
||||
"""Open/checkout a remote item."""
|
||||
text = item.text()
|
||||
if text.startswith("("):
|
||||
return
|
||||
# Strip badge if present
|
||||
text = text.lstrip("\u2713 ")
|
||||
pn = text.split()[0] if text else ""
|
||||
if not pn:
|
||||
return
|
||||
local_path = find_file_by_part_number(pn)
|
||||
if local_path and local_path.exists():
|
||||
FreeCAD.openDocument(str(local_path))
|
||||
else:
|
||||
_sync.open_item(pn)
|
||||
|
||||
def _on_local_clicked(self, item):
|
||||
"""Open a local recent file."""
|
||||
path = item.data(256) # Qt.UserRole
|
||||
if path and Path(path).exists():
|
||||
FreeCAD.openDocument(path)
|
||||
|
||||
|
||||
class Silo_StartPanel:
|
||||
"""Show the Silo Start Panel."""
|
||||
|
||||
def GetResources(self):
|
||||
return {
|
||||
"MenuText": "Start Panel",
|
||||
"ToolTip": "Show Silo start panel with checkouts and recent activity",
|
||||
"Pixmap": _icon("open"),
|
||||
}
|
||||
|
||||
def Activated(self):
|
||||
from PySide import QtCore, QtGui
|
||||
|
||||
mw = FreeCADGui.getMainWindow()
|
||||
if mw is None:
|
||||
return
|
||||
|
||||
# Reuse existing panel if it exists
|
||||
panel = mw.findChild(QtGui.QDockWidget, "SiloStartPanel")
|
||||
if panel:
|
||||
panel.show()
|
||||
panel.raise_()
|
||||
return
|
||||
|
||||
# Create new dock widget
|
||||
content = SiloStartPanel()
|
||||
dock = QtGui.QDockWidget("Silo", mw)
|
||||
dock.setObjectName("SiloStartPanel")
|
||||
dock.setWidget(content.widget)
|
||||
dock.setAllowedAreas(
|
||||
QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea
|
||||
)
|
||||
mw.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
|
||||
|
||||
def IsActive(self):
|
||||
return True
|
||||
|
||||
|
||||
class _DiagWorker(QtCore.QThread):
|
||||
"""Background worker that runs connectivity diagnostics."""
|
||||
|
||||
result = QtCore.Signal(str, bool, str) # (test_name, passed, detail)
|
||||
finished_all = QtCore.Signal()
|
||||
_HTTP_TIMEOUT = 10
|
||||
_DNS_TIMEOUT = 5
|
||||
|
||||
def run(self):
|
||||
api_url = _get_api_url()
|
||||
base_url = api_url.rstrip("/")
|
||||
if base_url.endswith("/api"):
|
||||
base_url = base_url[:-4]
|
||||
self._test_dns(base_url)
|
||||
self._test_http("Health", f"{base_url}/health", auth=False)
|
||||
self._test_http("Ready", f"{base_url}/ready", auth=False)
|
||||
self._test_http("Auth", f"{api_url.rstrip('/')}/auth/me", auth=True)
|
||||
self._test_sse(api_url)
|
||||
self.finished_all.emit()
|
||||
|
||||
def _test_dns(self, base_url):
|
||||
parsed = urllib.parse.urlparse(base_url)
|
||||
hostname = parsed.hostname
|
||||
if not hostname:
|
||||
self.result.emit("DNS", False, "no hostname in URL")
|
||||
return
|
||||
try:
|
||||
addrs = socket.getaddrinfo(
|
||||
hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM
|
||||
)
|
||||
first_ip = addrs[0][4][0] if addrs else "?"
|
||||
self.result.emit("DNS", True, f"{hostname} -> {first_ip}")
|
||||
except socket.gaierror as e:
|
||||
self.result.emit("DNS", False, f"{hostname}: {e}")
|
||||
except Exception as e:
|
||||
self.result.emit("DNS", False, str(e))
|
||||
|
||||
def _test_http(self, name, url, auth=False):
|
||||
try:
|
||||
headers = {}
|
||||
if auth:
|
||||
headers.update(_get_auth_headers())
|
||||
req = urllib.request.Request(url, headers=headers, method="GET")
|
||||
resp = urllib.request.urlopen(
|
||||
req, context=_get_ssl_context(), timeout=self._HTTP_TIMEOUT
|
||||
)
|
||||
code = resp.getcode()
|
||||
body = resp.read(4096).decode("utf-8", errors="replace").strip()
|
||||
detail = f"HTTP {code}"
|
||||
try:
|
||||
data = json.loads(body)
|
||||
if isinstance(data, dict):
|
||||
parts = []
|
||||
for key in ("status", "username", "role"):
|
||||
if key in data:
|
||||
parts.append(f"{key}={data[key]}")
|
||||
if parts:
|
||||
detail += f" ({', '.join(parts)})"
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
if len(body) <= 80:
|
||||
detail += f" {body}"
|
||||
self.result.emit(name, code < 400, detail)
|
||||
except urllib.error.HTTPError as e:
|
||||
self.result.emit(name, False, f"HTTP {e.code} {e.reason}")
|
||||
except urllib.error.URLError as e:
|
||||
self.result.emit(name, False, str(e.reason))
|
||||
except Exception as e:
|
||||
self.result.emit(name, False, str(e))
|
||||
|
||||
def _test_sse(self, api_url):
|
||||
url = f"{api_url.rstrip('/')}/events"
|
||||
try:
|
||||
headers = {"Accept": "text/event-stream"}
|
||||
headers.update(_get_auth_headers())
|
||||
req = urllib.request.Request(url, headers=headers, method="GET")
|
||||
resp = urllib.request.urlopen(
|
||||
req, context=_get_ssl_context(), timeout=self._HTTP_TIMEOUT
|
||||
)
|
||||
content_type = resp.headers.get("Content-Type", "")
|
||||
code = resp.getcode()
|
||||
resp.close()
|
||||
if "text/event-stream" in content_type:
|
||||
self.result.emit("SSE", True, f"HTTP {code} event-stream")
|
||||
else:
|
||||
self.result.emit("SSE", True, f"HTTP {code} (type: {content_type})")
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code in (404, 501):
|
||||
self.result.emit("SSE", False, f"HTTP {e.code} (not supported)")
|
||||
else:
|
||||
self.result.emit("SSE", False, f"HTTP {e.code} {e.reason}")
|
||||
except urllib.error.URLError as e:
|
||||
self.result.emit("SSE", False, str(e.reason))
|
||||
except Exception as e:
|
||||
self.result.emit("SSE", False, str(e))
|
||||
|
||||
|
||||
class Silo_Diag:
|
||||
"""Command to run connection diagnostics."""
|
||||
|
||||
_worker = None
|
||||
|
||||
def GetResources(self):
|
||||
return {
|
||||
"MenuText": "Diagnostics",
|
||||
"ToolTip": "Test DNS, health, readiness, auth, and SSE connectivity",
|
||||
"Pixmap": _icon("info"),
|
||||
}
|
||||
|
||||
def Activated(self):
|
||||
if self._worker is not None and self._worker.isRunning():
|
||||
FreeCAD.Console.PrintWarning("Silo: diagnostics already running\n")
|
||||
return
|
||||
api_url = _get_api_url()
|
||||
FreeCAD.Console.PrintMessage(f"--- Silo Diagnostics ({api_url}) ---\n")
|
||||
self._worker = _DiagWorker()
|
||||
self._worker.result.connect(self._on_result)
|
||||
self._worker.finished_all.connect(self._on_finished)
|
||||
self._worker.start()
|
||||
|
||||
def _on_result(self, name, passed, detail):
|
||||
if passed:
|
||||
FreeCAD.Console.PrintMessage(f" PASS {name}: {detail}\n")
|
||||
else:
|
||||
FreeCAD.Console.PrintError(f" FAIL {name}: {detail}\n")
|
||||
|
||||
def _on_finished(self):
|
||||
FreeCAD.Console.PrintMessage("--- Diagnostics complete ---\n")
|
||||
self._worker = None
|
||||
|
||||
def IsActive(self):
|
||||
return True
|
||||
|
||||
|
||||
# Register commands
|
||||
FreeCADGui.addCommand("Silo_Open", Silo_Open())
|
||||
FreeCADGui.addCommand("Silo_New", Silo_New())
|
||||
@@ -2947,5 +3462,7 @@ FreeCADGui.addCommand("Silo_TagProjects", Silo_TagProjects())
|
||||
FreeCADGui.addCommand("Silo_Rollback", Silo_Rollback())
|
||||
FreeCADGui.addCommand("Silo_SetStatus", Silo_SetStatus())
|
||||
FreeCADGui.addCommand("Silo_Settings", Silo_Settings())
|
||||
FreeCADGui.addCommand("Silo_ToggleMode", Silo_ToggleMode())
|
||||
|
||||
FreeCADGui.addCommand("Silo_Auth", Silo_Auth())
|
||||
FreeCADGui.addCommand("Silo_StartPanel", Silo_StartPanel())
|
||||
FreeCADGui.addCommand("Silo_Diag", Silo_Diag())
|
||||
|
||||
@@ -11,8 +11,7 @@ providing the standardized origin interface.
|
||||
|
||||
import FreeCAD
|
||||
import FreeCADGui
|
||||
|
||||
from .silo_commands import (
|
||||
from silo_commands import (
|
||||
_client,
|
||||
_sync,
|
||||
collect_document_properties,
|
||||
|
||||
Submodule silo-client updated: a6ac3d4d06...68a4139251
Reference in New Issue
Block a user