-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
821 lines (695 loc) · 25.5 KB
/
Copy path__init__.py
File metadata and controls
821 lines (695 loc) · 25.5 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
# SPDX-License-Identifier: LGPL-3.0-or-later
bl_info = {
"name": "Custom Pie Menu Creator",
"description": "Preference-backed nested pie menus with actions and shortcuts",
"author": "Grok (xAI)",
"version": (2, 1, 1),
"blender": (5, 1, 0),
"location": "Edit > Preferences > Add-ons",
"category": "Interface",
}
import json
import uuid
import zlib
from pathlib import Path
import bpy
from bpy.props import (
BoolProperty,
CollectionProperty,
EnumProperty,
IntProperty,
StringProperty,
)
from bpy.types import AddonPreferences, Menu, Operator, PropertyGroup, UIList
from bpy_extras.io_utils import ExportHelper, ImportHelper
ADDON_ID = __package__ or __name__
PRESET_PATH = Path(__file__).with_name("CustomPieMenuConfig.json")
addon_keymaps = []
active_pie_id = ""
submenu_enum_items_cache = []
def _key_items():
items = [(letter, letter, "") for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
items.extend(
[
("ZERO", "0", ""),
("ONE", "1", ""),
("TWO", "2", ""),
("THREE", "3", ""),
("FOUR", "4", ""),
("FIVE", "5", ""),
("SIX", "6", ""),
("SEVEN", "7", ""),
("EIGHT", "8", ""),
("NINE", "9", ""),
]
)
items.extend([(f"F{number}", f"F{number}", "") for number in range(1, 25)])
items.extend(
[
("SPACE", "Space", ""),
("ESC", "Escape", ""),
("TAB", "Tab", ""),
("RET", "Enter", ""),
("BACK_SPACE", "Backspace", ""),
("DEL", "Delete", ""),
("INSERT", "Insert", ""),
("HOME", "Home", ""),
("END", "End", ""),
("PAGE_UP", "Page Up", ""),
("PAGE_DOWN", "Page Down", ""),
("LEFT_ARROW", "Left Arrow", ""),
("RIGHT_ARROW", "Right Arrow", ""),
("UP_ARROW", "Up Arrow", ""),
("DOWN_ARROW", "Down Arrow", ""),
("ACCENT_GRAVE", "Accent Grave", ""),
("MINUS", "Minus", ""),
("EQUAL", "Equals", ""),
("LEFT_BRACKET", "Left Bracket", ""),
("RIGHT_BRACKET", "Right Bracket", ""),
("SEMI_COLON", "Semicolon", ""),
("QUOTE", "Quote", ""),
("COMMA", "Comma", ""),
("PERIOD", "Period", ""),
("SLASH", "Slash", ""),
("BACK_SLASH", "Backslash", ""),
]
)
items.extend([(f"NUMPAD_{number}", f"Numpad {number}", "") for number in range(10)])
items.extend(
[
("NUMPAD_PERIOD", "Numpad Period", ""),
("NUMPAD_PLUS", "Numpad Plus", ""),
("NUMPAD_MINUS", "Numpad Minus", ""),
("NUMPAD_ASTERIX", "Numpad Multiply", ""),
("NUMPAD_SLASH", "Numpad Divide", ""),
("NUMPAD_ENTER", "Numpad Enter", ""),
]
)
return items
KEY_ITEMS = _key_items()
KEY_TYPES = {item[0] for item in KEY_ITEMS}
DIGIT_KEYS = {
"0": "ZERO",
"1": "ONE",
"2": "TWO",
"3": "THREE",
"4": "FOUR",
"5": "FIVE",
"6": "SIX",
"7": "SEVEN",
"8": "EIGHT",
"9": "NINE",
}
def get_preferences(context=None):
context = context or bpy.context
addon = context.preferences.addons.get(ADDON_ID)
return addon.preferences if addon else None
def submenu_enum_items(self, context):
prefs = get_preferences(context)
items = [("NONE", "None", "Do not open another pie menu", 0, 0)]
used_values = {0}
if prefs:
for pie in prefs.pies:
if not pie.identifier:
continue
value = zlib.crc32(pie.identifier.encode("utf-8")) & 0x7FFFFFFF
value = value or 1
while value in used_values:
value = (value + 1) & 0x7FFFFFFF or 1
used_values.add(value)
items.append(
(
pie.identifier,
pie.name or "Unnamed Pie",
f"Open {pie.name or 'this pie menu'}",
0,
value,
)
)
# Blender requires dynamically generated enum strings to remain referenced.
submenu_enum_items_cache[:] = items
return submenu_enum_items_cache
def new_identifier():
return uuid.uuid4().hex
def normalize_key_type(value):
value = str(value or "A").upper()
value = DIGIT_KEYS.get(value, value)
return value if value in KEY_TYPES else "A"
def remove_shortcuts(context=None):
context = context or bpy.context
wm = getattr(context, "window_manager", None)
kc = wm.keyconfigs.addon if wm and wm.keyconfigs else None
for km, kmi in addon_keymaps:
try:
km.keymap_items.remove(kmi)
except (ReferenceError, RuntimeError):
pass
addon_keymaps.clear()
# Also remove registrations left behind by a script reload.
if kc:
for km in kc.keymaps:
for kmi in list(km.keymap_items):
if kmi.idname == "pie.invoke_pie":
km.keymap_items.remove(kmi)
def rebuild_shortcuts(context=None):
context = context or bpy.context
remove_shortcuts(context)
prefs = get_preferences(context)
wm = getattr(context, "window_manager", None)
kc = wm.keyconfigs.addon if wm and wm.keyconfigs else None
if not prefs or not kc:
return 0, []
km = kc.keymaps.new(name="3D View", space_type="VIEW_3D")
errors = []
for pie in prefs.pies:
if not pie.use_shortcut:
continue
if not pie.identifier:
pie.identifier = new_identifier()
try:
kmi = km.keymap_items.new(
"pie.invoke_pie",
type=pie.key,
value="PRESS",
ctrl=pie.ctrl,
alt=pie.alt,
shift=pie.shift,
oskey=pie.oskey,
)
kmi.properties.pie_id = pie.identifier
addon_keymaps.append((km, kmi))
except (TypeError, ValueError, RuntimeError) as error:
errors.append(f"{pie.name}: {error}")
return len(addon_keymaps), errors
class PieItem(PropertyGroup):
name: StringProperty(name="Name", default="New Item")
type: EnumProperty(
name="Type",
items=[
("ACTION", "Action", "Run a Blender operator or Python action"),
("SUBMENU", "Submenu", "Open another configured pie menu"),
],
default="ACTION",
)
action_type: EnumProperty(
name="Action",
items=[
("OP", "Blender Operator", "Run a Blender operator"),
("MACRO", "Python", "Run Python code"),
],
default="OP",
)
operator: StringProperty(name="Operator", default="object.select_all")
icon: StringProperty(name="Icon", default="")
submenu_id: EnumProperty(name="Menu", items=submenu_enum_items)
macro_code: StringProperty(
name="Python Code",
default='bpy.ops.object.select_all(action="SELECT")',
)
class CustomPie(PropertyGroup):
identifier: StringProperty(options={"HIDDEN"})
name: StringProperty(name="Name", default="My Pie")
use_shortcut: BoolProperty(name="Enable Shortcut", default=False)
key: EnumProperty(name="Key", items=KEY_ITEMS, default="A")
ctrl: BoolProperty(name="Ctrl", default=False)
alt: BoolProperty(name="Alt", default=False)
shift: BoolProperty(name="Shift", default=False)
oskey: BoolProperty(name="OS Key", default=False)
items: CollectionProperty(type=PieItem)
class VIEW3D_UL_pies(UIList):
def draw_item(
self,
context,
layout,
data,
item,
icon,
active_data,
active_propname,
index,
):
layout.prop(item, "name", text="", emboss=False)
if item.use_shortcut:
layout.label(text="", icon="KEYINGSET")
class CustomPiePreferences(AddonPreferences):
bl_idname = ADDON_ID
pies: CollectionProperty(type=CustomPie)
pies_index: IntProperty(default=0)
preset_initialized: BoolProperty(default=False, options={"HIDDEN"})
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
storage = layout.box()
storage.label(text="Menus are stored in Blender preferences, not in .blend files.")
row = storage.row(align=True)
row.operator("pie.save_preferences", icon="FILE_TICK")
row.operator("pie.export_json", text="Export Backup", icon="EXPORT")
row.operator("pie.import_json", text="Import Backup", icon="IMPORT")
storage.operator("pie.load_bundled_preset", text="Load Bundled Preset")
row = layout.row()
row.template_list(
"VIEW3D_UL_pies",
"",
self,
"pies",
self,
"pies_index",
rows=5,
)
controls = row.column(align=True)
controls.operator("pie.add_pie", icon="ADD", text="")
controls.operator("pie.remove_pie", icon="X", text="")
if not self.pies:
layout.label(text="Add a pie menu to begin.", icon="INFO")
return
self.pies_index = min(max(self.pies_index, 0), len(self.pies) - 1)
pie = self.pies[self.pies_index]
general = layout.box()
general.label(text="Menu")
general.prop(pie, "name")
shortcut = layout.box()
shortcut.label(text="Keyboard Shortcut")
shortcut.prop(pie, "use_shortcut")
shortcut_settings = shortcut.column()
shortcut_settings.enabled = pie.use_shortcut
shortcut_settings.prop(pie, "key")
modifiers = shortcut_settings.row(align=True)
modifiers.prop(pie, "ctrl", toggle=True)
modifiers.prop(pie, "alt", toggle=True)
modifiers.prop(pie, "shift", toggle=True)
modifiers.prop(pie, "oskey", toggle=True)
shortcut.label(
text="Use Apply & Save Settings after changing shortcuts.",
icon="INFO",
)
items_box = layout.box()
header = items_box.row()
header.label(text=f"Menu Items ({len(pie.items)}/8)")
header.operator("pie.add_item", icon="ADD", text="Add Item")
for index, item in enumerate(pie.items):
item_box = items_box.box()
row = item_box.row(align=True)
row.prop(item, "name", text="")
row.prop(item, "type", text="")
remove = row.operator("pie.remove_item", text="", icon="X")
remove.index = index
if item.type == "ACTION":
item_box.prop(item, "action_type")
if item.action_type == "OP":
item_box.prop(item, "operator")
else:
item_box.prop(item, "macro_code")
item_box.prop(item, "icon", text="Icon (optional)")
else:
item_box.prop(item, "submenu_id", text="Menu")
item_box.prop(item, "icon", text="Icon (optional)")
class PIE_OT_execute_macro(Operator):
bl_idname = "pie.execute_macro"
bl_label = "Execute Python Action"
bl_options = {"REGISTER", "UNDO"}
code: StringProperty()
def execute(self, context):
if not self.code.strip():
return {"CANCELLED"}
try:
exec(
self.code,
{
"__builtins__": __builtins__,
"bpy": bpy,
"context": context,
"C": context,
},
)
except Exception as error:
self.report({"ERROR"}, f"Macro Error: {error}")
return {"CANCELLED"}
return {"FINISHED"}
class VIEW3D_MT_PIE_dynamic(Menu):
bl_label = "Custom Pie"
def draw(self, context):
pie_layout = self.layout.menu_pie()
prefs = get_preferences(context)
pie = (
next(
(item for item in prefs.pies if item.identifier == active_pie_id),
None,
)
if prefs
else None
)
if not pie:
pie_layout.label(text="Pie menu not found")
return
for item in pie.items:
icon = item.icon.strip()
try:
if item.type == "SUBMENU":
target = next(
(
target
for target in prefs.pies
if target.identifier == item.submenu_id
),
None,
)
if not target:
pie_layout.label(
text=f"Missing submenu: {item.name}", icon="ERROR"
)
continue
op = pie_layout.operator(
"pie.invoke_pie",
text=item.name or target.name,
icon=icon or "TRIA_RIGHT",
)
op.pie_id = target.identifier
elif item.action_type == "MACRO":
op = pie_layout.operator(
"pie.execute_macro",
text=item.name,
icon=icon or "PLAY",
)
op.code = item.macro_code
elif icon:
pie_layout.operator(item.operator, text=item.name, icon=icon)
else:
pie_layout.operator(item.operator, text=item.name)
except Exception:
pie_layout.label(text=f"Invalid item: {item.name}", icon="ERROR")
class PIE_OT_invoke_pie(Operator):
bl_idname = "pie.invoke_pie"
bl_label = "Invoke Custom Pie Menu"
bl_options = {"REGISTER"}
pie_id: StringProperty()
def execute(self, context):
global active_pie_id
prefs = get_preferences(context)
if not prefs or not any(p.identifier == self.pie_id for p in prefs.pies):
self.report({"ERROR"}, "Pie menu not found")
return {"CANCELLED"}
active_pie_id = self.pie_id
bpy.ops.wm.call_menu_pie(name="VIEW3D_MT_PIE_dynamic")
return {"FINISHED"}
class PIE_OT_add_pie(Operator):
bl_idname = "pie.add_pie"
bl_label = "Add Pie Menu"
def execute(self, context):
prefs = get_preferences(context)
if not prefs:
return {"CANCELLED"}
pie = prefs.pies.add()
pie.identifier = new_identifier()
pie.name = f"Pie {len(prefs.pies)}"
prefs.pies_index = len(prefs.pies) - 1
return {"FINISHED"}
class PIE_OT_remove_pie(Operator):
bl_idname = "pie.remove_pie"
bl_label = "Remove Pie Menu"
def execute(self, context):
prefs = get_preferences(context)
if not prefs:
return {"CANCELLED"}
index = prefs.pies_index
if 0 <= index < len(prefs.pies):
removed_id = prefs.pies[index].identifier
for pie in prefs.pies:
for item in pie.items:
if item.type == "SUBMENU" and item.submenu_id == removed_id:
item.submenu_id = "NONE"
prefs.pies.remove(index)
prefs.pies_index = min(max(0, index - 1), max(0, len(prefs.pies) - 1))
rebuild_shortcuts(context)
return {"FINISHED"}
class PIE_OT_add_item(Operator):
bl_idname = "pie.add_item"
bl_label = "Add Pie Item"
def execute(self, context):
prefs = get_preferences(context)
if not prefs or not (0 <= prefs.pies_index < len(prefs.pies)):
return {"CANCELLED"}
pie = prefs.pies[prefs.pies_index]
if len(pie.items) >= 8:
self.report({"WARNING"}, "A pie menu supports at most 8 items")
return {"CANCELLED"}
pie.items.add()
return {"FINISHED"}
class PIE_OT_remove_item(Operator):
bl_idname = "pie.remove_item"
bl_label = "Remove Pie Item"
index: IntProperty(default=0)
def execute(self, context):
prefs = get_preferences(context)
if not prefs or not (0 <= prefs.pies_index < len(prefs.pies)):
return {"CANCELLED"}
items = prefs.pies[prefs.pies_index].items
if 0 <= self.index < len(items):
items.remove(self.index)
return {"FINISHED"}
def serialize_preferences(prefs):
data = []
for pie in prefs.pies:
items = []
for item in pie.items:
item_data = {
"name": item.name,
"type": item.type,
"icon": item.icon,
}
if item.type == "ACTION":
item_data["action_type"] = item.action_type
if item.action_type == "OP":
item_data["operator"] = item.operator
else:
item_data["macro_code"] = item.macro_code
else:
item_data["submenu_id"] = item.submenu_id
items.append(item_data)
data.append(
{
"identifier": pie.identifier,
"name": pie.name,
"use_shortcut": pie.use_shortcut,
"key": pie.key,
"ctrl": pie.ctrl,
"alt": pie.alt,
"shift": pie.shift,
"oskey": pie.oskey,
"items": items,
}
)
return data
def validate_preset_data(data):
if not isinstance(data, list):
raise ValueError("the root JSON value must be a list")
identifiers = set()
for pie_data in data:
if not isinstance(pie_data, dict):
raise ValueError("each pie menu must be an object")
identifier = pie_data.get("identifier")
if not isinstance(identifier, str) or not identifier:
raise ValueError("each pie menu requires a non-empty identifier")
if identifier in identifiers:
raise ValueError(f"duplicate pie menu identifier: {identifier}")
identifiers.add(identifier)
items = pie_data.get("items")
if not isinstance(items, list):
raise ValueError(f"{identifier}: items must be a list")
if len(items) > 8:
raise ValueError(f"{identifier}: pie menus support at most 8 items")
for item_data in items:
if not isinstance(item_data, dict):
raise ValueError(f"{identifier}: each menu item must be an object")
item_type = item_data.get("type")
if item_type not in {"ACTION", "SUBMENU"}:
raise ValueError(
f"{identifier}: menu item type must be ACTION or SUBMENU"
)
if item_type == "ACTION" and item_data.get("action_type") not in {
"OP",
"MACRO",
}:
raise ValueError(
f"{identifier}: action_type must be OP or MACRO"
)
for pie_data in data:
for item_data in pie_data["items"]:
if item_data["type"] == "SUBMENU":
target_id = item_data.get("submenu_id")
if target_id not in identifiers:
raise ValueError(
f"{pie_data['identifier']}: unknown submenu {target_id!r}"
)
def apply_preset_data(prefs, data):
validate_preset_data(data)
prefs.pies.clear()
created_pies = []
for pie_data in data:
pie = prefs.pies.add()
pie.identifier = pie_data["identifier"]
pie.name = str(pie_data.get("name", "Pie Menu"))
pie.use_shortcut = bool(pie_data.get("use_shortcut", False))
pie.key = normalize_key_type(pie_data.get("key", "A"))
pie.ctrl = bool(pie_data.get("ctrl", False))
pie.alt = bool(pie_data.get("alt", False))
pie.shift = bool(pie_data.get("shift", False))
pie.oskey = bool(pie_data.get("oskey", False))
created_pies.append((pie, pie_data))
for pie, pie_data in created_pies:
for item_data in pie_data["items"]:
item = pie.items.add()
item.name = str(item_data.get("name", "Item"))
item.type = item_data["type"]
item.icon = str(item_data.get("icon", ""))
if item.type == "ACTION":
item.action_type = item_data["action_type"]
if item.action_type == "OP":
item.operator = str(
item_data.get("operator", "object.select_all")
)
else:
item.macro_code = str(item_data.get("macro_code", ""))
else:
item.submenu_id = item_data["submenu_id"]
prefs.pies_index = 0
return len(created_pies)
def read_preset_file(filepath):
with open(filepath, "r", encoding="utf-8") as file:
data = json.load(file)
validate_preset_data(data)
return data
def initialize_bundled_preset():
prefs = get_preferences()
if not prefs or prefs.preset_initialized:
return
if prefs.pies:
prefs.preset_initialized = True
return
try:
data = read_preset_file(PRESET_PATH)
apply_preset_data(prefs, data)
except (OSError, ValueError, json.JSONDecodeError) as error:
print(f"Custom Pie Menu Creator: could not load bundled preset: {error}")
return
prefs.preset_initialized = True
class PIE_OT_export_json(Operator, ExportHelper):
bl_idname = "pie.export_json"
bl_label = "Export Pie Menu Backup"
filename_ext = ".json"
filter_glob: StringProperty(default="*.json", options={"HIDDEN"})
def execute(self, context):
prefs = get_preferences(context)
if not prefs:
return {"CANCELLED"}
try:
with open(self.filepath, "w", encoding="utf-8") as file:
json.dump(serialize_preferences(prefs), file, indent=4)
except OSError as error:
self.report({"ERROR"}, f"Export failed: {error}")
return {"CANCELLED"}
self.report({"INFO"}, f"Exported {len(prefs.pies)} pie menus")
return {"FINISHED"}
class PIE_OT_import_json(Operator, ImportHelper):
bl_idname = "pie.import_json"
bl_label = "Import Pie Menu Backup"
filename_ext = ".json"
filter_glob: StringProperty(default="*.json", options={"HIDDEN"})
def execute(self, context):
prefs = get_preferences(context)
if not prefs:
return {"CANCELLED"}
try:
data = read_preset_file(self.filepath)
menu_count = apply_preset_data(prefs, data)
except (OSError, ValueError, json.JSONDecodeError) as error:
self.report({"ERROR"}, f"Import failed: {error}")
return {"CANCELLED"}
prefs.preset_initialized = True
count, errors = rebuild_shortcuts(context)
if errors:
self.report({"WARNING"}, f"Imported with {len(errors)} shortcut error(s)")
else:
self.report(
{"INFO"},
f"Imported {menu_count} pie menus and registered {count} shortcuts",
)
return {"FINISHED"}
class PIE_OT_load_bundled_preset(Operator):
bl_idname = "pie.load_bundled_preset"
bl_label = "Load Bundled Preset"
bl_description = "Replace the current menus with the bundled preset"
def invoke(self, context, event):
prefs = get_preferences(context)
if prefs and prefs.pies:
return context.window_manager.invoke_confirm(self, event)
return self.execute(context)
def execute(self, context):
prefs = get_preferences(context)
if not prefs:
return {"CANCELLED"}
try:
data = read_preset_file(PRESET_PATH)
menu_count = apply_preset_data(prefs, data)
except (OSError, ValueError, json.JSONDecodeError) as error:
self.report({"ERROR"}, f"Preset load failed: {error}")
return {"CANCELLED"}
prefs.preset_initialized = True
shortcut_count, errors = rebuild_shortcuts(context)
if errors:
self.report(
{"WARNING"},
f"Loaded {menu_count} menus with {len(errors)} shortcut error(s)",
)
else:
self.report(
{"INFO"},
f"Loaded {menu_count} menus and {shortcut_count} shortcuts",
)
return {"FINISHED"}
class PIE_OT_save_preferences(Operator):
bl_idname = "pie.save_preferences"
bl_label = "Apply & Save Settings"
def execute(self, context):
count, errors = rebuild_shortcuts(context)
if errors:
self.report({"ERROR"}, "; ".join(errors))
return {"CANCELLED"}
try:
bpy.ops.wm.save_userpref()
except RuntimeError as error:
self.report({"ERROR"}, f"Could not save Blender preferences: {error}")
return {"CANCELLED"}
self.report({"INFO"}, f"Saved settings with {count} shortcut(s)")
return {"FINISHED"}
classes = (
PieItem,
CustomPie,
VIEW3D_UL_pies,
CustomPiePreferences,
VIEW3D_MT_PIE_dynamic,
PIE_OT_invoke_pie,
PIE_OT_execute_macro,
PIE_OT_add_pie,
PIE_OT_remove_pie,
PIE_OT_add_item,
PIE_OT_remove_item,
PIE_OT_save_preferences,
PIE_OT_load_bundled_preset,
PIE_OT_export_json,
PIE_OT_import_json,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
initialize_bundled_preset()
rebuild_shortcuts()
def unregister():
remove_shortcuts()
for cls in reversed(classes):
try:
bpy.utils.unregister_class(cls)
except RuntimeError:
pass
if __name__ == "__main__":
register()