-
Notifications
You must be signed in to change notification settings - Fork 41
/
__init__.py
421 lines (338 loc) · 13 KB
/
__init__.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
# Reload submodules if not the initial load
if "bpy" in locals():
current_package_prefix = __name__ + "."
for name, module in sys.modules.copy().items():
if name.startswith(current_package_prefix):
print("Reloading: ", name)
importlib.reload(module)
import bpy, re, json, os, platform, subprocess, sys, importlib
from bpy.props import *
from bpy_extras.io_utils import ImportHelper
from . operators import general, selection, generate, modify, materials, vertex_colors, cut, animation, snapping, files
from . common.common import *
addon_directory = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
library_directory = os.path.join(addon_directory, 'blend')
nodes_path = os.path.join(addon_directory, 'blend', 'nodetools.blend')
app = {
"items": [],
"keymaps": []
}
def get_user_preferences():
return bpy.context.preferences.addons[__package__].preferences
def get_builtin_config_paths():
return [
(os.path.join(addon_directory, 'configs', 'default.json'), True),
]
def draw_menu(self, items):
layout = self.layout
if len(items) == 0:
layout.label(text='No menu items loaded', icon='ERROR')
layout.label(text='Add a config file in the addon preferences')
return
i = 0
for item in items:
if 'mode' in item and item['mode'] != bpy.context.mode:
continue
title = item['title']
i += 1
if i < 10 and not title.startswith('('):
title = f'({i}) {title}'
if 'children' in item:
layout.menu(item['idname'], text=title)
elif item['title'] == '[Separator]':
layout.separator()
i -= 1
elif 'nodetool' in item:
icon = item['icon'] if 'icon' in item else 'NODETREE'
if is_in_editmode():
operator = layout.operator('geometry.execute_node_group', text=title, icon=icon)
operator.name = item['nodetool']
operator.asset_library_type = item['nodetool_library_type'] if 'nodetool_library_type' in item else 'CUSTOM'
operator.asset_library_identifier = item['nodetool_library_identifier'] if 'nodetool_library_identifier' in item else 'QuickMenuLibrary'
operator.relative_asset_identifier = 'nodetools.blend/NodeTree/' + item['nodetool']
else:
layout.operator('qm.void_edit_mode_only', text=title, icon=icon)
elif 'operator' in item:
icon = 'NODETREE' if item['operator'] == 'geometry.execute_node_group' else 'NONE'
if 'icon' in item: icon = item['icon']
operator = layout.operator(item['operator'], text=title, icon=icon)
if not operator:
layout.label(text='Operator not found: ' + item['operator'], icon='ERROR')
continue
if 'params' in item:
for key, val in item['params'].items():
if isinstance(val, list):
val = tuple(val)
setattr(operator, key, val)
elif 'menu' in item:
layout.menu(item['menu'], text=title)
def register_menu_type(menu_definition):
title = menu_definition['title']
items = menu_definition['children']
idname = menu_definition['idname']
def draw(self, context):
draw_menu(self, items)
menu_type = type(idname + "Menu", (bpy.types.Menu,), {
'bl_idname': idname,
'bl_label': title,
'draw': draw
})
bpy.utils.register_class(menu_type)
def get_or_create_menu_definition_at_path(path, items):
for item in items:
if item['title'] == path[0]:
return item if len(path) == 1 else get_or_create_menu_definition_at_path(path[1:], item['children'])
menu_definition = {
'title': path[0],
'children': [],
'idname': 'OBJECT_MT_Menu' + re.sub('[^A-Za-z0-9]+', '', path[0])
}
register_menu_type(menu_definition)
items.append(menu_definition)
return menu_definition
def config_path_is_builtin(path):
return path in [path[0] for path in get_builtin_config_paths()]
def check_json_syntax(path):
if not os.path.exists(path):
return False
with open(path, 'r') as file:
data = file.read()
try:
obj = json.loads(data)
except ValueError as e:
return False
if not 'items' in obj:
return False
return True
# Load the items from the config and add them to the menu
def load_items():
app['items'] = []
for config in get_user_preferences().configs:
if not config.enabled:
continue
if not os.path.exists(config.path):
print(f'[QuickMenu] Config file not found: {config.path}')
continue
with open(config.path, 'r') as config:
data = config.read()
try:
obj = json.loads(data)
except:
raise Exception('Decoding JSON has failed')
if not 'items' in obj:
raise Exception('No items in config')
for item in obj['items']:
# Split by "/" and remove whitespace
path = re.split('\s*\/\s*', item['path'])
item['title'] = path[-1]
if len(path) == 1:
app['items'].append(item)
else:
menu = get_or_create_menu_definition_at_path(path[:-1], app['items'])
menu['children'].append(item)
def register_asset_library():
asset_libraries = bpy.context.preferences.filepaths.asset_libraries
if asset_libraries.find("QuickMenuLibrary") == -1:
library = asset_libraries.new(name="QuickMenuLibrary", directory=library_directory)
library.import_method = "LINK"
def register_hotkey():
keymaps = bpy.context.window_manager.keyconfigs.addon.keymaps
keymap = keymaps.new(name='3D View', space_type='VIEW_3D')
keymap_item = keymap.keymap_items.new('wm.call_menu', type='D', value='PRESS')
keymap_item.properties.name = QuickMenu.bl_idname
app['keymaps'].append((keymap, keymap_item))
def unregister_hotkey():
for keymap, keymap_item in app['keymaps']:
keymap.keymap_items.remove(keymap_item)
app['keymaps'].clear()
class VoidEditModeOnlyOperator(bpy.types.Operator):
"""Edit Mode Only"""
bl_idname = 'qm.void_edit_mode_only'
bl_label = 'Edit Mode Only'
@classmethod
def poll(cls, context):
return is_in_editmode()
def execute(self, context):
return {'FINISHED'}
class QuickMenuAddConfigOperator(bpy.types.Operator, ImportHelper):
"""Add Config"""
bl_idname = 'qm.add_config'
bl_label = 'Add Config'
bl_description = 'Add a new config file'
def execute(self, context):
path = self.properties.filepath
if path == '':
return {'CANCELLED'}
if not os.path.exists(path):
return {'CANCELLED'}
if not path.endswith('.json') or not check_json_syntax(path):
self.report({'ERROR'}, 'The file must be a valid JSON file!')
return {'CANCELLED'}
for config in get_user_preferences().configs:
if config.path == path:
self.report({'ERROR'}, 'The file already exists!')
return {'CANCELLED'}
get_user_preferences().configs.add().path = path
load_items()
return {'FINISHED'}
class QuickMenuRemoveConfigOperator(bpy.types.Operator):
"""Remove Config"""
bl_idname = 'qm.remove_config'
bl_label = 'Remove Config'
bl_description = 'Remove the active config file'
def execute(self, context):
user_preferences = get_user_preferences()
user_preferences.configs.remove(user_preferences.active_config_index)
load_items()
return {'FINISHED'}
class QuickMenuEditConfigOperator(bpy.types.Operator):
"""Edit Config"""
bl_idname = 'qm.edit_config'
bl_label = 'Edit Config'
bl_description = 'Open the active config file in the default text editor'
def execute(self, context):
path = get_user_preferences().configs[get_user_preferences().active_config_index].path
if platform.system() == 'Darwin': # macOS
subprocess.call(('open', path))
elif platform.system() == 'Windows': # Windows
os.startfile(path)
else: # Linux variants
subprocess.call(('xdg-open', path))
return {'FINISHED'}
class QuickMenuReloadMenuItemsOperator(bpy.types.Operator):
"""Reload Menu Items"""
bl_idname = 'qm.reload_menu_items'
bl_label = 'Reload Menu Items'
bl_description = 'Reload the menu items from the config files'
def execute(self, context):
load_items()
return {'FINISHED'}
def reset_configs():
configs = get_user_preferences().configs
configs.clear()
for path in get_builtin_config_paths():
config = configs.add()
config.path = path[0]
config.enabled = path[1]
load_items()
class QuickMenuResetConfigsOperator(bpy.types.Operator):
"""Reset Configs"""
bl_idname = 'qm.reset_configs'
bl_label = 'Reset Configs'
bl_description = 'Reset the config files to the default'
def execute(self, context):
reset_configs()
return {'FINISHED'}
class QuickMenu(bpy.types.Menu):
bl_idname = 'OBJECT_MT_quick_menu'
bl_label = 'Quick Menu'
def draw(self, context):
layout = self.layout
# Draw a label that shows a warning if the current version is less than blender 4.3.0
if bpy.app.version < (4, 3, 0):
layout.label(text=f'You need Blender 4.3 or newer for the addon to work properly', icon='ERROR')
layout.label(text=f'Current version: {bpy.app.version_string}')
draw_menu(self, app['items'])
class QuickMenuConfig(bpy.types.PropertyGroup):
enabled: BoolProperty(default=True, update=lambda self, context: load_items())
path: StringProperty(default='')
class UI_UL_QuickMenuConfigList(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
row = layout.row()
row.alignment = 'LEFT'
if not os.path.exists(item.path):
row.label(text='', icon='ERROR')
else:
row.prop(item, 'enabled', text='')
basename = os.path.basename(item.path)
row.label(text=basename)
row.label(text='(Not found)') if not os.path.exists(item.path) else None
if config_path_is_builtin(item.path):
row.label(text='(Builtin)')
class QuickMenuPreferences(bpy.types.AddonPreferences):
bl_idname = __package__
configs: CollectionProperty(
name = 'Configs',
type = QuickMenuConfig
)
active_config_index: IntProperty(
name = 'Active Config Index'
)
def draw(self, context):
layout = self.layout
layout.label(text="Menu Configs:")
row = layout.row(align=True)
row.template_list("UI_UL_QuickMenuConfigList", "", self, "configs", self, "active_config_index")
column = row.column(align=True)
column.operator('qm.add_config', icon='ADD', text='')
column.operator('qm.remove_config', icon='REMOVE', text='')
column.operator('qm.edit_config', icon='GREASEPENCIL', text='')
column.operator('qm.reload_menu_items', icon='FILE_REFRESH', text='')
column.operator('qm.reset_configs', icon='LOOP_BACK', text='')
# Make sure active config index is in range
if self.active_config_index >= len(self.configs):
self.active_config_index = 0
# Display the path of the current config
if len(self.configs) > 0:
layout.label(text=self.configs[self.active_config_index].path)
box = layout.box()
box.label(text='To change the menu hotkey, go to "Keymap" and search for "Quick Menu"', icon='INFO')
class QuickMenuProperties(bpy.types.PropertyGroup):
# Used to track the current vertex color index. This is used to generate unique
# vertex colors for id maps in apps like Substance Painter
vertex_color_index: bpy.props.IntProperty(name='Vertex Color Index', default=3)
def register():
bpy.utils.register_class(QuickMenu)
bpy.utils.register_class(VoidEditModeOnlyOperator)
bpy.utils.register_class(QuickMenuConfig)
bpy.utils.register_class(UI_UL_QuickMenuConfigList)
bpy.utils.register_class(QuickMenuAddConfigOperator)
bpy.utils.register_class(QuickMenuRemoveConfigOperator)
bpy.utils.register_class(QuickMenuEditConfigOperator)
bpy.utils.register_class(QuickMenuReloadMenuItemsOperator)
bpy.utils.register_class(QuickMenuResetConfigsOperator)
bpy.utils.register_class(QuickMenuPreferences)
bpy.utils.register_class(QuickMenuProperties)
general.register()
selection.register()
generate.register()
modify.register()
materials.register()
vertex_colors.register()
cut.register()
animation.register()
snapping.register()
files.register()
bpy.types.Scene.quick_menu = bpy.props.PointerProperty(type=QuickMenuProperties)
register_hotkey()
register_asset_library()
# Add the default config if the list is empty
configs = get_user_preferences().configs
if len(configs) == 0:
reset_configs()
else:
load_items()
def unregister():
bpy.utils.unregister_class(QuickMenu)
bpy.utils.unregister_class(VoidEditModeOnlyOperator)
bpy.utils.unregister_class(QuickMenuConfig)
bpy.utils.unregister_class(UI_UL_QuickMenuConfigList)
bpy.utils.unregister_class(QuickMenuAddConfigOperator)
bpy.utils.unregister_class(QuickMenuRemoveConfigOperator)
bpy.utils.unregister_class(QuickMenuEditConfigOperator)
bpy.utils.unregister_class(QuickMenuReloadMenuItemsOperator)
bpy.utils.unregister_class(QuickMenuResetConfigsOperator)
bpy.utils.unregister_class(QuickMenuPreferences)
bpy.utils.unregister_class(QuickMenuProperties)
general.unregister()
selection.unregister()
generate.unregister()
modify.unregister()
materials.unregister()
vertex_colors.unregister()
cut.unregister()
animation.unregister()
snapping.unregister()
files.unregister()
del bpy.types.Scene.quick_menu
unregister_hotkey()