ferrocad 0.1.4

FerroCAD: a Rust reimplementation of FreeCAD's App core, exposed as the FreeCAD Python package
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
"""The FerroCAD-only ``Gui`` API (the extensions upstream FreeCADGui lacks).

A mod that imports ``FerroCADGui`` declares a FerroCAD dependency. Nothing here
is aliased onto ``FreeCADGui``: the upstream namespace keeps only the
upstream-shaped command registry, selection snapshot and dialog helpers. See
``docs/architecture/api-namespaces.md``.

What lives here:

* the **mod provider registry** — ``registerProvider`` / ``providers`` /
  ``activeProvider`` / ``setActiveProvider`` / ``refreshProviders``: a mod
  declares which *feature* a backend provides, exactly one backend per feature
  is active, and switching runs the outgoing ``deactivate`` and incoming
  ``activate`` callbacks; a later request can run the active backend's
  ``refresh`` callback without switching (see
  ``docs/workbenches/mod-providers.md``);
* the **provider settings schema** — a provider may advertise its knobs in
  ``registerProvider(..., settings=[...])``; ``settings`` returns the active
  backend's rows in the property-pane row shape and ``setSetting`` validates,
  stores and refreshes (see ``docs/tasks/settings-model.md`` S0);
* the **pull overlay bridge** — ``addOverlay`` / ``removeOverlay`` (Coin);
* the **document-listener slot** — ``addDocumentListener`` /
  ``removeDocumentListener``, with ``onDocumentCreated`` / ``onDocumentActivated``
  / ``onDocumentDeactivated`` / ``onDocumentClosed`` callbacks.
  ``FreeCADGui.addDocumentObserver`` forwards here (the upstream-shaped name),
  and the App observer reports creation/activation/deletion but never
  deactivation — which is why a per-document attachment used to linger until the
  next activation;
* a **read-only view state** (``ViewState.grid``, ``ViewState.projection``),
  filled by the shell for a checkable command's ``IsChecked``.

The command registry, the selection snapshot and the private bridge helpers the
app script calls (``_command_list``, ``_run``, ``_accept``, ``_cancel``) stay on
``FreeCADGui``, because upstream has them.
"""

from __future__ import annotations

import re
import sys

import FreeCAD

from FreeCADGui import _error_text

#: Provider manifests: ``feature -> backend -> record``. Both levels keep
#: registration order, which is the deterministic tie-break for equal priorities.
_PROVIDERS: dict = {}

#: ``feature -> backend`` whose ``activate``/``deactivate`` callbacks last ran.
#: A persisted choice alone does not mean the effects were applied: the first
#: explicit switch is what runs them.
_PROVIDER_APPLIED: dict = {}

#: The document the applied provider effects are attached to. Deactivation only
#: runs for that document, so closing an inactive document leaves the active
#: one's attachment alone.
_PROVIDER_DOCUMENT = None

#: Monotonic registration serial (never reused), for the priority tie-break.
_PROVIDER_SERIAL: int = 0

#: ``(feature, backend, hook)`` provider callbacks already reported, so a broken
#: backend does not spam the console on every switch.
_PROVIDER_REPORTED: set = set()

#: The parameter group a mod's provider choice is persisted in.
PROVIDER_PREFERENCES = "User parameter:BaseApp/Preferences/Mods"

#: Setting kinds the editor knows how to edit. A schema may declare another
#: kind: the row is then read-only and the problem is reported once.
_SETTING_KINDS = ("text", "bool", "int", "float", "quantity", "enum", "color")

#: Setting kind -> the property type id a row reports (``properties`` uses the
#: same ids to pick an editor), so one renderer serves both surfaces.
_SETTING_TYPES = {
    "text": "App::PropertyString",
    "bool": "App::PropertyBool",
    "int": "App::PropertyInteger",
    "float": "App::PropertyFloat",
    "quantity": "App::PropertyQuantity",
    "enum": "App::PropertyEnumeration",
    "color": "App::PropertyString",
}

#: A sensible default when a schema entry supplies none. ``enum`` and the
#: unknown kinds are handled separately (first choice / empty text).
_SETTING_DEFAULTS = {
    "text": "",
    "bool": False,
    "int": 0,
    "float": 0.0,
    "quantity": 0.0,
    "color": "#000000",
}

#: ``(feature, backend, setting)`` settings problems already reported.
_SETTING_REPORTED: set = set()

#: Observers registered through :func:`addDocumentListener`, in registration
#: order. Identity is the key: one registration per object, no duplicates.
_DOCUMENT_LISTENERS: list = []

#: ``(id(observer), hook)`` document callbacks already reported, so a broken
#: observer does not spam the console on every document operation.
_OBSERVER_REPORTED: set = set()

#: Lifecycle event -> observer method. The names are FerroCAD's; upstream
#: FreeCADGui has no equivalent slot.
_DOCUMENT_HOOKS = {
    "created": "onDocumentCreated",
    "activated": "onDocumentActivated",
    "deactivated": "onDocumentDeactivated",
    "closed": "onDocumentClosed",
}

_COLOR_RE = re.compile(r"#[0-9a-fA-F]{6}\Z")


# ---------------------------------------------------------------------------
# Document lifecycle observers
#
# App-side document creation and activation already exist, but the facade has
# no GUI document observer and no *deactivation* event. A provider that attaches
# something per document (the Coin grid) therefore kept it until the next
# activation. These observers are fired by the FerroCAD lifecycle wrappers and
# by the shell, which is the host's single path through document creation,
# activation and closing.
# ---------------------------------------------------------------------------


