def create(cls): # Build main menu cls._delete_old() Logger.info("Building {0} menu...".format(cls.MAIN_MENU_LABEL)) pm.menu(cls.MAIN_MENU_ID, label=cls.MAIN_MENU_LABEL, parent=cls.MAIN_WINDOW, tearOff=1) MenuUtil.addMenuItem(cls.MAIN_MENU_ID, divider=1, label="Tools") # Tools MenuUtil.addMenuItem(cls.MAIN_MENU_ID, label="Builder", command=tool_cmds.luna_builder, icon="builder.svg") cls._add_external_tools() # Developer tools cls._add_dev_menu() # Help and config section MenuUtil.addMenuItem(cls.MAIN_MENU_ID, divider=1) MenuUtil.addMenuItem(cls.MAIN_MENU_ID, label="Configuration", command=tool_cmds.luna_configer, icon="config.svg") cls._add_help_menu()
def run_all_tests(): test_suite = unittest.TestLoader().discover(start_dir=directories.TEST_DIR_PATH, pattern="*_test.py") Logger.info("Running {0} tests...".format(test_suite.countTestCases())) test_runner = unittest.TextTestRunner(verbosity=2, resultclass=TestResult) test_runner.failfast = False test_runner.buffer = Config.get(TestVars.buffer_output, default=True) test_runner.run(test_suite)
def _delete_old(cls): if pm.menu(cls.MAIN_MENU_ID, label=cls.MAIN_MENU_ID, exists=1, parent=cls.MAIN_WINDOW): pm.deleteUI(pm.menu(cls.MAIN_MENU_ID, e=1, deleteAllItems=1)) Logger.debug("Deleted existing {} object".format(cls.MAIN_MENU_ID))
def add_luna_callbacks(): if Config.get(LunaVars.callback_licence, True): try: callbacks.remove_licence_popup_callback() Logger.info("Added file save licence callback") except RuntimeError: Logger.exception("Failed to add file save licence callback!")
def load_pickle(path): try: with open(path, "r") as read_file: data = pickle.load(read_file) except IOError as e: Logger.exception("Failed to load file {0}".format(path), exc_info=e) return None return data
def create_file(path, data=""): try: with open(path, "w") as f: f.write(data) except IOError: Logger.exception("Failed to create file {0}".format(path)) return None return path
def open_port(lang="python"): port = Config.get(LunaVars.command_port, default=7221) if not pm.commandPort("127.0.0.1:{0}".format(port), n=1, q=1): try: pm.commandPort(name="127.0.0.1:{0}".format(port), stp="python", echoOutput=True) Logger.info("Command port opened: Python - {0}".format(port)) except Exception as e: Logger.exception("Failed to open command port", exc_info=e)
def get_config_path(cls): """Get path to config file. Copy a default one if one doesn't exist. Returns: str: Path to config file """ if not os.path.isfile(cls.FILE_PATH): shutil.copy2(cls.DEFAULT_CONFIG_PATH, cls.FILE_PATH) Logger.debug("Default config copied to: {0}".format(cls.FILE_PATH)) return cls.FILE_PATH
def reload_rig_components(*args): """Reloads all modules located in in Luna_rig.components package""" avoid_reload = set("Luna_rig.core.meta, Luna_rig.core.component") to_reload = set() for mod_name in sys.modules.keys(): if "Luna_rig.components" in mod_name and "pymel" not in mod_name: to_reload.add(mod_name) for mod_name in to_reload.difference(avoid_reload): mod = sys.modules.get(mod_name) if mod: reload(mod) Logger.info("Reloaded {0}".format(mod_name))
def set(path): if not Project.is_project(path): Logger.error("Not a project: {0}".format(path)) return project_instance = Project(path) project_instance.update_meta() # Set enviroment variables and refresh HUD environFn.set_project_var(project_instance) Config.set(ProjectVars.previous_project, project_instance.path) project_instance.add_to_recent() LunaHud.refresh() return project_instance
def delete_oldest(directory, file_limit): all_files = [ "{0}/{1}".format(directory, child) for child in os.listdir(directory) ] if file_limit and len(all_files) > file_limit: try: oldest_file = min(all_files, key=os.path.getctime) os.remove(oldest_file) return oldest_file except Exception as e: Logger.exception("Failed to delete file {0}".format(oldest_file), exc_info=e) return None
def create(cls): hud_instance = None Logger.info("Building {0}...".format(cls.HUD_NAME)) # Delete old cls.remove() hud_instance = pm.headsUpDisplay(cls.HUD_NAME, section=cls.SECTION, block=cls.BLOCK, blockSize=cls.BLOCK_SIZE, labelFontSize=cls.FONT_SIZE, command=cls.getHudText, event=cls.UPDATE_EVENT) Logger.info("Successfully created HUD: {0}".format(cls.HUD_NAME)) return hud_instance
def load_json(path, string_data=False): try: with open(path, "r") as json_file: if string_data: data = json.loads(json_file) else: data = json.load(json_file) except IOError as e: Logger.exception("{0} is not a valid file path".format(path), exc_info=e) return None except BaseException: Logger.exception("Failed to load file {0}".format(path), exc_info=e) return None return data # type:dict
def delete_temp_files(cls): """Delete the temp files in the cache and clear the cache.""" # If we don't want to keep temp files around for debugging purposes, delete them when # all tests in this TestCase have been run if Config.get(TestVars.delete_dirs, True): for d in cls.dirs_created: if os.path.isdir(d): shutil.rmtree(d) Logger.info("Deleted dir: {0}".format(d)) cls.dirs_created = [] if Config.get(TestVars.delete_files, default=True): for f in cls.files_created: if os.path.exists(f): os.remove(f) Logger.info("Deleted temp file: {0}".format(f)) cls.files_created = []
def _add_external_tools(cls): register = fileFn.load_json(directories.EXTERNAL_TOOLS_REGISTER) found = set(register).intersection(set(pm.moduleInfo(lm=1))) if not found: return tools_menu = MenuUtil.addSubMenu(cls.MAIN_MENU_ID, label="External", tear_off=1, icon="") for tool in found: MenuUtil.addMenuItem( tools_menu, label=register[tool].get("label"), command=register[tool].get("command"), icon=register[tool].get("icon"), use_maya_icons=register[tool].get("useMayaIcon")) Logger.info("Added {0} to Luna >> Tools menu".format(tool))
def create(path): if Project.is_project(path): Logger.error("Already a project: {0}".format(path)) return new_project = Project(path) # Create missing meta and tag files fileFn.create_missing_dir(new_project.path) fileFn.create_file(path=new_project.tag_path) creation_date = datetime.now().strftime("%d/%m/%Y %H:%M:%S") new_project.meta_data = ("created", creation_date) # Set enviroment variables and refresh HUD environFn.set_project_var(new_project) Config.set(ProjectVars.previous_project, new_project.path) new_project.add_to_recent() LunaHud.refresh() return new_project
def write_pickle(path, data): backup_data = {} status = 1 backup_data = load_pickle(path) # Check if backup was saved if not status: return path, status try: with open(path, "w") as new_file: pickle.dump(data, new_file) except IOError: Logger.exception("Failed to saved file: {0}".format(path)) pickle.dump(backup_data, new_file) Logger.warning("Reverted backup data for {0}".format(0)) status = 0 return path, status
def addMenuItem(parent=None, label="", command=_null_command, icon="", divider=False, option_box=False, check_box=False, use_maya_icons=False, var_name=None, default_value=False): if icon and not use_maya_icons: icon = fileFn.get_icon_path(icon) if divider: return pm.menuItem(p=parent, dl=label, i=icon, d=divider) elif option_box: return pm.menuItem(p=parent, l=label, i=icon, ob=option_box, c=command) elif check_box: if not var_name: Logger.error( "Menuitem: {0}::{1} is not connected to config!".format( parent, label)) return checkBox_value = Config.get(var_name, default_value) checkBox = pm.menuItem(p=parent, l=label, i=icon, cb=checkBox_value, c=partial(Config.set, var_name)) return checkBox else: return pm.menuItem(p=parent, l=label, i=icon, c=command)
def copy_empty_scene(new_path): """Copy empty scenes from Luna's resource directory ot a given path. Scene version is based on current Maya version. Args: new_path (str): Full path to a new scene file location. Raises: IOError: If scene for selected maya version doesn't exist. """ if os.path.isfile(new_path): return source_path = os.path.join(directories.EMPTY_SCENES_PATH, "EmptyScene_Maya{0}.ma".format(pm.about(v=1))) Logger.debug("Copying file {0} to {1}".format(source_path, new_path)) if not os.path.isfile(source_path): raise IOError try: shutil.copy2(source_path, new_path) except Exception: Logger.exception("Failed to copy scene {0}".format(source_path))
def run(): # Logging Logger.write_to_rotating_file(directories.LOG_FILE, level=30) Logger.info("Logging to file: {0}".format(directories.LOG_FILE)) Logger.info("Current logging level: {0}".format(Logger.get_level(name=1))) # Luna initialization open_port(lang="python") build_luna_menu() build_luna_hud() add_luna_callbacks()
def write_json(path, data={}, as_string=False, sort_keys=True): try: with open(path, "w") as json_file: if as_string: json_file.write( json.dumps(data, sort_keys=sort_keys, indent=4, separators=(",", ":"))) else: json.dump(data, json_file, indent=4) except IOError as e: Logger.exception("{0} is not a valid file path".format(path), exc_info=e) return None except BaseException: Logger.exception("Failed to write file {0}".format(path), exc_info=1) return None return path
def set_asset_var(value): environ.data["LUNA_ASSET"] = value Logger.debug("LUNA_ASSET: {0}".format(value))
def build_luna_hud(): try: LunaHud.create() except Exception: Logger.exception("Failed to create HUD")
import pymel.core as pm from functools import partial from Luna import Logger DEBUG_MODE = Logger.get_level() == 10 try: from Luna import Config from Luna.static import directories from Luna.interface.commands import tool_cmds from Luna.interface.commands import help_cmds from Luna.utils import devFn from Luna.utils import fileFn from Luna import TestVars except Exception as e: Logger.exception("Failed to import modules", exc_info=e) if DEBUG_MODE: try: reload(tool_cmds) reload(help_cmds) reload(devFn) Logger.debug("Menu - reloaded command modules") except ImportError: Logger.exception("Failed to reload command modules") def _null_command(*args): pass class MenuUtil:
def set_project_var(value): environ.data["LUNA_PROJECT"] = value Logger.debug("LUNA_PROJECT: {0}".format(value))
def set_character_var(value): environ.data["LUNA_CHARACTER"] = value Logger.debug("LUNA_CHARACTER : {0}".format(value))
import os from collections import deque from datetime import datetime from Luna import Logger try: from Luna.utils import fileFn from Luna.utils import environFn from Luna import Config from Luna import ProjectVars from Luna.interface.hud import LunaHud except Exception: Logger.exception("Failed to import modules") class Project(object): """ Base project class. Represents rigging project """ TAG_FILE = "luna.proj" def __repr__(self): return "{0}({1}): {2}".format(self.name, self.path, self.meta_data) def __init__(self, path): self.path = path # type: str @property def name(self): name = os.path.basename(self.path) # type:str return name
def reset(cls): """ Reset config to default. Copies default config file with normal config name """ shutil.copy2(directories.DEFAULT_CONFIG_PATH, directories.CONFIG_PATH) Logger.info("Luna config reset to default")
def is_project(cls, path): search_file = os.path.join(path, cls.TAG_FILE) Logger.debug("isProject check ({0}) - {1}".format( os.path.isfile(search_file), path)) return os.path.isfile(search_file)
def open_docs(*args): Logger.debug("TODO: open Luna docs")