Пример #1
0
def reload_addons(do_reload=True, do_reverse=True):
    modules = addon_modules_sorted()
    addons = bpy.context.preferences.addons

    disable_addons()

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

        for mod in modules:
            mod_name = mod.__name__
            print("\tdisabling:", mod_name)
            addon_utils.disable(mod_name, default_set=True)
            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 shouldn't
            modules.reverse()
Пример #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:
                # in case order matters when it shouldnt
                modules.reverse()
Пример #3
0
def unregister():

    # BlenRig Props
    del bpy.types.WindowManager.blenrig_5_props
    # BlenRig Object Add Panel
    bpy.types.INFO_MT_armature_add.remove(blenrig5_add_menu_func)

    # unload BlenRig internal classes
    for c in armature_classes:
        bpy.utils.unregister_class(c)
    for c in alignment_classes:
        bpy.utils.unregister_class(c)
    for c in snapping_classes:
        bpy.utils.unregister_class(c)
    for c in body_picker_biped_classes:
        bpy.utils.unregister_class(c)
    for c in body_picker_quadruped_classes:
        bpy.utils.unregister_class(c)
    for c in face_picker_classes:
        bpy.utils.unregister_class(c)
    for c in blenrig_rigs_classes:
        bpy.utils.unregister_class(c)

    # unload add-on dependencies
    import addon_utils
    for addon_id in addon_dependencies:
        addon_utils.disable(addon_id, default_set=False)
Пример #4
0
def reload_addons(do_reload=True, do_reverse=True):
    modules = addon_modules_sorted()
    addons = bpy.context.user_preferences.addons

    disable_addons()

    # 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, default_set=True)
            assert (mod_name in addons)

        for mod in 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 shouldn't
            modules.reverse()
Пример #5
0
            def _disable_addons(
                addon_module_names,
                save_userpref=True,
                default_set=True,
                **kwargs,
            ):
                """Disables a set of addons by module name.

                Parameters
                ----------

                addon_module_names : list
                  Name of the addons modules (without the ``.py`` extension).

                save_userpref : bool
                  Save user preferences after disable.
                """
                import addon_utils  # noqa F401

                for addon_module_name in addon_module_names:
                    addon_utils.disable(
                        addon_module_name,
                        default_set=default_set,
                        **kwargs,
                    )
                if save_userpref:
                    import bpy  # noqa F401

                    bpy.ops.wm.save_userpref()
Пример #6
0
 def DisableAddon(self, addon_name):
     addon_utils.disable(addon_name, default_set=True)
     addon_utils.modules_refresh()
     return {
         'is_enabled': addon_utils.check(addon_name)[0],
         'is_loaded': addon_utils.check(addon_name)[1],
     }
Пример #7
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()
Пример #8
0
def disable(module):
    if Get.ops('wm.addon_disable'):
        bpy.ops.wm.addon_disable(module=module)
    elif Get.ops('preferences.addon_disable'):
        bpy.ops.preferences.addon_disable(module=module)
    else:
        addon_utils.disable(module_name=module)
Пример #9
0
def disable_named_addon(addon_name):
  # Try to disable the addon to let it cleanly unregister itself
  try:
    _log.info('disable %s', addon_name)
    addon_utils.disable(addon_name)
  except:
    _log.error('addon_utils.disable failed: %s', exc_info=True)
Пример #10
0
    def remesh(self, context):
        lr = self.copiedobject
        hr = self.initialobject

        if self.manifold_method == "print3d":
            isloaded = addon_utils.check("object_print3d_utils")[0]
            if not isloaded:
                addon_utils.enable("object_print3d_utils")
            bpy.ops.mesh.print3d_clean_non_manifold()
            if not isloaded:
                addon_utils.disable("object_print3d_utils")

        elif self.manifold_method == "fill":
            bpy.ops.object.editmode_toggle()
            bpy.ops.mesh.select_mode(type="EDGE")
            bpy.ops.mesh.select_all(action='DESELECT')
            bpy.ops.mesh.select_non_manifold()
            bpy.ops.mesh.fill()
            bpy.ops.object.editmode_toggle()

        elif self.manifold_method == "manifold":
            self.report({"ERROR"}, "Manifold is not implemented yet")
            return {"CANCELLED"}

        elif self.manifold_method == "meshlab":
            self.report({"ERROR"},
                        "Meshlab manifolding is not implemented yet")
            return {"CANCELLED"}

        return {"FINISHED"}
Пример #11
0
    def execute(self, context):
        bpy.ops.code_autocomplete.save_files()

        addon_name = get_addon_name()
        module = sys.modules.get(addon_name)
        if module:
            addon_utils.disable(addon_name)
            importlib.reload(module)
        addon_utils.enable(addon_name)
        return {"FINISHED"}
 def execute(self, context):
     bpy.ops.code_autocomplete.save_files()
     
     addon_name = get_addon_name()
     module = sys.modules.get(addon_name)
     if module:  
         addon_utils.disable(addon_name)
         importlib.reload(module)
     addon_utils.enable(addon_name)
     return {"FINISHED"}        
Пример #13
0
 def tearDown(self):
     TestReadyOperator.report_catcher = self.__prev_report_catcher
     if os.path.exists(self.__tmp):
         if self.__save_test_data:
             bpy.ops.wm.save_mainfile(filepath=os.path.join(self.__tmp, 'result.blend'))
             new_path = os.path.join(self.__tmp_base, self.__class__.__name__, self._testMethodName)
             os.renames(self.__tmp, new_path)
         else:
             shutil.rmtree(self.__tmp)
     addon_utils.disable('io_scene_xray')
Пример #14
0
 def tearDown(self):
     if os.path.exists(self.__tmp):
         if self.__save_test_data:
             bpy.ops.wm.save_mainfile(
                 filepath=os.path.join(self.__tmp, 'result.blend'))
             new_path = os.path.join(self.__tmp_base,
                                     self.__class__.__name__,
                                     self._testMethodName)
             os.renames(self.__tmp, new_path)
         else:
             shutil.rmtree(self.__tmp)
     addon_utils.disable('animation_retarget')
Пример #15
0
    def execute(self, context):
        pl_prop = context.scene.devpack_props.addon_list
        for ad in pl_prop:
            if not ad.select:
                continue
            if self.enable:
                print(f'Enabling {ad.name} -> {ad.addon_module}')
                addon_utils.enable(ad.addon_module)
            else:
                print(f'Disabling {ad.name} -> {ad.addon_module}')
                addon_utils.disable(ad.addon_module)

        return {"FINISHED"}