def addDocumentListener(observer) -> None:
    """Register ``observer`` for document lifecycle notifications.

    ``observer`` is any object. For each event, the matching method is called
    when it exists: ``onDocumentCreated(name)``, ``onDocumentActivated(name)``,
    ``onDocumentDeactivated(name)`` and ``onDocumentClosed(name)``. A missing
    method is simply not called, so an observer may implement only the events it
    cares about.

    Registration is by **identity**: adding the same object twice is a no-op.
    An observer that raises is reported once per ``(observer, method)`` and is
    skipped; it never prevents the document operation or the other observers.
    This slot lives on ``FerroCADGui`` because it is a FerroCAD extension: the
    App observer reports creation/activation/deletion without a deactivation
    event, and ``FreeCADGui.addDocumentObserver`` forwards here for the
    upstream-shaped name (see ``docs/architecture/api-namespaces.md``).
    """
    if any(existing is observer for existing in _DOCUMENT_LISTENERS):
        return
    _DOCUMENT_LISTENERS.append(observer)


def removeDocumentListener(observer) -> bool:
    """Unregister ``observer``; returns whether it was registered."""
    for index, existing in enumerate(_DOCUMENT_LISTENERS):
        if existing is observer:
            del _DOCUMENT_LISTENERS[index]
            _OBSERVER_REPORTED.difference_update(
                {key for key in _OBSERVER_REPORTED if key[0] == id(observer)}
            )
            return True
    return False


def _report_observer(observer, hook: str, exc: BaseException) -> None:
    """Report a failing observer callback once per ``(observer, hook)``."""
    key = (id(observer), hook)
    if key in _OBSERVER_REPORTED:
        return
    _OBSERVER_REPORTED.add(key)
    label = getattr(observer, "__name__", None) or type(observer).__name__
    print(
        f"FerroCADGui: document observer {label!r} {hook} raised: "
        f"{_error_text(exc)}",
        file=sys.stderr,
    )


def _document_event(event: str, name: str) -> None:
    """Deliver one lifecycle event to every registered observer (private).

    Called by the App facade (``FreeCAD``) and by ``ferrocad_shell``. The
    callbacks are isolated individually, so one broken observer cannot stop the
    document operation or another observer.

    ``closed`` also drops the ``FreeCADGui`` view cached for that document, when
    the facade is loaded: the view owns a scene graph and may hold an overlay
    registration, so leaving it behind would keep drawing a closed document.
    """
    hook = _DOCUMENT_HOOKS[event]
    for observer in list(_DOCUMENT_LISTENERS):
        callback = getattr(observer, hook, None)
        if not callable(callback):
            continue
        try:
            callback(name)
        except Exception as exc:  # noqa: BLE001 - one observer is not fatal
            _report_observer(observer, hook, exc)
    if event == "closed":
        gui = sys.modules.get("FreeCADGui")
        forget = getattr(gui, "_forget_document", None) if gui is not None else None
        if forget is not None:
            try:
                forget(name)
            except Exception as exc:  # noqa: BLE001 - a stale view is not fatal
                _report_observer(gui, "_forget_document", exc)


# ---------------------------------------------------------------------------
# Mod providers
#
# A mod that replaces a feature's implementation (the semantic and Coin grids
# are the first pair) declares itself from ``InitGui.py`` with
# :func:`registerProvider`. The registry keeps exactly one active backend per
# feature and switches the viewport state by calling the outgoing provider's
# ``deactivate`` and the incoming provider's ``activate``. A command that changed
# shared state without switching can ask the active backend to re-read it with
# :func:`refreshProviders`. See ``docs/workbenches/mod-providers.md``.
# ---------------------------------------------------------------------------


def _provider_prefs():
    """The parameter group holding one backend id per feature."""
    return FreeCAD.ParamGet(PROVIDER_PREFERENCES).GetGroup("Providers")


def _report_provider(feature, backend, hook: str, exc: BaseException) -> None:
    """Report a failing ``activate``/``deactivate``/``refresh`` once per hook."""
    key = (feature, backend, hook)
    if key in _PROVIDER_REPORTED:
        return
    _PROVIDER_REPORTED.add(key)
    print(
        f"FerroCADGui: provider {backend!r} for {feature!r} {hook} raised: "
        f"{_error_text(exc)}",
        file=sys.stderr,
    )


def _report_setting(feature, backend, name: str, exc: BaseException) -> None:
    """Report a broken schema default/hook once per setting."""
    key = (feature, backend, name)
    if key in _SETTING_REPORTED:
        return
    _SETTING_REPORTED.add(key)
    print(
        f"FerroCADGui: setting {name!r} of provider {backend!r} for {feature!r} "
        f"raised: {_error_text(exc)}",
        file=sys.stderr,
    )


