Ejemplo n.º 1
0
    def execute(self, context):
        # disable all wrong versions
        for mod in addon_utils.modules():
            if mod.bl_info['name'] == "Shotariya-don":
                if addon_utils.check(mod.__name__)[0]:
                    try:
                        bpy.ops.wm.addon_disable(module=mod.__name__)
                    except:
                        pass
                    continue
            if mod.bl_info['name'] == "Shotariya's Material Combiner":
                if mod.bl_info['version'] < (2, 1, 1, 2) and addon_utils.check(mod.__name__)[0]:
                    try:
                        bpy.ops.wm.addon_disable(module=mod.__name__)
                    except:
                        pass
                    continue

        # then enable correct version
        for mod in addon_utils.modules():
            if mod.bl_info['name'] == "Shotariya's Material Combiner":
                if mod.bl_info['version'] < (2, 1, 1, 2):
                    continue
                if not addon_utils.check(mod.__name__)[0]:
                    bpy.ops.wm.addon_enable(module=mod.__name__)
                    break
        self.report({'INFO'}, 'Enabled Material Combiner!')
        return {'FINISHED'}
Ejemplo n.º 2
0
def reload_addons(do_reload=True, do_reverse=True):
    modules = addon_utils.modules({})
    modules.sort(key=lambda mod: mod.__name__)
    addons = bpy.context.user_preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name)

    assert (bool(addons) == False)

    # Run twice each time.
    for i in (0, 1):
        for mod in modules:
            mod_name = mod.__name__
            print("\tenabling:", mod_name)
            addon_utils.enable(mod_name)
            assert (mod_name in addons)

        for mod in addon_utils.modules({}):
            mod_name = mod.__name__
            print("\tdisabling:", mod_name)
            addon_utils.disable(mod_name)
            assert (not (mod_name in addons))

            # now test reloading
            if do_reload:
                imp.reload(sys.modules[mod_name])

            if do_reverse:
                # incase order matters when it shouldnt
                modules.reverse()
Ejemplo n.º 3
0
def reload_addons(do_reload=True, do_reverse=True):
    modules = addon_utils.modules({})
    modules.sort(key=lambda mod: mod.__name__)
    addons = bpy.context.user_preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name)

    assert(bool(addons) == False)

    # Run twice each time.
    for i in (0, 1):
        for mod in modules:
            mod_name = mod.__name__
            print("\tenabling:", mod_name)
            addon_utils.enable(mod_name)
            assert(mod_name in addons)

        for mod in addon_utils.modules({}):
            mod_name = mod.__name__
            print("\tdisabling:", mod_name)
            addon_utils.disable(mod_name)
            assert(not (mod_name in addons))

            # now test reloading
            if do_reload:
                imp.reload(sys.modules[mod_name])

            if do_reverse:
                # in case order matters when it shouldnt
                modules.reverse()
    def execute(self, context):
        global lastError
        
        bpy.ops.addon_registry.update_database()
        
        installed_addons = {}
        for mod in addon_utils.modules(refresh=False):
            installed_addons[mod.__name__] = mod

        for name, addon in configuration["addons"].items():
            info = addon["info"]
            available_version = info["version"]

            installed_addon = installed_addons.get(name, None)
            is_installed = bool(installed_addon)
            if is_installed:
                installed_info = addon_utils.module_bl_info(installed_addon)
                installed_version = list(installed_info["version"])
                is_newer_available = is_newer_version(available_version, installed_version)
                
                if is_newer_available:
                    lastError = install(name)
                    
                    if lastError == ERROR_EXTRACT_MANUALLY:
                        return {"RUNNING_MODAL"}
                    
                    if lastError != ERROR_NONE:
                        self.report({'ERROR'}, error_titles[lastError])
                        return {'CANCELLED'}
                    
        addon_utils.modules(refresh=True)
        bpy.utils.refresh_script_paths()
        bpy.ops.script.reload()
        
        return {"FINISHED"}
	def reload_addon(self):
		# if post_update false, skip this function
		# else, unload/reload addon & trigger popup
		if self._auto_reload_post_update == False:
			print("Restart blender to reload addon and complete update")
			return

		if self._verbose: print("Reloading addon...")
		addon_utils.modules(refresh=True)
		bpy.utils.refresh_script_paths()

		# not allowed in restricted context, such as register module
		# toggle to refresh
		bpy.ops.wm.addon_disable(module=self._addon_package)
		bpy.ops.wm.addon_refresh()
		bpy.ops.wm.addon_enable(module=self._addon_package)
Ejemplo n.º 6
0
def shotariya_installed():
    installed = False
    correct_version = False

    for mod2 in addon_utils.modules():
        if mod2.bl_info.get('name') == addon_name:
            installed = True

            if mod2.bl_info.get('version') >= min_version:
                correct_version = True

    if not installed:
        bpy.ops.cats_atlas.install_shotariya_popup('INVOKE_DEFAULT',
                                                   action='INSTALL')
        print(addon_name + " not installed.")
        return False

    if not correct_version:
        bpy.ops.cats_atlas.install_shotariya_popup('INVOKE_DEFAULT',
                                                   action='VERSION')
        print(addon_name + " has wrong version.")
        return False

    try:
        bpy.ops.shotariya.list_actions('INVOKE_DEFAULT', action='CLEAR_MAT')
        bpy.ops.shotariya.list_actions('INVOKE_DEFAULT', action='ALL_MAT')
    except AttributeError:
        print(addon_name + " not enabled.")
        bpy.ops.cats_atlas.install_shotariya_popup('INVOKE_DEFAULT',
                                                   action='ENABLE')
        return False

    print(addon_name + " was successfully found!!!")
    return True
    def enable_addons():
        """For now, enable all official addons, before extracting msgids."""
        import addon_utils
        import bpy

        userpref = bpy.context.user_preferences
        used_ext = {ext.module for ext in userpref.addons}
        support = {"OFFICIAL"}
        # collect the categories that can be filtered on
        addons = [(mod, addon_utils.module_bl_info(mod)) for mod in
                  addon_utils.modules(addon_utils.addons_fake_modules)]

        for mod, info in addons:
            module_name = mod.__name__
            if module_name in used_ext or info["support"] not in support:
                continue
            print("    Enabling module ", module_name)
            bpy.ops.wm.addon_enable(module=module_name)

        # XXX There are currently some problems with bpy/rna...
        #     *Very* tricky to solve!
        #     So this is a hack to make all newly added operator visible by
        #     bpy.types.OperatorProperties.__subclasses__()
        for cat in dir(bpy.ops):
            cat = getattr(bpy.ops, cat)
            for op in dir(cat):
                getattr(cat, op).get_rna()