Пример #16
0
def load_addons():
    modules = addon_modules_sorted()
    addons = bpy.context.user_preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name, default_set=True)

    assert (bool(addons) is False)

    for mod in modules:
        mod_name = mod.__name__
        addon_utils.enable(mod_name, default_set=True)
        assert (mod_name in addons)
def load_addons():
    modules = addon_modules_sorted()
    addons = bpy.context.user_preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name, default_set=True)

    assert(bool(addons) is False)

    for mod in modules:
        mod_name = mod.__name__
        addon_utils.enable(mod_name, default_set=True)
        assert(mod_name in addons)
Пример #18
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)
Пример #19
0
    def processRemoteCommand(self, cmd):
        exists = os.path.isfile(cmd)
        if exists:
            print('try execute "' + cmd + '"')
            exec(compile(open(cmd).read(), cmd, 'exec'))
            return True
        else:
            addonName = cmd
            print('try restart "' + addonName + '"')
            addon_utils.disable(addonName)
            addon_utils.enable(addonName)
            return True

        print('no command given')
        return False
Пример #20
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) is False)

    for mod in modules:
        mod_name = mod.__name__
        addon_utils.enable(mod_name)
        assert (mod_name in addons)
Пример #21
0
    def execute(self, _context):
        import addon_utils

        err_str = ""

        def err_cb(ex):
            import traceback
            nonlocal err_str
            err_str = traceback.format_exc()
            print(err_str)

        addon_utils.disable(self.module, default_set=True, handle_error=err_cb)

        if err_str:
            self.report({'ERROR'}, err_str)

        return {'FINISHED'}
Пример #22
0
def load_addons():
    modules = addon_modules_sorted()
    addons = bpy.context.preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name, default_set=True)

    assert(bool(addons) is False)

    for mod in modules:
        mod_name = mod.__name__
        if mod_name in BLACKLIST:
            continue
        addon_utils.enable(mod_name, default_set=True)
        if not (mod_name in addons):
            raise Exception("'addon_utils.enable(%r)' call failed" % mod_name)
Пример #23
0
def load_addons():
    modules = addon_modules_sorted()
    addons = bpy.context.user_preferences.addons

    # first disable all
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name, default_set=True)

    assert(bool(addons) is False)

    for mod in modules:
        mod_name = mod.__name__
        if mod_name in BLACKLIST:
            continue
        addon_utils.enable(mod_name, default_set=True)
        if not (mod_name in addons):
            raise Exception("'addon_utils.enable(%r)' call failed" % mod_name)
Пример #24
0
    def execute(self, _context):
        import addon_utils

        err_str = ""

        def err_cb(ex):
            import traceback
            nonlocal err_str
            err_str = traceback.format_exc()
            print(err_str)

        addon_utils.disable(self.module, default_set=True, handle_error=err_cb)

        if err_str:
            self.report({'ERROR'}, err_str)

        return {'FINISHED'}
Пример #25
0
    def execute(self, context):
        path, isdir = WM_OT_addon_remove.path_from_addon(self.module)
        if path is None:
            self.report('WARNING', "Addon path %r could not be found" % path)
            return {'CANCELLED'}

        # incase its enabled
        addon_utils.disable(self.module)

        import shutil
        if isdir:
            shutil.rmtree(path)
        else:
            os.remove(path)

        context.area.tag_redraw()
        return {'FINISHED'}
Пример #26
0
    def execute(self, context):
        path, isdir = WM_OT_addon_remove.path_from_addon(self.module)
        if path is None:
            self.report('WARNING', "Addon path %r could not be found" % path)
            return {'CANCELLED'}

        # incase its enabled
        addon_utils.disable(self.module)

        import shutil
        if isdir:
            shutil.rmtree(path)
        else:
            os.remove(path)

        context.area.tag_redraw()
        return {'FINISHED'}
    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')
Пример #28
0
    def _teardown_addons(self):
        import sys

        sys_path = self._addon_store["sys_path"]
        for path in sys_path:
            # should always succeed, but if not it doesn't matter
            # (someone else was changing the sys.path), ignore!
            try:
                sys.path.remove(path)
            except:
                pass

        addons = self._addon_store["addons"]
        import addon_utils
        for addon in addons:
            addon_utils.disable(addon)

        self._addon_store.clear()
        self._addon_store = None
Пример #29
0
    def _teardown_addons(self):
        import sys

        sys_path = self._addon_store["sys_path"]
        for path in sys_path:
            # should always succeed, but if not it doesn't matter
            # (someone else was changing the sys.path), ignore!
            try:
                sys.path.remove(path)
            except:
                pass

        addons = self._addon_store["addons"]
        import addon_utils
        for addon in addons:
            addon_utils.disable(addon)

        self._addon_store.clear()
        self._addon_store = None
def reload_addon(context, name):
    if not name in (m.__name__ for m in addon_utils.modules()): return False

    # Disable addon
    if name in context.user_preferences.addons.keys():
        addon_utils.disable(name)

    # Remove sub modules
    mod_names = list(filter(lambda m: m.startswith(name), sys.modules))
    mod_names.sort()
    for mod_name in mod_names:
        try:
            importlib.reload(importlib.import_module(mod_name))
        except AttributeError:
            pass

    # Enable addon
    addon_utils.enable(name)

    return True
Пример #31
0
 def execute(self, context):
     done, addon_msg = addon_utils.disable(self.module)
     if done:
         if addon_msg: self.report({'INFO'}, addon_msg)
         return {'FINISHED'}
     else:
         if addon_msg:
             self.report({'WARNING'}, addon_msg)
         else:
             self.report({'WARNING'}, "Disabled with some warnings")
         return {'CANCELLED'}
Пример #32
0
 def execute(self, context):
     done,addon_msg = addon_utils.disable(self.module)
     if done :
         if addon_msg : self.report({'INFO'}, addon_msg)
         return {'FINISHED'}
     else:
         if addon_msg :
             self.report({'WARNING'}, addon_msg)
         else :
             self.report({'WARNING'}, "Disabled with some warnings")
         return {'CANCELLED'}
Пример #33
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')
Пример #34
0
    def execute(self, context):
        import addon_utils
        import os

        path, isdir = PREFERENCES_OT_addon_remove.path_from_addon(self.module)
        if path is None:
            self.report({'WARNING'}, "Add-on path %r could not be found" % path)
            return {'CANCELLED'}

        # in case its enabled
        addon_utils.disable(self.module, default_set=True)

        import shutil
        if isdir and (not os.path.islink(path)):
            shutil.rmtree(path)
        else:
            os.remove(path)

        addon_utils.modules_refresh()

        context.area.tag_redraw()
        return {'FINISHED'}
