forked from waylow/boneWidget
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperators.py
More file actions
1620 lines (1283 loc) · 55.7 KB
/
operators.py
File metadata and controls
1620 lines (1283 loc) · 55.7 KB
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
import bpy
import os
from .functions.main_functions import (
find_match_bones,
from_widget_find_bone,
symmetrize_widget_helper,
match_bone_matrix,
create_widget,
edit_widget,
return_to_armature,
get_collection,
get_view_layer_collection,
recursive_layer_collection,
delete_unused_widgets,
clear_bone_widgets,
resync_widget_names,
add_object_as_widget,
advanced_options_toggled,
set_bone_color,
copy_bone_color,
get_preferences,
)
from .functions.json_functions import (
add_remove_widgets,
get_widget_data,
import_widget_library,
export_widget_library,
update_custom_image,
reset_default_images,
update_widget_library,
save_color_sets,
add_color_set,
scan_armature_color_presets,
import_color_presets,
export_color_presets,
update_color_presets,
)
from .functions.preview_functions import (
remove_custom_image,
copy_custom_image,
create_wireframe_copy,
setup_viewport,
restore_viewport_position,
render_widget_thumbnail,
add_camera_from_view
)
from .props import ImportColorSet, ImportItemData, get_import_options
from .classes import ColorSet
from bpy.props import FloatProperty, BoolProperty, FloatVectorProperty, IntVectorProperty, StringProperty, EnumProperty
class BONEWIDGET_OT_shared_property_group(bpy.types.PropertyGroup):
"""Storage class for Shared Attribute Properties"""
custom_image_data = ("", "")
import_library_filepath = ""
color_sets: bpy.props.CollectionProperty(type=ImportColorSet)
import_item_data: bpy.props.CollectionProperty(type=ImportItemData)
image_collection = bpy.utils.previews.new()
class BONEWIDGET_OT_create_widget(bpy.types.Operator):
"""Creates a widget for selected bone"""
bl_idname = "bonewidget.create_widget"
bl_label = "Create Widget"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (context.object and context.object.mode == 'POSE' and context.selected_pose_bones)
relative_size: BoolProperty(
name="Scale to Bone length",
default=True,
description="Scale Widget to bone length"
)
use_face_data: BoolProperty(
name="Use Face Data",
default=False,
description="When enabled this option will include the widget's face data (if available)"
)
advanced_options: BoolProperty(
name="Advanced options",
default=False,
description="Show advanced options",
update=advanced_options_toggled
)
global_size_simple: FloatProperty(
name="Global Size",
default=1.0,
description="Global Size"
)
global_size_advanced: FloatVectorProperty(
name="Global Size",
default=(1.0, 1.0, 1.0),
subtype='XYZ',
description="Global Size"
)
slide_simple: FloatProperty(
name="Slide",
default=0.0,
subtype='NONE',
unit='NONE',
description="Slide widget along bone y axis"
)
slide_advanced: FloatVectorProperty(
name="Slide",
default=(0.0, 0.0, 0.0),
subtype='XYZ',
unit='NONE',
description="Slide widget along bone xyz axes"
)
rotation: FloatVectorProperty(
name="Rotation",
description="Rotate the widget",
default=(0.0, 0.0, 0.0),
subtype='EULER',
unit='ROTATION',
precision=1,
)
wireframe_width: FloatProperty(
name="Wire Width",
default=2.0,
min=1.0,
max=16,
soft_max=10,
description="Set the thickness of a wireframe widget"
)
def draw(self, context):
layout = self.layout
layout.use_property_split = True
col = layout.column()
row = col.row(align=True)
row.prop(self, "relative_size")
row = col.row(align=True)
if self.advanced_options:
row.prop(self, "use_face_data")
row = col.row(align=True)
row.prop(
self, "global_size_advanced" if self.advanced_options else "global_size_simple", expand=False)
row = col.row(align=True)
row.prop(
self, "slide_advanced" if self.advanced_options else "slide_simple", text="Slide")
row = col.row(align=True)
row.prop(self, "rotation", text="Rotation")
row = col.row(align=True)
if bpy.app.version >= (4, 2, 0):
row.prop(self, "wireframe_width", text="Wire Width")
row = col.row(align=True)
row.prop(self, "advanced_options")
def execute(self, context):
widget_data = get_widget_data(context.window_manager.widget_list)
slide = self.slide_advanced if self.advanced_options else (
0.0, self.slide_simple, 0.0)
global_size = self.global_size_advanced if self.advanced_options else (
self.global_size_simple,) * 3
use_face_data = self.use_face_data if self.advanced_options else False
for bone in bpy.context.selected_pose_bones:
create_widget(bone, widget_data, self.relative_size, global_size, slide, self.rotation,
get_collection(context), use_face_data, self.wireframe_width)
return {'FINISHED'}
class BONEWIDGET_OT_edit_widget(bpy.types.Operator):
"""Edit the widget for selected bone"""
bl_idname = "bonewidget.edit_widget"
bl_label = "Edit Widget"
bl_options = {'REGISTER'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'ARMATURE' and context.object.mode == 'POSE'
and context.active_pose_bone is not None and context.active_pose_bone.custom_shape is not None)
def execute(self, context):
active_bone = context.active_pose_bone
try:
edit_widget(active_bone)
except KeyError:
self.report({'INFO'}, 'This widget is the Widget Collection')
return {'FINISHED'}
class BONEWIDGET_OT_return_to_armature(bpy.types.Operator):
"""Switch back to the armature"""
bl_idname = "bonewidget.return_to_armature"
bl_label = "Return to armature"
bl_options = {'REGISTER'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'MESH'
and context.object.mode in ['EDIT', 'OBJECT'])
def execute(self, context):
b = bpy.context.object
if from_widget_find_bone(bpy.context.object):
return_to_armature(bpy.context.object)
else:
self.report({'INFO'}, 'Object is not a bone widget')
return {'FINISHED'}
class BONEWIDGET_OT_match_bone_transforms(bpy.types.Operator):
"""Match the widget to the bone transforms"""
bl_idname = "bonewidget.match_bone_transforms"
bl_label = "Match bone transforms"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
if bpy.context.mode == "POSE":
for bone in bpy.context.selected_pose_bones:
match_bone_matrix(bone.custom_shape, bone)
else:
for ob in bpy.context.selected_objects:
if ob.type == 'MESH':
match_bone = from_widget_find_bone(ob)
if match_bone:
match_bone_matrix(ob, match_bone)
return {'FINISHED'}
class BONEWIDGET_OT_match_symmetrize_shape(bpy.types.Operator):
"""Symmetrize to the opposite side ONLY if it is named with a .L or .R (default settings)"""
bl_idname = "bonewidget.symmetrize_shape"
bl_label = "Symmetrize"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'ARMATURE'
and context.object.mode in ['POSE'])
def execute(self, context):
widget = bpy.context.active_pose_bone.custom_shape
if widget is None:
self.report({"INFO"}, "There is no widget on this bone.")
return {'FINISHED'}
collection = get_view_layer_collection(context, widget)
widgets_and_bones = find_match_bones()[0]
active_object = find_match_bones()[1]
widgets_and_bones = find_match_bones()[0]
if not active_object:
self.report({"INFO"}, "No active bone or object")
return {'FINISHED'}
for bone in widgets_and_bones:
symmetrize_widget_helper(
bone, collection, active_object, widgets_and_bones)
return {'FINISHED'}
class BONEWIDGET_OT_image_select(bpy.types.Operator):
"""Open a Fileselect browser and get the image location"""
bl_idname = "bonewidget.image_select"
bl_label = "Select Image"
bl_options = {'INTERNAL'}
filter_glob: StringProperty(
default='*.jpg;*.jpeg;*.png;*.tif;',
options={'HIDDEN'}
)
filename: StringProperty(
name='Filename',
subtype='FILE_NAME',
description='Name of custom image',
)
filepath: StringProperty(
subtype="FILE_PATH"
)
def invoke(self, context, event):
self.filename = ""
context.window_manager.fileselect_add(self)
if context.area:
context.area.tag_redraw()
return {'RUNNING_MODAL'}
def execute(self, context):
bpy.context.window_manager.prop_grp.custom_image_name = self.filename
setattr(BONEWIDGET_OT_shared_property_group,
"custom_image_data", (self.filepath, self.filename))
context.area.tag_redraw()
return {'FINISHED'}
class BONEWIDGET_OT_add_custom_image(bpy.types.Operator):
"""Add a custom image to selected preview panel widget"""
bl_idname = "bonewidget.add_custom_image"
bl_label = "Select Image"
bl_options = {'REGISTER', 'UNDO'}
filter_glob: StringProperty(
default='*.jpg;*.jpeg;*.png;*.tif;',
options={'HIDDEN'}
)
filename: StringProperty(
name='Filename',
subtype='FILE_NAME',
description='Name of custom image',
)
filepath: StringProperty(
subtype="FILE_PATH"
)
def invoke(self, context, event):
self.filename = ""
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
def execute(self, context):
if self.filepath:
# first remove previous custom image if present
current_widget = context.window_manager.widget_list
remove_custom_image(get_widget_data(current_widget).get("image"))
# copy over the image to custom folder
copy_custom_image(self.filepath, self.filename)
# update the json files with new image data
update_custom_image(self.filename)
self.report({'INFO'}, "Custom image has been added!")
return {'FINISHED'}
class BONEWIDGET_OT_add_widgets(bpy.types.Operator):
"""Add selected mesh object to Bone Widget Library and optionally Render Thumbnail"""
bl_idname = "bonewidget.add_widgets"
bl_label = "Add New Widget to Library"
bl_options = {'UNDO'}
widget_name: StringProperty(
name="Widget Name",
default="",
description="The name of the new widget",
options={"TEXTEDIT_UPDATE"},
)
image_mode: EnumProperty(
name="Thumbnail",
description="Choose how the widget image is handled",
items=[
('AUTO_RENDER', "Auto Render", "Render the widget automatically"),
('CUSTOM_IMAGE', "Custom Image", "Use a custom image"),
('PLACEHOLDER_IMAGE', "Placeholder Image", "Use the placeholder image"),
],
default='AUTO_RENDER'
)
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'MESH' and context.object.mode == 'OBJECT'
and context.active_object is not None)
def draw(self, context):
layout = self.layout
row = layout.row()
row.label(text="Widget Name:")
row.prop(self, "widget_name", text="")
row = layout.row()
# adding custom image this way doesn't work in blender 3.6
if bpy.app.version > (3, 7, 0):
row.prop(self, "image_mode")
if self.image_mode == 'CUSTOM_IMAGE':
row = layout.row()
if bpy.app.version >= (4, 1, 0):
row.prop(bpy.context.window_manager.prop_grp, "custom_image_name",
text="", placeholder="Choose an image...", icon="FILE_IMAGE")
else:
row.prop(bpy.context.window_manager.prop_grp,
"custom_image_name", text="", icon="FILE_IMAGE")
row.operator('bonewidget.image_select',
icon='FILEBROWSER', text="")
def invoke(self, context, event):
if bpy.context.selected_objects:
self.widget_name = context.active_object.name
setattr(BONEWIDGET_OT_shared_property_group,
"custom_image_name", StringProperty(name="Image Name"))
return context.window_manager.invoke_props_dialog(self)
self.report({'WARNING'}, 'Please select an object first!')
return {'CANCELLED'}
def execute(self, context):
objects = []
if bpy.context.mode == "POSE":
for bone in bpy.context.selected_pose_bones:
objects.append(bone.custom_shape)
else:
for ob in bpy.context.selected_objects:
if ob.type == 'MESH':
objects.append(ob)
if not objects:
self.report({'WARNING'}, 'Select Meshes or Pose bones')
return {'CANCELLED'}
# make sure widget name isn't empty
if not self.widget_name:
self.report({'WARNING'}, "Widget name can't be empty!")
return {'CANCELLED'}
# get filepath to custom image if specified and transfer to custom image folder
custom_image_name = ""
custom_image_path = ""
message_extra = ""
if self.image_mode == 'CUSTOM_IMAGE':
# context.window_manager.custom_image
custom_image_path, custom_image_name = bpy.context.window_manager.prop_grp.custom_image_data
# no image path found
if not custom_image_path:
# check if user pasted an image path into text field
text_field = bpy.context.window_manager.prop_grp.custom_image_name
if os.path.isfile(text_field) and text_field.endswith((".jpg", ".jpeg" ".png", ".tif")):
custom_image_name = os.path.basename(text_field)
custom_image_path = text_field
else:
message_extra = " - WARNING - No custom image specified!"
if custom_image_name and custom_image_path:
copy_custom_image(custom_image_path, custom_image_name)
# make sure the field is empty for next time
bpy.context.window_manager.prop_grp.custom_image_name = ""
elif self.image_mode == 'PLACEHOLDER_IMAGE':
# Use the user_defined image
directory = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', 'thumbnails'))
custom_image_path = os.path.join(directory, "user_defined.png")
elif self.image_mode == 'AUTO_RENDER':
# Render the widget
custom_image_name = self.widget_name + '.png'
bpy.ops.bonewidget.render_widget_thumbnail(
image_name=custom_image_name, use_blend_path=False)
custom_image_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', 'custom_thumbnails'))
message_type, return_message = add_remove_widgets(context, "add", bpy.types.WindowManager.widget_list.keywords['items'],
objects, self.widget_name, custom_image_name)
if return_message:
self.report({message_type}, return_message + message_extra)
return {'FINISHED'}
class BONEWIDGET_OT_remove_widgets(bpy.types.Operator):
"""Remove selected widget object from the Bone Widget Library"""
bl_idname = "bonewidget.remove_widgets"
bl_label = "Remove Widgets"
bl_options = {'INTERNAL'}
def execute(self, context):
objects = bpy.context.window_manager.widget_list
# try and remove the image - will abort if no custom image assigned or if missing
remove_custom_image(get_widget_data(objects).get("image"))
message_type, return_message = add_remove_widgets(
context, "remove", bpy.types.WindowManager.widget_list.keywords['items'], objects)
if return_message:
self.report({message_type}, return_message)
return {'FINISHED'}
class BONEWIDGET_OT_import_items_summary_popup(bpy.types.Operator):
"""Display summary of imported Items"""
bl_idname = "bonewidget.import_summary_popup"
bl_label = "Imported Item Summary"
bl_options = {'INTERNAL'}
def draw(self, context):
layout = self.layout
layout.scale_x = 1.2
layout.separator()
row = layout.row()
if context.window_manager.custom_data.json_import_error:
row.alert = True
row.label(text=f"Error: Unsupported or damaged import file!")
row.alert = False
layout.separator()
else:
row.label(
text=f"Imported Items: {context.window_manager.custom_data.imported()}")
row = layout.row()
row.label(
text=f"Skipped Items: {context.window_manager.custom_data.skipped()}")
row = layout.row()
row.label(
text=f"Failed Items: {context.window_manager.custom_data.failed()}")
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
return {'FINISHED'}
def update_selected_options(self, context):
wm = context.window_manager
selected_values = []
items = wm.prop_grp.import_item_data
for i, item in enumerate(items):
if self.select_all_items:
selected_values.append(item.import_option)
if item.import_option != "RENAME":
item.import_option = "OVERWRITE"
else:
if i < len(BONEWIDGET_OT_import_items_ask_popup.selected_options_values):
value = BONEWIDGET_OT_import_items_ask_popup.selected_options_values[i]
if value != "RENAME":
item.import_option = value
if self.select_all_items:
# reset and store only once
BONEWIDGET_OT_import_items_ask_popup.selected_options_values = selected_values
class BONEWIDGET_OT_import_items_ask_popup(bpy.types.Operator):
"""Ask user how to handle name collisions from the imported items"""
bl_idname = "bonewidget.import_items_ask_popup"
bl_label = "Imported Items"
bl_options = {'INTERNAL'}
import_options = get_import_options()
select_all_items: BoolProperty(name="Select All", description="Will select all items to be added",
default=False, update=update_selected_options)
selected_options_values = []
def draw(self, context):
layout = self.layout
layout.scale_x = 1.2
# layout.separator()
row = layout.row()
row.label(text="Choose an action:")
imported_items = context.window_manager.prop_grp.import_item_data
for i, _ in enumerate(self.custom_import_data.skipped_imports):
imported_item = imported_items[i]
if self.custom_import_data.import_type == "widget":
row = layout.row(align=True)
row.scale_x = 2.0
# Rename
if imported_item.import_option == self.import_options[2][0]:
row.prop(imported_item, "name", text="")
else:
row.label(text=str(imported_item.name))
widget_name = self.custom_import_data.skipped_imports[i].name
icon_id = context.window_manager.prop_grp.image_collection[widget_name].icon_id
icon_row = row.row(align=True)
icon_row.scale_x = 6
icon_row.template_icon(icon_id, scale=1.4)
row.separator(factor=0.4)
row.prop(imported_item, "import_option", text="")
elif self.custom_import_data.import_type == "colorset":
row = layout.row(align=True)
row.scale_x = 3.0
# Rename
if imported_item.import_option == self.import_options[2][0]:
row.prop(imported_item, "name", text="")
else:
row.label(text=str(imported_item.name))
row.separator(factor=0.4)
# color sets
color_set = context.window_manager.prop_grp.color_sets[i]
split = row.split(factor=0.9)
color_row = split.row(align=True)
color_row.prop(color_set, "normal", text="")
color_row.prop(color_set, "select", text="")
color_row.prop(color_set, "active", text="")
# options dropdown
row.separator(factor=0.4)
row.prop(imported_item, "import_option", text="")
row = layout.row()
row = layout.row()
row = layout.row()
row.prop(self, "select_all_items")
layout.separator()
def invoke(self, context, event):
self.custom_import_data = bpy.context.window_manager.custom_data
import_type = self.custom_import_data.import_type
# make sure class values are empty
BONEWIDGET_OT_import_items_ask_popup.selected_options_values = []
# make sure the shared property group has a clean slate
context.window_manager.prop_grp.color_sets.clear()
context.window_manager.prop_grp.import_item_data.clear()
context.window_manager.prop_grp.image_collection.clear()
# generate the x number of drop down lists and widget names needed
for n, widget in enumerate(self.custom_import_data.skipped_imports):
# add new imported item
import_item = context.window_manager.prop_grp.import_item_data.add()
import_item.name = widget.name
# add the color fields if the import is a color set
if import_type == "colorset":
color_instance = context.window_manager.prop_grp.color_sets.add()
color_instance.name = widget.name
color_instance.normal = widget.normal
color_instance.select = widget.select
color_instance.active = widget.active
# widget preview images
if import_type == "widget":
image_path = os.path.join(
bpy.app.tempdir, "custom_thumbnails", widget.image)
context.window_manager.prop_grp.image_collection.load(
widget.name, image_path, 'IMAGE')
return context.window_manager.invoke_props_dialog(self, width=350)
def execute(self, context):
widget_results = {}
widget_images = set()
import_type = self.custom_import_data.import_type
total_imports = len(self.custom_import_data.skipped_imports)
for i, widget in enumerate(self.custom_import_data.skipped_imports[:]):
imported_item = context.window_manager.prop_grp.import_item_data[i]
action = imported_item.import_option
if action == self.import_options[1][0]: # skip
continue
new_widget_name = imported_item.name
# error check before proceeding - widget renamed to empty string
if widget.name != new_widget_name and new_widget_name.strip() == "":
self.custom_import_data.failed_imports.update(widget)
continue
if import_type == "widget":
widget_data = widget
widget_image = widget.image
# only append custom images
widget_image = widget_image if widget_image != "user_defined.png" else ""
elif import_type == "colorset":
widget_data = context.window_manager.prop_grp.color_sets[i]
widget_data = ColorSet.from_pg(
widget_data) # convert to ColorSet class
if action == self.import_options[0][0]: # overwrite
if import_type == "widget":
widget_results.update(widget_data.to_dict())
if widget_image:
widget_images.add(widget_image)
elif import_type == "colorset":
# check if the import item name exists already and if it does, overwrite
color_set_list = context.window_manager.custom_color_presets
for index, item in enumerate(color_set_list):
if item.name == new_widget_name:
# Update the existing entry
item.normal = widget_data.normal
item.select = widget_data.select
item.active = widget_data.active
break
else:
widget_data.name = new_widget_name
add_color_set(context, widget_data)
elif action == self.import_options[2][0]: # Rename
widget_data.name = new_widget_name
if import_type == "widget":
# we need the dict version
widget_results.update(widget_data.to_dict())
if widget_image:
widget_images.add(widget_image)
elif import_type == "colorset":
add_color_set(context, widget_data)
# update the stats
self.custom_import_data.new_imported_items += 1
self.custom_import_data.skipped_imports.remove(widget)
if import_type == "widget":
update_widget_library(widget_results, widget_images,
bpy.context.window_manager.prop_grp.import_library_filepath)
# clear image collection if widgets were imported
context.window_manager.prop_grp.image_collection.clear()
# clear out all import item data
context.window_manager.prop_grp.import_item_data.clear()
# clear out all color sets
context.window_manager.prop_grp.color_sets.clear()
# del bpy.types.WindowManager.custom_data
self.custom_import_data = None
# reset previous selected options
BONEWIDGET_OT_import_items_ask_popup.selected_options_values = []
# display summary of imported widgets
bpy.ops.bonewidget.import_summary_popup('INVOKE_DEFAULT')
return {'FINISHED'}
class BONEWIDGET_OT_import_widget_library(bpy.types.Operator):
"""Import User Defined Widgets"""
bl_idname = "bonewidget.import_widget_library"
bl_label = "Import Library"
bl_options = {'REGISTER'}
filter_glob: StringProperty(
default='*.zip',
options={'HIDDEN'}
)
filename: StringProperty(
name='Filename',
subtype='FILE_NAME',
description='Name of file to be imported',
)
filepath: StringProperty(
subtype="FILE_PATH"
)
import_option: EnumProperty(
name="Import Option",
items=[
("OVERWRITE", "Overwrite", "Overwrite existing widget"),
("SKIP", "Skip", "Skip widget"),
("ASK", "Ask", "Ask user what to do")],
default="ASK",
)
def draw(self, context):
layout = self.layout
row = layout.row(align=True)
row.label(text="If duplicates are found:")
row = layout.row(align=True)
row.prop(self, "import_option", expand=True)
def execute(self, context):
if self.filepath and self.import_option:
import_library_data = import_widget_library(
self.filepath, self.import_option)
setattr(BONEWIDGET_OT_shared_property_group,
"import_library_filepath", self.filepath)
bpy.types.WindowManager.custom_data = import_library_data
# if the number of failed widgets are equal to total imported widgets - call summary popup
if import_library_data.failed() == import_library_data.total() or import_library_data.failed() == -1:
import_library_data.reset_imports()
bpy.ops.bonewidget.import_summary_popup('INVOKE_DEFAULT')
elif self.import_option == "ASK":
bpy.ops.bonewidget.import_items_ask_popup('INVOKE_DEFAULT')
elif self.import_option in ["OVERWRITE", "SKIP"]:
widget_images = set()
widgets = {}
# convert Widget objects to dict items and extract image names if any
for widget in import_library_data.imported_items:
widgets.update(widget.to_dict())
widget_images.add(widget.image)
update_widget_library(widgets, widget_images, self.filepath)
bpy.ops.bonewidget.import_summary_popup('INVOKE_DEFAULT')
else:
bpy.ops.bonewidget.import_summary_popup('INVOKE_DEFAULT')
return {'FINISHED'}
def invoke(self, context, event):
self.filename = ""
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class BONEWIDGET_OT_export_widget_library(bpy.types.Operator):
"""Export User Defined Widgets"""
bl_idname = "bonewidget.export_widget_library"
bl_label = "Export Library"
bl_options = {'REGISTER'}
filter_glob: StringProperty(
default='*.zip',
options={'HIDDEN'}
)
filename: StringProperty(
name='Filename',
subtype='FILE_NAME',
description='Name of file to be exported',
)
filepath: StringProperty(
subtype="FILE_PATH"
)
def execute(self, context):
if self.filepath and self.filename:
num_widgets = export_widget_library(self.filepath)
if num_widgets:
self.report(
{'INFO'}, f"{num_widgets} user defined widgets exported successfully!")
else:
self.report({'INFO'}, "0 user defined widgets exported!")
return {'FINISHED'}
def invoke(self, context, event):
self.filename = "widget_library.zip"
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class BONEWIDGET_OT_toggle_collection_visibility(bpy.types.Operator):
"""Show/hide the bone widget collection"""
bl_idname = "bonewidget.toggle_collection_visibilty"
bl_label = "Collection Visibilty"
bl_options = {'INTERNAL'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'ARMATURE' and context.object.mode == 'POSE')
def execute(self, context):
if not get_preferences(context).use_rigify_defaults:
bw_collection_name = get_preferences(
context).bonewidget_collection_name
else:
bw_collection_name = 'WGTS_' + context.active_object.name
bw_collection = recursive_layer_collection(
bpy.context.view_layer.layer_collection, bw_collection_name)
bw_collection.hide_viewport = not bw_collection.hide_viewport
# need to recursively search for the view_layer
bw_collection.exclude = False
return {'FINISHED'}
class BONEWIDGET_OT_delete_unused_widgets(bpy.types.Operator):
"""Delete unused objects in the WGT collection"""
bl_idname = "bonewidget.delete_unused_widgets"
bl_label = "Delete Unused Widgets"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'ARMATURE' and context.object.mode == 'POSE')
def execute(self, context):
try:
delete_unused_widgets()
except:
self.report(
{'INFO'}, "Can't find the Widget Collection. Does it exist?")
return {'FINISHED'}
class BONEWIDGET_OT_clear_bone_widgets(bpy.types.Operator):
"""Clears widgets from selected pose bones but doesn't remove them from the scene"""
bl_idname = "bonewidget.clear_widgets"
bl_label = "Clear Widgets"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'ARMATURE' and context.object.mode == 'POSE')
def execute(self, context):
clear_bone_widgets()
return {'FINISHED'}
class BONEWIDGET_OT_resync_widget_names(bpy.types.Operator):
"""Clear widgets from selected pose bones"""
bl_idname = "bonewidget.resync_widget_names"
bl_label = "Resync Widget Names"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (context.object and context.object.type == 'ARMATURE' and context.object.mode == 'POSE')
def execute(self, context):
resync_widget_names()
return {'FINISHED'}
class BONEWIDGET_OT_add_object_as_widget(bpy.types.Operator):
"""Add selected object as widget for active bone"""
bl_idname = "bonewidget.add_as_widget"
bl_label = "Confirm selected Object as widget shape"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return (len(context.selected_objects) == 2 and context.object.mode == 'POSE')
def execute(self, context):
add_object_as_widget(context, get_collection(context))
return {'FINISHED'}
class BONEWIDGET_OT_reset_default_images(bpy.types.Operator):
"""Resets the thumbnails for all default widgets"""
bl_idname = "bonewidget.reset_default_images"
bl_label = "Reset"
bl_options = {'INTERNAL'}
def execute(self, context):
reset_default_images()
return {'FINISHED'}
class BONEWIDGET_OT_user_data_filebrowser(bpy.types.Operator):
"""Select Location for Custom User Data"""
bl_idname = "bonewidget.user_data_filebrowser"
bl_label = "Select Location"
bl_options = {'INTERNAL'}
directory: StringProperty(
name="User Data Directory",
description="Choose a directory to store user data",
subtype='DIR_PATH'
)
def execute(self, context):
get_preferences(context).user_data_location = self.directory
# self.report({'INFO'}, f"User data path set to: {self.directory}")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class BONEWIDGET_OT_set_bone_color(bpy.types.Operator):
"""Add bone color to selected widgets"""
bl_idname = "bonewidget.set_bone_color"
bl_label = "Set Bone Color to Widget"