Ejemplo n.º 8
0
def check_for_smc():
    global draw_smc_ui, old_smc_version, smc_is_disabled, found_very_old_smc

    draw_smc_ui = None
    found_very_old_smc = False

    for mod in addon_utils.modules():
        if mod.bl_info['name'] == "Shotariya-don":
            if hasattr(bpy.context.scene, 'shotariya_tex_idx'):
                found_very_old_smc = True
            continue
        if mod.bl_info['name'] == "Shotariya's Material Combiner":
            # print(mod.__name__, mod.bl_info['version'])
            # print(addon_utils.check(mod.__name__))
            if mod.bl_info['version'] < (2, 1, 1, 2):
                old_smc_version = True
                # print('TOO OLD!')
                continue
            if not addon_utils.check(mod.__name__)[0]:
                smc_is_disabled = True
                # print('DISABLED!')
                continue

            # print('FOUND!')
            old_smc_version = False
            smc_is_disabled = False
            found_very_old_smc = False
            draw_smc_ui = getattr(import_module(mod.__name__ + '.operators.ui.include'), 'draw_ui')
            break
    def draw(self, context):
        layout = self.layout

        layout.label(text='Otoy')
        layout.operator('wm.url_open', icon='URL',
                        text='Documents').url = 'https://docs.otoy.com'
        layout.operator(
            'wm.url_open', icon='URL',
            text='Forum').url = 'https://render.otoy.com/forum/index.php'
        layout.operator(
            'wm.url_open', icon='URL', text='General'
        ).url = 'https://render.otoy.com/forum/viewforum.php?f=9'
        layout.operator(
            'wm.url_open', icon='URL', text='Blender'
        ).url = 'https://render.otoy.com/forum/viewforum.php?f=32'
        layout.separator()

        layout.label(text='Connect')
        layout.operator(
            'wm.url_open', icon='URL', text='Releases'
        ).url = 'https://render.otoy.com/forum/viewforum.php?f=113'
        layout.operator(
            'wm.url_open', icon='URL', text='Bug Reports'
        ).url = 'https://render.otoy.com/forum/viewforum.php?f=114'
        layout.operator(
            'wm.url_open', icon='URL', text='User Requests'
        ).url = 'https://render.otoy.com/forum/viewforum.php?f=115'
        layout.operator(
            'wm.url_open', icon='URL', text='Facebook Group'
        ).url = 'https://www.facebook.com/groups/500738480259364'
        layout.separator()

        layout.label(text='Resources')
        layout.operator('wm.url_open', icon='URL',
                        text='ArtStation').url = 'https://www.artstation.com/'
        layout.operator('wm.url_open', icon='URL',
                        text='Pinterest').url = 'https://www.pinterest.com/'
        layout.operator('wm.url_open', icon='URL',
                        text='Behance').url = 'https://www.behance.net/'
        layout.operator('wm.url_open', icon='URL',
                        text='HDRIHaven').url = 'https://hdrihaven.com/hdris/'
        layout.operator('wm.url_open', icon='URL',
                        text='CC0 Textures').url = 'https://cc0textures.com/'
        layout.separator()

        layout.label(text='Plugin')
        layout.operator(
            'wm.url_open', icon='URL', text='Wiki'
        ).url = 'https://github.com/Yichen-Dou/OC-Blender-Helper-Addon'
        layout.operator(
            'wm.url_open', icon='URL', text='Downloads'
        ).url = 'https://github.com/Yichen-Dou/OC-Blender-Helper-Addon/releases'
        layout.separator()

        version = [
            addon.bl_info['version'] for addon in addon_utils.modules()
            if (addon.bl_info['name'] == 'Octane Helper')
        ][0]
        layout.label(
            text='Ver.{}.{}.{}'.format(version[0], version[1], version[2]))
Ejemplo n.º 10
0
def get_addon(addon, debug=False):
    """
    look for addon by name and find folder name and path
    Note, this will also find addons that aren't registered!
    """
    import addon_utils

    for mod in addon_utils.modules():
        name = mod.bl_info["name"]
        version = mod.bl_info.get("version", None)
        foldername = mod.__name__
        path = mod.__file__
        enabled = addon_utils.check(foldername)[1]

        if name == addon:
            if debug:
                print(name)
                print("  enabled:", enabled)
                print("  folder name:", foldername)
                print("  version:", version)
                print("  path:", path)
                print()

            return enabled, foldername, version, path
    return None, None, None, None
 def update_addon(self, context):
     if self.addon:
         for mod in addon_utils.modules(refresh=False):
             if mod.__file__ == self.addon:
                 self.text_ctxt = mod.__name__
                 break
     return None
Ejemplo n.º 12
0
 def execute(self, context):
     for mod in addon_utils.modules():
         if mod.bl_info['name'] == "Shotariya's Material Combiner":
             bpy.ops.wm.addon_enable(module=mod.__name__)
             break
     self.report({'INFO'}, 'Enabled Material Combiner!')
     return {'FINISHED'}
