File: extension.py

package info (click to toggle)
utopia-documents 2.4.4-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 30,560 kB
  • ctags: 24,084
  • sloc: cpp: 179,735; ansic: 16,208; python: 13,446; xml: 1,937; sh: 1,918; ruby: 1,594; makefile: 527; sql: 6
file content (124 lines) | stat: -rw-r--r-- 4,786 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
###############################################################################
#   
#    This file is part of the Utopia Documents application.
#        Copyright (c) 2008-2014 Lost Island Labs
#            <info@utopiadocs.com>
#    
#    Utopia Documents is free software: you can redistribute it and/or modify
#    it under the terms of the GNU GENERAL PUBLIC LICENSE VERSION 3 as
#    published by the Free Software Foundation.
#    
#    Utopia Documents is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#    Public License for more details.
#    
#    In addition, as a special exception, the copyright holders give
#    permission to link the code of portions of this program with the OpenSSL
#    library under certain conditions as described in each individual source
#    file, and distribute linked combinations including the two.
#    
#    You must obey the GNU General Public License in all respects for all of
#    the code used other than OpenSSL. If you modify file(s) with this
#    exception, you may extend this exception to your version of the file(s),
#    but you are not obligated to do so. If you do not wish to do so, delete
#    this exception statement from your version.
#    
#    You should have received a copy of the GNU General Public License
#    along with Utopia Documents. If not, see <http://www.gnu.org/licenses/>
#   
###############################################################################

import os, sys, fnmatch, uuid, inspect

# Define metaclass for managing extensions
class MetaExtension(type):
    __extensions = dict()

    def _typeName(cls):
        return "%s.%s" % (cls.__module__, cls.__name__)

    def __init__(cls, name, bases, attrs):
        # Keep track of subclasses of Extension
        if not attrs.get('__module__', '').startswith('utopia.') and not cls.__name__.startswith('_'):
            cls.__extensions[cls._typeName()] = cls
            cls.__uuid__ = uuid.uuid4().urn
            print '    Found', cls
            # Give this class' module the name of its loaded plugin
            inspect.getmodule(cls).__dict__['__plugin__'] = inspect.stack()[-3][0].f_globals['__name__']

    def __del__(cls):
        # Keep track of subclasses of Extension
        del cls.__extensions[cls._typeName()]

    def types(cls):
        return tuple([c for c in cls.__extensions.values() if issubclass(c, cls) and c != cls])

    def typeNames(cls):
        return [n for (n, c) in cls.__extensions.iteritems() if issubclass(c, cls) and c != cls]

    def typeOf(cls, name):
        return cls.__extensions[name]

    def describe(cls, name):
        return str(cls.__doc__).strip()

# Abstract base class for extensions
class Extension(object):
    __metaclass__ = MetaExtension
    def uuid(self):
        return getattr(self, '__uuid__', None)

# Clear up directory of cached Python plugins
def cleanPluginDir(dir):
    print 'Cleaning path:', dir
    if os.path.isdir(dir):
        # Clear up dir
        for doomed in os.listdir(dir):
            if fnmatch.fnmatch(doomed, '[!_]*.py[co]'):
                os.unlink(os.path.join(dir, doomed))

def _makeLoader(module_path):
    class Loader:
        def get_data(self, data_path):
            try:
                path = os.path.join(module_path, data_path)
                return open(path, 'r').read()
            except:
                pass
    return Loader()

# Load all extensions from a given plugin object
def loadPlugin(path):
    print "Loading extensions from:", path
    dir, p = os.path.split(path)
    if os.path.isdir(path):
        if fnmatch.fnmatch(p, '[!_]*.zip'):
            try:
                sys.path.append(os.path.join(dir, p, 'python'))
                mod = __import__(os.path.splitext(p)[0])
                mod.__file__ = path
                mod.__loader__ = _makeLoader(path)
                sys.path.pop()
            except Exception, e:
                print "Failed to load %s\n%s" % (p, e)
    else:
        # Attempt to load the plugin
        if fnmatch.fnmatch(path, '[!_]*.py'):
            try:
                sys.path.append(dir)
                __import__(os.path.splitext(p)[0]).__file__ = path
                sys.path.pop()
            except Exception, e:
                print "Failed to load %s\n%s" % (p, e)
        elif fnmatch.fnmatch(p, '[!_]*.zip'):
            try:
                sys.path.append(os.path.join(dir, p, 'python'))
                __import__(os.path.splitext(p)[0]).__file__ = path
                sys.path.pop()
            except Exception, e:
                print "Failed to load %s\n%s" % (p, e)



__all__ = ['Extension', 'loadPlugin']