Пример #35
0
    def execute(self, context):
        import addon_utils
        import os

        path, isdir = PREFERENCES_OT_addon_remove.path_from_addon(self.module)
        if path is None:
            self.report({'WARNING'}, "Add-on path %r could not be found" % path)
            return {'CANCELLED'}

        # in case its enabled
        addon_utils.disable(self.module, default_set=True)

        import shutil
        if isdir and (not os.path.islink(path)):
            shutil.rmtree(path)
        else:
            os.remove(path)

        addon_utils.modules_refresh()

        context.area.tag_redraw()
        return {'FINISHED'}
Пример #36
0
def test_disable_addon():
    """Disables the nif scripts addon, so all tests can use it."""

    enabled = False
    if (nif_module_name in bpy.context.user_preferences.addons.keys()):
        enabled = True

    nose.tools.assert_true(enabled)

    try:
        addon_utils.disable(module_name=nif_module_name,
                            default_set=True,
                            handle_error=None)
    except:
        pass

    disabled = False
    modules = bpy.context.user_preferences.addons.keys()
    if (nif_module_name not in modules):
        disabled = True

    nose.tools.assert_true(disabled)
Пример #37
0
def load_scripts(reload_scripts=False, refresh_scripts=False):
    """
    Load scripts and run each modules register function.

    :arg reload_scripts: Causes all scripts to have their unregister method
       called before loading.
    :type reload_scripts: bool
    :arg refresh_scripts: only load scripts which are not already loaded
       as modules.
    :type refresh_scripts: bool
    """
    use_time = _bpy.app.debug_python

    if use_time:
        import time
        t_main = time.time()

    loaded_modules = set()

    if refresh_scripts:
        original_modules = _sys.modules.values()

    if reload_scripts:
        _bpy_types.TypeMap.clear()

        # just unload, don't change user defaults, this means we can sync
        # to reload. note that they will only actually reload of the
        # modification time changes. This `won't` work for packages so...
        # its not perfect.
        for module_name in [ext.module for ext in _user_preferences.addons]:
            _addon_utils.disable(module_name, default_set=False)

    def register_module_call(mod):
        register = getattr(mod, "register", None)
        if register:
            try:
                register()
            except:
                import traceback
                traceback.print_exc()
        else:
            print("\nWarning! '%s' has no register function, "
                  "this is now a requirement for registerable scripts" %
                  mod.__file__)

    def unregister_module_call(mod):
        unregister = getattr(mod, "unregister", None)
        if unregister:
            try:
                unregister()
            except:
                import traceback
                traceback.print_exc()

    def test_reload(mod):
        import imp
        # reloading this causes internal errors
        # because the classes from this module are stored internally
        # possibly to refresh internal references too but for now, best not to.
        if mod == _bpy_types:
            return mod

        try:
            return imp.reload(mod)
        except:
            import traceback
            traceback.print_exc()

    def test_register(mod):

        if refresh_scripts and mod in original_modules:
            return

        if reload_scripts and mod:
            print("Reloading:", mod)
            mod = test_reload(mod)

        if mod:
            register_module_call(mod)
            _global_loaded_modules.append(mod.__name__)

    if reload_scripts:

        # module names -> modules
        _global_loaded_modules[:] = [_sys.modules[mod_name]
                                     for mod_name in _global_loaded_modules]

        # loop over and unload all scripts
        _global_loaded_modules.reverse()
        for mod in _global_loaded_modules:
            unregister_module_call(mod)

        for mod in _global_loaded_modules:
            test_reload(mod)

        del _global_loaded_modules[:]

    from bpy_restrict_state import RestrictBlend

    with RestrictBlend():
        for base_path in script_paths():
            for path_subdir in _script_module_dirs:
                path = _os.path.join(base_path, path_subdir)
                if _os.path.isdir(path):
                    _sys_path_ensure(path)

                    # only add this to sys.modules, don't run
                    if path_subdir == "modules":
                        continue

                    for mod in modules_from_path(path, loaded_modules):
                        test_register(mod)

    # deal with addons separately
    _addon_utils.reset_all(reload_scripts)

    # run the active integration preset
    filepath = preset_find(_user_preferences.inputs.active_keyconfig, "keyconfig")

    if filepath:
        keyconfig_set(filepath)

    if reload_scripts:
        import gc
        print("gc.collect() -> %d" % gc.collect())

    if use_time:
        print("Python Script Load Time %.4f" % (time.time() - t_main))
import bpy
import addon_utils

from pathlib import Path
import shutil

addon_name = 'rprblender'

# disable addon first
addon_utils.disable(addon_name, default_set=True)

# find addon package and remove its folder
for mod in addon_utils.modules():
    if addon_name == mod.__name__:
        filepath = Path(mod.__file__)
        if filepath.exists():
            addon_dir = filepath.parent
            if addon_name == addon_dir.name:
                print('removing', addon_dir)
                shutil.rmtree(str(addon_dir))

# this operator fails in --background mode by trying to call context.area.tag_redraw
# bpy.ops.preferences.addon_remove(module='rprblender')
bpy.ops.wm.save_userpref()
Пример #39
0
 def execute(self, context):
     addon_utils.disable(self.module)
     return {'FINISHED'}
Пример #40
0
import addon_utils

_, luxblend_is_enabled = addon_utils.check("luxrender")
if luxblend_is_enabled:
    addon_utils.disable("luxrender", default_set=True)
    print("Disabled the old LuxBlend addon.")
    raise Exception("\n\nThe old LuxBlend addon causes conflicts, "
                    "so it was disabled. Save your user preferences "
                    "and restart Blender before you can enable the "
                    "new addon.")

try:
    from .bin import pyluxcore
except ImportError as error:
    msg = "\n\nCould not import pyluxcore."
    import platform
    if platform.system() == "Windows":
        msg += ("\nYou probably forgot to install one of the "
                "redistributable packages.\n"
                "They are listed in the release announcement post.")
    # Raise from None to suppress the unhelpful
    # "during handling of the above exception, ..."
    raise Exception(msg + "\n\nImportError: %s" % error) from None