def registerProvider(
    feature: str,
    backend: str,
    label: str,
    command=None,
    priority: int = 0,
    activate=None,
    deactivate=None,
    refresh=None,
    settings=None,
    skin=None,
):
    """Declare that ``backend`` provides ``feature`` (called from ``InitGui.py``).

    ``label`` is the user-facing name the ``Mods_Settings`` dialog shows;
    ``command`` is the command id the backend owns (``None`` when it has none);
    ``priority`` decides the default backend (higher wins, earliest registration
    breaks a tie); ``activate``/``deactivate`` are optional zero-argument
    callbacks that make the backend the drawn one and undo that; ``refresh`` is
    the optional zero-argument callback for "shared state changed, re-read it"
    (see :func:`refreshProviders`). All three callbacks run only when asked —
    never at registration — and their errors are isolated. One exception: if
    this registration takes the selection over (a higher priority, or a saved
    choice), the outgoing backend's ``deactivate`` runs so a mod that drew
    during its own import cannot keep drawing. The incoming backend is still
    activated by the first switch.

    ``settings`` is the optional schema the provider advertises: a list of
    dicts, each with a non-empty ``name`` and a ``kind`` (``text``, ``bool``,
    ``int``, ``float``, ``quantity``, ``enum``, ``color``), plus ``label``,
    ``default``, ``min``/``max``, ``unit``, ``choices`` and optional ``get``/
    ``set`` callables. It is validated here and stored; **no default is written**
    at registration, so importing a mod stays free of side effects. An unknown
    kind is allowed and reported once; its row is read-only. See
    ``docs/tasks/settings-model.md`` S0.

    ``skin`` is the optional WGSL source text of the material program this
    backend supplies for a capability that hosts one (the manipulator gizmo
    does). It is **not** a setting: it never appears in the settings manifest or
    in the mods dialog, and the host asks for it through :func:`providerSkin`.
    Supplying no skin means the host draws its native material. A reload
    replaces the source like every other field; omitting it clears a previously
    supplied one. It is stored trimmed.

    Registering the same ``(feature, backend)`` again replaces the record (a mod
    reload) without moving it in the registration order. Returns the manifest.
    """
    global _PROVIDER_SERIAL

    if not isinstance(feature, str) or not feature:
        raise ValueError("a provider feature must be a non-empty string")
    if not isinstance(backend, str) or not backend:
        raise ValueError("a provider backend must be a non-empty string")
    if command is not None and not isinstance(command, str):
        raise TypeError("a provider command must be a command id string or None")
    if activate is not None and not callable(activate):
        raise TypeError(f"provider {feature!r}/{backend!r} activate is not callable")
    if deactivate is not None and not callable(deactivate):
        raise TypeError(f"provider {feature!r}/{backend!r} deactivate is not callable")
    if refresh is not None and not callable(refresh):
        raise TypeError(f"provider {feature!r}/{backend!r} refresh is not callable")
    schema = _validate_settings(feature, backend, settings)
    if skin is not None and not isinstance(skin, str):
        raise TypeError(f"provider {feature!r}/{backend!r} skin must be WGSL source text")
    source = None if skin is None else skin.strip()
    if source == "":
        raise ValueError(f"provider {feature!r}/{backend!r} skin is empty")

    text = str(label if label is not None else backend).strip()
    records = _PROVIDERS.get(feature)
    if records is None:
        records = _PROVIDERS.setdefault(feature, {})
    before = _selected(feature)
    existing = records.get(backend)
    order = existing["order"] if existing is not None else _PROVIDER_SERIAL
    if existing is None:
        _PROVIDER_SERIAL += 1
    records[backend] = {
        "feature": feature,
        "backend": backend,
        "label": text or backend,
        "command": command,
        "priority": int(priority),
        "order": order,
        "activate": activate,
        "deactivate": deactivate,
        "refresh": refresh,
        "settings": schema,
        "skin": source,
    }
    _PROVIDER_REPORTED.difference_update(
        {key for key in _PROVIDER_REPORTED if key[0] == feature and key[1] == backend}
    )
    _SETTING_REPORTED.difference_update(
        {key for key in _SETTING_REPORTED if key[0] == feature and key[1] == backend}
    )
    for spec in schema:
        if spec["kind"] not in _SETTING_KINDS:
            _report_setting(
                feature,
                backend,
                spec["name"],
                ValueError(
                    f"unknown kind {spec['kind']!r}; the row is read-only"
                ),
            )

    # A takeover is a selection change caused by registration. Stop the outgoing
    # backend, but leave the incoming one for the first explicit switch (which
    # keeps ``activate`` out of import time).
    selected = _selected(feature)
    if selected == backend and before is not None and before != backend:
        outgoing = records.get(before)
        if outgoing is not None:
            _deactivate_on_takeover(outgoing, feature)
            if _PROVIDER_APPLIED.get(feature) == before:
                _PROVIDER_APPLIED.pop(feature, None)
    return _manifest(records[backend], feature)


def refreshProviders(feature: str) -> dict:
    """Ask the active backend of ``feature`` to re-read the shared state.

    This is the counterpart of ``activate``/``deactivate`` for a change that is
    not a switch: a command (or a dialog) already applied a request, and a
    backend that draws from its own store has to look at the shared store again
    — the grid toggle writes ``FerroCAD.Grid.enabled`` and the Coin overlay then
    re-binds from it. Like the other provider callbacks it runs **only when
    asked**, never at registration or on a switch, and a failure is reported and
    collected instead of raised.

    Only the active backend runs; an absent ``refresh`` callback (or no provider
    for the feature) is a no-op. A callback may return the same dict a command
    may return, so ``view`` carries a request the caller can merge (the grid
    toggle reads the ``grid_overlay`` claim from it). Returns ``ok``,
    ``feature``, ``backend``, ``view``, ``status`` and ``errors``; it never
    raises for a backend problem.
    """
    result = {
        "ok": True,
        "feature": feature,
        "backend": None,
        "view": {},
        "status": "",
        "errors": [],
    }
    records = _PROVIDERS.get(feature)
    if not records:
        return result
    backend = _selected(feature)
    result["backend"] = backend
    statuses = []
    _invoke_provider(records[backend], feature, "refresh", result, statuses)
    if statuses:
        result["status"] = "; ".join(statuses)
    return result