Ejemplo n.º 13
0
def register():

    for mod in addon_utils.modules():
        if mod.bl_info.get('name', (-1, -1, -1)) == "Rigify":
            if not addon_utils.check(mod.__name__)[1]:
                addon_utils.enable(mod.__name__,
                                   default_set=True,
                                   handle_error=None)

    for cls in classes:
        bpy.utils.register_class(cls)

    wm = bpy.context.window_manager
    kc = wm.keyconfigs.addon

    if kc:

        km = kc.keymaps.new(name="3D View", space_type="VIEW_3D")
        kmi = km.keymap_items.new("wm.call_menu",
                                  type="A",
                                  value="PRESS",
                                  shift=True,
                                  ctrl=True)
        kmi.properties.name = "RIGIFY_PARTS_MT_add_master_menu"
        addon_keymaps.append([km, kmi])
Ejemplo n.º 14
0
def get_addon(addon, debug=False):
    """
    look for addon by name
    return registration status, foldername, version and path
    """
    import addon_utils

    for mod in addon_utils.modules():
        name = mod.bl_info["name"]
        version = mod.bl_info.get("version", None)
        foldername = mod.__name__
        path = mod.__file__
        enabled = addon_utils.check(foldername)[1]

        if name == addon:
            if debug:
                print(name)
                print("  enabled:", enabled)
                print("  folder name:", foldername)
                print("  version:", version)
                print("  path:", path)
                print()

            return enabled, foldername, version, path
    return False, None, None, None
Ejemplo n.º 15
0
def addon_modules_sorted():
    modules = addon_utils.modules({})
    modules[:] = [
        mod for mod in modules if not mod.__file__.startswith(BLACKLIST_DIRS)
    ]
    modules.sort(key=lambda mod: mod.__name__)
    return modules
Ejemplo n.º 16
0
    def reload_addon(self):
        # if post_update false, skip this function
        # else, unload/reload addon & trigger popup
        if self._auto_reload_post_update == False:
            print("Restart blender to reload addon and complete update")
            return

        if self._verbose: print("Reloading addon...")
        addon_utils.modules(refresh=True)
        bpy.utils.refresh_script_paths()

        # not allowed in restricted context, such as register module
        # toggle to refresh
        bpy.ops.wm.addon_disable(module=self._addon_package)
        bpy.ops.wm.addon_refresh()
        bpy.ops.wm.addon_enable(module=self._addon_package)
Ejemplo n.º 17
0
    def execute(self, context):
        bpy.ops.screen.userpref_show('INVOKE_AREA')
        util.get_preferences(context).active_section = "ADDONS"
        bpy.data.window_managers["WinMan"].addon_search = "MCprep"

        addons_ids = [
            mod for mod in addon_utils.modules(refresh=False)
            if mod.__name__ == __package__
        ]
        addon_blinfo = addon_utils.module_bl_info(addons_ids[0])
        if not addon_blinfo["show_expanded"]:
            if hasattr(bpy.ops, "preferences") and hasattr(
                    bpy.ops.preferences,
                    "addon_expand") and util.bv28():  # later 2.8 buids
                bpy.ops.preferences.addon_expand(module=__package__)
            elif hasattr(bpy.ops, "wm") and hasattr(
                    bpy.ops.wm, "addon_expand"):  # old 2.8 and 2.7
                bpy.ops.wm.addon_expand(module=__package__)
            else:
                self.report(
                    {"INFO"},
                    "Search for and expand the MCprep addon in preferences")

        addon_prefs = util.get_user_preferences(context)
        addon_prefs.preferences_tab = self.tab
        return {'FINISHED'}
Ejemplo n.º 18
0
 def addon_version(self):
     for mod in addon_utils.modules():
         if mod.bl_info.get('name') == 'GoB':
             n = self.extract_numbers(
                 str(mod.bl_info.get('version', (-1, -1, -1))))
             version = "v" + str(n[0]) + "_" + str(n[1]) + "_" + str(n[2])
             return version
Ejemplo n.º 19
0
def DDSAddManPanel(context, layout, mode='non-panel'):
    #Addon Settings
    addons = [(mod, addon_utils.module_bl_info(mod))
              for mod in addon_utils.modules(refresh=False)]
    col = layout.column(align=True)
    AC = -1
    for Mod_Name in AO:
        AC = AC + 1
        #Go through list of all addons
        for Mod, info in addons:
            #Check to see if Addon exist
            if (Mod.__name__ == Mod_Name):
                is_enabled = context.preferences.addons.find(Mod_Name)

                if is_enabled > -1:
                    col.operator("preferences.addon_disable",
                                 icon='CHECKBOX_HLT',
                                 text=AN[AC],
                                 emboss=True).module = Mod_Name
                else:
                    col.operator("preferences.addon_enable",
                                 icon='CHECKBOX_DEHLT',
                                 text=AN[AC],
                                 emboss=True).module = Mod_Name

                break
Ejemplo n.º 20
0
class CompositorDiscCachePrefs(bpy.types.AddonPreferences):
    bl_idname = __package__

    for mod in addon_utils.modules():
        if mod.bl_info['name'] == "Compositor Disc Cache":
            filepath = mod.__file__

    if platform == "win32":
        templatepath= str(Path(filepath).parent) + str(Path('/Template/Comp_VSE_Template.blend'))
    else:
        templatepath= str(Path(filepath).parent) + str(Path('/Template/Comp_VSE_Template.blend'))
    
    
    templatefilepath: bpy.props.StringProperty(
        name="Blender Template",
        subtype='FILE_PATH',
        default = str(templatepath)
    )

    templatename: bpy.props.StringProperty(
    name="Blender Template",
    # subtype='FILE_PATH',
    default = "Comp_VSE"
    )


    def draw(self, context):
        layout = self.layout
        layout.label(text="""Blender file path to import the template from""")
        layout.prop(self, "templatefilepath")
        layout.label(text="""The template to import""")
        layout.prop(self, "templatename")
    def enable_addons():
        """For now, enable all official addons, before extracting msgids."""
        import addon_utils
        import bpy

        userpref = bpy.context.user_preferences
        used_ext = {ext.module for ext in userpref.addons}
        support = {"OFFICIAL"}
        # collect the categories that can be filtered on
        addons = [(mod, addon_utils.module_bl_info(mod)) for mod in
                  addon_utils.modules(addon_utils.addons_fake_modules)]

        for mod, info in addons:
            module_name = mod.__name__
            if module_name in used_ext or info["support"] not in support:
                continue
            print("    Enabling module ", module_name)
            bpy.ops.wm.addon_enable(module=module_name)

        # XXX There are currently some problems with bpy/rna...
        #     *Very* tricky to solve!
        #     So this is a hack to make all newly added operator visible by
        #     bpy.types.OperatorProperties.__subclasses__()
        for cat in dir(bpy.ops):
            cat = getattr(bpy.ops, cat)
            for op in dir(cat):
                getattr(cat, op).get_rna()