bl_info = {
    "name": "LuxCore",
    "author": "Simon Wendsche (B.Y.O.B.), Michael Klemm (neo2068), Philstix",
    "version": (2, 3),
    "blender": (2, 80, 0),
    "category": "Render",
    "location": "Info header, render engine menu",
Пример #41
0
    def execute(self, context):
        import addon_utils
        import traceback
        import zipfile
        import shutil
        import os

        pyfile = self.filepath

        if self.target == 'DEFAULT':
            # don't use bpy.utils.script_paths("addons") because we may not be able to write to it.
            path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True)
        else:
            path_addons = context.preferences.filepaths.script_directory
            if path_addons:
                path_addons = os.path.join(path_addons, "addons")

        if not path_addons:
            self.report({'ERROR'}, "Failed to get add-ons path")
            return {'CANCELLED'}

        if not os.path.isdir(path_addons):
            try:
                os.makedirs(path_addons, exist_ok=True)
            except:
                traceback.print_exc()

        # Check if we are installing from a target path,
        # doing so causes 2+ addons of same name or when the same from/to
        # location is used, removal of the file!
        addon_path = ""
        pyfile_dir = os.path.dirname(pyfile)
        for addon_path in addon_utils.paths():
            if os.path.samefile(pyfile_dir, addon_path):
                self.report({'ERROR'}, "Source file is in the add-on search path: %r" % addon_path)
                return {'CANCELLED'}
        del addon_path
        del pyfile_dir
        # done checking for exceptional case

        addons_old = {mod.__name__ for mod in addon_utils.modules()}

        # check to see if the file is in compressed format (.zip)
        if zipfile.is_zipfile(pyfile):
            try:
                file_to_extract = zipfile.ZipFile(pyfile, 'r')
            except:
                traceback.print_exc()
                return {'CANCELLED'}

            if self.overwrite:
                for f in file_to_extract.namelist():
                    module_filesystem_remove(path_addons, f)
            else:
                for f in file_to_extract.namelist():
                    path_dest = os.path.join(path_addons, os.path.basename(f))
                    if os.path.exists(path_dest):
                        self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
                        return {'CANCELLED'}

            try:  # extract the file to "addons"
                file_to_extract.extractall(path_addons)
            except:
                traceback.print_exc()
                return {'CANCELLED'}

        else:
            path_dest = os.path.join(path_addons, os.path.basename(pyfile))

            if self.overwrite:
                module_filesystem_remove(path_addons, os.path.basename(pyfile))
            elif os.path.exists(path_dest):
                self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
                return {'CANCELLED'}

            # if not compressed file just copy into the addon path
            try:
                shutil.copyfile(pyfile, path_dest)
            except:
                traceback.print_exc()
                return {'CANCELLED'}

        addons_new = {mod.__name__ for mod in addon_utils.modules()} - addons_old
        addons_new.discard("modules")

        # disable any addons we may have enabled previously and removed.
        # this is unlikely but do just in case. bug [#23978]
        for new_addon in addons_new:
            addon_utils.disable(new_addon, default_set=True)

        # possible the zip contains multiple addons, we could disallow this
        # but for now just use the first
        for mod in addon_utils.modules(refresh=False):
            if mod.__name__ in addons_new:
                info = addon_utils.module_bl_info(mod)

                # show the newly installed addon.
                context.window_manager.addon_filter = 'All'
                context.window_manager.addon_search = info["name"]
                break

        # in case a new module path was created to install this addon.
        bpy.utils.refresh_script_paths()

        # print message
        msg = (
            tip_("Modules Installed (%s) from %r into %r") %
            (", ".join(sorted(addons_new)), pyfile, path_addons)
        )
        print(msg)
        self.report({'INFO'}, msg)

        return {'FINISHED'}
