from __future__ import annotations
import math
import FreeCAD
FEATURE = "grid"
BACKEND = "ferrocad"
PREFERENCES = "User parameter:BaseApp/Preferences/Mods/%s/%s" % (FEATURE, BACKEND)
LEGACY_PREFERENCES = "User parameter:BaseApp/Preferences/View"
DEFAULT_ENABLED = False
DEFAULT_COLOR = "#94a3b8"
DEFAULT_OPACITY = 1.0
DEFAULT_MINOR = 10.0
DEFAULT_MAJOR = 100.0
DEFAULT_RADIUS = 0.0
DEFAULT_SHADOWS = False
DEFAULT_SHADOW_OPACITY = 0.30
SETTINGS_SCHEMA = (
{
"name": "enabled",
"label": "Show grid",
"kind": "bool",
"default": DEFAULT_ENABLED,
},
{
"name": "color",
"label": "Grid colour",
"kind": "color",
"default": DEFAULT_COLOR,
},
{
"name": "opacity",
"label": "Opacity",
"kind": "float",
"default": DEFAULT_OPACITY,
"min": 0.0,
"max": 1.0,
},
{
"name": "minor",
"label": "Minor spacing",
"kind": "quantity",
"unit": "mm",
"default": DEFAULT_MINOR,
"min": 0.001,
},
{
"name": "major",
"label": "Major spacing",
"kind": "quantity",
"unit": "mm",
"default": DEFAULT_MAJOR,
"min": 0.001,
},
{
"name": "radius",
"label": "Grid extent",
"kind": "quantity",
"unit": "mm",
"default": DEFAULT_RADIUS,
"min": 0.0,
},
{
"name": "shadows",
"label": "Show ground shadow",
"kind": "bool",
"default": DEFAULT_SHADOWS,
},
{
"name": "shadow_opacity",
"label": "Shadow opacity",
"kind": "float",
"default": DEFAULT_SHADOW_OPACITY,
"min": 0.0,
"max": 1.0,
},
)
_LEGACY_KEYS = {
"enabled": "GridEnabled",
"color": "GridColor",
"opacity": "GridOpacity",
"minor": "GridMinorStep",
"major": "GridMajorStep",
"radius": "GridRadius",
"shadows": "GridShadow",
"shadow_opacity": "GridShadowOpacity",
}
_SPECS = {entry["name"]: entry for entry in SETTINGS_SCHEMA}
_HEX_DIGITS = "0123456789abcdefABCDEF"
def _prefs():
return FreeCAD.ParamGet(PREFERENCES)
def _legacy_prefs():
return FreeCAD.ParamGet(LEGACY_PREFERENCES)
def _present(group, name: str, kind: str) -> bool:
if kind == "bool":
return name in group.GetBools()
if kind in ("float", "quantity"):
return name in group.GetFloats()
return name in group.GetStrings()
def _read_group(group, name: str, kind: str):
if kind == "bool":
return group.GetBool(name, False)
if kind in ("float", "quantity"):
return group.GetFloat(name, 0.0)
return group.GetString(name, "")
def _store(group, spec: dict, value) -> None:
name = spec["name"]
kind = spec["kind"]
if kind == "bool":
group.SetBool(name, bool(value))
elif kind in ("float", "quantity"):
group.SetFloat(name, float(value))
else:
group.SetString(name, str(value))
def _migrate(spec: dict, group) -> None:
legacy_key = _LEGACY_KEYS.get(spec["name"])
if legacy_key is None or _present(group, spec["name"], spec["kind"]):
return
legacy = _legacy_prefs()
if not _present(legacy, legacy_key, spec["kind"]):
return
_store(group, spec, _read_group(legacy, legacy_key, spec["kind"]))
def _read(spec: dict):
group = _prefs()
_migrate(spec, group)
name = spec["name"]
kind = spec["kind"]
default = spec["default"]
if kind == "bool":
return group.GetBool(name, bool(default))
if kind in ("float", "quantity"):
return group.GetFloat(name, float(default))
return group.GetString(name, str(default))
def _write(spec: dict, value) -> None:
_store(_prefs(), spec, value)
def _colour(value) -> str:
if not isinstance(value, str):
raise ValueError("a grid colour must be a '#rrggbb' string, got %r" % (value,))
text = value.strip()
if not text.startswith("#"):
raise ValueError("a grid colour must start with '#', got %r" % (text,))
digits = text[1:]
if len(digits) == 3:
digits = "".join(digit * 2 for digit in digits)
elif len(digits) != 6:
raise ValueError("a grid colour must be #rgb or #rrggbb, got %r" % (text,))
if any(digit not in _HEX_DIGITS for digit in digits):
raise ValueError("a grid colour has a non-hex digit, got %r" % (text,))
return "#" + digits.lower()
def _number(value, name: str, *, minimum=0.0, maximum=None, positive=False) -> float:
try:
number = float(value)
except (TypeError, ValueError):
raise ValueError("%s must be a number, got %r" % (name, value)) from None
if not math.isfinite(number):
raise ValueError("%s must be finite, got %r" % (name, value))
if positive:
if number <= 0.0:
raise ValueError("%s must be positive, got %r" % (name, value))
elif number < minimum:
raise ValueError("%s must be at least %s, got %r" % (name, minimum, value))
if maximum is not None and number > maximum:
raise ValueError("%s must be at most %s, got %r" % (name, maximum, value))
return number
def _step(value, name: str) -> float:
return _number(value, name, positive=True)
def _radius(value) -> float:
return _number(value, "the grid radius", minimum=0.0)
def _alpha(value, name: str) -> float:
return _number(value, name, minimum=0.0, maximum=1.0)
class _GridSettings:
def schema(self) -> list:
return [dict(entry) for entry in SETTINGS_SCHEMA]
@property
def enabled(self) -> bool:
return bool(_read(_SPECS["enabled"]))
@enabled.setter
def enabled(self, value) -> None:
_write(_SPECS["enabled"], bool(value))
@property
def color(self) -> str:
return _colour(_read(_SPECS["color"]))
@color.setter
def color(self, value) -> None:
_write(_SPECS["color"], _colour(value))
@property
def opacity(self) -> float:
return _alpha(_read(_SPECS["opacity"]), "the grid opacity")
@opacity.setter
def opacity(self, value) -> None:
_write(_SPECS["opacity"], _alpha(value, "the grid opacity"))
@property
def spacing(self) -> float:
return self.minor
@spacing.setter
def spacing(self, value) -> None:
step = _step(value, "the grid spacing")
_write(_SPECS["minor"], step)
_write(_SPECS["major"], step * 10.0)
@property
def minor(self) -> float:
return _step(_read(_SPECS["minor"]), "the grid minor step")
@minor.setter
def minor(self, value) -> None:
_write(_SPECS["minor"], _step(value, "the grid minor step"))
@property
def major(self) -> float:
return _step(_read(_SPECS["major"]), "the grid major step")
@major.setter
def major(self, value) -> None:
_write(_SPECS["major"], _step(value, "the grid major step"))
@property
def radius(self) -> float:
return _radius(_read(_SPECS["radius"]))
@radius.setter
def radius(self, value) -> None:
_write(_SPECS["radius"], _radius(value))
@property
def axis_cross(self) -> bool:
from . import _axis
return _axis.axis().enabled
@axis_cross.setter
def axis_cross(self, value) -> None:
from . import _axis
_axis.axis().enabled = value
@property
def shadows(self) -> bool:
return bool(_read(_SPECS["shadows"]))
@shadows.setter
def shadows(self, value) -> None:
_write(_SPECS["shadows"], bool(value))
@property
def shadow_opacity(self) -> float:
return _alpha(_read(_SPECS["shadow_opacity"]), "the grid shadow opacity")
@shadow_opacity.setter
def shadow_opacity(self, value) -> None:
_write(
_SPECS["shadow_opacity"],
_alpha(value, "the grid shadow opacity"),
)
def apply(self) -> dict:
minor = self.minor
major = self.major
if major < minor:
raise ValueError(
"the grid major step (%s) cannot be below the minor one (%s)"
% (major, minor)
)
return {
"view": {
"grid": self.enabled,
"grid_minor": minor,
"grid_major": major,
"grid_radius": self.radius,
"grid_color": self.color,
"grid_alpha": self.opacity,
}
}
def snapshot(self) -> dict:
mirror = self._mirror()
if mirror is not None:
return {
"grid": bool(mirror.grid),
"grid_minor": float(mirror.grid_minor),
"grid_major": float(mirror.grid_major),
"grid_radius": (
None if mirror.grid_radius is None else float(mirror.grid_radius)
),
"grid_color": getattr(mirror, "grid_color", self.color),
"grid_alpha": float(getattr(mirror, "grid_alpha", self.opacity)),
"shadows": self.shadows,
"shadow_opacity": self.shadow_opacity,
}
return {
"grid": self.enabled,
"grid_minor": self.minor,
"grid_major": self.major,
"grid_radius": self.radius if self.radius > 0.0 else None,
"grid_color": self.color,
"grid_alpha": self.opacity,
"shadows": self.shadows,
"shadow_opacity": self.shadow_opacity,
}
@staticmethod
def _mirror():
if not FreeCAD.GuiUp:
return None
try:
import FerroCADGui
except Exception: return None
return getattr(FerroCADGui, "ViewState", None)
def reset(self) -> None:
_prefs().Clear()
legacy = _legacy_prefs()
for name, key in _LEGACY_KEYS.items():
kind = _SPECS[name]["kind"]
if kind == "bool":
legacy.RemBool(key)
elif kind in ("float", "quantity"):
legacy.RemFloat(key)
else:
legacy.RemString(key)
_INSTANCE = None
def grid() -> _GridSettings:
global _INSTANCE
if _INSTANCE is None:
_INSTANCE = _GridSettings()
return _INSTANCE