Ejemplo n.º 22
0
 def __init__(self):
     # get version and github_path
     for mod in addon_utils.modules():
         if mod.bl_info.get("name", "") == addon_name:
             self.version = mod.bl_info.get("version", "")
             self.github_path = mod.bl_info.get("tracker_url", "")
             break
     self.txt_name = addon_name + "_error_report.txt"
Ejemplo n.º 23
0
def enable_addons(addon_list):
  """Ensure that the Floored addons are enabled and refreshed

  Raises an error if an addon can't be enabled.

  """

  _log.info("entering")

  # This is needed to successfully run this as a background script if
  # the user addons path didn't already exist
  bpy.utils.refresh_script_paths()

  addon_utils.modules(refresh=True)

  for a in addon_list:
    enable_named_addon(a)
Ejemplo n.º 24
0
 def __init__(self):
     # get version and github_path
     for mod in addon_utils.modules():
         if mod.bl_info.get("name", "") == addon_name:
             self.version = mod.bl_info.get("version", "")
             self.github_path = mod.bl_info.get("tracker_url", "")
             break
     self.txt_name = addon_name + "_error_report.txt"
Ejemplo n.º 25
0
def addon_modules_sorted():
    modules = addon_utils.modules({})
    modules[:] = [
            mod for mod in modules
            if not (mod.__file__.startswith(BLACKLIST_DIRS))
            if not (mod.__name__ in BLACKLIST_ADDONS)]
    modules.sort(key=lambda mod: mod.__name__)
    return modules
Ejemplo n.º 26
0
    def execute(self, context):
        global lastError

        addon_name = str(self.addon_name)
        lastError = install(addon_name)

        if lastError == ERROR_EXTRACT_MANUALLY:
            return {"RUNNING_MODAL"}

        if lastError != ERROR_NONE:
            self.report({'ERROR'}, error_titles[lastError])
            return {'CANCELLED'}

        addon_utils.modules(refresh=True)
        bpy.utils.refresh_script_paths()
        bpy.ops.script.reload()

        return {'FINISHED'}
Ejemplo n.º 27
0
def get_binary_module_desc():
    for mod in addon_utils.modules(refresh=False):
        if mod.bl_info['name'] == 'Blend4Web':
            init_script_path = mod.__file__
            break
    libname = "b4w_bin" + get_platform_suffix()
    path = os.path.dirname(os.path.abspath(init_script_path))

    # Move the binary into 'temp' dir and link it from that path
    filename = libname + ".so"
    if libname.find("Windows") >= 0:
        filename = libname + ".pyd"
    v1 = bpy.app.version[0]
    v2 = bpy.app.version[1]
    lower = False
    higher = False
    filepath = ""
    while True:
        filepath = os.path.join(path, "bin", str(v1) + "_" + str(v2), filename)
        if not os.path.exists(filepath):
            # at least 2.76 version is always present
            if v1 < 2 or (v1 == 2 and v2 < 76):
                higher = True
                v1 = 2
                v2 = 76
            else:
                lower = True
                v2 -= 1
        else:
            break

    if lower:
        blend4web.init_mess.append(
            _("Using low version of Blend4Web binary module. Blend4Web update is recommended!"
              ))
    if higher:
        blend4web.init_mess.append(
            _("Using high version of Blend4Web binary module. Blender update is recommended!"
              ))

    tempdir = bpy.app.tempdir
    if tempdir == "":
        tempdir = os.path.join(path, "..", "temp")
    ensure_dir(tempdir)
    copy_filepath = os.path.join(tempdir, filename)

    # cleanup old copies
    files = [f for f in os.listdir(tempdir) if re.match(filename + r'.*', f)]
    for f in files:
        rmfile = os.path.join(tempdir, f)
        try:
            os.remove(rmfile)
        except BaseException:
            pass

    binary_path = make_file_copy(filepath, copy_filepath)
    return (libname, binary_path)
Ejemplo n.º 28
0
def reload_scripts():
    for mod in addon_utils.modules():
        if mod.bl_info['name'] == 'Cats Blender Plugin':
            # importlib.reload(mod)
            # bpy.ops.wm.addon_enable(module=mod.__name__)
            # bpy.ops.preferences.addon_disable(module=mod.__name__)
            # bpy.ops.preferences.addon_enable(module=mod.__name__)
            bpy.ops.script.reload()
            break
Ejemplo n.º 29
0
 def ListAddons(self, _):
     user_scripts_path = bpy.utils.user_resource('SCRIPTS')
     return {v.__name__: {
         'is_enabled': addon_utils.check(v.__name__)[0],
         'is_loaded': addon_utils.check(v.__name__)[1],
         'is_user_addon': v.__file__.startswith(user_scripts_path),
         'path': v.__file__ if not v.__file__.endswith('/__init__.py') else v.__file__[:-11],
         'info': v.bl_info
     } for v in addon_utils.modules()}
 def execute(self, context):
     global lastError
     
     addon_name = str(self.addon_name)
     lastError = install(addon_name)
     
     if lastError == ERROR_EXTRACT_MANUALLY:
         return {"RUNNING_MODAL"}
     
     if lastError != ERROR_NONE:
         self.report({'ERROR'}, error_titles[lastError])
         return {'CANCELLED'}
     
     addon_utils.modules(refresh=True)
     bpy.utils.refresh_script_paths()
     bpy.ops.script.reload()
     
     return {'FINISHED'}