Пример #42
0
def smartconfig_import_config(filepath, context, import_datafiles_folders,
                              import_startup_file, install_userfolder,
                              import_bookmarks, import_users_prefs,
                              import_presets, import_config_folders):
    temp = os.path.join(os.path.dirname(filepath), "_sc_temp_")
    chk_p = 0
    wrong = []
    # suppress previous temp folder
    if os.path.isdir(temp) == True:
        try:
            shutil.rmtree(temp)
        except:
            try:
                change_permissions_recursive(temp, 0o777)
                shutil.rmtree(temp)
            except:
                print(
                    'Smart Config warning : Unable to delete previous temp folder, please delete it manually'
                )
                chk_p = 1
    # create temp folder
    if chk_p == 0:
        os.makedirs(os.path.join(os.path.dirname(filepath), "_sc_temp_"))
        # error handler
        try:
            tempfolder = os.path.join(temp, "addons")
            user_path = bpy.utils.resource_path('USER')
            chk2 = 0
            to_install = []
            try:
                print()
                print('Smart Config warning : Unpacking File')
                shutil.unpack_archive(filepath, temp, 'zip')
                csvfile = os.path.join(temp, "to_install.txt")
                with open(csvfile, 'r') as f:
                    total = (sum(1 for row in f))
            except shutil.ReadError:
                print('Smart Config warning : Wrong File Format')
                chk2 = 1
            if chk2 == 0:
                # addons
                nb = 0
                job = "Smart Config warning : Importing Addons"
                print()
                if install_userfolder == True:
                    addfolder = bpy.utils.user_resource('SCRIPTS', "addons")
                    addfolder2 = os.path.join(bpy.utils.script_paths()[1],
                                              "addons")
                else:
                    addfolder = os.path.join(bpy.utils.script_paths()[1],
                                             "addons")
                    addfolder2 = bpy.utils.user_resource('SCRIPTS', "addons")
                for file in os.listdir(tempfolder):
                    #messages
                    nb += 1
                    chk = 0
                    filep = os.path.join(tempfolder, file)
                    if os.path.isfile(filep):
                        for mod in addon_utils.modules():
                            if file == str(mod).split("'")[1] + ".py":
                                chk = 1
                        for f in os.listdir(addfolder2):
                            if f == file:
                                chk = 1
                        if chk == 0:
                            shutil.copy2(
                                os.path.join(tempfolder, file),
                                os.path.join(addfolder,
                                             os.path.basename(file)))
                    elif os.path.isdir(filep):
                        for f in os.listdir(addfolder):
                            if file == f:
                                chk = 1
                        for f in os.listdir(addfolder2):
                            if f == file:
                                chk = 1
                        if chk == 0:
                            shutil.copytree(
                                os.path.join(tempfolder, file),
                                os.path.join(addfolder,
                                             os.path.basename(file)))
                    update_progress_console(job, nb / total)
                with open(csvfile, 'r') as f:
                    for line in f.readlines():
                        name = line.split("\n")[0]
                        if name != "" and name not in bpy.context.user_preferences.addons.keys(
                        ):
                            try:
                                bpy.ops.wm.addon_enable(module=name)
                            except:
                                try:
                                    addon_utils.disable(name)
                                    bpy.ops.wm.addon_disable(module=name)
                                    bpy.ops.wm.addon_enable(module=name)
                                except:
                                    wrong.append(name)
                    print("Smart Config warning : " + str(total) +
                          " addons activated")
                #startup_file
                if import_startup_file == True:
                    path_s = os.path.join(temp, "startup.blend")
                    if os.path.isfile(path_s) == True:
                        path_d = os.path.join(
                            os.path.join(user_path, "config"), "startup.blend")
                        shutil.copy(path_s, path_d)
                        print('Smart Config warning : Startup File installed')
                # copy bookmarks file
                if import_bookmarks == True:
                    path_s = os.path.join(temp, "bookmarks.txt")
                    if os.path.isfile(path_s) == True:
                        path_d = os.path.join(
                            os.path.join(user_path, "config"), "bookmarks.txt")
                        shutil.copy(path_s, path_d)
                        print(
                            'Smart Config warning : Bookmarks File installed')
                # copy userprefs file
                if import_users_prefs == True:
                    path_s = os.path.join(temp, "userpref.blend")
                    if os.path.isfile(path_s) == True:
                        path_d = os.path.join(
                            os.path.join(user_path, "config"),
                            "userpref.blend")
                        shutil.copy(path_s, path_d)
                        print(
                            'Smart Config warning : User Preferences File installed'
                        )
                # copy presets folder
                if import_presets == True:
                    path_p = os.path.join(temp, "presets")
                    if os.path.isdir(path_p) == True:
                        path_d = os.path.join(
                            os.path.join(user_path, "scripts"), "presets")
                        recursive_copy_dir_tree(path_p, path_d)
                        print(
                            'Smart Config warning : Preset Folders installed')
                # copy config folders
                if import_config_folders == True:
                    path_p = os.path.join(temp, "config")
                    if os.path.isdir(path_p) == True:
                        config_d = os.path.join(user_path, "config")
                        recursive_copy_dir_tree(path_p, config_d)
                        print(
                            'Smart Config warning : Config Folders installed')
                # copy datafiles folder
                if import_datafiles_folders == True:
                    path_p = os.path.join(temp, "datafiles")
                    if os.path.isdir(path_p) == True:
                        path_d = os.path.join(user_path, "datafiles")
                        recursive_copy_dir_tree(path_p, path_d)
                        print(
                            'Smart Config warning : Datafiles Folders installed'
                        )

            try:
                shutil.rmtree(temp)
            except:
                try:
                    change_permissions_recursive(temp, 0o777)
                    shutil.rmtree(temp)
                except:
                    print(
                        'Smart Config warning : Unable to delete temp folder - Please delete it manually'
                    )
            # error report
            if len(wrong) != 0:
                if addon_preferences.errors_report == True:
                    error = os.path.join(
                        os.path.dirname(filepath),
                        (os.path.basename(filepath).split(".sc")[0] +
                         "_import_errors.txt"))
                    errorfile = open(error, "w")
                    errorfile.write(
                        "IMPOSSIBLE TO ACTIVATE THESE ADDONS :\n\n")
                    for a in wrong:
                        errorfile.write(a + "\n")
                    errorfile.close()
                for a in wrong:
                    print('Smart Config warning : Addon Problem with - ' + a)

            print()
            print('Smart Config warning : Import Finished')
        except:
            shutil.rmtree(temp)
            print('Smart Config warning : Unexpected Error')
    return {'FINISHED'}
Пример #43
0
 def test_disable_enable(self):
     with self.assert_logs_no_errors():
         info("Disabling Sverchok")
         addon_utils.disable("sverchok")
         info("Enabling Sverchok")
         addon_utils.enable("sverchok")
Пример #44
0
 def execute(self,context):
     addon_utils.disable("wallcreator")
     addon_utils.enable("wallcreator")
     return {'FINISHED'}
Пример #45
0
def disable_addons():
    # first disable all
    addons = bpy.context.user_preferences.addons
    for mod_name in list(addons.keys()):
        addon_utils.disable(mod_name)
    assert(bool(addons) is False)
Пример #46
0
def load_scripts(reload_scripts=False, refresh_scripts=False):
    """
    Load scripts and run each modules register function.

    :arg reload_scripts: Causes all scripts to have their unregister method
       called before loading.
    :type reload_scripts: bool
    :arg refresh_scripts: only load scripts which are not already loaded
       as modules.
    :type refresh_scripts: bool
    """
    use_time = _bpy.app.debug_python

    if use_time:
        import time
        t_main = time.time()

    loaded_modules = set()

    if refresh_scripts:
        original_modules = _sys.modules.values()

    if reload_scripts:
        _bpy_types.TypeMap.clear()

        # just unload, don't change user defaults, this means we can sync
        # to reload. note that they will only actually reload of the
        # modification time changes. This `won't` work for packages so...
        # its not perfect.
        for module_name in [ext.module for ext in _user_preferences.addons]:
            _addon_utils.disable(module_name)

    def register_module_call(mod):
        register = getattr(mod, "register", None)
        if register:
            try:
                register()
            except:
                import traceback
                traceback.print_exc()
        else:
            print("\nWarning! '%s' has no register function, "
                  "this is now a requirement for registerable scripts" %
                  mod.__file__)

    def unregister_module_call(mod):
        unregister = getattr(mod, "unregister", None)
        if unregister:
            try:
                unregister()
            except:
                import traceback
                traceback.print_exc()

    def test_reload(mod):
        import importlib
        # reloading this causes internal errors
        # because the classes from this module are stored internally
        # possibly to refresh internal references too but for now, best not to.
        if mod == _bpy_types:
            return mod

        try:
            return importlib.reload(mod)
        except:
            import traceback
            traceback.print_exc()

    def test_register(mod):

        if refresh_scripts and mod in original_modules:
            return

        if reload_scripts and mod:
            print("Reloading:", mod)
            mod = test_reload(mod)

        if mod:
            register_module_call(mod)
            _global_loaded_modules.append(mod.__name__)

    if reload_scripts:

        # module names -> modules
        _global_loaded_modules[:] = [
            _sys.modules[mod_name] for mod_name in _global_loaded_modules
        ]

        # loop over and unload all scripts
        _global_loaded_modules.reverse()
        for mod in _global_loaded_modules:
            unregister_module_call(mod)

        for mod in _global_loaded_modules:
            test_reload(mod)

        del _global_loaded_modules[:]

    from bpy_restrict_state import RestrictBlend

    with RestrictBlend():
        for base_path in script_paths():
            for path_subdir in _script_module_dirs:
                path = _os.path.join(base_path, path_subdir)
                if _os.path.isdir(path):
                    _sys_path_ensure(path)

                    # only add this to sys.modules, don't run
                    if path_subdir == "modules":
                        continue

                    for mod in modules_from_path(path, loaded_modules):
                        test_register(mod)

    # deal with addons separately
    _initialize = getattr(_addon_utils, "_initialize", None)
    if _initialize is not None:
        # first time, use fast-path
        _initialize()
        del _addon_utils._initialize
    else:
        _addon_utils.reset_all(reload_scripts)
    del _initialize

    # run the active integration preset
    filepath = preset_find(_user_preferences.inputs.active_keyconfig,
                           "keyconfig")

    if filepath:
        keyconfig_set(filepath)

    if reload_scripts:
        import gc
        print("gc.collect() -> %d" % gc.collect())

    if use_time:
        print("Python Script Load Time %.4f" % (time.time() - t_main))
