Source code for cgl.plugins.blender.custom_menu
import importlib
import logging
import os
from cgl.core.utils.general import load_json
try:
import bpy
except ImportError:
pass
from importlib import reload
import cgl.plugins.CustomMenu as cm
from cgl.core.config.query import AlchemyConfigManager
from cgl.core.utils.read_write import load_text_file, save_text_lines
reload(cm)
[docs]
class Menu(cm.CustomMenu):
def __init__(self, software="blender", type_="menus"):
cm.CustomMenu.__init__(self, software, type_)
self.cfg = AlchemyConfigManager()
[docs]
def add_button(
self,
menu_label,
label="",
annotation="",
command="",
icon="",
image_overlay_label="",
hot_key="",
):
"""
add a button to a menu
Args:
menu_label (str): name of the menu to add the button to (must already exist)
label (str): label of the button
annotation (str): annotation of the button
command (str): command to run when button is clicked
icon (str): icon to display on the button
image_overlay_label (str): image_plane overlay label to display on the button
hot_key (str): hot key to assign to the button
"""
# menu_path = f"{self.menus_folder}/{menu}/{label}.py"
cmd = command.split(" ")[-1]
module_name = cmd.split(".")[0]
real_module_name = None
menu_dir = os.path.join(self.menus_folder, menu_label)
for file in os.listdir(menu_dir):
if file.lower().startswith(module_name.lower()) and file.endswith(".py"):
real_module_name = file.replace(".py", "")
logging.info(real_module_name)
break
# module = menu_path.split("cookbook\\")[-1].replace("\\", ".").replace(".py", "")
module = f"cookbook.blender.menus.{menu_label}.{module_name}"
try:
module_result = importlib.import_module(module)
button_class = getattr(module_result, module_name)
if button_class:
try:
bpy.utils.register_class(button_class)
print(f"✅ Registered operator: {button_class.__name__}")
print("module: {0} found".format(module))
except ValueError:
print(f"⚠️ Operator {button_class.__name__} already registered")
else:
print(f"❌ No operator class found in module: {module}")
except ModuleNotFoundError:
print("module: {0} not found".format(module))
[docs]
def add_operator_buttons_to_panel(panel_file="", prefix="alchemy"):
"""
This function is used to add buttons to the panel in blender
"""
filename = os.path.basename(panel_file).replace(".py", "")
this_file = panel_file.split("menus")[0]
menu_file_path = f"{this_file}menus.cgl"
menus = load_json(menu_file_path)["blender"]
ordered_buttons = []
for m in menus:
if m["name"] == filename:
for i, button in enumerate(m["buttons"]):
ordered_buttons.append(
["{}.{}".format(prefix, button["name"].lower()), button["label"]]
)
return ordered_buttons
[docs]
def get_blender_button_template(cookbook_root, recipe_type):
"""
This function gets the blender menu file template
Args:
recipe_type:
recipe_name:
Returns:
"""
return f"{cookbook_root}/cookbook/templates/blender/buttons/for_{recipe_type}.py"
if __name__ == "__main__":
create_blender_menu_file(r"E:/Alchemy/cgl/config", "menus", "art", "Art")