Ejemplo n.º 31
0
def addon_modules_sorted():
    # Pass in an empty module cache to prevent `addon_utils` local module cache being manipulated.
    modules = addon_utils.modules(module_cache={})
    modules[:] = [
        mod for mod in modules if not (mod.__file__.startswith(BLACKLIST_DIRS))
        if not (mod.__name__ in BLACKLIST_ADDONS)
    ]
    modules.sort(key=lambda mod: mod.__name__)
    return modules
    def setupCleanBlenderEnvironment(self):
        name = 'arx_addon'

        import addon_utils
        from bpy import context

        # Disable the module first to prevent log spam
        for module in addon_utils.modules():
            if module.__name__ == name:
                is_enabled, is_loaded = addon_utils.check(name)
                if is_loaded:
                    addon_utils.disable(name)

        #bpy.ops.wm.read_homefile()
        bpy.ops.wm.read_factory_settings()

        #addon_utils.modules_refresh()

        moduleFound = False
        for module in addon_utils.modules():
            if module.__name__ == name:
                default, enable = addon_utils.check(name)
                if not enable:
                    addon_utils.enable(name,
                                       default_set=True,
                                       persistent=False,
                                       handle_error=None)
                    context.user_preferences.addons[
                        name].preferences.arxAssetPath = self.dataDirectory
                moduleFound = True

        if not moduleFound:
            raise Exception("Addon not found: {0}".format(name))

        # Cleanup the default scene
        def removeObj(name):
            defaultCube = bpy.context.scene.objects.get(name)
            if defaultCube:
                defaultCube.select = True
                bpy.ops.object.delete()

        removeObj('Cube')
        removeObj('Camera')
        removeObj('Lamp')
Ejemplo n.º 33
0
 def path_from_addon(module):
     for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules):
         if mod.__name__ == module:
             filepath = mod.__file__
             if os.path.exists(filepath):
                 if os.path.splitext(os.path.basename(filepath))[0] == "__init__":
                     return os.path.dirname(filepath), True
                 else:
                     return filepath, False
     return None, False
Ejemplo n.º 34
0
    def read_add_ons(self):
        """Przypisuje do pola *add_ons* słownik zawierający listę zaintalowanych wtyczek:
        ich nazwy i numery wersji.
        """

        self.add_ons = []
        for mod in addon_utils.modules():
            self.add_ons.append(
                dict(version=mod.bl_info.get('version'),
                     name=mod.bl_info.get('name')))
 def path_from_addon(module):
     for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules):
         if mod.__name__ == module:
             filepath = mod.__file__
             if os.path.exists(filepath):
                 if os.path.splitext(os.path.basename(filepath))[0] == "__init__":
                     return os.path.dirname(filepath), True
                 else:
                     return filepath, False
     return None, False
Ejemplo n.º 36
0
 def get_application_version(self):
     return ".".join(
         [
             str(x)
             for x in [
                 addon.bl_info.get("version", (-1, -1, -1))
                 for addon in addon_utils.modules()
                 if addon.bl_info["name"] == "BlenderBIM"
             ][0]
         ]
     )
Ejemplo n.º 37
0
def get_installed_addons():
    """获取用户安装的插件信息。

    key: 插件模块名称
    value: dict() bl_info 内容字典
    """
    import addon_utils
    addons = dict()
    for mod in addon_utils.modules():
        addons[mod.__name__] = mod.bl_info
    return addons
Ejemplo n.º 38
0
def addon_version() -> str:
    """
    Gets the addon version.

    Returns:
        str: A formatted version string.
    """
    for mod in addon_utils.modules():
        if mod.bl_info["name"] == "NICO Export":
            version = mod.bl_info.get("version", (0, 0))
            return f"v{version[0]}.{version[1]}"
Ejemplo n.º 39
0
def get_binary_module_desc():
    for mod in addon_utils.modules(refresh=False):
        if mod.bl_info['name'] == 'Blend4Web':
            init_script_path = mod.__file__
            break
    libname = "b4w_bin" + get_platform_suffix()
    path = os.path.dirname(os.path.abspath(init_script_path))

    # Move the binary into 'temp' dir and link it from that path
    filename = libname + ".so"
    if libname.find("Windows") >= 0:
        filename = libname + ".pyd"
    v1 = bpy.app.version[0]
    v2 = bpy.app.version[1]
    lower = False
    higher = False
    filepath = ""
    while True:
        filepath = os.path.join(path, "bin", str(v1) + "_" + str(v2), filename)
        if not os.path.exists(filepath):
            # at least 2.76 version is always present
            if v1 < 2 or (v1 == 2 and v2 < 76):
                higher = True
                v1 = 2
                v2 = 76
            else:
                lower = True
                v2 -= 1
        else:
            break

    if lower:
        blend4web.init_mess.append(_("Using low version of Blend4Web binary module. Blend4Web update is recommended!"))
    if higher:
        blend4web.init_mess.append(_("Using high version of Blend4Web binary module. Blender update is recommended!"))

    tempdir = bpy.app.tempdir
    if tempdir == "":
        tempdir = os.path.join(path, "..", "temp")
    ensure_dir(tempdir)
    copy_filepath = os.path.join(tempdir, filename)

    # cleanup old copies
    files = [f for f in os.listdir(tempdir) if re.match(filename + r'.*', f)]
    for f in files:
        rmfile = os.path.join(tempdir, f)
        try:
            os.remove(rmfile)
        except BaseException:
            pass

    binary_path = make_file_copy(filepath, copy_filepath)
    return (libname, binary_path)