Пример #47
0
def reload(self, context, modules):
    global prev
    addons = addon_utils.addons_fake_modules

    os.system('cls')
    try:
        for addon_name in modules:
            disable(addon_name)
            addon_utils.disable(module_name=addon_name)
            os.system("cls")
    except:
        os.system("cls")
        self.report({'INFO'}, f"Error: Addon['{modules}'] failed to disable")
        error()

    for addon_name in modules:
        try:
            addon = sys.modules.get(addon_name)
            if addon is None or addon.__spec__ is None:
                self.report({
                    'INFO'
                }, f"Error: could not find addon['{addon_name}'] in sys.modules"
                            )
                print(
                    f"Error reloading {addon_name}, not found in sys.modules")
                continue
                # if not addons.get(addon_name):
                # self.report({'INFO'}, message="Addon not available")
                # continue
                # try:
                # print(f"Addon ['{addon_name}'] not found in system, but still exists. \nDefaulting to addon operators for reload.")
                # disable(addon_name)
                # refresh(addon_name)
                # enable(addon_name)
                # except:
                # self.report({'INFO'}, f"Error: Addon['{addon_name}'] failed to initialize or reload")
                # error()
                # continue

            if len(modules) == 1 or addon_name == modules[0]:
                print(f"Reloading {addon_name}")
                if addon_name != prev:  # Print filepath when selecting a new addon
                    print(f"\t{addon.__file__}")

            (root, folder) = Get.path(addon)
            if folder is not None:  # Is folder addon
                for sub_name in sys.modules:
                    sub_addon = sys.modules[sub_name]
                    (file, sub_folder) = Get.path(sub_addon)
                    if file is None or not file.startswith(
                            folder) or sub_addon.__spec__ is None:
                        continue
                    try:
                        importlib.reload(sub_addon)
                    except:
                        self.report({
                            'INFO'
                        }, f"Error: Sub Module['{sub_name}'] failed to reload")
                        error()
            # TODO: folders using dots in name would reload too, despite being two separate base folders:
            #   ex: ["scripts/addon/files", "scripts/addon.different_folder/files"]
            importlib.reload(addon)
            enable(addon_name)
        except:
            self.report({'INFO'},
                        f"Error: Addon['{addon_name}'] failed to reload")
            error()

    prev = modules[0]
Пример #48
0
    # sino se hace el primer import
    # importando archivos en el mismo directorio que el __init__.py
    from .basics import *
    from .fabrickbrick import *

import bpy
from bpy.props import *
import random

###############################################
# para tener un boton que recarga el addon
###############################################
import addon_utils
###############################################
addon_utils.enable("__init__", default_set=False, persistent=False, handle_error=None)
addon_utils.disable("__init__", default_set=False, handle_error=None)
class ReloadMyAdoon(bpy.types.Operator):
    bl_idname = "object.zebus_dialog2"
    bl_label = "Reset addon"
    def execute(self,context):
        addon_utils.disable("wallcreator")
        addon_utils.enable("wallcreator")
        return {'FINISHED'}
###############################################
        
class DialogOperator(bpy.types.Operator):
    bl_idname = "object.zebus_dialog"
    bl_label = "Wall Bricks Creator v02"
    ###############################################
    # Defaults:
    ###############################################
Пример #49
0
def load_scripts(*, reload_scripts=False, refresh_scripts=False):
    """
    Load scripts and run each modules register function.

    :arg reload_scripts: Causes all scripts to have their unregister method
       called before loading.
    :type reload_scripts: bool
    :arg refresh_scripts: only load scripts which are not already loaded
       as modules.
    :type refresh_scripts: bool
    """
    use_time = use_class_register_check = _bpy.app.debug_python
    use_user = not _is_factory_startup

    if use_time:
        import time
        t_main = time.time()

    loaded_modules = set()

    if refresh_scripts:
        original_modules = _sys.modules.values()

    if reload_scripts:
        # just unload, don't change user defaults, this means we can sync
        # to reload. note that they will only actually reload of the
        # modification time changes. This `won't` work for packages so...
        # its not perfect.
        for module_name in [ext.module for ext in _preferences.addons]:
            _addon_utils.disable(module_name)

    def register_module_call(mod):
        register = getattr(mod, "register", None)
        if register:
            try:
                register()
            except:
                import traceback
                traceback.print_exc()
        else:
            print("\nWarning! '%s' has no register function, "
                  "this is now a requirement for registerable scripts" %
                  mod.__file__)

    def unregister_module_call(mod):
        unregister = getattr(mod, "unregister", None)
        if unregister:
            try:
                unregister()
            except:
                import traceback
                traceback.print_exc()

    def test_reload(mod):
        import importlib
        # reloading this causes internal errors
        # because the classes from this module are stored internally
        # possibly to refresh internal references too but for now, best not to.
        if mod == _bpy_types:
            return mod

        try:
            return importlib.reload(mod)
        except:
            import traceback
            traceback.print_exc()

    def test_register(mod):

        if refresh_scripts and mod in original_modules:
            return

        if reload_scripts and mod:
            print("Reloading:", mod)
            mod = test_reload(mod)

        if mod:
            register_module_call(mod)
            _global_loaded_modules.append(mod.__name__)

    if reload_scripts:

        # module names -> modules
        _global_loaded_modules[:] = [
            _sys.modules[mod_name] for mod_name in _global_loaded_modules
        ]

        # loop over and unload all scripts
        _global_loaded_modules.reverse()
        for mod in _global_loaded_modules:
            unregister_module_call(mod)

        for mod in _global_loaded_modules:
            test_reload(mod)

        del _global_loaded_modules[:]

    from bpy_restrict_state import RestrictBlend

    with RestrictBlend():
        for base_path in script_paths(use_user=use_user):
            for path_subdir in _script_module_dirs:
                path = _os.path.join(base_path, path_subdir)
                if _os.path.isdir(path):
                    _sys_path_ensure_prepend(path)

                    # Only add to 'sys.modules' unless this is 'startup'.
                    if path_subdir == "startup":
                        for mod in modules_from_path(path, loaded_modules):
                            test_register(mod)

    # load template (if set)
    if any(_bpy.utils.app_template_paths()):
        import bl_app_template_utils
        bl_app_template_utils.reset(reload_scripts=reload_scripts)
        del bl_app_template_utils

    # deal with addons separately
    _initialize = getattr(_addon_utils, "_initialize", None)
    if _initialize is not None:
        # first time, use fast-path
        _initialize()
        del _addon_utils._initialize
    else:
        _addon_utils.reset_all(reload_scripts=reload_scripts)
    del _initialize

    if reload_scripts:
        _bpy.context.window_manager.tag_script_reload()

        import gc
        print("gc.collect() -> %d" % gc.collect())

    if use_time:
        print("Python Script Load Time %.4f" % (time.time() - t_main))

    if use_class_register_check:
        for cls in _bpy.types.bpy_struct.__subclasses__():
            if getattr(cls, "is_registered", False):
                for subcls in cls.__subclasses__():
                    if not subcls.is_registered:
                        print("Warning, unregistered class: %s(%s)" %
                              (subcls.__name__, cls.__name__))
