~siretart/ubuntu/utopic/blender/libav10

« back to all changes in this revision

Viewing changes to release/scripts/modules/addon_utils.py

  • Committer: Package Import Robot
  • Author(s): Matteo F. Vescovi
  • Date: 2012-07-23 08:54:18 UTC
  • mfrom: (14.2.16 sid)
  • mto: (14.2.19 sid)
  • mto: This revision was merged to the branch mainline in revision 42.
  • Revision ID: package-import@ubuntu.com-20120723085418-9foz30v6afaf5ffs
Tags: 2.63a-2
* debian/: Cycles support added (Closes: #658075)
  For now, this top feature has been enabled only
  on [any-amd64 any-i386] architectures because
  of OpenImageIO failing on all others
* debian/: scripts installation path changed
  from /usr/lib to /usr/share:
  + debian/patches/: patchset re-worked for path changing
  + debian/control: "Breaks" field added on yafaray-exporter

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# ##### BEGIN GPL LICENSE BLOCK #####
 
2
#
 
3
#  This program is free software; you can redistribute it and/or
 
4
#  modify it under the terms of the GNU General Public License
 
5
#  as published by the Free Software Foundation; either version 2
 
6
#  of the License, or (at your option) any later version.
 
7
#
 
8
#  This program is distributed in the hope that it will be useful,
 
9
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
#  GNU General Public License for more details.
 
12
#
 
13
#  You should have received a copy of the GNU General Public License
 
14
#  along with this program; if not, write to the Free Software Foundation,
 
15
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
16
#
 
17
# ##### END GPL LICENSE BLOCK #####
 
18
 
 
19
# <pep8-80 compliant>
 
20
 
 
21
__all__ = (
 
22
    "paths",
 
23
    "modules",
 
24
    "check",
 
25
    "enable",
 
26
    "disable",
 
27
    "reset_all",
 
28
    "module_bl_info",
 
29
    )
 
30
 
 
31
import bpy as _bpy
 
32
 
 
33
 
 
34
error_duplicates = False
 
35
error_encoding = False
 
36
addons_fake_modules = {}
 
37
 
 
38
 
 
39
def paths():
 
40
    # RELEASE SCRIPTS: official scripts distributed in Blender releases
 
41
    addon_paths = _bpy.utils.script_paths("addons")
 
42
 
 
43
    # CONTRIB SCRIPTS: good for testing but not official scripts yet
 
44
    # if folder addons_contrib/ exists, scripts in there will be loaded too
 
45
    addon_paths += _bpy.utils.script_paths("addons_contrib")
 
46
 
 
47
    # EXTERN SCRIPTS: external projects scripts
 
48
    # if folder addons_extern/ exists, scripts in there will be loaded too
 
49
    addon_paths += _bpy.utils.script_paths("addons_extern")
 
50
 
 
51
    return addon_paths
 
52
 
 
53
 
 
54
def modules(module_cache):
 
55
    global error_duplicates
 
56
    global error_encoding
 
57
    import os
 
58
 
 
59
    error_duplicates = False
 
60
    error_encoding = False
 
61
 
 
62
    path_list = paths()
 
63
 
 
64
    # fake module importing
 
65
    def fake_module(mod_name, mod_path, speedy=True, force_support=None):
 
66
        global error_encoding
 
67
 
 
68
        if _bpy.app.debug_python:
 
69
            print("fake_module", mod_path, mod_name)
 
70
        import ast
 
71
        ModuleType = type(ast)
 
72
        file_mod = open(mod_path, "r", encoding='UTF-8')
 
73
        if speedy:
 
74
            lines = []
 
75
            line_iter = iter(file_mod)
 
76
            l = ""
 
77
            while not l.startswith("bl_info"):
 
78
                try:
 
79
                    l = line_iter.readline()
 
80
                except UnicodeDecodeError as e:
 
81
                    if not error_encoding:
 
82
                        error_encoding = True
 
83
                        print("Error reading file as UTF-8:", mod_path, e)
 
84
                    file_mod.close()
 
85
                    return None
 
86
 
 
87
                if len(l) == 0:
 
88
                    break
 
89
            while l.rstrip():
 
90
                lines.append(l)
 
91
                try:
 
92
                    l = line_iter.readline()
 
93
                except UnicodeDecodeError as e:
 
94
                    if not error_encoding:
 
95
                        error_encoding = True
 
96
                        print("Error reading file as UTF-8:", mod_path, e)
 
97
                    file_mod.close()
 
98
                    return None
 
99
 
 
100
            data = "".join(lines)
 
101
 
 
102
        else:
 
103
            data = file_mod.read()
 
104
 
 
105
        file_mod.close()
 
106
 
 
107
        try:
 
108
            ast_data = ast.parse(data, filename=mod_path)
 
109
        except:
 
110
            print("Syntax error 'ast.parse' can't read %r" % mod_path)
 
111
            import traceback
 
112
            traceback.print_exc()
 
113
            ast_data = None
 
114
 
 
115
        body_info = None
 
116
 
 
117
        if ast_data:
 
118
            for body in ast_data.body:
 
119
                if body.__class__ == ast.Assign:
 
120
                    if len(body.targets) == 1:
 
121
                        if getattr(body.targets[0], "id", "") == "bl_info":
 
122
                            body_info = body
 
123
                            break
 
124
 
 
125
        if body_info:
 
126
            try:
 
127
                mod = ModuleType(mod_name)
 
128
                mod.bl_info = ast.literal_eval(body.value)
 
129
                mod.__file__ = mod_path
 
130
                mod.__time__ = os.path.getmtime(mod_path)
 
131
            except:
 
132
                print("AST error in module %s" % mod_name)
 
133
                import traceback
 
134
                traceback.print_exc()
 
135
                raise
 
136
 
 
137
            if force_support is not None:
 
138
                mod.bl_info["support"] = force_support
 
139
 
 
140
            return mod
 
141
        else:
 
142
            return None
 
143
 
 
144
    modules_stale = set(module_cache.keys())
 
145
 
 
146
    for path in path_list:
 
147
 
 
148
        # force all contrib addons to be 'TESTING'
 
149
        if path.endswith("addons_contrib") or path.endswith("addons_extern"):
 
150
            force_support = 'TESTING'
 
151
        else:
 
152
            force_support = None
 
153
 
 
154
        for mod_name, mod_path in _bpy.path.module_names(path):
 
155
            modules_stale -= {mod_name}
 
156
            mod = module_cache.get(mod_name)
 
157
            if mod:
 
158
                if mod.__file__ != mod_path:
 
159
                    print("multiple addons with the same name:\n  %r\n  %r" %
 
160
                          (mod.__file__, mod_path))
 
161
                    error_duplicates = True
 
162
 
 
163
                elif mod.__time__ != os.path.getmtime(mod_path):
 
164
                    print("reloading addon:",
 
165
                          mod_name,
 
166
                          mod.__time__,
 
167
                          os.path.getmtime(mod_path),
 
168
                          mod_path,
 
169
                          )
 
170
                    del module_cache[mod_name]
 
171
                    mod = None
 
172
 
 
173
            if mod is None:
 
174
                mod = fake_module(mod_name,
 
175
                                  mod_path,
 
176
                                  force_support=force_support)
 
177
                if mod:
 
178
                    module_cache[mod_name] = mod
 
179
 
 
180
    # just in case we get stale modules, not likely
 
181
    for mod_stale in modules_stale:
 
182
        del module_cache[mod_stale]
 
183
    del modules_stale
 
184
 
 
185
    mod_list = list(module_cache.values())
 
186
    mod_list.sort(key=lambda mod: (mod.bl_info['category'],
 
187
                                   mod.bl_info['name'],
 
188
                                   ))
 
189
    return mod_list
 
190
 
 
191
 
 
192
def check(module_name):
 
193
    """
 
194
    Returns the loaded state of the addon.
 
195
 
 
196
    :arg module_name: The name of the addon and module.
 
197
    :type module_name: string
 
198
    :return: (loaded_default, loaded_state)
 
199
    :rtype: tuple of booleans
 
200
    """
 
201
    import sys
 
202
    loaded_default = module_name in _bpy.context.user_preferences.addons
 
203
 
 
204
    mod = sys.modules.get(module_name)
 
205
    loaded_state = mod and getattr(mod, "__addon_enabled__", Ellipsis)
 
206
 
 
207
    if loaded_state is Ellipsis:
 
208
        print("Warning: addon-module %r found module "
 
209
               "but without __addon_enabled__ field, "
 
210
               "possible name collision from file: %r" %
 
211
               (module_name, getattr(mod, "__file__", "<unknown>")))
 
212
 
 
213
        loaded_state = False
 
214
 
 
215
    return loaded_default, loaded_state
 
216
 
 
217
 
 
218
def enable(module_name, default_set=True):
 
219
    """
 
220
    Enables an addon by name.
 
221
 
 
222
    :arg module_name: The name of the addon and module.
 
223
    :type module_name: string
 
224
    :return: the loaded module or None on failure.
 
225
    :rtype: module
 
226
    """
 
227
 
 
228
    import os
 
229
    import sys
 
230
    import imp
 
231
 
 
232
    def handle_error():
 
233
        import traceback
 
234
        traceback.print_exc()
 
235
 
 
236
    # reload if the mtime changes
 
237
    mod = sys.modules.get(module_name)
 
238
    # chances of the file _not_ existing are low, but it could be removed
 
239
    if mod and os.path.exists(mod.__file__):
 
240
        mod.__addon_enabled__ = False
 
241
        mtime_orig = getattr(mod, "__time__", 0)
 
242
        mtime_new = os.path.getmtime(mod.__file__)
 
243
        if mtime_orig != mtime_new:
 
244
            print("module changed on disk:", mod.__file__, "reloading...")
 
245
 
 
246
            try:
 
247
                imp.reload(mod)
 
248
            except:
 
249
                handle_error()
 
250
                del sys.modules[module_name]
 
251
                return None
 
252
            mod.__addon_enabled__ = False
 
253
 
 
254
    # Split registering up into 3 steps so we can undo
 
255
    # if it fails par way through.
 
256
 
 
257
    # 1) try import
 
258
    try:
 
259
        mod = __import__(module_name)
 
260
        mod.__time__ = os.path.getmtime(mod.__file__)
 
261
        mod.__addon_enabled__ = False
 
262
    except:
 
263
        handle_error()
 
264
        return None
 
265
 
 
266
    # 2) try register collected modules
 
267
    # removed, addons need to handle own registration now.
 
268
 
 
269
    # 3) try run the modules register function
 
270
    try:
 
271
        mod.register()
 
272
    except:
 
273
        handle_error()
 
274
        del sys.modules[module_name]
 
275
        return None
 
276
 
 
277
    # * OK loaded successfully! *
 
278
    if default_set:
 
279
        # just in case its enabled already
 
280
        ext = _bpy.context.user_preferences.addons.get(module_name)
 
281
        if not ext:
 
282
            ext = _bpy.context.user_preferences.addons.new()
 
283
            ext.module = module_name
 
284
 
 
285
    mod.__addon_enabled__ = True
 
286
 
 
287
    if _bpy.app.debug_python:
 
288
        print("\taddon_utils.enable", mod.__name__)
 
289
 
 
290
    return mod
 
291
 
 
292
 
 
293
def disable(module_name, default_set=True):
 
294
    """
 
295
    Disables an addon by name.
 
296
 
 
297
    :arg module_name: The name of the addon and module.
 
298
    :type module_name: string
 
299
    """
 
300
    import sys
 
301
    mod = sys.modules.get(module_name)
 
302
 
 
303
    # possible this addon is from a previous session and didn't load a
 
304
    # module this time. So even if the module is not found, still disable
 
305
    # the addon in the user prefs.
 
306
    if mod:
 
307
        mod.__addon_enabled__ = False
 
308
 
 
309
        try:
 
310
            mod.unregister()
 
311
        except:
 
312
            import traceback
 
313
            traceback.print_exc()
 
314
    else:
 
315
        print("addon_utils.disable", module_name, "not loaded")
 
316
 
 
317
    # could be in more then once, unlikely but better do this just in case.
 
318
    addons = _bpy.context.user_preferences.addons
 
319
 
 
320
    if default_set:
 
321
        while module_name in addons:
 
322
            addon = addons.get(module_name)
 
323
            if addon:
 
324
                addons.remove(addon)
 
325
 
 
326
    if _bpy.app.debug_python:
 
327
        print("\taddon_utils.disable", module_name)
 
328
 
 
329
 
 
330
def reset_all(reload_scripts=False):
 
331
    """
 
332
    Sets the addon state based on the user preferences.
 
333
    """
 
334
    import sys
 
335
    import imp
 
336
 
 
337
    # RELEASE SCRIPTS: official scripts distributed in Blender releases
 
338
    paths_list = paths()
 
339
 
 
340
    for path in paths_list:
 
341
        _bpy.utils._sys_path_ensure(path)
 
342
        for mod_name, mod_path in _bpy.path.module_names(path):
 
343
            is_enabled, is_loaded = check(mod_name)
 
344
 
 
345
            # first check if reload is needed before changing state.
 
346
            if reload_scripts:
 
347
                mod = sys.modules.get(mod_name)
 
348
                if mod:
 
349
                    imp.reload(mod)
 
350
 
 
351
            if is_enabled == is_loaded:
 
352
                pass
 
353
            elif is_enabled:
 
354
                enable(mod_name)
 
355
            elif is_loaded:
 
356
                print("\taddon_utils.reset_all unloading", mod_name)
 
357
                disable(mod_name)
 
358
 
 
359
 
 
360
def module_bl_info(mod, info_basis={"name": "",
 
361
                                    "author": "",
 
362
                                    "version": (),
 
363
                                    "blender": (),
 
364
                                    "location": "",
 
365
                                    "description": "",
 
366
                                    "wiki_url": "",
 
367
                                    "tracker_url": "",
 
368
                                    "support": 'COMMUNITY',
 
369
                                    "category": "",
 
370
                                    "warning": "",
 
371
                                    "show_expanded": False,
 
372
                                    }
 
373
                   ):
 
374
 
 
375
    addon_info = getattr(mod, "bl_info", {})
 
376
 
 
377
    # avoid re-initializing
 
378
    if "_init" in addon_info:
 
379
        return addon_info
 
380
 
 
381
    if not addon_info:
 
382
        mod.bl_info = addon_info
 
383
 
 
384
    for key, value in info_basis.items():
 
385
        addon_info.setdefault(key, value)
 
386
 
 
387
    if not addon_info["name"]:
 
388
        addon_info["name"] = mod.__name__
 
389
 
 
390
    addon_info["_init"] = None
 
391
    return addon_info