Ejemplo n.º 40
0
    def reload_addon(self):
        if self._auto_reload_post_update == False:
            print("Restart blender to reload")
            return



        if self._verbose:print("Reloading addon...")
        addon_utils.modules(refresh=True)
        bpy.utils.refresh_script_paths()

        # not allowed in restricted context, such as register module
        # toggle to refresh
        bpy.ops.wm.addon_disable(module=self._addon_package)

        bpy.ops.wm.addon_refresh()
        # consider removing cached files
        # __pycache__
        # try:
        # 	shutil//
        bpy.ops.wm.addon_enable(module=self._addon_package)
Ejemplo n.º 41
0
def register():
    print("-------------REGISTER SORCAR-------------")
    path = repr([
        i for i in addon_utils.modules() if i.bl_info['name'] == "Sorcar"
    ][0]).split("from '")[1].split("__init__.py'>")[0]
    classes_ops = import_ops(path)
    classes_sockets = import_sockets(path)
    classes_ui = import_ui(path)
    classes_nodes = import_nodes(path)

    global all_classes, addon_keymaps
    all_classes = [ScNodeTree]
    all_classes.extend(classes_ops)
    all_classes.extend(classes_sockets)
    all_classes.extend(classes_ui)
    all_classes.append(SorcarPreferences)

    total_nodes = 0
    node_categories = []
    for cat in classes_nodes:
        total_nodes += len(classes_nodes[cat])
        node_categories.append(
            ScNodeCategory(
                identifier="sc_" + cat,
                name=bpy.path.display_name(cat),
                items=[NodeItem(i.bl_idname) for i in classes_nodes[cat]]))
        all_classes.extend(classes_nodes[cat])

    for i in all_classes:
        bpy.utils.register_class(i)
    nodeitems_utils.register_node_categories("sc_node_categories",
                                             node_categories)
    if not (update_each_frame in bpy.app.handlers.frame_change_post):
        bpy.app.handlers.frame_change_post.append(update_each_frame)

    if (not bpy.app.background):
        kc = bpy.context.window_manager.keyconfigs.addon
        km = kc.keymaps.new(name="Node Generic", space_type='NODE_EDITOR')
        kmi = [
            km.keymap_items.new("sorcar.execute_node", 'E', 'PRESS'),
            km.keymap_items.new("sorcar.group_nodes", 'G', 'PRESS', ctrl=True),
            km.keymap_items.new("sorcar.edit_group", 'TAB', 'PRESS')
        ]
        for k in kmi:
            k.active = True
            addon_keymaps.append((km, k))

    addon_updater_ops.register(bl_info)

    print_log("REGISTERED",
              msg="{} operators, {} sockets, {} UI & {} nodes ({} categories)".
              format(len(classes_ops), len(classes_sockets), len(classes_ui),
                     total_nodes, len(classes_nodes)))
Ejemplo n.º 42
0
    def setupCleanBlenderEnvironment(self):
        name = 'arx_addon'

        import addon_utils
        from bpy import context

        # Disable the module first to prevent log spam
        for module in addon_utils.modules():
            if module.__name__ == name:
                is_enabled, is_loaded = addon_utils.check(name)
                if is_loaded:
                    addon_utils.disable(name)

        #bpy.ops.wm.read_homefile()
        bpy.ops.wm.read_factory_settings()

        #addon_utils.modules_refresh()

        moduleFound = False
        for module in addon_utils.modules():
            if module.__name__ == name:
                default, enable = addon_utils.check(name)
                if not enable:
                    addon_utils.enable(name, default_set=True, persistent=False, handle_error=None)
                    context.user_preferences.addons[name].preferences.arxAssetPath = self.dataDirectory
                moduleFound = True

        if not moduleFound:
            raise Exception("Addon not found: {0}".format(name))

        # Cleanup the default scene
        def removeObj(name):
            defaultCube = bpy.context.scene.objects.get(name)
            if defaultCube:
                defaultCube.select = True
                bpy.ops.object.delete()

        removeObj('Cube')
        removeObj('Camera')
        removeObj('Lamp')
Ejemplo n.º 43
0
    def loadAddon(self, name, version):
        import addon_utils

        for module in addon_utils.modules():
            if module.__name__ == name:
                if version == module.bl_info['version']:
                    print("Enabling addon: {0}".format(name))
                    addon_utils.enable(name, default_set=True, persistent=False, handle_error=None)
                    return
                else:
                    raise Exception("Unexpected addon version: {0}".format(str(module.bl_info['version'])))

        raise Exception("Addon not found: {0}".format(name))
Ejemplo n.º 44
0
    def path_from_addon(module):
        import os
        import addon_utils

        for mod in addon_utils.modules():
            if mod.__name__ == module:
                filepath = mod.__file__
                if os.path.exists(filepath):
                    if os.path.splitext(os.path.basename(filepath))[0] == "__init__":
                        return os.path.dirname(filepath), True
                    else:
                        return filepath, False
        return None, False
Ejemplo n.º 45
0
def load_addons():
    modules = addon_utils.modules({})
    modules.sort(key=lambda mod: mod.__name__)
    addons = bpy.context.user_preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name)

    assert(bool(addons) == False)

    for mod in modules:
        mod_name = mod.__name__
        addon_utils.enable(mod_name)
        assert(mod_name in addons)
Ejemplo n.º 46
0
def _init_addon_blacklist():

    # in case we built without cycles
    if not bpy.app.build_options.cycles:
        BLACKLIST_ADDONS.add("cycles")

    # in case we built without freestyle
    if not bpy.app.build_options.freestyle:
        BLACKLIST_ADDONS.add("render_freestyle_svg")

    # netrender has known problems re-registering
    BLACKLIST_ADDONS.add("netrender")

    for mod in addon_utils.modules():
        if addon_utils.module_bl_info(mod)['blender'] < (2, 80, 0):
            BLACKLIST_ADDONS.add(mod.__name__)