def _deactivate_on_takeover(record, feature) -> None:
    """Stop a backend whose feature changed hands while a mod was registering."""
    callback = record.get("deactivate")
    if callback is None:
        return
    try:
        callback()
    except Exception as exc:  # noqa: BLE001 - a broken backend is not fatal
        _report_provider(feature, record["backend"], "deactivate", exc)


def unregisterProvider(feature: str, backend: str) -> bool:
    """Drop a provider record; returns whether it existed.

    This is a reload/teardown helper and does **not** run ``deactivate``; the
    caller owns the effects (the Coin mod, for example, shuts its manager down
    before re-registering). A persisted choice is deliberately left alone, so a
    re-registered backend keeps its selection.
    """
    records = _PROVIDERS.get(feature)
    if not records or backend not in records:
        return False
    del records[backend]
    if not records:
        _PROVIDERS.pop(feature, None)
    if _PROVIDER_APPLIED.get(feature) == backend:
        _PROVIDER_APPLIED.pop(feature, None)
    _PROVIDER_REPORTED.difference_update(
        {key for key in _PROVIDER_REPORTED if key[0] == feature and key[1] == backend}
    )
    _SETTING_REPORTED.difference_update(
        {key for key in _SETTING_REPORTED if key[0] == feature and key[1] == backend}
    )
    return True


def _manifest(record, feature, active=None):
    """One provider as JSON-safe data (the callbacks never leave this module)."""
    if active is None:
        active = _selected(feature)
    return {
        "feature": feature,
        "backend": record["backend"],
        "label": record["label"],
        "command": record["command"],
        "priority": record["priority"],
        "active": record["backend"] == active,
    }


def _selected(feature):
    """The backend that *is* the provider: the persisted choice, else priority.

    A persisted value that no longer names a registered backend is ignored (a
    mod was removed or renamed); the highest priority wins. An equal priority is
    broken by registration order, earliest first, so the answer is deterministic.
    """
    records = _PROVIDERS.get(feature)
    if not records:
        return None
    saved = _provider_prefs().GetString(feature, "")
    if saved in records:
        return saved
    return max(
        records.values(),
        key=lambda record: (record["priority"], -record["order"]),
    )["backend"]


def providers(feature=None) -> list:
    """The provider manifests, in registration order.

    With a ``feature``, only that feature's backends (``[]`` when none are
    registered); without one, every feature in first-registration order. Each
    entry carries ``feature``, ``backend``, ``label``, ``command``, ``priority``
    and ``active``. The callbacks stay private so the list stays JSON-safe.
    """
    if feature is not None:
        records = _PROVIDERS.get(feature)
        if not records:
            return []
        active = _selected(feature)
        return [_manifest(record, feature, active) for record in records.values()]
    entries = []
    for name in _PROVIDERS:
        active = _selected(name)
        entries.extend(
            _manifest(record, name, active) for record in _PROVIDERS[name].values()
        )
    return entries


def activeProvider(feature):
    """The active backend for ``feature``, or ``None`` when none is registered.

    This is the declaration (the persisted choice, else the highest priority).
    A mod checks it in ``IsActive``/``Activated`` to refuse to run when another
    backend owns the feature.
    """
    return _selected(feature)


def providerSkin(feature, backend=None):
    """The WGSL material program of ``feature``'s backend, or ``None``.

    This is the host's channel for a provider-supplied shader skin: the shell
    asks a capability that hosts one (the manipulator gizmo) for its material
    program and draws with the source :func:`registerProvider` recorded under
    ``skin``. ``backend`` names a specific backend; ``None`` — the form the
    shell uses — means the **active** backend. That is the point: a switch makes
    the host ask again, so a stale skin cannot survive a provider change.

    ``None`` also means "draw the native material": an unknown feature or
    backend, and a backend that supplied no skin, all answer ``None``. Like
    :func:`activeProvider` this never raises for an unknown name, because the
    shell polls it across the interpreter boundary.
    """
    records = _PROVIDERS.get(feature)
    if not records:
        return None
    if backend is None:
        backend = _selected(feature)
    record = records.get(backend)
    if record is None:
        return None
    return record.get("skin")


