-
Notifications
You must be signed in to change notification settings - Fork 4
/
fpo.py
2259 lines (1861 loc) · 90.5 KB
/
fpo.py
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
# -*- coding: utf-8 -*-
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# (c) 2024 Frank David Martínez Muñoz.
#
from __future__ import annotations
__author__ = "Frank David Martínez Muñoz"
__copyright__ = "(c) 2024 Frank David Martínez Muñoz."
__license__ = "LGPL 2.1"
__version__ = "1.0.0-beta3"
__min_python__ = "3.8"
__min_freecad__ = "0.21"
# Conventions for sections in this file:
# ──────────────────────────────────────────────────────────────────────────────
# # Normal comments
# #: Code execute at import time, create objects in global module scope
# #$ Template code, creates injectable methods
# #@ Decorators code
# #% Type definitions
# #; Simple section label
# #! Warning note
# ──────────────────────────────────────────────────────────────────────────────
# General imports
# ──────────────────────────────────────────────────────────────────────────────
from dataclasses import dataclass
from typing import Any, Tuple, Callable, Dict, Iterable, Set, Union, NewType
from enum import IntEnum, Enum
import inspect
import re
import sys
import traceback
import textwrap
import contextlib
from pathlib import Path
import FreeCAD as App # type: ignore
from FreeCAD import Document # type: ignore
from FreeCAD import DocumentObject # type: ignore
# from FreeCAD import ParameterGrp # type: ignore !!! Not present in FreeCAD 1.0
from FreeCADGui import ViewProviderDocumentObject # type: ignore
from PySide.QtGui import QMenu, QMessageBox # type: ignore
from Part import Shape # type: ignore
##: Conditional imports
##: ─────────────────────────────────────────────────────────────────────────────
if App.GuiUp:
from pivy import coin # type: ignore
import FreeCADGui as Gui # type: ignore
from PySide import QtGui, QtCore # type: ignore
##: Logging
##: ─────────────────────────────────────────────────────────────────────────────
def print_log(*args):
"Print into the FreeCAD console with info level."
App.Console.PrintLog(f"[info] {' '.join(str(a) for a in args)}\n")
def print_err(*args):
"Print into the FreeCAD console with error level."
App.Console.PrintError(f"[error] {' '.join(str(a) for a in args)}\n")
##: FreeCAD defined c++ types (Just for the sake of documentation)
##: fake type hints compatible with python 3.8+
##: ─────────────────────────────────────────────────────────────────────────────
ObjectRef = Union[DocumentObject, ViewProviderDocumentObject]
##: User defined python Types (Just for the sake of documentation)
##: fake type hints compatible with python 3.8+
##: ─────────────────────────────────────────────────────────────────────────────
DataProxy = NewType("DataProxy", object) # Python proxy of DocumentObject
ViewProxy = NewType("ViewProxy", object) # Python proxy of ViewObject
Proxy = NewType("Proxy", object)
##: Defined symbols
##: ─────────────────────────────────────────────────────────────────────────────
_SO_VERSION = "SOInternalVersion"
_SO_META = "__so_meta__"
_SO_REF = "__so_ref__"
_ON_EXTENSION = "on_extension"
_ON_ATTACH = "on_attach"
_ON_CREATE = "on_create"
_ON_START = "on_start"
_ON_RESTORE = "on_restore"
_ON_EXECUTE = "on_execute"
_ON_CHANGE = "on_change"
_ON_BEFORE_CHANGE = "on_before_change"
_ON_SERIALIZE = "on_serialize"
_ON_DESERIALIZE = "on_deserialize"
_ON_REMOVE = "on_remove"
_IS_DIRTY = "is_dirty"
_ON_CONTEXT_MENU = "on_context_menu"
_ON_CLAIM_CHILDREN = "on_claim_children"
_ON_EDIT_START = "on_edit_start"
_ON_EDIT_END = "on_edit_end"
_ON_DELETE = "on_delete"
_ON_DBL_CLICK = "on_dbl_click"
_GET_ICON = "icon"
_SET_DISPLAY_MODE = "set_display_mode"
_DISPLAY_MODES = "display_modes"
_DEFAULT_DISPLAY_MODE = "default_display_mode"
_ON_OBJECT_CHANGE = "on_object_change"
_CAN_DRAG_OBJECTS = "can_drag_objects"
_CAN_DROP_OBJECTS = "can_drop_objects"
_CAN_DRAG_OBJECT = "can_drag_object"
_CAN_DROP_OBJECT = "can_drop_object"
_ON_DRAG_OBJECT = "on_drag_object"
_ON_DROP_OBJECT = "on_drop_object"
_ON_MIGRATE_CLASS = "on_migrate_class"
_ON_MIGRATE_UP = "on_migrate_upgrade"
_ON_MIGRATE_DOWN = "on_migrate_downgrade"
_ON_MIGRATE_COMPLETE = "on_migrate_complete"
_ON_MIGRATE_ERROR = "on_migrate_error"
_SET_VERSION = "set_version"
##: Supported Property types
##: Source: https://wiki.freecad.org/FeaturePython_Custom_Properties
##: ─────────────────────────────────────────────────────────────────────────────
_FC_PROPERTY_TYPES = (
"Acceleration",
"AmountOfSubstance",
"Angle",
"Area",
"Bool",
"BoolList",
"Color",
"ColorList",
"CurrentDensity",
"Density",
"Direction",
"DissipationRate",
"Distance",
"DynamicViscosity",
"ElectricCharge",
"ElectricCurrent",
"ElectricPotential",
"ElectricalCapacitance",
"ElectricalConductance",
"ElectricalConductivity",
"ElectricalInductance",
"ElectricalResistance",
"Enumeration",
"ExpressionEngine",
"File",
"FileIncluded",
"Float",
"FloatConstraint",
"FloatList",
"Font",
"Force",
"Frequency",
"HeatFlux",
"Integer",
"IntegerConstraint",
"IntegerList",
"IntegerSet",
"InverseArea",
"InverseLength",
"InverseVolume",
"KinematicViscosity",
"Length",
"Link",
"LinkChild",
"LinkGlobal",
"LinkHidden",
"LinkList",
"LinkListChild",
"LinkListGlobal",
"LinkListHidden",
"LinkSub",
"LinkSubChild",
"LinkSubGlobal",
"LinkSubHidden",
"LinkSubList",
"LinkSubListChild",
"LinkSubListGlobal",
"LinkSubListHidden",
"LuminousIntensity",
"MagneticFieldStrength",
"MagneticFlux",
"MagneticFluxDensity",
"Magnetization",
"Map",
"Mass",
"Material",
"MaterialList",
"Matrix",
"Path",
"Percent",
"PersistentObject",
"Placement",
"PlacementLink",
"PlacementList",
"Position",
"Power",
"Precision",
"Pressure",
"PythonObject",
"Quantity",
"QuantityConstraint",
"Rotation",
"ShearModulus",
"SpecificEnergy",
"SpecificHeat",
"Speed",
"Stiffness",
"Stress",
"String",
"StringList",
"Temperature",
"ThermalConductivity",
"ThermalExpansionCoefficient",
"ThermalTransferCoefficient",
"Time",
"UUID",
"UltimateTensileStrength",
"VacuumPermittivity",
"Vector",
"VectorDistance",
"VectorList",
"Velocity",
"Volume",
"VolumeFlowRate",
"VolumetricThermalExpansionCoefficient",
"Work",
"XLink",
"XLinkList",
"XLinkSub",
"XLinkSubList",
"YieldStrength",
"YoungsModulus",
)
##: Global private static registries
##: ─────────────────────────────────────────────────────────────────────────────
_extensions: Dict[str, ExtensionSupport] = dict()
# ┌────────────────────────────────────────────────────────────────────────────┐
# │ private Utility functions │
# └────────────────────────────────────────────────────────────────────────────┘
# ──────────────────────────────────────────────────────────────────────────────
def _call(obj, name: str, *args, **kwargs):
"""Call a method on obj if exists"""
func = getattr(obj, name, None)
if func:
return func(*args, **kwargs)
# ──────────────────────────────────────────────────────────────────────────────
def _snake_to_camel(text: str) -> str:
"""Transform text from snake naming to camel case"""
if text:
return "".join(token.capitalize() for token in text.split("_"))
# ──────────────────────────────────────────────────────────────────────────────
def _resolve_uri(path: str, base_dir: Path = None) -> str:
'''Resolve relative paths if prefixed with "self:"'''
if str(path).startswith("self:") and base_dir:
rel_path_elements = path[5:].lstrip(" /").split("/")
return str(Path(base_dir, *rel_path_elements))
return path
# ──────────────────────────────────────────────────────────────────────────────
def _prop_constructor(prop_type: str):
"""Create a constructor for a specific Property Type"""
def constructor(
*,
name: str = None,
section: str = "Data",
default: Any = None,
description: str = "",
mode: PropertyMode = PropertyMode.Default,
observer_func: Callable = None,
link_property: Union[str, bool] = False,
):
return Property(
type=prop_type,
section=section,
observer_func=observer_func,
name=name,
link_property=link_property,
default=default,
description=description,
mode=mode,
)
return constructor
# ──────────────────────────────────────────────────────────────────────────────
def _is(types: Any) -> Callable:
"""Returns a predicate to check the type of the passed object"""
def predicate(obj: Any) -> bool:
return isinstance(obj, types)
return predicate
# ──────────────────────────────────────────────────────────────────────────────
def _get_properties(cls) -> Iterable[Tuple[str, Property]]:
"""Returns the list of Properties defined in a proxy class"""
return inspect.getmembers(cls, _is(Property))
# ──────────────────────────────────────────────────────────────────────────────
def _get_display_modes(cls) -> Iterable[Tuple[str, DisplayMode]]:
"""Returns the list of Display Modes defined in a proxy class"""
return inspect.getmembers(cls, _is(DisplayMode))
# ──────────────────────────────────────────────────────────────────────────────
def _t_forward(cls, forward_from: str, forward_to: str):
"""
Create a function that forwards the call to another function
:param str forward_from: name of the original function
:param str forward_to: name of the target function
"""
overridden = getattr(cls, forward_from, None)
if overridden:
raise NameError(f"{forward_from} is already reserved. use {forward_to} instead")
forward = getattr(cls, forward_to, None)
if forward:
def handler(self, *args, **kwargs):
return forward(self, *args, **kwargs)
handler.__signature__ = inspect.signature(forward)
handler.__doc__ = forward.__doc__
handler.__name__ = forward_from
setattr(cls, forward_from, handler)
##% ┌───────────────────────────────────────────────────────────────────────────┐
##% │ Core types │
##% └───────────────────────────────────────────────────────────────────────────┘
##% ─────────────────────────────────────────────────────────────────────────────
class _DocIntEnum(IntEnum):
"""
IntEnum with member docs
See: https://stackoverflow.com/a/50473952/1524027
"""
def __new__(cls, value, doc=""):
self = int.__new__(cls, value)
self._value_ = value
self.__doc__ = doc
return self
##% ─────────────────────────────────────────────────────────────────────────────
class FeatureState(_DocIntEnum):
"""
ScriptedObject state. See lifecycle
"""
Attaching = -1, "FreeCAD is creating and binding the objects"
Creating = 0, "Setting up all stuff like properties, extensions, etc..."
Created = 1, "Already created"
Active = 2, "Ready for execution"
Restoring = 3, "Restoring from FCStd document"
Restored = 4, "Fully restored from FCStd document"
##% ─────────────────────────────────────────────────────────────────────────────
class PropertyMode(_DocIntEnum):
"""
Property mode flags
"""
Default = 0, "No special property type"
ReadOnly = 1, "Property is read-only in the editor"
Transient = 2, "Property won't be saved to file"
Hidden = 4, "Property won't appear in the editor"
Output = 8, "Modified property doesn't touch its parent container"
NoRecompute = 16, "Modified property doesn't touch its container for recompute"
NoPersist = 32, "Property won't be saved to file at all"
##% ─────────────────────────────────────────────────────────────────────────────
class PropertyEditorMode(_DocIntEnum):
"""
Editor Modes
"""
Default = 0, "No special mode"
ReadOnly = 1, "Property is read only in the editor"
Hidden = 2, "Property is hidden in the editor"
##% ─────────────────────────────────────────────────────────────────────────────
class EditMode(_DocIntEnum):
"""
ViewProvider Edit Mode
"""
Default = (
0,
"The object will be edited using the mode defined \
internally to be the most appropriate for the object type",
)
Transform = (
1,
"The object will have its placement editable with the \
`Std TransformManip` command",
)
Cutting = (
2,
"This edit mode is implemented as available but currently \
does not seem to be used by any object",
)
Color = (
3,
"The object will have the color of its individual faces \
editable with the Part FaceColors command",
)
##% ─────────────────────────────────────────────────────────────────────────────
class Property:
"""
Proxy object to create, access and manipulate remote freecad properties
in DocumentObject and ViewObject instances.
Ref: https://wiki.freecad.org/FeaturePython_Custom_Properties
"""
type: str # Type of the supported property
binding: str # Name of the property on the proxy class
observer_func: Callable # Change listener
observer_arity: int # Change listener arity
name: str # Actual name of the property
link_property: Union[str, bool] # Name of the Link Property to configure
section: str # Capitalized single word due to FC limitations
default: Any # Initial value
description: str # GUI description
mode: PropertyMode # PropertyEditor mode for the property
enum: Enum # Type of enum used by "App::PropertyEnumeration"
options: Callable # Callable that provides a list of options
# ──────────
def __init__(
self,
type: str,
binding: str = None,
section: str = "Data",
observer_func: Callable = None,
name: str = None,
link_property: Union[str, bool] = False,
default: Any = None,
description: str = "",
mode: PropertyMode = PropertyMode.Default,
enum: Enum = None,
options: Callable = None,
):
self.type = type
self.binding = binding
self.section = section
self.observer_func = observer_func
if observer_func:
self.observer(observer_func)
self.name = name or _snake_to_camel(binding)
self.link_property = link_property
self.default = default
self.description = description
self.mode = mode
self.enum = enum
self.options = options
##@ ─────────
def observer(self, func):
"""Decorator to register the listener for property change event"""
self.observer_func = func
sig = inspect.signature(func)
self.observer_arity = len(sig.parameters)
return func
# ──────────
def create(self, fp: ObjectRef):
"""Adds the property to the object and initialize it"""
if self.name not in fp.PropertiesList:
fp.addProperty(self.type, self.name, self.section, self.description, self.mode)
if self.enum:
setattr(fp, self.name, [str(e.value) for e in list(self.enum)])
elif self.options:
setattr(fp, self.name, self.options())
self.reset(fp)
# ──────────
def reset(self, fp: ObjectRef):
"""Set the value to its default"""
if self.default is not None:
self.update(fp, self.default)
# ──────────
def update(self, obj: ObjectRef, value: Any):
"""Set the value of the property in the remote object"""
if hasattr(obj, self.name):
if self.enum:
setattr(obj, self.name, str(value.value))
else:
attr = getattr(obj, self.name)
if hasattr(attr, "Value"):
attr.Value = value
else:
setattr(obj, self.name, value)
# ──────────
def read(self, obj: ObjectRef):
"""Get the value of the property from the remote object"""
if hasattr(obj, self.name):
v = getattr(obj, self.name)
if self.enum:
if v is None:
return tuple(self.enum)[0]
return self.enum(v)
elif hasattr(v, "Value"):
return v.Value
else:
return v
# ──────────
def set_mode(self, obj: ObjectRef, mode: PropertyEditorMode):
"""Change editor mode for the property"""
if hasattr(obj, self.name):
obj.setEditorMode(self.name, mode)
# ──────────
def set_status(self, obj: ObjectRef, status: str):
"""Change editor status for the property"""
if hasattr(obj, self.name):
obj.setPropertyStatus(self.name, status)
##% ─────────────────────────────────────────────────────────────────────────────
class DisplayMode:
"""
Declarator of Display Modes, allows to configure a mode and optionally
a builder method to create and register the coin object.
:param str name: Name of the display mode
:param bool is_default: Configure the DM as default, defaults to False
:param Callable[[ViewObject], coin.SoGroup] builder: Method to build the coin object if required
"""
name: str
_builder_func: Callable
is_default: bool
# ──────────
def __init__(
self,
name: str = None,
is_default: bool = False,
builder: Callable = None,
):
self.name = name
self.is_default = is_default
self._builder_func = builder
##@ ─────────
def builder(self, func):
"""Decorator to bind a builder for the coin object"""
self._builder_func = func
return func
##% ─────────────────────────────────────────────────────────────────────────────
@dataclass
class _Template:
"""
Internal class used to inject tailored methods into the proxy objects to
interface between FreeCAD internal objects and python proxy instances with
the new API.
"""
name: str # Name of the method to be created
aliases: Iterable[str] # Aliases to be injected also
builder: Callable # The actual method builder
allow_override: bool # allow/deny user defined methods that collide
override_error_msg: str # Message to suggest alternative names
# ──────────
def __call__(self, meta: "TypeMeta") -> None:
"""Apply the template"""
self.add(meta, self.name, self.allow_override)
if self.aliases:
for name in self.aliases:
self.add(meta, name, True)
# ──────────
def add(self, meta: "TypeMeta", name: str, allow_override: bool):
"""Build the method and inject with the name"""
overridden = getattr(meta.cls, name, None)
if overridden and not allow_override:
msg = self.override_error_msg or ""
raise NameError(f"Attribute {name} is already defined. {msg}")
attr = self.builder(overridden, meta)
if attr:
if hasattr(attr, "__name__"):
attr.__name__ = name
setattr(meta.cls, name, attr)
# ──────────
@property
def __doc__(self):
return self.builder.__doc__
##% ─────────────────────────────────────────────────────────────────────────────
class ExtensionSupport:
"""
Base class of extension managers
"""
name: str # Name of the supported extension
# ──────────
def __init__(self, name: str) -> None:
self.name = name
_extensions[name] = self
# ──────────
def on_create(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta"):
"""Extension listener for on_create event"""
pass
# ──────────
def on_restore(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta"):
"""Extension listener for on_restore event"""
pass
# ──────────
def on_attach(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta"):
"""Extension listener for on_attach event"""
self.add_extension(proxy, obj)
# ──────────
def on_start(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta"):
"""Extension listener for on_start event"""
self.add_extension(proxy, obj)
# ──────────
def on_execute(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta"):
"""Extension listener for on_execute event"""
pass
# ──────────
def on_add(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta"):
"""Extension listener for on_add event"""
pass
# ──────────
def on_change(self, proxy: Proxy, obj: ObjectRef, meta: "TypeMeta", prop: str):
"""Extension listener for on_change event"""
pass
# ──────────
def on_class(self, meta: "TypeMeta"):
"""Extension listener for on_class event"""
pass
# ──────────
def add_extension(self, proxy: Proxy, obj: ObjectRef, name: str = None):
"""Adds the extension to the object"""
_name = name or self.name
if _name not in _extensions:
raise NameError(f"Extension {_name} not found.")
if not obj.hasExtension(_name):
obj.addExtension(_name)
self.on_add(proxy, obj, self.find_meta(proxy))
_call(proxy, _ON_EXTENSION, obj, _name)
# ──────────
def find_meta(self, proxy: Proxy) -> "TypeMeta":
"""Returns the meta info associated with the proxy"""
meta = getattr(proxy.__class__, _SO_META, None)
if meta is None:
raise TypeError(f"Invalid proxy type: {proxy.__class__.__name__}")
##% ─────────────────────────────────────────────────────────────────────────────
class Part_AttachExtensionPython(ExtensionSupport):
"""Extension manager of: Part::AttachExtensionPython"""
# ──────────
def on_execute(self, proxy: DataProxy, obj: DocumentObject, meta: "TypeMeta"):
obj.positionBySupport()
##% ─────────────────────────────────────────────────────────────────────────────
class App_LinkBaseExtensionPython(ExtensionSupport):
"""Extension manager of App::LinkBaseExtensionPython"""
# ──────────
def on_class(self, meta: "TypeMeta"):
meta.view_provider_name_override = "Gui::ViewProviderLinkPython"
# ──────────
def resolve_link_prop(self, link_property: Union[str, bool], source: str) -> str:
if isinstance(link_property, bool) and link_property:
return source
return link_property
# ──────────
def on_start(self, proxy: DataProxy, obj: DocumentObject, meta: "TypeMeta"):
super().on_start(proxy, obj, meta)
mapping = {
self.resolve_link_prop(prop.link_property, prop.name): prop.name
for prop in meta.properties.values()
if prop.link_property
}
if len(mapping) > 0:
obj.configLinkProperty(**mapping)
##% ─────────────────────────────────────────────────────────────────────────────
class App_LinkExtensionPython(App_LinkBaseExtensionPython):
"""Extension manager of App::LinkBaseExtensionPython"""
pass
##% ─────────────────────────────────────────────────────────────────────────────
class TypeMeta:
"""
Metadata of the proxy classes. Inspects the original class and provides
mechanisms to enhance them by adding methods, properties, display modes,
extensions, etc...
"""
cls: any # proxy enhanced class
properties: Dict[str, Property] # map binding to property
property_lookup: Dict[str, Property] # map name to property
display_modes: Dict[str, DisplayMode] # display mode builders
view_proxy: ViewProxy # associated ViewProxy
extensions: Set[ExtensionSupport] # Added extensions
version: int # Proxy versions for migrations support
object_type: str # Type of DocumentObject
subtype: str # Subtype of Proxy
base_dir: Path # Directory where the class is declared
view_provider_name_override: str # Forced type of the view provider
icon: str # Icon path
# ──────────
def __init__(
self,
cls: Any,
object_type: str = None,
base_dir: Path = None,
subtype: str = None,
view_proxy: Any = None,
extensions: Iterable[str] = None,
version: int = 1,
view_provider_name_override: str = None,
icon: str = None,
):
self.cls = cls
self.version = version
self.object_type = object_type
self.subtype = subtype
self.base_dir = base_dir
self.properties = dict()
self.property_lookup = dict()
self.display_modes = dict()
self.icon = icon
for name, prop in _get_properties(self.cls):
if not bool(prop.binding):
prop.binding = name
if not bool(prop.name):
prop.name = _snake_to_camel(name)
self.properties[prop.binding] = prop
self.property_lookup[prop.name] = prop
for name, dm in _get_display_modes(self.cls):
if not bool(dm.name):
dm.name = name
self.display_modes[name] = dm
self.view_proxy = view_proxy
if extensions:
self.extensions = set(_extensions[name] for name in extensions)
else:
self.extensions = set()
self.view_provider_name_override = view_provider_name_override
cls.__so_meta__ = self
self.bind_properties()
# ──────────
def bind_properties(self):
"""Bind all available properties"""
for prop in self.properties.values():
self.bind_property(prop)
# ──────────
def bind_property(self, prop: Property):
"""Bind a property to a local proxy attribute"""
def getter(self):
return prop.read(self.__so_ref__)
def setter(self, value):
prop.update(self.__so_ref__, value)
setattr(
self.cls,
prop.binding,
property(getter, setter, doc=prop.description),
)
# ──────────
def add_property(self, fp: ObjectRef, prop: Property):
"""Create and register a property"""
if bool(prop.binding) and prop.binding in self.properties:
raise NameError(f'Binding "{self.cls.__name__}.{prop.binding}" already exists')
if prop.name in self.property_lookup:
raise NameError(f'Property "{self.cls.__name__}.Object.{prop.name}" already exists')
if prop.name in fp.PropertiesList:
raise NameError(f'Property "{self.cls.__name__}.Object.{prop.name}" already exists')
prop.create(fp)
# ──────────
def apply_extensions(
self,
proxy: Proxy,
obj: ObjectRef,
method_name: str,
*args,
**kwargs,
):
"""Call extensions runtime lifecycle"""
if self.extensions:
for ext in self.extensions:
method = getattr(ext, method_name)
method(proxy, obj, self, *args, **kwargs)
# ──────────
def apply_extensions_on_class(self):
"""Call extensions static lifecycle"""
if self.extensions:
for ext in self.extensions:
ext.on_class(self)
# ──────────
def add_version_prop(self, obj: ObjectRef):
"""Inject the fpo version into the proxy. (For migrations)"""
if _SO_VERSION not in obj.PropertiesList:
obj.addProperty(
"App::PropertyInteger",
_SO_VERSION,
"SO",
"Internal Scripted Object Version",
PropertyMode.Hidden.value,
)
setattr(obj, _SO_VERSION, self.version)
# ──────────
def ensure_properties(self, proxy: Proxy, obj: ObjectRef):
"""
Add missing properties to the ObjectRef, used to add new properties
on start if the class have declared new properties since the file
was saved.
"""
for prop in self.properties.values():
prop.create(obj)
# ──────────
def init_properties(self, proxy: Proxy, obj: ObjectRef):
for prop in self.properties.values():
prop.create(obj)
if prop.default is not None:
proxy.__so_old__[prop.name] = prop.default
# ──────────
def init_display_modes(self, proxy: ViewProxy, obj: ViewProviderDocumentObject):
if len(self.display_modes) > 0:
for dm in self.display_modes.values():
dm_obj = None
if dm._builder_func:
dm_obj = dm._builder_func(proxy, obj)
if not dm_obj:
dm_obj = coin.SoGroup()
obj.addDisplayMode(dm_obj, dm.name)
##% ─────────────────────────────────────────────────────────────────────────────
@dataclass
class Preference:
group: str
name: str
default: Any = None
value_type: type = None
root: str = "BaseApp"
many: bool = False
# ─────────
def __post_init__(self):
if self.value_type is None:
self.value_type = type(self.default) if self.default is not None else str
# ─────────
@property
def group_key(self):
return f"User parameter:{self.root}/{self.group}"
# ─────────
def read(self):
group = App.ParamGet(self.group_key)
try:
if self.value_type is bool:
v = group.GetBool(self.name)
return self.default if v is None else v
elif self.value_type is int:
return group.GetInt(self.name) or self.default
elif self.value_type is float:
return group.GetFloat(self.name) or self.default
elif self.value_type is str:
return group.GetString(self.name) or self.default
except BaseException:
print_err(f"Error reading preference: {self}")
return self.default
# ─────────
# Read/Write shortcut
def __call__(self, *args, **kwargs):
n = len(args)
if n == 0:
value = self.read()
if value is None and len(kwargs) > 0:
if len(kwargs) == 1 and "default" in kwargs:
return kwargs["default"]
raise NameError("only 'default' named argument is acceptable")
return value
if n > 1:
raise ValueError("This function accepts only one argument")
self.write(args[0])
# ─────────
def write(self, value):
group = App.ParamGet(self.group_key)
try:
if self.value_type is bool:
if value is None:
group.RemBool(self.name)
else:
group.SetBool(self.name, self.value_type(value))
elif self.value_type is int:
if value is None:
group.RemInt(self.name)
else:
group.SetInt(self.name, self.value_type(value))
elif self.value_type is float:
if value is None:
group.RemFloat(self.name)
else:
group.SetFloat(self.name, self.value_type(value))
elif self.value_type is str:
if value is None:
group.RemString(self.name)
else:
group.SetString(self.name, self.value_type(value))