-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbpx.py
3624 lines (2646 loc) · 94.3 KB
/
bpx.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 -*-
import uuid
import typing
import logging
import traceback
import contextlib
import collections
import functools
import ctypes # For SessionUuid
import itertools
# Avoid accidental access from user
import os as _os
import sys as _sys
import math as _math
import time as _time
import bpy
import bmesh
import mathutils
# Convenience
bpx = _sys.modules[__name__]
# Expose native mathutils types
Vector = mathutils.Vector
Matrix = mathutils.Matrix
Color = mathutils.Color
Euler = mathutils.Euler
Quaternion = mathutils.Quaternion
# Expose native math types
radians = _math.radians
degrees = _math.degrees
pi = _math.pi
e_cube = 2
e_empty = 11
e_mesh_plane = 1
e_mesh_cube = 2
e_mesh_circle = 3
e_mesh_uv_sphere = 4
e_mesh_ico_sphere = 5
e_mesh_cylinder = 6
e_mesh_cone = 7
e_mesh_torus = 8
e_mesh_grid = 9
e_mesh_suzanne = 10
e_empty_plain_axes = 12
e_empty_arrows = 13
e_empty_single_arrow = 14
e_empty_circle = 15
e_empty_cube = 16
e_empty_sphere = 17
e_empty_cone = 18
e_empty_image = 19
e_armature_empty = 20
e_armature_single_bone = 21
# Aliases
Object = bpy.types.Object
PoseBone = bpy.types.PoseBone
Bone = bpy.types.Bone
# Some nifty defaults
LinearTolerance = 0.0001 # i.e. 0.01 cm
AngularTolerance = 0.01
class _Timing:
def __init__(self):
self.duration = 0.0
self.count = 0
self.max = 0.0
self.min = 0xffffff
# Developer flags
BPX_DEVELOPER = bool(_os.getenv("BPX_DEVELOPER", False))
USE_PROFILING = BPX_DEVELOPER
USE_ORDERED_SELECTION = True
# End-user constants
BLENDER_3 = bpy.app.version[0] == 3
BLENDER_4 = bpy.app.version[0] == 4
#
# Internal state below, do not access internally or externally
#
# Use the experimental session_uuid, only tested in Blender 4.0
# It has better support for file linking and object duplication,
# at the expense of using internals of Blender's source which may change
_USE_SESSION_UUID = True
_SUSPENDED_CALLBACKS = False
# Maintain a list of selected objects and bones, in the order of selection
_ORDERED_SELECTION = []
_LAST_SELECTION = []
# Alternative name for a given BpxType
_ALIASES = {}
# bpx timings, in milliseconds
_TIMINGS = collections.defaultdict(_Timing)
# Internal logger, use `info()` etc.
_LOG = logging.getLogger("bpx")
# Is the file opened in a test environment?
_BACKGROUND = False
# Handle writing to bpxProperties.bpxId from another
# thread or restricted context, such as during rendering
_DEFERRED_BPXIDS = {}
_INSTALLED = False
# Public bpx callbacks
handlers = {
"selection_changed": [],
# An object was removed but can be undone
"object_removed": [],
# A previously removed object we undone
"object_unremoved": [],
# An object is permanently removed
"object_destroyed": [],
# An object was created
"object_created": [],
# An object was duplicated
"object_duplicated": [],
# Something, anything, changed
"depsgraph_changed": [],
# The global Blender mode has changed
"mode_changed": [],
}
# Thrown when accessing a property that does not exist
ExistError = type("ExistError", (RuntimeError,), {})
# Global dirty states, if *anything* has changed since last depsgraph update
DirtyObjectMode = True
DirtyPoseMode = True
ObjectMode = "OBJECT"
PoseMode = "POSE"
SculptMode = "SCULPT"
EditMode = "EDIT"
EditMeshMode = "EDIT_MESH"
EditArmatureMode = "EDIT_ARMATURE"
HierarchyOrder = False
SelectionOrder = True
@contextlib.contextmanager
def timing(name, verbose=False):
t = _Timing()
t0 = _time.perf_counter()
try:
yield t
finally:
t1 = _time.perf_counter()
t.duration = (t1 - t0) * 1000
if verbose:
info("%s in %.2fms" % (
name, t.duration
))
@contextlib.contextmanager
def cumulative_timing(name):
timing = _TIMINGS[name]
try:
t0 = _time.perf_counter()
yield timing
finally:
t1 = _time.perf_counter()
duration = (t1 - t0) * 1000 # milliseconds
timing.duration += duration
timing.count += 1
if duration > timing.max:
timing.max = duration
if duration < timing.min:
timing.min = duration
def with_timing(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
t0 = _time.perf_counter()
try:
return func(*args, **kwargs)
finally:
t1 = _time.perf_counter()
duration = t1 - t0
info("%s.%s in %.2fms" % (
func.__module__, func.__name__, duration * 1000
))
return wrapper
def _requires_install(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not _INSTALLED:
install()
return func(*args, **kwargs)
return wrapper
def with_cumulative_timing(func):
"""Aggregate timings for `func` such that the sum may be inspected
Use this, and then call `report_cumulative_timings()` to view
the result of a function once called on multiple occasions.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
t0 = _time.perf_counter()
try:
return func(*args, **kwargs)
finally:
t1 = _time.perf_counter()
duration = (t1 - t0) * 1000 # milliseconds
key = func.__module__.rsplit(".", 1)[-1] # lib.vendor.bpx -> bpx
key += "." + func.__name__
timing = _TIMINGS[key]
timing.duration += duration
timing.count += 1
if duration > timing.max:
timing.max = duration
if duration < timing.min:
timing.min = duration
if USE_PROFILING:
return wrapper
else:
return func
def reset_cumulative_timings():
"""Remove all prior timings"""
_TIMINGS.clear()
def report_cumulative_timings():
"""Print a table for the user to see what's going on
E.g.
____________________________________________________________________
| Call | Duration | Count | Min/Max |
|--------------------------|-----------|-------|---------------------|
| _is_valid | 0.00 ms | 34 | 0.00 < 1.24 ms/call |
| ls | 36.98 ms | 689 | 0.05 < 1.24 ms/call |
| flush_attribute_sets | 0.00 ms | 686 | 0.00 < 1.24 ms/call |
| _post_depsgraph_changed | 1.00 ms | 20 | 0.05 < 1.24 ms/call |
|__________________________|___________|_______|_____________________|
"""
if not USE_PROFILING:
return
timings = sorted(_TIMINGS.items(),
key=lambda item: item[1].duration,
reverse=True)
msg = []
longest_function_call = 1
for func, timing in timings:
if len(func) > longest_function_call:
longest_function_call = len(func)
template = "| {:%s} | {:>9.2f} ms | {:>7} | {:>5.3f} < {:<7.2f} ms |" % (
longest_function_call + 1,
)
msg.append("Cumulative Timings Report")
# Top line
msg.append(" " + ("_" * (len(template.format("", 0, 0, 0, 0)) - 2)) + " ")
# Header
header = "| Call " + " " * (longest_function_call - len("Call"))
header += "| Total | Count | Per call |"
msg.append(header)
footer = "|--" + "-" * longest_function_call
footer += "-|--------------|---------|--------------------|"
msg.append(footer)
for func, timing in timings:
msg.append(template.format(
func,
timing.duration,
timing.count,
timing.min,
timing.max
))
footer = "|__" + "_" * longest_function_call
footer += "_|______________|_________|____________________|"
msg.append(footer)
msg = "\n".join(msg)
info(msg)
return msg
class Timing:
def __init__(self):
self._t0 = _time.perf_counter()
@property
def s(self):
return self._seconds
@property
def ms(self):
return self._seconds * 1000
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
t1 = _time.perf_counter()
self._seconds = t1 - self._t0
@contextlib.contextmanager
def maintained_time(context):
"""Maintain time whilst manipulating the scene"""
initial_frame = context.scene.frame_current
try:
yield
finally:
context.scene.frame_set(initial_frame)
@contextlib.contextmanager
def suspension():
global _SUSPENDED_CALLBACKS
_SUSPENDED_CALLBACKS = True
bpy.app.handlers.depsgraph_update_post.remove(_post_depsgraph_changed)
try:
yield
finally:
_SUSPENDED_CALLBACKS = False
bpy.app.handlers.depsgraph_update_post.append(_post_depsgraph_changed)
def with_suspension(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with suspension():
return func(*args, **kwargs)
return wrapper
def with_tripwire(func):
"""Prevent `func` from throwing a recurring exception
Because many things in bpx are cached, an error is likely to repeat
itself using previously cached data. Therefore, this decorator
breaks the cache on any exception, thus preventing this kind of error
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
_clear_all_caches()
traceback.print_exc()
return wrapper
def debug(msg):
_LOG.debug(msg)
def info(msg):
_LOG.info(msg)
def warning(msg):
_LOG.warning(msg)
@contextlib.contextmanager
def maintained_selection(context=None):
"""Maintain selection whilst manipulating the scene"""
context = context or bpy.context
active_object = context.active_object
selected_objects = context.selected_objects
if active_object:
previous_mode = active_object.mode
else:
previous_mode = ObjectMode
try:
yield
finally:
if not active_object:
return bpy.ops.object.select_all(action="DESELECT")
context.view_layer.objects.active = active_object
if previous_mode == PoseMode:
bpy.ops.object.mode_set(mode=PoseMode)
if previous_mode == ObjectMode and selected_objects:
bpy.ops.object.mode_set(mode=ObjectMode)
bpy.ops.object.select_all(action="DESELECT")
for obj in selected_objects:
try:
obj.select_set(True)
except ReferenceError:
# May have been deleted
pass
def _persistent(func):
"""Ensure that `func` has a valid underlying Python object
Blender invalidates references to datablocks like objects during
undo, redo and file-open.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if self._dirty and not self._destroyed:
_restore(self)
return func(self, *args, **kwargs)
return wrapper
class ObjectHandle:
def __init__(self, obj):
self._obj = obj
self._valid = True
def __getattribute__(self, name):
if not self._valid:
raise ExistError("%s no longer exists" % self)
try:
return getattr(self._obj, name)
except Exception:
self._valid = False
raise
class SingletonProperty(type):
def __call__(cls, xobj, name, *args, **kwargs):
assert isinstance(xobj, BpxType)
# Properties are unique per {object, name}
key = (hash(xobj), name)
index = None
# Handle `myAttrY` etc, but avoid `myAttrXYZ`
if not name.endswith("XYZ"):
if name.endswith("X"):
name = name[:-1]
index = 0
if name.endswith("Y"):
name = name[:-1]
index = 1
if name.endswith("Z"):
name = name[:-1]
index = 2
if name.endswith("W"):
name = name[:-1]
index = 3
if kwargs.get("exists", True):
try:
prop = xobj._cached_properties[key]
except KeyError:
pass
except AssertionError:
# He's dead Jim
xobj._cached_properties.pop(key)
else:
return prop
group = xobj.property_group()
try:
prop = getattr(group, name)
except AttributeError:
raise ExistError("%s.%s did not exist" % (xobj, name))
if hasattr(prop, "add"):
sup = BpxCollectionProperty
else:
sup = BpxProperty
self = super(SingletonProperty, sup).__call__(
xobj, name, index, *args, **kwargs
)
xobj._cached_properties[key] = self
return self
class InvalidObject:
def __getattribute__(self, name):
raise ReferenceError("%s cannot be accessed" % name)
class SingletonType(type):
"""Re-use previous instances of Blender object
This enables persistent state of each object, even when
a object is discovered at a later time, such as via
:func:`Object.parent()` or :func:`Object.descendents()`
Arguments:
object (bpy.types.Object): Blender API object to wrap
exists (bool, optional): Whether or not to search for
an existing Python instance of this node
Examples:
>>> new()
>>> a = create_object(e_empty_cube, name="myCube")
>>> BpxType("myCube") is a
True
>>> a.handle().location[0]
0.0
>>> a.handle().location[0] = 1.0
>>> a.handle().location[0]
1.0
"""
_key_to_instance = {}
_instance_to_key = {}
def __call__(cls, object, **kwargs):
# Called with an existing BpxType instance
# E.g. BpxObject(xobj)
if isinstance(object, BpxType):
return object
# Called with the intent to convert a string to BpxType
# E.g. BpxObject("Cube.001")
if isinstance(object, str):
obj = bpy.context.scene.objects.get(object, None)
if obj is not None:
object = obj
else:
raise ValueError("%s not found" % object)
supported_types = (
bpy.types.Object,
bpy.types.Bone,
# Implicitly converted to Bone
bpy.types.PoseBone,
)
assert isinstance(object, supported_types), (
"%s was not an object nor pose bone" % object
)
# Object references are not persistent during undo
# so instead we create a new, persistent, identifier
key = _get_uuid(object)
if kwargs.get("exists", True):
try:
node = cls._key_to_instance[key]
except KeyError:
pass
# TODO: How can this happen?
except AssertionError:
# He's dead Jim
cls._key_to_instance.pop(key)
cls._instance_to_key.pop(node)
else:
return node
# It hasn't been instantiated before, let's do that.
# But first, make sure we instantiate the right type
if isinstance(object, bpy.types.Bone):
sup = BpxBone
elif isinstance(object, bpy.types.PoseBone):
sup = BpxBone
elif isinstance(object.data, bpy.types.Armature):
sup = BpxArmature
elif isinstance(object, bpy.types.Object):
sup = BpxObject
else:
raise TypeError("Unsupported type: %r(%s)" % (
object, type(object))
)
self = super(SingletonType, sup).__call__(object)
cls._key_to_instance[key] = self
cls._instance_to_key[self] = key
for handler in handlers["object_created"]:
try:
handler(self)
except Exception:
traceback.print_exc()
return self
@classmethod
def invalidate(cls):
for xobj in cls._instance_to_key:
xobj._handle = InvalidObject()
@classmethod
def destroy_all(cls):
for xobj in cls._instance_to_key.copy():
_destroy(xobj)
class BpxProperty(metaclass=SingletonProperty):
def __init__(self, xobj, name, index=None):
assert isinstance(xobj, BpxType), "%s was not a BpxType" % xobj
self._xobj = xobj
self._name = name
self._index = index
# Track dirty state and only return last up-to-date value
self._dirty = True
self._last_value = None
# Blender doesn't store the indices of enums,
# nor does it return the index when queried.
# -> bpx always returns indices.
self._enum_to_index = None
self._index_to_enum = None
self._is_enum = False
group = xobj.property_group()
typ = group.bl_rna.properties[self._name]
if isinstance(typ, bpy.types.EnumProperty):
self._enum_to_index = {
enum.name: enum.value
for enum in typ.enum_items
}
self._index_to_enum = {
enum.value: enum.name
for enum in typ.enum_items
}
self._is_enum = True
# Determine whether this property is driven or not
self._driven = False
# Determine whether property is driven
handle = xobj._handle
anim = handle.animation_data
action = getattr(handle.animation_data, "action", None)
if anim and action:
action = handle.animation_data.action
kwargs = {}
if index is not None:
kwargs = {"index": index}
curve_name = "%s.%s" % (group.type, name)
if action.fcurves.find(curve_name, **kwargs) is not None:
self._driven = True
elif anim.drivers:
for fcurve in anim.drivers:
if fcurve.data_path != fcurve:
continue
if fcurve.array_index != index:
continue
self._driven = True
break
def __str__(self):
return str(self.read())
def __repr__(self):
return "bpx.BpxProperty(%s=%s)" % (self._name, self.read())
def __getitem__(self, name):
# Index into a e.g. Vector
if isinstance(name, int):
value = self.read()[name]
else:
value = getattr(self.read(), name)
return value
def __setitem__(self, name, value):
group = self._xobj.property_group()
prop = getattr(group, self._name)
if isinstance(name, int):
prop[name] = value
else:
setattr(prop, name, value)
self.post_process()
def dirty(self):
self._dirty = True
def clean(self):
self._dirty = False
def is_driven(self):
return self._driven
def touch(self):
"""Trigger any update callbacks without changing its value"""
value = self.read()
# Was the property a PointerProperty?
if isinstance(value, BpxObject):
value = {"object": value}
self.write(value)
def post_process(self):
group = self._xobj.property_group()
Type = group.bl_rna.properties[self._name]
# Create a reverse relationship between pointer and pointee#
# Such that you can query the object carrying the pointer,
# and also the object for whom it is pointing to.
if isinstance(Type, bpy.types.PointerProperty):
other = self.read()
if isinstance(other, bpy.types.Object):
xother = BpxType(other)
xother._output_connections[self._name] = self._xobj
def write(self, value):
"""Write `value` to property
This method converts indices to enums automatically,
along with dictionaries to property groups.
Examples:
obj = create_object()
"""
group = self._xobj.property_group()
assert hasattr(group, self._name), (
"'%s.%s' did not exist" % (group, self._name)
)
if self._is_enum and isinstance(value, int):
value = self._index_to_enum[value]
# Support for setting pointer properties
if isinstance(value, BpxObject):
value = value.handle()
elif isinstance(value, BpxBone):
value = value.bone()
if isinstance(value, dict):
for key, value in value.items():
if isinstance(value, BpxType):
value = value.handle()
ptr = getattr(group, self._name)
setattr(ptr, key, value)
else:
if self._index is not None:
self[self._index] = value
else:
setattr(group, self._name, value)
@with_cumulative_timing
def read(self, animated=True):
"""Read this property, or return latest cached
Reading properties is expensive, so unless the property is
marked "dirty" it won't ask Blender for an updated value.
Instead it will output the last computed value.
Update heuristic:
1. A property is dirty, update
2. A property is driven, update
Arguments:
animated (bool, optional): Whether to forcibly read this property
even when not driven and not dirty
"""
if animated or self._dirty or self._driven:
self.update()
return self._last_value
@with_cumulative_timing
def update(self):
"""Store value of Blender property in _last_value
This works alongside `_dirty` to ensure performance is up to snuff
"""
group = self._xobj.property_group()
value = getattr(group, self._name)
if self._is_enum:
value = self._enum_to_index[value]
if self._index is not None:
value = value[self._index]
# Is this a { armature: boneid } pair?
if isinstance(value, bpy.types.PropertyGroup):
pg = value
if hasattr(value, "object") and hasattr(value, "boneidx"):
obj = pg.object
is_armature = obj and isinstance(obj.data, bpy.types.Armature)
value = None
xobj = None
if is_armature:
bone = None
if pg.boneidx is not None:
bone = find_bone_by_index(obj, pg.boneidx)
if bone is None and pg.boneid is not None:
bone = find_bone_by_uuid(obj, pg.boneid)
# Re-compute boneidx for next time
if bone is not None:
pg.boneidx = BpxBone(bone).boneidx(cached=False)
if bone is not None:
xobj = BpxBone(bone)
elif isinstance(obj, bpy.types.Object):
xobj = BpxObject(obj)
if xobj and xobj.is_alive():
value = xobj
# Was the property a PointerProperty?
if isinstance(value, bpy.types.Object):
value = BpxType(value)
self._dirty = False
previous = self._xobj._previous_values.get(self._name)
self._changed = str(value) != previous
# Since the BpxProperty is destroyed on undo, we can't
# store history here. But we *can* store it in the object.
self._xobj._previous_values[self._name] = str(value)
self._last_value = value
def changed(self):
"""Return whether the value of this property has changed
This is different from being dirty, since an attribute can change
to the same value as earlier, and can also be manually dirtied in
which case the value will not have changed.
"""
# In order to know whether it has changed, we first need to read it.
self.read()
return self._changed
def enum(self, converter=None):
assert self._is_enum, "%s was not an enum" % self
group = self._xobj.property_group()
value = getattr(group, self._name)
if converter:
value = getattr(converter, value)
return value
class BpxCollectionProperty(BpxProperty):
def __len__(self):
return len(self.read())
def clear(self):
"""Remove all items from collection"""
pg = self.read()
while len(pg) > 0:
pg.remove(len(pg) - 1)
def append(self, default=None):
item = self.read().add()
if isinstance(default, dict):
for key, value in default.items():
assert hasattr(item, key), "%s did not have '%s'" % (item, key)
setattr(item, key, value)
return item
def pop(self, default=None):
pg = self.read()
last = len(pg) - 1
if last < 0:
raise ValueError("Empty collection")
pg.remove(last)
def exists(self, query):
try:
self.index(query)
except IndexError:
return False
else:
return True
def index(self, query):
"""Find collection item by matching its property values
Arguments:
query (str | dict): Item name, or a dict for matching item
with key-value.
Returns:
int: Index of found item.
Raises:
IndexError: If not found.
TypeError: If `query` is not a str nor dict.