dissallow access to the context while addons import and register.

Since the window manager is needed for keymaps this is kept as an exception.

some addons will need updating, but in every case I've seen addons should not be accessing the context while registering.
(bad stuff! - declaring the scene as a global variable - which crashes when the users loads a new file, manipulating the active object or scene... tsk tsk)
This commit is contained in:
2012-12-19 07:27:23 +00:00
parent 5837c7f092
commit ef665b3d18
2 changed files with 26 additions and 9 deletions

View File

@@ -29,6 +29,14 @@ __all__ = (
)
import bpy as _bpy
_user_preferences = _bpy.context.user_preferences
class _RestrictedContext():
__slots__ = ()
@property
def window_manager(self):
return _bpy.data.window_managers[0]
_ctx_restricted = _RestrictedContext()
error_duplicates = False
@@ -201,7 +209,7 @@ def check(module_name):
:rtype: tuple of booleans
"""
import sys
loaded_default = module_name in _bpy.context.user_preferences.addons
loaded_default = module_name in _user_preferences.addons
mod = sys.modules.get(module_name)
loaded_state = mod and getattr(mod, "__addon_enabled__", Ellipsis)
@@ -259,6 +267,11 @@ def enable(module_name, default_set=True, persistent=False):
# Split registering up into 3 steps so we can undo
# if it fails par way through.
# first disable the context, using the context at all is
# really bad while loading an addon, don't do it!
ctx = _bpy.context
_bpy.context = _ctx_restricted
# 1) try import
try:
mod = __import__(module_name)
@@ -266,6 +279,7 @@ def enable(module_name, default_set=True, persistent=False):
mod.__addon_enabled__ = False
except:
handle_error()
_bpy.context = ctx
return None
# 2) try register collected modules
@@ -279,14 +293,18 @@ def enable(module_name, default_set=True, persistent=False):
getattr(mod, "__file__", module_name))
handle_error()
del sys.modules[module_name]
_bpy.context = ctx
return None
# finally restore the context
_bpy.context = ctx
# * OK loaded successfully! *
if default_set:
# just in case its enabled already
ext = _bpy.context.user_preferences.addons.get(module_name)
ext = _user_preferences.addons.get(module_name)
if not ext:
ext = _bpy.context.user_preferences.addons.new()
ext = _user_preferences.addons.new()
ext.module = module_name
mod.__addon_enabled__ = True
@@ -327,7 +345,7 @@ def disable(module_name, default_set=True):
(module_name, "disabled" if mod is None else "loaded"))
# could be in more then once, unlikely but better do this just in case.
addons = _bpy.context.user_preferences.addons
addons = _user_preferences.addons
if default_set:
while module_name in addons: