from __future__ import annotations
import contextlib
import io
import json
import sys
import traceback
import FreeCAD
import FreeCADGui
import FerroCAD
import FerroCADGui
_NAMESPACE: dict = {}
_EDITABLE_KINDS = {
"App::PropertyString": "text",
"App::PropertyBool": "bool",
"App::PropertyInteger": "int",
"App::PropertyFloat": "float",
"App::PropertyLength": "quantity",
"App::PropertyDistance": "quantity",
"App::PropertyAngle": "quantity",
"App::PropertyQuantity": "quantity",
"App::PropertyEnumeration": "enum",
}
_SETTINGS_ROOT = "Settings"
_SETTINGS_TYPE = "FerroCAD::Settings"
_VIEW_PREFERENCES = "User parameter:BaseApp/Preferences/View"
_GPU_ADAPTER_SETTING = "GpuAdapter"
_GPU_ADAPTER_FORMS = '"auto", "backend:vulkan|gl|metal|dx12", or "adapter:<name substring>"'
_GPU_BACKENDS = ("vulkan", "gl", "metal", "dx12")
def _json(payload) -> str:
return json.dumps(payload)
def hello() -> str:
version = ".".join(FreeCAD.Version()[:3])
return f"hello from Python {version} — FreeCAD backend: {FreeCAD.backend}"
def gpu_adapter() -> str:
return FreeCAD.ParamGet(_VIEW_PREFERENCES).GetString(_GPU_ADAPTER_SETTING, "auto")
def _gpu_adapter_ok(value: str) -> bool:
lowered = value.lower()
if lowered == "auto":
return True
if lowered.startswith("backend:"):
return lowered[len("backend:"):].strip() in _GPU_BACKENDS
if lowered.startswith("adapter:"):
return bool(value[len("adapter:"):].strip())
return False
def _gpu_adapter_error(value: str) -> str:
return f"invalid GPU adapter setting {value!r}; use {_GPU_ADAPTER_FORMS}"
def set_gpu_adapter(payload_json: str) -> str:
try:
payload = json.loads(payload_json)
value = payload.get("value")
except Exception as exc: return _json({"ok": False, "value": "", "error": str(exc)})
if not isinstance(value, str):
return _json(
{
"ok": False,
"value": "",
"error": f"GPU adapter setting must be a string; use {_GPU_ADAPTER_FORMS}",
}
)
value = value.strip()
if not value or not _gpu_adapter_ok(value):
return _json({"ok": False, "value": "", "error": _gpu_adapter_error(value)})
FreeCAD.ParamGet(_VIEW_PREFERENCES).SetString(_GPU_ADAPTER_SETTING, value)
return _json({"ok": True, "value": value, "error": ""})
def load_workbenches(dirs_json: str = "[]") -> str:
import os
try:
dirs = json.loads(dirs_json)
except Exception:
dirs = []
loaded = []
errors = []
for root in dirs:
if not os.path.isdir(root):
continue
for name in sorted(os.listdir(root)):
workbench_dir = os.path.join(root, name)
if not os.path.isdir(workbench_dir):
continue
for script in ("Init.py", "InitGui.py"):
path = os.path.join(workbench_dir, script)
if not os.path.isfile(path):
continue
namespace = {"__file__": path, "__name__": f"{name}.{script[:-3]}"}
try:
with open(path, encoding="utf-8") as handle:
source = handle.read()
exec(compile(source, path, "exec"), namespace)
loaded.append(f"{name}/{script}")
except Exception:
errors.append(
{
"workbench": name,
"script": script,
"traceback": traceback.format_exc(),
}
)
return _json({"loaded": loaded, "errors": errors})
def bootstrap(doc_name: str = "Shell") -> str:
FreeCADGui._cancel_all()
if FreeCAD.getDocument(doc_name) is not None:
FerroCAD.closeDocument(doc_name)
doc = FerroCAD.newDocument(doc_name)
params = doc.addObject("App::FeaturePython", "Params")
params.addProperty("App::PropertyLength", "Length", "Base", "Source length")
params.addProperty("App::PropertyEnumeration", "Mode", "Base", "Operation mode")
params.Mode = ["Fast", "Accurate"]
params.Length = FreeCAD.Units.Quantity("10 mm")
derived = doc.addObject("App::FeaturePython", "Derived")
derived.addProperty("App::PropertyLength", "Result", "Base", "Computed result")
derived.setExpression("Result", "Params.Length * 2")
group = doc.addObject("App::DocumentObjectGroup", "Group")
group.addObject(params)
doc.recompute()
_NAMESPACE.clear()
_NAMESPACE.update({"FreeCAD": FreeCAD, "App": FreeCAD, "doc": doc})
return _json(
{
"version": ".".join(FreeCAD.Version()[:3]),
"backend": FreeCAD.backend,
"document": doc.Name,
}
)
def _active_doc():
doc = FreeCAD.ActiveDocument
if doc is None:
raise RuntimeError("no active document")
return doc
def open_document(path: str) -> str:
doc = FreeCAD.open(path)
_NAMESPACE["doc"] = doc
_NAMESPACE.setdefault("FreeCAD", FreeCAD)
_NAMESPACE.setdefault("App", FreeCAD)
return _json({"document": doc.Name, "objects": len(doc.Objects)})
def close_document(name: str) -> str:
FerroCAD.closeDocument(name)
return _json({"ok": True})
def model_tree() -> str:
docs = []
settings = _settings_root()
if settings["objects"]:
docs.append(settings)
for name in FreeCAD.listDocuments():
doc = FreeCAD.getDocument(name)
if doc is None:
continue
objects = [
{"name": obj.Name, "label": obj.Label, "type": obj.TypeId}
for obj in doc.Objects
]
docs.append({"name": doc.Name, "label": doc.Label, "objects": objects})
return _json(docs)
def _settings_root() -> dict:
features = []
seen = set()
for manifest in FerroCADGui.providers():
feature = manifest["feature"]
if feature in seen:
continue
seen.add(feature)
features.append(feature)
objects = [
{
"name": f"{_SETTINGS_ROOT}/{feature}",
"label": str(feature).title(),
"type": _SETTINGS_TYPE,
}
for feature in features
]
return {"name": _SETTINGS_ROOT, "label": _SETTINGS_ROOT, "objects": objects}
def _settings_feature(object_name):
prefix = _SETTINGS_ROOT + "/"
if not isinstance(object_name, str) or not object_name.startswith(prefix):
return None
node = object_name[len(prefix):]
features = []
for manifest in FerroCADGui.providers():
feature = manifest["feature"]
if feature not in features:
features.append(feature)
if node in features:
return node
for feature in features:
if str(feature).title() == node:
return feature
return node
def _settings_properties(feature: str) -> list:
manifests = FerroCADGui.providers(feature)
if not manifests:
return []
active = FerroCADGui.activeProvider(feature)
label = next(
(item["label"] for item in manifests if item["backend"] == active),
str(active or ""),
)
rows = [
{
"name": "provider",
"label": "Provider",
"type": "App::PropertyEnumeration",
"value": label,
"status": "provider",
"editable": True,
"kind": "enum",
"choices": [item["label"] for item in manifests],
}
]
rows.extend(FerroCADGui.settings(feature))
return rows
def _expression_properties(obj) -> set:
try:
return {name for name, _ in obj.ExpressionEngine}
except Exception:
return set()
def properties(object_name: str) -> str:
feature = _settings_feature(object_name)
if feature is not None:
return _json(_settings_properties(feature))
doc = _active_doc()
obj = doc.getObject(object_name)
if obj is None:
return _json([])
driven = _expression_properties(obj)
rows = []
for prop in obj.PropertiesList:
try:
value = getattr(obj, prop)
except Exception:
value = "<error>"
try:
status = ", ".join(obj.getTypeOfProperty(prop))
except Exception:
status = ""
type_id = obj.getTypeIdOfProperty(prop)
kind = _EDITABLE_KINDS.get(type_id, "")
rows.append(
{
"name": prop,
"type": type_id,
"value": str(value),
"status": status,
"editable": bool(kind) and prop not in driven,
"kind": kind,
}
)
return _json(rows)
def _coerce(kind: str, text: str):
if kind in ("text", "enum"):
return text
if kind == "bool":
return text.strip().lower() in ("1", "true", "yes", "on")
if kind == "int":
return int(float(text))
if kind == "float":
return float(text)
if kind == "quantity":
return FreeCAD.Units.Quantity(text)
raise ValueError(f"unsupported editor kind {kind!r}")
def set_property(object_name: str, prop: str, text: str) -> str:
feature = _settings_feature(object_name)
if feature is not None:
return _json(_set_setting(feature, object_name, prop, text))
doc = _active_doc()
obj = doc.getObject(object_name)
if obj is None:
return _json({"ok": False, "error": f"no object {object_name!r}"})
if prop not in obj.PropertiesList:
return _json({"ok": False, "error": f"no property {prop!r}"})
kind = _EDITABLE_KINDS.get(obj.getTypeIdOfProperty(prop), "")
if not kind:
return _json({"ok": False, "error": f"{prop} is not editable"})
if prop in _expression_properties(obj):
return _json({"ok": False, "error": f"{prop} is set by an expression"})
try:
value = _coerce(kind, text)
except Exception as exc:
return _json({"ok": False, "error": str(exc)})
doc.openTransaction(f"Edit {prop}")
try:
setattr(obj, prop, value)
except Exception as exc:
doc.abortTransaction()
return _json({"ok": False, "error": str(exc)})
doc.commitTransaction()
doc.recompute()
return _json({"ok": True, "error": ""})
def _set_setting(feature: str, object_name: str, prop: str, text: str) -> dict:
manifests = FerroCADGui.providers(feature)
if not manifests:
return {"ok": False, "error": f"no object {object_name!r}"}
if prop == "provider":
backend = next(
(
item["backend"]
for item in manifests
if text in (item["label"], item["backend"])
),
None,
)
if backend is None:
return {
"ok": False,
"error": f"no provider {text!r} for feature {feature!r}",
}
try:
return FerroCADGui.setActiveProvider(feature, backend)
except Exception as exc: return {"ok": False, "error": str(exc)}
return FerroCADGui.setSetting(feature, prop, text)
def add_namespace(name: str, value) -> None:
_NAMESPACE[name] = value
def evaluate(code: str) -> str:
buf = io.StringIO()
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
try:
value = eval(code, _NAMESPACE)
if value is not None:
print(repr(value))
except SyntaxError:
exec(code, _NAMESPACE)
return _json({"ok": True, "output": buf.getvalue().rstrip("\n")})
except Exception:
buf.write(traceback.format_exc())
return _json({"ok": False, "output": buf.getvalue().rstrip("\n")})
def _base_link(obj):
try:
link = obj.Base
except Exception:
return None
if not isinstance(link, tuple) or not link:
return None
linked = link[0]
name = getattr(linked, "Name", None)
if name is None:
return None
return name, list(link[1]) if len(link) > 1 else []
def stage_meshes() -> str:
try:
doc = _active_doc()
except Exception:
return "[]"
objects = list(doc.Objects)
consumed = set()
for obj in objects:
link = _base_link(obj)
if link is not None:
consumed.add(link[0])
meshes = []
for index, obj in enumerate(objects, start=1):
if obj.Name in consumed:
continue
mesh = FerroCAD.display_mesh(obj)
if mesh is None:
continue
meshes.append({"object": obj.Name, "label": obj.Label, "entity": index, **mesh})
return _json(meshes)
def interaction(
object_name: str, manipulator: str, action: str, element: str, values_json: str
) -> str:
try:
doc = _active_doc()
except Exception as exc:
return _json({"ok": False, "error": str(exc)})
base = doc.getObject(object_name)
if base is None:
return _json({"ok": False, "error": f"no object named {object_name}"})
try:
values = [float(value) for value in json.loads(values_json)]
except Exception as exc:
return _json({"ok": False, "error": f"bad values: {exc}"})
result = FerroCAD.interaction(base, manipulator, action, element, values)
if result is None:
return _json(
{"ok": False, "error": f"no module handles {manipulator} {action}"}
)
return _json(result)
def manipulator_specs(payload_json: str) -> str:
try:
payload = json.loads(payload_json)
except Exception:
payload = {}
if not isinstance(payload, dict):
payload = {}
object_name = payload.get("object")
if object_name is None:
object_name = ""
element = payload.get("element")
try:
specs = FerroCAD.manipulator_specs(object_name, element)
except Exception as exc: print(
"ferrocad_shell: manipulator specs failed: %s" % exc,
file=sys.stderr,
)
specs = []
serialisable = []
for spec in specs:
try:
json.dumps(spec)
except (TypeError, ValueError) as exc:
print(
"ferrocad_shell: dropping a non-serialisable manipulator spec: %s"
% exc,
file=sys.stderr,
)
continue
serialisable.append(spec)
return _json({"specs": serialisable})
def commands() -> str:
entries = FreeCADGui._command_list()
registry = getattr(FreeCADGui, "_COMMANDS", {})
read_resources = getattr(FreeCADGui, "_resources", None)
for entry in entries:
command = registry.get(entry["id"])
resources = read_resources(command) if command is not None and read_resources else {}
entry["surface"] = str(resources.get("FerroCAD_Surface") or "")
entry["parent"] = str(resources.get("FerroCAD_Parent") or "")
entry["short"] = str(resources.get("FerroCAD_Short") or "")
entry["tone"] = str(resources.get("FerroCAD_Tone") or "")
entry["checkable"] = bool(resources.get("Checkable")) or callable(
getattr(command, "IsChecked", None)
)
return _json(entries)
def run_command(name: str) -> str:
return _json(FreeCADGui._run(name))
def dialog_accept(payload_json: str) -> str:
payload = json.loads(payload_json)
return _json(
FreeCADGui._accept(payload["token"], payload.get("values") or {})
)
def dialog_cancel(token: str) -> str:
return _json(FreeCADGui._cancel(token))
def set_selection(pairs_json: str) -> str:
items = json.loads(pairs_json)
FreeCADGui.Selection._set(
[(item["object"], item.get("elements") or []) for item in items]
)
return _json({"ok": True})
def set_view_state(state_json: str) -> str:
state = json.loads(state_json)
FerroCADGui.ViewState.grid = bool(state.get("grid", False))
FerroCADGui.ViewState.axis_cross = bool(state.get("axis_cross", True))
FerroCADGui.ViewState.projection = str(state.get("projection", "persp"))
FerroCADGui.ViewState.grid_minor = float(state.get("grid_minor", 10.0))
FerroCADGui.ViewState.grid_major = float(state.get("grid_major", 100.0))
radius = state.get("grid_radius")
FerroCADGui.ViewState.grid_radius = None if radius is None else float(radius)
return _json({"ok": True})
def _selection() -> list:
return list(FreeCADGui.Selection.getSelection())
class _DeleteCommand:
def GetResources(self):
return {
"MenuText": "Delete",
"ToolTip": "Delete the selected objects",
"Accel": "Del",
"Group": "Edit",
"CmdType": "ForEdit",
"FerroCAD_Surface": "radial",
"FerroCAD_Tone": "destructive",
}
def IsActive(self):
return FreeCAD.ActiveDocument is not None and bool(_selection())
def Activated(self):
doc = FreeCAD.ActiveDocument
objects = _selection()
if not objects:
return {"status": "nothing selected"}
doc.openTransaction("Delete")
try:
for obj in objects:
doc.removeObject(obj.Name)
doc.recompute()
doc.commitTransaction()
except Exception as exc: doc.abortTransaction()
return {"status": f"delete failed: {exc}"}
return {"status": f"deleted {len(objects)} object(s)"}
class _MoveCommand:
def GetResources(self):
return {
"MenuText": "Move",
"ToolTip": "Move the selected objects by a delta",
"Accel": "Ctrl+Shift+M",
"Group": "Edit",
"CmdType": "ForEdit",
"FerroCAD_Surface": "radial",
"FerroCAD_Tone": "structural",
}
def IsActive(self):
return FreeCAD.ActiveDocument is not None and bool(_selection())
def Activated(self, dx=None, dy=None, dz=None):
if dx is not None or dy is not None or dz is not None:
return _move_selection(float(dx or 0.0), float(dy or 0.0), float(dz or 0.0))
return {
"title": "Move",
"accept": "Move",
"presentation": "float",
"preview": "translation",
"fields": [
{"name": "dx", "label": "ΔX", "kind": "quantity", "value": 0.0},
{"name": "dy", "label": "ΔY", "kind": "quantity", "value": 0.0},
{"name": "dz", "label": "ΔZ", "kind": "quantity", "value": 0.0},
],
"on_accept": lambda values: _move_selection(
float(values.get("dx", 0.0)),
float(values.get("dy", 0.0)),
float(values.get("dz", 0.0)),
),
}
def _move_selection(dx, dy, dz):
doc = FreeCAD.ActiveDocument
objects = _selection()
if not objects:
return {"status": "nothing selected"}
delta = FreeCAD.Placement(FreeCAD.Vector(dx, dy, dz))
doc.openTransaction("Move")
try:
for obj in objects:
obj.Placement = delta * obj.Placement
doc.recompute()
doc.commitTransaction()
except Exception as exc: doc.abortTransaction()
return {"status": f"move failed: {exc}"}
return {"status": f"moved {len(objects)} object(s)"}
FreeCADGui.addCommand("App_Delete", _DeleteCommand())
FreeCADGui.addCommand("App_Move", _MoveCommand())
_GRID_FEATURE = "grid"
_AXIS_FEATURE = "axis"
_GRID_SETTINGS_NODE = "Settings/Grid"
_AXIS_SETTINGS_NODE = "Settings/Axis"
def grid_summary() -> str:
manifests = FerroCADGui.providers(_GRID_FEATURE)
providers = [
{
"backend": manifest["backend"],
"label": manifest["label"],
"active": bool(manifest["active"]),
}
for manifest in manifests
]
if not manifests:
return _json(
{
"feature": _GRID_FEATURE,
"backend": None,
"label": None,
"spacing": None,
"providers": [],
}
)
active = next(
(manifest for manifest in manifests if manifest["active"]), manifests[0]
)
rows = {row["name"]: row for row in FerroCADGui.settings(_GRID_FEATURE)}
spacing = None
for name in ("spacing", "minor"):
row = rows.get(name)
if row is not None:
spacing = row["value"]
break
if spacing is None:
spacing = "%g mm" % FerroCAD.Grid.spacing
return _json(
{
"feature": _GRID_FEATURE,
"backend": active["backend"],
"label": active["label"],
"spacing": spacing,
"providers": providers,
}
)
def _grid_view_request():
request = FerroCAD.Grid.apply()
refreshed = FerroCADGui.refreshProviders(_GRID_FEATURE)
owned = (refreshed.get("view") or {}).get("grid_overlay")
if owned is not None:
request["view"]["grid_overlay"] = bool(request["view"].get("grid")) and bool(
owned
)
return request
def axis_summary() -> str:
manifests = FerroCADGui.providers(_AXIS_FEATURE)
providers = [
{
"backend": manifest["backend"],
"label": manifest["label"],
"active": bool(manifest["active"]),
}
for manifest in manifests
]
if not manifests:
return _json(
{
"feature": _AXIS_FEATURE,
"backend": None,
"label": None,
"length": None,
"width": None,
"providers": [],
}
)
active = next(
(manifest for manifest in manifests if manifest["active"]), manifests[0]
)
rows = {row["name"]: row for row in FerroCADGui.settings(_AXIS_FEATURE)}
size = {}
for name in ("length", "width"):
row = rows.get(name)
if row is not None:
size[name] = "%s px" % row["value"]
else:
size[name] = "%g px" % getattr(FerroCAD.Axis, name)
return _json(
{
"feature": _AXIS_FEATURE,
"backend": active["backend"],
"label": active["label"],
"length": size["length"],
"width": size["width"],
"providers": providers,
}
)
def provider_features() -> str:
features = {}
for manifest in FerroCADGui.providers():
features.setdefault(manifest["feature"], []).append(
{
"backend": manifest["backend"],
"label": manifest["label"],
"active": bool(manifest["active"]),
"command": manifest["command"],
}
)
return _json(
[
{"feature": feature, "providers": providers}
for feature, providers in features.items()
]
)
def provider_skin(payload_json: str) -> str:
try:
payload = json.loads(payload_json)
feature = str(payload.get("feature") or "")
except Exception: feature = ""
source = FerroCADGui.providerSkin(feature) if feature else None
return _json({"source": source})
def _axis_view_request():
request = FerroCAD.Axis.apply()
refreshed = FerroCADGui.refreshProviders(_AXIS_FEATURE)
owned = ((refreshed.get("view") or {}).get("axis") or {}).get("overlay")
if owned is not None:
request["view"]["axis"]["overlay"] = bool(
request["view"]["axis"]["enabled"]
) and bool(owned)
return request
def set_provider(payload_json: str) -> str:
try:
payload = json.loads(payload_json)
feature = str(payload.get("feature") or "")
backend = str(payload.get("backend") or "")
except Exception as exc: return _json({"ok": False, "error": str(exc), "status": "", "view": {}})
try:
result = FerroCADGui.setActiveProvider(feature, backend)
except Exception as exc: return _json({"ok": False, "error": str(exc), "status": "", "view": {}})
errors = result.get("errors") or []
return _json(
{
"ok": bool(result.get("ok", True)),
"error": "; ".join(str(error) for error in errors),
"status": str(result.get("status") or ""),
"view": dict(result.get("view") or {}),
}
)
class _GridCommand:
def GetResources(self):
return {
"MenuText": "Grid",
"ToolTip": "Show the reference grid",
"Group": "View",
"CmdType": "ForView",
"Checkable": True,
"FerroCAD_Surface": "grid",
}
def IsChecked(self):
return bool(FerroCADGui.ViewState.grid)
def Activated(self):
grid = FerroCAD.Grid
grid.enabled = not grid.enabled
return _grid_view_request()
FreeCADGui.addCommand("App_ToggleGrid", _GridCommand())
class _AxisCrossCommand:
def GetResources(self):
return {
"MenuText": "Axis cross",
"ToolTip": "Show the world axis cross",
"Group": "View",
"CmdType": "ForView",
"Checkable": True,
"FerroCAD_Surface": "axis",
}
def IsChecked(self):
return bool(FerroCADGui.ViewState.axis_cross)
def Activated(self):
axis = getattr(FerroCAD, "Axis", None)
if axis is None:
return {"view": {"axis_cross": not FerroCADGui.ViewState.axis_cross}}
axis.enabled = not axis.enabled
return _axis_view_request()
FreeCADGui.addCommand("App_ToggleAxisCross", _AxisCrossCommand())
class _ReloadAxisSettingsCommand:
def GetResources(self):
return {
"MenuText": "Reload axis settings",
"ToolTip": "Apply the axis preferences",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "axis",
"FerroCAD_Parent": "App_ToggleAxisCross",
}
def Activated(self):
if getattr(FerroCAD, "Axis", None) is None:
return {"view": {"axis_cross": bool(FerroCADGui.ViewState.axis_cross)}}
return _axis_view_request()
FreeCADGui.addCommand("App_ReloadAxisSettings", _ReloadAxisSettingsCommand())
class _AxisSettingsCommand:
def GetResources(self):
return {
"MenuText": "Axis settings",
"ToolTip": "Edit the axis cross",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "axis",
"FerroCAD_Parent": "App_ToggleAxisCross",
}
def Activated(self):
if FerroCADGui.providers(_AXIS_FEATURE):
return {"select": _AXIS_SETTINGS_NODE}
return {"status": "no axis provider is registered"}
FreeCADGui.addCommand("View_AxisSettings", _AxisSettingsCommand())
class _GridSettingsCommand:
def GetResources(self):
return {
"MenuText": "Grid settings",
"ToolTip": "Change the reference grid's appearance",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "grid",
"FerroCAD_Parent": "App_ToggleGrid",
}
def Activated(self):
if FerroCADGui.providers(_GRID_FEATURE):
return {"select": _GRID_SETTINGS_NODE}
grid = FerroCAD.Grid
return {
"title": "Grid settings",
"accept": "Apply",
"fields": [
{
"name": "enabled",
"label": "Show grid",
"kind": "bool",
"value": grid.enabled,
},
{
"name": "color",
"label": "Colour",
"kind": "text",
"value": grid.color,
},
{
"name": "opacity",
"label": "Opacity",
"kind": "float",
"value": grid.opacity,
"min": 0.0,
"max": 1.0,
},
{
"name": "spacing",
"label": "Spacing (mm)",
"kind": "quantity",
"value": grid.spacing,
"min": 0.001,
},
{
"name": "shadows",
"label": "Shadows",
"kind": "bool",
"value": grid.shadows,
},
{
"name": "shadow_opacity",
"label": "Shadow opacity",
"kind": "float",
"value": grid.shadow_opacity,
"min": 0.0,
"max": 1.0,
},
],
"on_accept": _apply_grid_settings,
}
def _apply_grid_settings(values):
grid = FerroCAD.Grid
grid.enabled = bool(values.get("enabled", grid.enabled))
grid.color = str(values.get("color", grid.color))
grid.opacity = float(values.get("opacity", grid.opacity))
grid.spacing = float(values.get("spacing", grid.spacing))
grid.shadows = bool(values.get("shadows", grid.shadows))
grid.shadow_opacity = float(values.get("shadow_opacity", grid.shadow_opacity))
return _grid_view_request()
FreeCADGui.addCommand("View_GridSettings", _GridSettingsCommand())
class _ModsSettingsCommand:
def GetResources(self):
return {
"MenuText": "Mods",
"ToolTip": "Choose which mod provides each feature",
"Group": "Edit",
"CmdType": "ForEdit",
"FerroCAD_Surface": "mods",
"FerroCAD_DevOnly": "true",
}
def Activated(self):
features = {}
for provider in FerroCADGui.providers():
features.setdefault(provider["feature"], []).append(provider)
if not features:
return {"status": "no mod providers are registered"}
fields = []
for feature, items in features.items():
active = FerroCADGui.activeProvider(feature)
current = next(
(item for item in items if item["backend"] == active), items[0]
)
fields.append(
{
"name": feature,
"label": feature.replace("_", " ").title(),
"kind": "enum",
"values": [item["label"] for item in items],
"value": current["label"],
}
)
return {
"title": "Mod providers",
"accept": "Apply",
"fields": fields,
"on_accept": _apply_mod_settings,
}
def _apply_mod_settings(values):
view = {}
changed = []
problems = []
for feature, choice in values.items():
items = FerroCADGui.providers(feature)
if not items:
problems.append(str(feature))
continue
backend = None
for item in items:
if str(choice) in (item["label"], item["backend"]):
backend = item["backend"]
break
if backend is None:
problems.append("%s=%s" % (feature, choice))
continue
if backend == FerroCADGui.activeProvider(feature):
continue
result = FerroCADGui.setActiveProvider(feature, backend)
view.update(result.get("view") or {})
problems.extend(result.get("errors") or [])
changed.append("%s: %s" % (feature, backend))
if changed:
status = "active provider: " + ", ".join(changed)
elif problems:
status = "unknown provider: " + ", ".join(problems)
else:
status = "no provider changed"
if problems and changed:
status += "; " + "; ".join(problems)
if view:
return {"view": view, "status": status}
return {"status": status}
FreeCADGui.addCommand("Mods_Settings", _ModsSettingsCommand())
class _ReloadGridSettingsCommand:
def GetResources(self):
return {
"MenuText": "Reload grid settings",
"ToolTip": "Apply the grid preferences",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "grid",
"FerroCAD_Parent": "App_ToggleGrid",
}
def Activated(self):
return _grid_view_request()
FreeCADGui.addCommand("App_ReloadGridSettings", _ReloadGridSettingsCommand())
class _ActivateWorkplaneCommand:
def GetResources(self):
return {
"MenuText": "Activate workplane",
"ToolTip": "Sketch on the face under the pointer",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "workplane",
"FerroCAD_Parent": "App_ViewWorkplane",
}
def Activated(self):
return {"view": {"workplane": "activate"}}
class _ClearWorkplaneCommand:
def GetResources(self):
return {
"MenuText": "Clear workplane",
"ToolTip": "Return to the world frame",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "workplane",
"FerroCAD_Parent": "App_ViewWorkplane",
}
def Activated(self):
return {"view": {"workplane": "clear"}}
class _ViewWorkplaneCommand:
def GetResources(self):
return {
"MenuText": "View workplane",
"ToolTip": "Look down the active workplane's normal",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "workplane",
}
def Activated(self):
return {"view": {"workplane": "view"}}
FreeCADGui.addCommand("App_ActivateWorkplane", _ActivateWorkplaneCommand())
FreeCADGui.addCommand("App_ClearWorkplane", _ClearWorkplaneCommand())
FreeCADGui.addCommand("App_ViewWorkplane", _ViewWorkplaneCommand())
class _DevToggleToolsCommand:
def GetResources(self):
return {
"MenuText": "Dev Tools",
"ToolTip": "Open or close the developer tools window",
"Accel": "Ctrl+Shift+D",
"Group": "View",
"CmdType": "ForView",
"FerroCAD_Surface": "hidden",
}
def IsActive(self):
return True
def Activated(self):
return {"status": "dev tools: no GUI window to toggle"}
FreeCADGui.addCommand("Dev_ToggleTools", _DevToggleToolsCommand())