from __future__ import annotations
import os
import sys
import FreeCAD
__version__ = "0.1.0"
_COMMANDS: dict = {}
_REPORTED: set = set()
_DIALOGS: dict = {}
_DIALOG_SERIAL: int = 0
def _error_text(exc: BaseException) -> str:
message = str(exc).strip().splitlines()
detail = message[0] if message else ""
return f"{type(exc).__name__}: {detail}".strip()
def _report_once(name: str, method: str, exc: BaseException) -> None:
key = (name, method)
if key in _REPORTED:
return
_REPORTED.add(key)
print(f"FreeCADGui: command {name!r} {method} raised: {_error_text(exc)}", file=sys.stderr)
_DOCUMENTS: dict = {}
_REPORTED_VIEWS: set = set()
def _report_view_once(topic: str, exc: BaseException) -> None:
if topic in _REPORTED_VIEWS:
return
_REPORTED_VIEWS.add(topic)
print(f"FreeCADGui: {topic} unavailable: {_error_text(exc)}", file=sys.stderr)
def _coin_module():
try:
from pivy import coin
except Exception as exc: _report_view_once("pivy.coin", exc)
return None
return coin
def _document_name(name):
if isinstance(name, str):
return name
candidate = getattr(name, "Name", None)
if isinstance(candidate, str):
return candidate
raise TypeError("a document name or an App document is required")
def _detach_children(root) -> None:
remove_all = getattr(root, "removeAllChildren", None)
if callable(remove_all):
try:
remove_all()
return
except Exception: pass
while True:
try:
if not root.getNumChildren():
return
root.removeChild(root.getChild(0))
except Exception: return
class View3DInventor:
def __init__(self, document: "GuiDocument") -> None:
self._document = document
self._event_callbacks: dict = {}
self._fits: int = 0
self._redraws: int = 0
def getSceneGraph(self):
return self._document._scene_graph()
def addEventCallback(self, name, callback) -> None:
if not isinstance(name, str) or not name:
raise ValueError("an event callback name must be a non-empty string")
if not callable(callback):
raise TypeError("an event callback must be callable")
self._event_callbacks.setdefault(name, []).append(callback)
def removeEventCallback(self, name, callback) -> bool:
callbacks = self._event_callbacks.get(name)
if not callbacks:
return False
try:
callbacks.remove(callback)
except ValueError:
return False
if not callbacks:
del self._event_callbacks[name]
return True
def fitAll(self):
self._fits += 1
return True
def redraw(self):
self._redraws += 1
return True
def getPoint(self, callback=None, *args):
if callback is None:
raise RuntimeError(
"a headless view has no interactive point picker; pass a "
"callback and drive it with FreeCADGui.draft.pick(point)"
)
snapper = globals().get("Snapper")
if snapper is None:
raise RuntimeError(
"FreeCADGui.Snapper is unavailable; the Draft module did not load"
)
return snapper.getPoint(callback, *args)
class GuiDocument:
def __init__(self, name: str, document) -> None:
self.Name = name
self._document = document
self.ActiveView = View3DInventor(self)
self._root = None
self._overlay = False
self._closed = False
def _scene_graph(self):
if self._closed:
return None
if self._root is None:
coin = _coin_module()
if coin is None:
return None
try:
self._root = coin.SoSeparator()
except Exception as exc: _report_view_once("pivy.coin.SoSeparator", exc)
return None
self._register_overlay()
return self._root
def _register_overlay(self) -> None:
if not getattr(FreeCAD, "GuiUp", 0):
return
try:
import FerroCADGui as bridge
except Exception as exc: _report_view_once("FerroCADGui overlay bridge", exc)
return
add = getattr(bridge, "addOverlay", None)
if add is None:
_report_view_once(
"FerroCADGui.addOverlay", AttributeError("not available")
)
return
try:
add(self._root)
except Exception as exc: _report_view_once("FerroCADGui.addOverlay", exc)
return
self._overlay = True
def _unregister_overlay(self) -> None:
if not self._overlay:
return
self._overlay = False
if self._root is None:
return
try:
import FerroCADGui as bridge
except Exception as exc: _report_view_once("FerroCADGui overlay bridge", exc)
return
remove = getattr(bridge, "removeOverlay", None)
if remove is None:
return
try:
remove(self._root)
except Exception as exc: _report_view_once("FerroCADGui.removeOverlay", exc)
def close(self) -> None:
if self._closed:
return
self._unregister_overlay()
root, self._root = self._root, None
self._closed = True
if root is not None:
_detach_children(root)
def _forget_document(name) -> None:
if not isinstance(name, str):
name = getattr(name, "Name", name)
document = _DOCUMENTS.pop(name, None)
if document is not None:
document.close()
def _clear_documents() -> None:
for name in list(_DOCUMENTS):
_forget_document(name)
def getDocument(name):
name = _document_name(name)
document = FreeCAD.getDocument(name)
if document is None:
_forget_document(name)
return None
cached = _DOCUMENTS.get(name)
if (
cached is not None
and cached._document is document
and not cached._closed
):
return cached
if cached is not None:
cached.close()
view = GuiDocument(name, document)
_DOCUMENTS[name] = view
return view
def activeDocument():
document = FreeCAD.ActiveDocument
if document is None:
return None
return getDocument(document)
def addDocumentObserver(observer) -> None:
import FerroCADGui
FerroCADGui.addDocumentListener(observer)
def removeDocumentObserver(observer) -> bool:
import FerroCADGui
return FerroCADGui.removeDocumentListener(observer)
class _NoDocument:
@staticmethod
def _scene_graph():
return None
_HEADLESS_VIEW = View3DInventor(_NoDocument())
class _HeadlessMainWindow:
Name = "FerroCAD MainWindow"
ObjectName = "FerroCAD MainWindow"
def getActiveWindow(self):
document = activeDocument()
if document is not None:
return document.ActiveView
return _HEADLESS_VIEW
def getWindowsOfType(self, _type=None):
return [entry.ActiveView for entry in _DOCUMENTS.values() if not entry._closed]
def findChild(self, *_args, **_kwargs):
return None
def addToolBar(self, *_args, **_kwargs):
return None
def removeToolBar(self, *_args, **_kwargs):
return None
def getObjectName(self):
return self.ObjectName
_MAIN_WINDOW = _HeadlessMainWindow()
_PENDING_MODULES: list = []
def addModule(name: str) -> None:
if not isinstance(name, str) or not name:
raise ValueError("a module name must be a non-empty string")
if name not in _PENDING_MODULES:
_PENDING_MODULES.append(name)
def _take_modules() -> list:
modules = list(_PENDING_MODULES)
_PENDING_MODULES.clear()
return modules
def doCommand(text: str):
if not isinstance(text, str) or not text.strip():
raise ValueError("FreeCADGui.doCommand needs a non-empty command string")
runner = getattr(FreeCAD, "runCommand", None)
try:
if callable(runner):
return runner(text)
exec(compile(text, "<FreeCADGui.doCommand>", "exec"), FreeCAD.__dict__)
except Exception as exc: raise RuntimeError(
f"FreeCADGui.doCommand failed: {_error_text(exc)}\n{text}"
) from exc
return None
def getMainWindow():
return _MAIN_WINDOW
_DRAFT_IMPORT_ERROR = None
_DRAFT_NAMES = ("draft", "Snapper", "draftToolBar", "HintManager", "InputHint", "UserInput")
def __getattr__(name):
if name == "ActiveDocument":
return activeDocument()
if name in _DRAFT_NAMES and _DRAFT_IMPORT_ERROR is not None:
raise ImportError(
f"FreeCADGui.{name} is unavailable: the Draft GUI module failed to "
f"import ({_error_text(_DRAFT_IMPORT_ERROR)})"
) from _DRAFT_IMPORT_ERROR
raise AttributeError("module 'FreeCADGui' has no attribute '%s'" % name)
def addCommand(name: str, command) -> None:
if not isinstance(name, str) or not name:
raise ValueError("a command name must be a non-empty string")
if not callable(getattr(command, "Activated", None)):
raise TypeError(f"command {name!r} has no callable Activated")
if name in _COMMANDS:
raise ValueError(f"command {name!r} is already registered")
_COMMANDS[name] = command
def removeCommand(name: str) -> None:
_COMMANDS.pop(name, None)
_REPORTED.difference_update({key for key in _REPORTED if key[0] == name})
def listCommands() -> list:
return list(_COMMANDS)
def runCommand(name: str, *args):
command = _COMMANDS.get(name)
if command is None:
raise KeyError(name)
return command.Activated(*args)
def _resources(command) -> dict:
get = getattr(command, "GetResources", None)
if get is None:
return {}
try:
resources = get()
except Exception as exc: _report_once(_name_of(command), "GetResources", exc)
return {}
return resources if isinstance(resources, dict) else {}
def _name_of(command) -> str:
for name, candidate in _COMMANDS.items():
if candidate is command:
return name
return repr(command)
def _enabled(name: str, command) -> bool:
is_active = getattr(command, "IsActive", None)
if is_active is None:
return True
try:
return bool(is_active())
except Exception as exc: _report_once(name, "IsActive", exc)
return False
def _checked(name: str, command) -> bool:
is_checked = getattr(command, "IsChecked", None)
if is_checked is None:
return False
try:
return bool(is_checked())
except Exception as exc: _report_once(name, "IsChecked", exc)
return False
def _command_list() -> list:
commands = []
for name, command in _COMMANDS.items():
resources = _resources(command)
commands.append(
{
"id": name,
"menu": str(resources.get("MenuText") or name),
"tooltip": str(resources.get("ToolTip") or ""),
"accel": str(resources.get("Accel") or ""),
"group": str(resources.get("Group") or ""),
"cmd_type": str(resources.get("CmdType") or ""),
"enabled": _enabled(name, command),
"checked": _checked(name, command),
"dev_only": bool(resources.get("FerroCAD_DevOnly")),
}
)
return commands
def _run(name: str) -> dict:
command = _COMMANDS.get(name)
if command is None:
return {"ok": False, "error": f"unknown command {name!r}"}
try:
result = command.Activated()
except Exception as exc: return {"ok": False, "error": _error_text(exc)}
return _payload(result)
def _register_dialog(callback) -> str:
global _DIALOG_SERIAL
_DIALOG_SERIAL += 1
token = f"d{_DIALOG_SERIAL}"
_DIALOGS[token] = callback
return token
def _payload(result) -> dict:
payload = {"ok": True}
if not isinstance(result, dict):
if result is not None:
payload["value"] = repr(result)
return payload
callback = result.get("on_accept")
if callback is not None:
payload["dialog"] = {
key: result[key]
for key in (
"title",
"fields",
"accept",
"cancel",
"presentation",
"preview",
)
if key in result
}
payload["token"] = _register_dialog(callback)
if "status" in result:
payload["status"] = result["status"]
if "value" in result:
payload["value"] = result["value"]
if "view" in result:
payload["view"] = result["view"]
if "tool" in result:
payload["tool"] = result["tool"]
if "select" in result:
payload["select"] = result["select"]
return payload
def _accept(token: str, values: dict) -> dict:
callback = _DIALOGS.pop(token, None)
if callback is None:
return {"ok": False, "error": f"no open dialog {token!r}"}
try:
result = callback(values)
except Exception as exc: return {"ok": False, "error": _error_text(exc)}
return _payload(result)
def _cancel(token: str) -> dict:
_DIALOGS.pop(token, None)
return {"ok": True}
def _cancel_all() -> None:
_DIALOGS.clear()
class _Selection:
def __init__(self) -> None:
self._pairs: list = []
def _objects(self) -> list:
doc = FreeCAD.ActiveDocument
if doc is None:
return []
resolved = []
for name, elements in self._pairs:
obj = doc.getObject(name)
if obj is not None:
resolved.append((obj, list(elements)))
return resolved
def getSelection(self) -> list:
return [obj for obj, _ in self._objects()]
def getSelectionEx(self) -> list:
return self._objects()
def isSelected(self, obj) -> bool:
name = obj if isinstance(obj, str) else getattr(obj, "Name", None)
return any(candidate == name for candidate, _ in self._pairs)
def _set(self, pairs) -> None:
self._pairs = [
(str(name), [str(element) for element in (elements or [])])
for name, elements in pairs
]
Selection = _Selection()
def _import_ui_extension():
try:
import ferrocad_ui_py
except ImportError as exc:
raise ImportError(
"FreeCADGui.PySideUic.loadUi requires the `ferrocad_ui_py` "
"extension module. Build it with `cargo build -p ferrocad_ui_py` "
"and make the resulting library importable as `ferrocad_ui_py` "
"(copy `libferrocad_ui_py.so` to `ferrocad_ui_py.abi3.so` in the "
"`python/` directory, or point PYTHONPATH at it)."
) from exc
return ferrocad_ui_py
def _resolve_resource(path: str):
from PySide.QtCore import QFile
handle = QFile(path)
if not handle.open(QFile.ReadOnly):
raise OSError(f"FreeCADGui.PySideUic.loadUi: cannot open resource {path!r}")
return handle
class _PySideUic:
@staticmethod
def loadUi(path_or_file):
module = _import_ui_extension()
if isinstance(path_or_file, (str, bytes, os.PathLike)):
path = os.fsdecode(os.fspath(path_or_file))
if path.startswith(":"):
return module.load_ui(_resolve_resource(path), path)
return module.load_ui(path)
if hasattr(path_or_file, "readAll") or hasattr(path_or_file, "data"):
return module.load_ui(path_or_file)
raise TypeError(
"FreeCADGui.PySideUic.loadUi expects a path, a ':/' resource, or a "
"QFile-like object with readAll()/data(), got "
f"{type(path_or_file).__name__}"
)
PySideUic = _PySideUic()
try:
from . import draft as draft except Exception as _exc: _DRAFT_IMPORT_ERROR = _exc