Ejemplo n.º 47
0
 def draw(self, context):
     import addon_utils
     
     layout = self.layout
     
     userpref = context.user_preferences
     used_ext = {ext.module for ext in userpref.addons}
     
     for mod in addon_utils.modules(refresh=False):
         if mod.bl_info['category'] == 'Library Add-on':
             if mod.__name__ in used_ext:
                 layout.operator('wm.addon_disable',text=mod.bl_info["name"],icon='CHECKBOX_HLT').module = mod.__name__
             else:
                 layout.operator('wm.addon_enable',text=mod.bl_info["name"],icon='CHECKBOX_DEHLT').module = mod.__name__
     layout.separator()
     layout.operator('wm.save_userpref',text="Save User Preferences",icon='FILE_TICK')
Ejemplo n.º 48
0
    def addon_filter_items(self, context):
        import addon_utils

        items = [('All', "All", ""),
                 ('Enabled', "Enabled", ""),
                 ('Disabled', "Disabled", ""),
                ]

        items_unique = set()

        for mod in addon_utils.modules(addon_utils.addons_fake_modules):
            info = addon_utils.module_bl_info(mod)
            items_unique.add(info["category"])

        items.extend([(cat, cat, "") for cat in sorted(items_unique)])
        return items
Ejemplo n.º 49
0
    def addon_filter_items(self, context):
        import addon_utils

        items = [('All', "All", "All Add-ons"),
                 ('User', "User", "All Add-ons Installed by User"),
                 ('Enabled', "Enabled", "All Enabled Add-ons"),
                 ('Disabled', "Disabled", "All Disabled Add-ons"),
                 ]

        items_unique = set()

        for mod in addon_utils.modules(refresh=False):
            info = addon_utils.module_bl_info(mod)
            items_unique.add(info["category"])

        items.extend([(cat, cat, "") for cat in sorted(items_unique)])
        return items
Ejemplo n.º 50
0
    def execute(self, context):
        import addon_utils

        module_name = self.module

        _modules = addon_utils.modules(refresh=False)
        mod = addon_utils.addons_fake_modules.get(module_name)
        if mod is not None:
            info = addon_utils.module_bl_info(mod)
            info["show_expanded"] = True

            context.preferences.active_section = 'ADDONS'
            context.window_manager.addon_filter = 'All'
            context.window_manager.addon_search = info["name"]
            bpy.ops.screen.userpref_show('INVOKE_DEFAULT')

        return {'FINISHED'}
    def addon_filter_items(self, context):
        import addon_utils

        items = [
            ("All", "All", "All Addons"),
            ("New Version Available", "New Version Available", "All New Version Available Addons"),
            ("Installed", "Installed", "All Installed Addons"),
            ("Not Installed", "Not Installed", "All Not Installed Addons")
        ]

        items_unique = set()

        for mod in addon_utils.modules(refresh=False):
            info = addon_utils.module_bl_info(mod)
            items_unique.add(info["category"])

        items.extend([(cat, cat, "") for cat in sorted(items_unique)])
        return items
Ejemplo n.º 52
0
    def draw(self, context):
        layout = self.layout
        # align just to pack more tightly
        col = layout.box().column(align=True)

        workspace = context.workspace
        prefs = context.preferences

        col.active = workspace.use_filter_by_owner

        import addon_utils
        addon_map = {mod.__name__: mod for mod in addon_utils.modules()}
        owner_ids = {owner_id.name for owner_id in workspace.owner_ids}

        for addon in prefs.addons:
            module_name = addon.module
            info = addon_utils.module_bl_info(addon_map[module_name])
            if not info["use_owner"]:
                continue
            is_enabled = module_name in owner_ids
            row = col.row()
            row.operator(
                "wm.owner_disable" if is_enabled else "wm.owner_enable",
                icon='CHECKBOX_HLT' if is_enabled else 'CHECKBOX_DEHLT',
                text="",
                emboss=False,
            ).owner_id = module_name
            row.label(text="%s: %s" % (info["category"], info["name"]))
            if is_enabled:
                owner_ids.remove(module_name)

        # Detect unused
        if owner_ids:
            layout.label(text="Unknown add-ons", icon='ERROR')
            col = layout.box().column(align=True)
            for module_name in sorted(owner_ids):
                row = col.row()
                row.operator(
                    "wm.owner_disable",
                    icon='CHECKBOX_HLT',
                    text="",
                    emboss=False,
                ).owner_id = module_name
                row.label(text=module_name)
Ejemplo n.º 53
0
def detect_sdk():
    init_script_path = None
    for mod in addon_utils.modules(refresh=False):
        if mod.bl_info['name'] == 'Blend4Web':
            init_script_path = mod.__file__
            break

    if not init_script_path:
        return None

    signaure_file_path = os.path.join(
        os.path.dirname(os.path.abspath(init_script_path)), "..", "..", "..", "VERSION")
    result = None
    try:
        with open(signaure_file_path) as f:
            lines = f.readlines()
        params = lines[0].split()
        if not params[0] == "Blend4Web":
            return None
        # parse version
        v_split = params[1].split(".")
        version = []

        try:
            for v in v_split:
                version.append(int(v))
        except ValueError:
            return None
        vl_info_ver = mod.bl_info['version']

        # extend if lengths not equals
        for i in range(len(vl_info_ver) - len(version)):
            version.append(0)

        for i in range(len(vl_info_ver)):
            if not vl_info_ver[i] == version[i]:
                return None

        result = os.path.dirname(os.path.realpath(os.path.normpath(signaure_file_path)))
    except:
        return None

    return result
Ejemplo n.º 54
0
	def execute(self, context):
		bpy.ops.screen.userpref_show('INVOKE_AREA')
		util.get_preferences(context).active_section = "ADDONS"
		bpy.data.window_managers["WinMan"].addon_search = "MCprep"

		addons_ids = [mod for mod in addon_utils.modules(refresh=False)
						if mod.__name__ == __package__]
		addon_blinfo = addon_utils.module_bl_info(addons_ids[0])
		if not addon_blinfo["show_expanded"]:
			if hasattr(bpy.ops, "wm") and hasattr(bpy.ops.wm, "addon_expand"): # old 2.8 and 2.7
				bpy.ops.wm.addon_expand(module=__package__)
			elif hasattr(bpy.ops, "preferences") and hasattr(bpy.ops.preferences, "addon_expand"): # later 2.8 buids
				bpy.ops.preferences.addon_expand(module=__package__)
			else:
				self.report({"INFO"}, "Navigate to the MCprep addon in preferences")

		addon_prefs = util.get_user_preferences(context)
		addon_prefs.preferences_tab = self.tab
		return {'FINISHED'}