def setActiveProvider(feature: str, backend: str) -> dict:
    """Make ``backend`` the active provider for ``feature`` and apply it.

    The choice is persisted first, then the outgoing backend is deactivated and
    the incoming one activated, each at most once per change. The outgoing
    backend is the applied one when there is one, else the declared active one,
    so a first switch still restores the default it left. Selecting the
    already-declared backend runs its ``activate`` once (the bootstrap case).

    Callback errors are caught and reported (never fatal), as command callbacks
    are; they are listed under ``errors``. Returns a dict with ``ok``,
    ``feature``, ``backend``, ``previous``, the merged ``view`` request and a
    one-line ``status``. An unknown feature or backend raises ``ValueError``.
    """
    global _PROVIDER_DOCUMENT

    records = _PROVIDERS.get(feature)
    if not records:
        raise ValueError(f"no provider is registered for feature {feature!r}")
    if backend not in records:
        raise ValueError(f"{backend!r} does not provide feature {feature!r}")

    # The declared active backend before the choice changes. It is the outgoing
    # one even when its effects were never applied: its ``deactivate`` is an
    # idempotent "restore the default", so the first switch still leaves the
    # viewport consistent. Selecting the already-declared default is the one case
    # that still runs ``activate`` once, which is how a backend is bootstrapped.
    declared = _selected(feature)
    applied = _PROVIDER_APPLIED.get(feature)
    outgoing_backend = applied if applied is not None else declared
    _provider_prefs().SetString(feature, backend)

    result = {
        "ok": True,
        "feature": feature,
        "backend": backend,
        "previous": declared,
        "view": {},
        "status": "",
        "errors": [],
    }
    statuses = []
    if outgoing_backend != backend:
        outgoing = records.get(outgoing_backend) if outgoing_backend is not None else None
        if outgoing is not None:
            _invoke_provider(outgoing, feature, "deactivate", result, statuses)
        _invoke_provider(records[backend], feature, "activate", result, statuses)
    elif applied is None:
        _invoke_provider(records[backend], feature, "activate", result, statuses)
    _PROVIDER_APPLIED[feature] = backend
    document = FreeCAD.activeDocument()
    if document is not None:
        # Explicit switches are a document attachment too; recording it here
        # keeps the close/deactivate path correct even when a caller drove only
        # the registry (a script, or a document created through upstream
        # ``FreeCAD`` rather than the FerroCAD lifecycle wrappers).
        _PROVIDER_DOCUMENT = document.Name

    message = f"{feature}: {backend} is the active provider"
    if statuses:
        message = "; ".join(statuses) + "; " + message
    if result["errors"]:
        message += " (reported: " + "; ".join(result["errors"]) + ")"
    result["status"] = message
    return result


def _invoke_provider(record, feature, hook, result, statuses) -> None:
    """Run one provider callback, isolating and collecting its result."""
    callback = record.get(hook)
    if callback is None:
        return
    try:
        value = callback()
    except Exception as exc:  # noqa: BLE001 - one broken backend is not fatal
        _report_provider(feature, record["backend"], hook, exc)
        result["errors"].append(f"{hook}: {_error_text(exc)}")
        return
    if not isinstance(value, dict):
        return
    view = value.get("view")
    if isinstance(view, dict):
        result["view"].update(view)
    status = value.get("status")
    if status:
        statuses.append(str(status))


# ---------------------------------------------------------------------------
# Provider attachment follows the active document
#
# The registry applies a backend's effects once (activate) and undoes them on a
# switch (deactivate). Those effects may be per-document — the Coin grid builds
# one overlay per document — so the document lifecycle must drive the same
# callbacks. A closed document's attachment used to survive until the next
# activation; this observer makes deactivation immediate.
# ---------------------------------------------------------------------------


class _ProviderDocumentObserver:
    """Attach the applied providers to the active document and detach them."""

    def onDocumentActivated(self, name) -> None:
        _activate_document_providers(name)

    def onDocumentDeactivated(self, name) -> None:
        _deactivate_document_providers(name)

    def onDocumentClosed(self, name) -> None:
        _deactivate_document_providers(name)


def _activate_document_providers(name) -> None:
    """Run every provider's ``activate`` for the document becoming active.

    This is the bootstrap path as well as the re-attach after a switch: the
    declared backend of every registered feature becomes drawn again. It is
    idempotent per document, so a caller that reports both a creation and an
    activation (or an activation twice) does not run ``activate`` twice.
    """
    global _PROVIDER_DOCUMENT
    if not isinstance(name, str) or not name:
        return
    if _PROVIDER_DOCUMENT == name:
        return
    if _PROVIDER_DOCUMENT is not None:
        # A caller skipped the deactivate event (upstream ``FreeCAD`` created or
        # activated a document directly); stop the stale attachment first.
        _deactivate_document_providers(_PROVIDER_DOCUMENT)
    for feature, records in list(_PROVIDERS.items()):
        backend = _selected(feature)
        record = records.get(backend)
        if record is None:
            continue
        result = {
            "ok": True,
            "feature": feature,
            "backend": backend,
            "view": {},
            "status": "",
            "errors": [],
        }
        _invoke_provider(record, feature, "activate", result, [])
        _PROVIDER_APPLIED[feature] = backend
    _PROVIDER_DOCUMENT = name


def _deactivate_document_providers(name) -> None:
    """Run the applied providers' ``deactivate`` for the document leaving.

    The applied record is dropped **before** the callback runs, so a document
    that is deactivated and then closed (or closed twice) cannot call
    ``deactivate`` twice. Once a provider is no longer applied, the next
    activation bootstraps it again through :func:`_activate_document_providers`.
    """
    global _PROVIDER_DOCUMENT
    if _PROVIDER_DOCUMENT != name:
        return
    _PROVIDER_DOCUMENT = None
    for feature, backend in list(_PROVIDER_APPLIED.items()):
        _PROVIDER_APPLIED.pop(feature, None)
        records = _PROVIDERS.get(feature)
        record = records.get(backend) if records else None
        if record is None:
            continue
        result = {
            "ok": True,
            "feature": feature,
            "backend": backend,
            "view": {},
            "status": "",
            "errors": [],
        }
        _invoke_provider(record, feature, "deactivate", result, [])


addDocumentListener(_ProviderDocumentObserver())


# ---------------------------------------------------------------------------
# Provider settings (S0, docs/tasks/settings-model.md)
#
# A provider declares its knobs once, at registration, and FerroCAD owns the
# store: one parameter group per ``(feature, backend)``, one typed key per
# setting. The rows are the property pane's row contract, so the tree and the
# pane render a provider's settings without a second renderer. Nothing is
# written at registration: a default is materialised on read, which keeps
# importing a mod side-effect free.
# ---------------------------------------------------------------------------


def _settings_group(feature, backend):
    """The parameter group holding one backend's setting values."""
    return FreeCAD.ParamGet(f"{PROVIDER_PREFERENCES}/{feature}/{backend}")


def _validate_settings(feature, backend, settings) -> list:
    """Validate a provider's schema and return its normalised form.

    A malformed schema is a programmer error at registration time, so it raises
    ``TypeError``/``ValueError`` with the offending entry named. An unknown kind
    is deliberately **not** an error: it is allowed, reported once by the
    caller, and rendered read-only.
    """
    if settings is None:
        return []
    if not isinstance(settings, (list, tuple)):
        raise TypeError(
            f"provider {feature!r}/{backend!r} settings must be a list of dicts"
        )
    schema = []
    names = set()
    for index, entry in enumerate(settings):
        if not isinstance(entry, dict):
            raise TypeError(
                f"provider {feature!r}/{backend!r} setting #{index} is not a dict"
            )
        name = entry.get("name")
        if not isinstance(name, str) or not name.strip():
            raise ValueError(
                f"provider {feature!r}/{backend!r} setting #{index} needs a "
                "non-empty 'name'"
            )
        name = name.strip()
        if name in names:
            raise ValueError(
                f"provider {feature!r}/{backend!r} declares setting {name!r} twice"
            )
        names.add(name)
        kind = entry.get("kind")
        if not isinstance(kind, str) or not kind.strip():
            raise ValueError(
                f"provider {feature!r}/{backend!r} setting {name!r} needs a 'kind'"
            )
        spec = {
            "name": name,
            "kind": kind.strip(),
            "label": str(entry.get("label") or name),
        }
        unit = entry.get("unit")
        if unit is not None:
            if not isinstance(unit, str) or not unit.strip():
                raise ValueError(
                    f"provider {feature!r}/{backend!r} setting {name!r} has a "
                    "non-string 'unit'"
                )
            spec["unit"] = unit.strip()
        choices = entry.get("choices")
        if choices is not None:
            if not isinstance(choices, (list, tuple)) or not all(
                isinstance(choice, str) and choice for choice in choices
            ):
                raise ValueError(
                    f"provider {feature!r}/{backend!r} setting {name!r} needs "
                    "'choices' to be a list of non-empty strings"
                )
            spec["choices"] = list(choices)
        if spec["kind"] == "enum" and not spec.get("choices"):
            raise ValueError(
                f"provider {feature!r}/{backend!r} setting {name!r} has kind "
                "'enum' but no 'choices'"
            )
        for bound in ("min", "max"):
            value = entry.get(bound)
            if value is None:
                continue
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                raise TypeError(
                    f"provider {feature!r}/{backend!r} setting {name!r} "
                    f"'{bound}' must be a number"
                )
            spec[bound] = float(value)
        if "min" in spec and "max" in spec and spec["min"] > spec["max"]:
            raise ValueError(
                f"provider {feature!r}/{backend!r} setting {name!r} has "
                f"min > max ({spec['min']:g} > {spec['max']:g})"
            )
        for hook in ("get", "set"):
            callback = entry.get(hook)
            if callback is None:
                continue
            if not callable(callback):
                raise TypeError(
                    f"provider {feature!r}/{backend!r} setting {name!r} "
                    f"'{hook}' is not callable"
                )
            spec[hook] = callback
        if "default" in entry:
            default = entry["default"]
            if spec["kind"] in _SETTING_KINDS:
                default = _coerce_setting(spec, default)
            spec["default"] = default
        elif spec["kind"] == "enum":
            spec["default"] = spec["choices"][0]
        else:
            spec["default"] = _SETTING_DEFAULTS.get(spec["kind"], "")
        schema.append(spec)
    return schema


def _coerce_setting(spec, value):
    """Coerce one value to the setting's kind, enforcing range and choices.

    Raises ``ValueError`` (with the setting named) when the value does not fit;
    callers turn that into an error result and leave the store untouched.
    """
    kind = spec["kind"]
    name = spec["name"]
    if kind == "text":
        result = value if isinstance(value, str) else str(value)
    elif kind == "bool":
        if isinstance(value, bool):
            result = value
        elif isinstance(value, (int, float)):
            result = bool(value)
        elif isinstance(value, str):
            text = value.strip().lower()
            if text in ("1", "true", "yes", "on"):
                result = True
            elif text in ("0", "false", "no", "off", ""):
                result = False
            else:
                raise ValueError(f"setting {name!r} expects true or false")
        else:
            raise ValueError(f"setting {name!r} expects true or false")
    elif kind == "int":
        if isinstance(value, bool):
            raise ValueError(f"setting {name!r} expects an integer")
        try:
            number = float(value) if isinstance(value, str) else value
        except (TypeError, ValueError):
            raise ValueError(f"setting {name!r} expects an integer") from None
        if isinstance(number, float) and not number.is_integer():
            raise ValueError(f"setting {name!r} expects an integer")
        try:
            result = int(number)
        except (TypeError, ValueError):
            raise ValueError(f"setting {name!r} expects an integer") from None
    elif kind == "float":
        if isinstance(value, bool):
            raise ValueError(f"setting {name!r} expects a number")
        try:
            result = float(value)
        except (TypeError, ValueError):
            raise ValueError(f"setting {name!r} expects a number") from None
    elif kind == "quantity":
        result = _quantity_value(spec, value)
    elif kind == "enum":
        text = value if isinstance(value, str) else str(value)
        if text not in spec["choices"]:
            choices = ", ".join(repr(choice) for choice in spec["choices"])
            raise ValueError(
                f"setting {name!r} must be one of {choices}; got {text!r}"
            )
        result = text
    elif kind == "color":
        text = str(value).strip()
        if not _COLOR_RE.match(text):
            raise ValueError(
                f"setting {name!r} expects a colour as #rrggbb; got {text!r}"
            )
        result = text.lower()
    else:
        raise ValueError(f"setting {name!r} has unsupported kind {kind!r}")

    if kind in ("int", "float", "quantity"):
        minimum = spec.get("min")
        maximum = spec.get("max")
        if minimum is not None and result < minimum:
            raise ValueError(
                f"setting {name!r} must be at least {minimum:g}; got {result:g}"
            )
        if maximum is not None and result > maximum:
            raise ValueError(
                f"setting {name!r} must be at most {maximum:g}; got {result:g}"
            )
    return result


def _quantity_value(spec, value) -> float:
    """A quantity as a number in the setting's ``unit`` (or its own value)."""
    name = spec["name"]
    unit = spec.get("unit")
    if isinstance(value, FreeCAD.Units.Quantity):
        quantity = value
    elif isinstance(value, bool):
        raise ValueError(f"setting {name!r} expects a quantity")
    elif isinstance(value, (int, float)):
        # A bare number means "that many of the declared unit".
        quantity = (
            FreeCAD.Units.Quantity(float(value), unit)
            if unit
            else FreeCAD.Units.Quantity(float(value))
        )
    else:
        text = str(value).strip()
        try:
            number = float(text)
        except ValueError:
            number = None
        if number is not None:
            # A bare numeric string is "that many of the declared unit", like
            # a bare Python number.
            quantity = (
                FreeCAD.Units.Quantity(number, unit)
                if unit
                else FreeCAD.Units.Quantity(number)
            )
        else:
            try:
                quantity = FreeCAD.Units.Quantity(text)
            except Exception as exc:
                raise ValueError(
                    f"setting {name!r} expects a quantity: {exc}"
                ) from None
    if not unit:
        return quantity.Value
    try:
        return quantity.getValueAs(unit).Value
    except Exception as exc:
        raise ValueError(
            f"setting {name!r} expects a quantity in {unit!r}: {exc}"
        ) from None


def _display_setting(spec, value) -> str:
    """The row's display string (``"10 mm"`` for a quantity)."""
    if spec["kind"] != "quantity":
        return str(value)
    if isinstance(value, FreeCAD.Units.Quantity):
        return str(value)
    unit = spec.get("unit")
    if not unit:
        return str(value)
    try:
        return str(FreeCAD.Units.Quantity(float(value), unit))
    except Exception:
        return str(value)


def _read_setting(spec, group):
    """``(value, status)`` for one schema entry, without writing anything.

    ``status`` names the source of the value: ``computed`` for a ``get`` hook,
    ``provider`` for the parameter group (a stored value or the materialised
    default), ``unsupported kind`` for a kind the editor cannot edit.
    """
    getter = spec.get("get")
    if getter is not None:
        return getter(), "computed"
    kind = spec["kind"]
    name = spec["name"]
    default = spec["default"]
    if kind not in _SETTING_KINDS:
        return default, "unsupported kind"
    if kind == "bool":
        return group.GetBool(name, bool(default)), "provider"
    if kind == "int":
        return group.GetInt(name, int(default)), "provider"
    if kind in ("float", "quantity"):
        return group.GetFloat(name, float(default)), "provider"
    return group.GetString(name, str(default)), "provider"


def _write_setting(spec, group, value) -> None:
    """Store a coerced value in the provider's parameter group (by kind)."""
    kind = spec["kind"]
    name = spec["name"]
    if kind == "bool":
        group.SetBool(name, bool(value))
    elif kind == "int":
        group.SetInt(name, int(value))
    elif kind in ("float", "quantity"):
        group.SetFloat(name, float(value))
    else:
        group.SetString(name, str(value))


def settings(feature: str, backend=None) -> list:
    """The settings rows of ``feature``'s active provider (or ``backend``).

    The rows use the property pane's contract — ``name``, ``label``, ``type``,
    ``value``, ``status``, ``editable``, ``kind``, plus ``unit``/``choices``
    where the schema declares them — so the pane needs no new renderer. ``value``
    is the display string (``"10 mm"`` for a quantity).

    Nothing is written here: an unset value shows its declared default. ``[]``
    means "nothing to show": an unknown feature or backend, no provider at all,
    or a provider that advertises no schema.
    """
    records = _PROVIDERS.get(feature)
    if not records:
        return []
    if backend is None:
        backend = _selected(feature)
    record = records.get(backend)
    if record is None:
        return []
    schema = record.get("settings") or []
    if not schema:
        return []
    group = _settings_group(feature, backend)
    rows = []
    for spec in schema:
        try:
            raw, status = _read_setting(spec, group)
        except Exception as exc:  # noqa: BLE001 - one broken knob is not fatal
            _report_setting(feature, backend, spec["name"], exc)
            raw, status = spec["default"], "error"
        kind = spec["kind"]
        has_get = spec.get("get") is not None
        has_set = spec.get("set") is not None
        row = {
            "name": spec["name"],
            "label": spec["label"],
            "type": _SETTING_TYPES.get(kind, ""),
            "value": _display_setting(spec, raw),
            "status": status,
            "editable": kind in _SETTING_KINDS and (has_set or not has_get),
            "kind": kind,
        }
        if "unit" in spec:
            row["unit"] = spec["unit"]
        if "choices" in spec:
            row["choices"] = list(spec["choices"])
        rows.append(row)
    return rows