Пример #50
0
    def execute(self, context):
        import addon_utils
        import traceback
        import zipfile
        import shutil
        import os

        pyfile = self.filepath

        if self.target == 'DEFAULT':
            # don't use bpy.utils.script_paths("addons") because we may not be able to write to it.
            path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True)
        else:
            path_addons = context.preferences.filepaths.script_directory
            if path_addons:
                path_addons = os.path.join(path_addons, "addons")

        if not path_addons:
            self.report({'ERROR'}, "Failed to get add-ons path")
            return {'CANCELLED'}

        if not os.path.isdir(path_addons):
            try:
                os.makedirs(path_addons, exist_ok=True)
            except:
                traceback.print_exc()

        # Check if we are installing from a target path,
        # doing so causes 2+ addons of same name or when the same from/to
        # location is used, removal of the file!
        addon_path = ""
        pyfile_dir = os.path.dirname(pyfile)
        for addon_path in addon_utils.paths():
            if os.path.samefile(pyfile_dir, addon_path):
                self.report({'ERROR'}, "Source file is in the add-on search path: %r" % addon_path)
                return {'CANCELLED'}
        del addon_path
        del pyfile_dir
        # done checking for exceptional case

        addons_old = {mod.__name__ for mod in addon_utils.modules()}

        # check to see if the file is in compressed format (.zip)
        if zipfile.is_zipfile(pyfile):
            try:
                file_to_extract = zipfile.ZipFile(pyfile, 'r')
            except:
                traceback.print_exc()
                return {'CANCELLED'}

            if self.overwrite:
                for f in file_to_extract.namelist():
                    module_filesystem_remove(path_addons, f)
            else:
                for f in file_to_extract.namelist():
                    path_dest = os.path.join(path_addons, os.path.basename(f))
                    if os.path.exists(path_dest):
                        self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
                        return {'CANCELLED'}

            try:  # extract the file to "addons"
                file_to_extract.extractall(path_addons)
            except:
                traceback.print_exc()
                return {'CANCELLED'}

        else:
            path_dest = os.path.join(path_addons, os.path.basename(pyfile))

            if self.overwrite:
                module_filesystem_remove(path_addons, os.path.basename(pyfile))
            elif os.path.exists(path_dest):
                self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
                return {'CANCELLED'}

            # if not compressed file just copy into the addon path
            try:
                shutil.copyfile(pyfile, path_dest)
            except:
                traceback.print_exc()
                return {'CANCELLED'}

        addons_new = {mod.__name__ for mod in addon_utils.modules()} - addons_old
        addons_new.discard("modules")

        # disable any addons we may have enabled previously and removed.
        # this is unlikely but do just in case. bug [#23978]
        for new_addon in addons_new:
            addon_utils.disable(new_addon, default_set=True)

        # possible the zip contains multiple addons, we could disallow this
        # but for now just use the first
        for mod in addon_utils.modules(refresh=False):
            if mod.__name__ in addons_new:
                info = addon_utils.module_bl_info(mod)

                # show the newly installed addon.
                context.window_manager.addon_filter = 'All'
                context.window_manager.addon_search = info["name"]
                break

        # in case a new module path was created to install this addon.
        bpy.utils.refresh_script_paths()

        # print message
        msg = (
            tip_("Modules Installed (%s) from %r into %r") %
            (", ".join(sorted(addons_new)), pyfile, path_addons)
        )
        print(msg)
        self.report({'INFO'}, msg)

        return {'FINISHED'}