Ejemplo n.º 55
0
def enum_addons(self, context):
    global _cached_enum_addons
    setts = getattr(self, "settings", settings.settings)
    if not _cached_enum_addons:
        for mod in addon_utils.modules(addon_utils.addons_fake_modules):
            mod_info = addon_utils.module_bl_info(mod)
            # Skip OFFICIAL addons, they are already translated in main i18n system (together with Blender itself).
            if mod_info["support"] in {'OFFICIAL'}:
                continue
            src = mod.__file__
            if src.endswith("__init__.py"):
                src = os.path.dirname(src)
            has_translation, _ = utils_i18n.I18n.check_py_module_has_translations(src, setts)
            name = mod_info["name"]
            if has_translation:
                name = name + " *"
            _cached_enum_addons.append((mod.__name__, name, mod_info["description"]))
        _cached_enum_addons.sort(key=lambda i: i[1])
    return _cached_enum_addons
	def execute(self, context):
		import addon_utils
		my_info = None
		for module in addon_utils.modules():
			info = addon_utils.module_bl_info(module)
			if info['name'] == common.addon_name:
				my_info = info
				break
		area = common.get_request_area(context, 'USER_PREFERENCES')
		if area and my_info:
			context.user_preferences.active_section = 'ADDONS'
			context.window_manager.addon_search = my_info['name']
			context.window_manager.addon_filter = 'All'
			if 'COMMUNITY' not in context.window_manager.addon_support:
				context.window_manager.addon_support = {'OFFICIAL', 'COMMUNITY'}
			if not my_info['show_expanded']:
				bpy.ops.wm.addon_expand(module=__name__.split('.')[0])
		else:
			self.report(type={'ERROR'}, message="表示できるエリアが見つかりませんでした")
			return {'CANCELLED'}
		return {'FINISHED'}
Ejemplo n.º 57
0
def get_binary_module_desc():
    for mod in addon_utils.modules(refresh=False):
        if mod.bl_info['name'] == 'Blend4Web':
            init_script_path = mod.__file__
            break
    libname = "b4w_bin" + get_platform_suffix()
    path = os.path.dirname(os.path.abspath(init_script_path))
    binary_path = os.path.join(path, libname + ".so")

    # For windows move the binary into 'temp' dir and link it from that path
    if libname.find("Windows") >= 0:
        filename = libname + ".pyd"
        filepath = os.path.join(path,filename)
        tempdir = tempfile.gettempdir()
        if tempdir is None:
            tempdir = os.path.join(path, "..", "temp")
        ensure_dir(tempdir)
        copy_filepath = os.path.join(tempdir, filename)
        binary_path = make_file_copy(filepath, copy_filepath)

    return (libname, binary_path)
Ejemplo n.º 58
0
def enable_addons(addons={}, support={}, disable=False):
    """
    Enable (or disable) addons based either on a set of names, or a set of 'support' types.
    Returns the list of all affected addons (as fake modules)!
    """
    import addon_utils
    import bpy

    userpref = bpy.context.user_preferences
    used_ext = {ext.module for ext in userpref.addons}

    ret = [mod for mod in addon_utils.modules(addon_utils.addons_fake_modules)
           if ((addons and mod.__name__ in addons) or
               (not addons and addon_utils.module_bl_info(mod)["support"] in support))]

    for mod in ret:
        module_name = mod.__name__
        if disable:
            if module_name not in used_ext:
                continue
            print("    Disabling module ", module_name)
            bpy.ops.wm.addon_disable(module=module_name)
        else:
            if module_name in used_ext:
                continue
            print("    Enabling module ", module_name)
            bpy.ops.wm.addon_enable(module=module_name)

    # XXX There are currently some problems with bpy/rna...
    #     *Very* tricky to solve!
    #     So this is a hack to make all newly added operator visible by
    #     bpy.types.OperatorProperties.__subclasses__()
    for cat in dir(bpy.ops):
        cat = getattr(bpy.ops, cat)
        for op in dir(cat):
            getattr(cat, op).get_rna()

    return ret
Ejemplo n.º 59
0
 def draw(self, context):
     layout = self.layout
     userpref = context.user_preferences
     used_ext = {ext.module for ext in userpref.addons}
     
     for mod in addon_utils.modules(refresh=False):
         if mod.bl_info["category"] == "Fluid Designer":
             module_name = mod.__name__
             is_enabled = module_name in used_ext  
                           
             if is_enabled:
                 layout.operator("wm.addon_disable", 
                                 icon='CHECKBOX_HLT', 
                                 text=mod.bl_info["name"], 
                                 emboss=False).module = module_name
             else:
                 layout.operator("wm.addon_enable", 
                                 icon='CHECKBOX_DEHLT', 
                                 text=mod.bl_info["name"], 
                                 emboss=False).module = module_name
                 
     layout.separator()
     
     layout.operator("wm.save_userpref", text="Save User Settings")
Ejemplo n.º 60
0
def test_load_addons():
    modules = addon_utils.modules({})
    modules.sort(key=lambda mod: mod.__name__)

    disable_addons()

    addons = bpy.context.user_preferences.addons

    addons_fail = []

    for mod in modules:
        mod_name = mod.__name__
        print("\tenabling:", mod_name)
        addon_utils.enable(mod_name)
        if mod_name not in addons:
            addons_fail.append(mod_name)

    if addons_fail:
        print("addons failed to load (%d):" % len(addons_fail))
        for mod_name in addons_fail:
            print("    %s" % mod_name)
    else:
        print("addons all loaded without errors!")
    print("")