def setSetting(feature: str, name: str, value) -> dict:
    """Coerce, validate and store one setting, then refresh the provider.

    The value may be a string from the property editor (``"5 mm"``,
    ``"true"``, ``"#94a3b8"``) or a Python value of the right type. On success
    the parameter is written (or the schema's ``set`` hook is called), the
    active backend's ``refresh`` runs through :func:`refreshProviders`, and the
    result carries its ``view`` claim so the caller can apply it. On a
    validation failure nothing changes and the result has ``ok: False`` and an
    ``error``.
    """
    records = _PROVIDERS.get(feature)
    if not records:
        return {
            "ok": False,
            "error": f"no provider is registered for feature {feature!r}",
        }
    backend = _selected(feature)
    schema = records[backend].get("settings") or []
    spec = next((entry for entry in schema if entry["name"] == name), None)
    if spec is None:
        return {
            "ok": False,
            "error": f"no setting {name!r} for feature {feature!r}",
        }
    kind = spec["kind"]
    if kind not in _SETTING_KINDS:
        return {
            "ok": False,
            "error": f"setting {name!r} has unsupported kind {kind!r}",
        }
    setter = spec.get("set")
    if spec.get("get") is not None and setter is None:
        return {"ok": False, "error": f"setting {name!r} is read-only"}
    try:
        coerced = _coerce_setting(spec, value)
    except Exception as exc:  # noqa: BLE001 - validation is an expected failure
        return {"ok": False, "error": str(exc)}

    if setter is not None:
        try:
            setter(coerced)
        except Exception as exc:  # noqa: BLE001 - a broken hook is not fatal
            _report_setting(feature, backend, name, exc)
            return {"ok": False, "error": _error_text(exc)}
    else:
        try:
            _write_setting(spec, _settings_group(feature, backend), coerced)
        except Exception as exc:  # noqa: BLE001
            return {"ok": False, "error": _error_text(exc)}

    refresh = refreshProviders(feature)
    display = _display_setting(spec, coerced)
    return {
        "ok": True,
        "feature": feature,
        "backend": backend,
        "name": name,
        "value": display,
        "status": f"{feature}: {name} = {display}",
        "view": refresh.get("view", {}),
        "errors": list(refresh.get("errors", [])),
    }


# ---------------------------------------------------------------------------
# Pull-based overlays (G5)
# ---------------------------------------------------------------------------


def _coin_module():
    """The ``pivy.coin`` module, imported only when an overlay is used.

    Headless builds and the GUI facade itself do not need Coin, so this import is
    deliberately lazy: ``import FerroCADGui`` keeps working without the extension.
    """
    try:
        from pivy import coin
    except ImportError as exc:  # noqa: BLE001 - re-raised with the contract
        raise RuntimeError(
            "overlays need the Coin facade (pivy.coin) in this build"
        ) from exc
    return coin


def addOverlay(node) -> None:
    """Register a Coin node as a viewport overlay (FerroCAD extension).

    The node is **extracted now**: the shell keeps a copy of its subtree and draws
    it beside the document scene on the next refresh. This is the pull bridge that
    replaces Coin's ``getSceneGraph()``; see ``docs/workbenches/grid-overlay-plan.md`` §3.2.
    A later in-place edit does not reach the copy, so an author re-registers the
    node (``removeOverlay`` then ``addOverlay``) after changing it.
    """
    return _coin_module().addOverlay(node)


def removeOverlay(node) -> bool:
    """Drop a previously registered overlay, keyed by Python object identity."""
    return _coin_module().removeOverlay(node)


# ---------------------------------------------------------------------------
# View state (read-only; pushed by the shell)
# ---------------------------------------------------------------------------


class _ViewState:
    """The shell's presentation state, pushed by the shell (read-only here).

    ``grid`` is the reference-grid flag, ``axis_cross`` the world triad's, ``projection``
    is ``"persp"`` or ``"ortho"``, ``grid_minor``/``grid_major`` are the world grid's
    steps (mm) and ``grid_radius`` is a fixed extent (mm, or ``None`` for the
    camera-derived one). A checkable command reads these in ``IsChecked``, which is what
    makes a ``{"view": …}`` request close the loop.
    """

    grid = False
    axis_cross = True
    projection = "persp"
    grid_minor = 10.0
    grid_major = 100.0
    grid_radius = None


ViewState = _ViewState()


__all__ = [
    "addDocumentListener",
    "removeDocumentListener",
    "registerProvider",
    "unregisterProvider",
    "providers",
    "providerSkin",
    "activeProvider",
    "setActiveProvider",
    "refreshProviders",
    "settings",
    "setSetting",
    "addOverlay",
    "removeOverlay",
    "ViewState",
    "PROVIDER_PREFERENCES",
]