Пример #51
0
def load_scripts(reload_scripts=False, refresh_scripts=False):
    """
    Load scripts and run each modules register function.

    :arg reload_scripts: Causes all scripts to have their unregister method
       called before loading.
    :type reload_scripts: bool
    :arg refresh_scripts: only load scripts which are not already loaded
       as modules.
    :type refresh_scripts: bool
    """
    use_time = use_class_register_check = _bpy.app.debug_python
    use_user = not _is_factory_startup

    if use_time:
        import time
        t_main = time.time()

    loaded_modules = set()

    if refresh_scripts:
        original_modules = _sys.modules.values()

    if reload_scripts:
        # just unload, don't change user defaults, this means we can sync
        # to reload. note that they will only actually reload of the
        # modification time changes. This `won't` work for packages so...
        # its not perfect.
        for module_name in [ext.module for ext in _user_preferences.addons]:
            _addon_utils.disable(module_name)

        # *AFTER* unregistering all add-ons, otherwise all calls to
        # unregister_module() will silently fail (do nothing).
        _bpy_types.TypeMap.clear()

    def register_module_call(mod):
        register = getattr(mod, "register", None)
        if register:
            try:
                register()
            except:
                import traceback
                traceback.print_exc()
        else:
            print("\nWarning! '%s' has no register function, "
                  "this is now a requirement for registerable scripts" %
                  mod.__file__)

    def unregister_module_call(mod):
        unregister = getattr(mod, "unregister", None)
        if unregister:
            try:
                unregister()
            except:
                import traceback
                traceback.print_exc()

    def test_reload(mod):
        import importlib
        # reloading this causes internal errors
        # because the classes from this module are stored internally
        # possibly to refresh internal references too but for now, best not to.
        if mod == _bpy_types:
            return mod

        try:
            return importlib.reload(mod)
        except:
            import traceback
            traceback.print_exc()

    def test_register(mod):

        if refresh_scripts and mod in original_modules:
            return

        if reload_scripts and mod:
            print("Reloading:", mod)
            mod = test_reload(mod)

        if mod:
            register_module_call(mod)
            _global_loaded_modules.append(mod.__name__)

    if reload_scripts:

        # module names -> modules
        _global_loaded_modules[:] = [_sys.modules[mod_name]
                                     for mod_name in _global_loaded_modules]

        # loop over and unload all scripts
        _global_loaded_modules.reverse()
        for mod in _global_loaded_modules:
            unregister_module_call(mod)

        for mod in _global_loaded_modules:
            test_reload(mod)

        del _global_loaded_modules[:]

    from bpy_restrict_state import RestrictBlend

    with RestrictBlend():
        for base_path in script_paths(use_user=use_user):
            for path_subdir in _script_module_dirs:
                path = _os.path.join(base_path, path_subdir)
                if _os.path.isdir(path):
                    _sys_path_ensure(path)

                    # only add this to sys.modules, don't run
                    if path_subdir == "modules":
                        continue

                    for mod in modules_from_path(path, loaded_modules):
                        test_register(mod)

    # load template (if set)
    if any(_bpy.utils.app_template_paths()):
        import bl_app_template_utils
        bl_app_template_utils.reset(reload_scripts=reload_scripts)
        del bl_app_template_utils

    # deal with addons separately
    _initialize = getattr(_addon_utils, "_initialize", None)
    if _initialize is not None:
        # first time, use fast-path
        _initialize()
        del _addon_utils._initialize
    else:
        _addon_utils.reset_all(reload_scripts=reload_scripts)
    del _initialize

    # run the active integration preset
    filepath = preset_find(_user_preferences.inputs.active_keyconfig,
                           "keyconfig")

    if filepath:
        keyconfig_set(filepath)

    if reload_scripts:
        import gc
        print("gc.collect() -> %d" % gc.collect())

    if use_time:
        print("Python Script Load Time %.4f" % (time.time() - t_main))

    if use_class_register_check:
        for cls in _bpy.types.bpy_struct.__subclasses__():
            if getattr(cls, "is_registered", False):
                for subcls in cls.__subclasses__():
                    if not subcls.is_registered:
                        print(
                            "Warning, unregistered class: %s(%s)" %
                            (subcls.__name__, cls.__name__)
                        )
Пример #52
0
    def execute(self, context):
        import traceback
        import zipfile
        import shutil

        pyfile = self.filepath

        if self.target == 'DEFAULT':
            # dont use bpy.utils.script_paths("addons") because we may not be able to write to it.
            path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True)
        else:
            path_addons = bpy.context.user_preferences.filepaths.script_directory
            if path_addons:
                path_addons = os.path.join(path_addons, "addons")

        if not path_addons:
            self.report({'ERROR'}, "Failed to get addons path")
            return {'CANCELLED'}

        # create dir is if missing.
        if not os.path.exists(path_addons):
            os.makedirs(path_addons)

        # Check if we are installing from a target path,
        # doing so causes 2+ addons of same name or when the same from/to
        # location is used, removal of the file!
        addon_path = ""
        pyfile_dir = os.path.dirname(pyfile)
        for addon_path in addon_utils.paths():
            if os.path.samefile(pyfile_dir, addon_path):
                self.report({'ERROR'}, "Source file is in the addon search path: %r" % addon_path)
                return {'CANCELLED'}
        del addon_path
        del pyfile_dir
        # done checking for exceptional case

        addons_old = {mod.__name__ for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules)}

        #check to see if the file is in compressed format (.zip)
        if zipfile.is_zipfile(pyfile):
            try:
                file_to_extract = zipfile.ZipFile(pyfile, 'r')
            except:
                traceback.print_exc()
                return {'CANCELLED'}

            if self.overwrite:
                for f in file_to_extract.namelist():
                    WM_OT_addon_install._module_remove(path_addons, f)
            else:
                for f in file_to_extract.namelist():
                    path_dest = os.path.join(path_addons, os.path.basename(f))
                    if os.path.exists(path_dest):
                        self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
                        return {'CANCELLED'}

            try:  # extract the file to "addons"
                file_to_extract.extractall(path_addons)

                # zip files can create this dir with metadata, don't need it
                macosx_dir = os.path.join(path_addons, '__MACOSX')
                if os.path.isdir(macosx_dir):
                    shutil.rmtree(macosx_dir)

            except:
                traceback.print_exc()
                return {'CANCELLED'}

        else:
            path_dest = os.path.join(path_addons, os.path.basename(pyfile))

            if self.overwrite:
                WM_OT_addon_install._module_remove(path_addons, os.path.basename(pyfile))
            elif os.path.exists(path_dest):
                self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
                return {'CANCELLED'}

            #if not compressed file just copy into the addon path
            try:
                shutil.copyfile(pyfile, path_dest)

            except:
                traceback.print_exc()
                return {'CANCELLED'}

        addons_new = {mod.__name__ for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules)} - addons_old
        addons_new.discard("modules")

        # disable any addons we may have enabled previously and removed.
        # this is unlikely but do just incase. bug [#23978]
        for new_addon in addons_new:
            addon_utils.disable(new_addon)

        # possible the zip contains multiple addons, we could disallow this
        # but for now just use the first
        for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules):
            if mod.__name__ in addons_new:
                info = addon_utils.module_bl_info(mod)

                # show the newly installed addon.
                context.window_manager.addon_filter = 'All'
                context.window_manager.addon_search = info["name"]
                break

        # incase a new module path was created to install this addon.
        bpy.utils.refresh_script_paths()

        # TODO, should not be a warning.
        # self.report({'WARNING'}, "File installed to '%s'\n" % path_dest)
        return {'FINISHED'}