File: Plugins.py

package info (click to toggle)
boa-constructor 0.4.4cvs20050714-4
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 10,080 kB
  • ctags: 9,175
  • sloc: python: 56,189; sh: 545; makefile: 40
file content (256 lines) | stat: -rw-r--r-- 8,941 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#-----------------------------------------------------------------------------
# Name:        Plugins.py
# Purpose:     
#
# Author:      Riaan Booysen
#
# Created:     2003
# RCS-ID:      $Id: Plugins.py,v 1.5 2005/05/18 13:20:13 riaan Exp $
# Copyright:   (c) 2003 - 2005
# Licence:     GPL
#-----------------------------------------------------------------------------

import os, glob, new, pprint

#from wxPython import wx

import Preferences, Utils

# MVC
from Models import EditorHelper, Controllers
# Components
import PaletteStore
# Explorers
from Explorers import ExplorerNodes


class PluginError(Exception):
    pass

class SkipPlugin(PluginError):
    """ Special error, used to abort importing plugins early if they depend
    on modules not loaded

    Warning indicating problem is displayed """

class SkipPluginSilently(SkipPlugin):
    """ Special error, used to abort importing plugins early if they depend
    on modules not available.

    Plugin is skipped silently.
    Used when user can do nothing about the problem (like switching platforms ;)
    """

def importFromPlugins(name):
    # find module
    pluginsPath = Preferences.pyPath + '/Plug-ins'
    paths = [pluginsPath]
    if Preferences.extraPluginsPath:
        paths.append(Preferences.extraPluginsPath)
    pluginRcPath = Preferences.rcPath+ '/Plug-ins'
    if Preferences.rcPath != Preferences.pyPath and os.path.isdir(pluginRcPath):
        paths.append(pluginRcPath)

    modname = name.replace('.', '/') + '.py'
    for pth in paths:
        modpath = os.path.join(pth, modname)
        if os.path.isfile(modpath):
            break
    else:
        raise ImportError, 'Module %s could not be found in Plug-ins'

    mod = new.module(name)

    execfile(modpath, mod.__dict__)

    return mod

def transportInstalled(transport):
    return transport in eval(
         Utils.createAndReadConfig('Explorer').get('explorer', 
                                                   'installedtransports'),{})

def readPluginsState(section):
    cfg = Utils.createAndReadConfig('Explorer')
    if cfg.has_section(section):
        if cfg.has_option(section, 'ordered'):
            ordered = eval(cfg.get(section, 'ordered'), {})
        else:
            ordered = []
        if cfg.has_option(section, 'disabled'):
            disabled = eval(cfg.get(section, 'disabled'), {})
        else:
            disabled = []
        return ordered, disabled
    else:
        return [], []
    
def writePluginsState(section, ordered, disabled):
    cfg = Utils.createAndReadConfig('Explorer')
    if not cfg.has_section(section):
        cfg.add_section(section)
    cfg.set(section, 'ordered', pprint.pformat(ordered))
    cfg.set(section, 'disabled', pprint.pformat(disabled))
    
    Utils.writeConfig(cfg)
    
def buildPluginExecList():
    if not Preferences.pluginSections:
        return []

    pluginExecList = []
    pluginPathGlobs = []
    for sect, path in zip(Preferences.pluginSections, Preferences.pluginPaths):
        pluginState = readPluginsState(sect)
        pluginPathGlobs.append( (os.path.join(path, '*.plug-in.py'), pluginState) )

    for globPath, (ordered, disabled) in pluginPathGlobs:
        globList = glob.glob(globPath)

        insIdx = 0
        orderedPlugins = []
        for pluginName in ordered:
            pluginFilename = os.path.join(os.path.dirname(globPath),
                                          pluginName)+'.plug-in.py'
            try:
                idx = globList.index(pluginFilename)
            except ValueError:
                #wx.LogWarning('Ordered plugin: %s not found: %'%pluginFilename)
                pass
            else:
                del globList[idx]
                globList.insert(insIdx, pluginFilename)
                insIdx = insIdx + 1
                orderedPlugins.append(pluginFilename)

        disabledPlugins = []
        for pluginName in disabled:
            disabledPlugins.append(os.path.join(os.path.dirname(globPath),
                                                pluginName)+'.plug-in.py')

        for pluginFilename in globList:
            pluginExecList.append( (pluginFilename,
                                    pluginFilename in orderedPlugins,
                                    pluginFilename not in disabledPlugins) )
    return pluginExecList

def assureConfigFile(filename, data):
    if not os.path.exists(filename):
        open(filename, 'w').write(data)


#---Registration API------------------------------------------------------------

def registerFileType(Controller, Model=None, newName='', addToNew=True,
                     aliasExts=()):
    """ Registers an IDE filetype that can be created from the New Palette page 
    """
    if Model is None:
        Model = Controller.Model

    EditorHelper.modelReg[Model.modelIdentifier] = Model
    if aliasExts:
        for ext in aliasExts:
            EditorHelper.extMap[ext] = Model

    Controllers.modelControllerReg[Model] = Controller

    if addToNew:
        if not newName:
            newName = Model.modelIdentifier
        PaletteStore.newControllers[newName] = Controller
        PaletteStore.paletteLists['New'].append(newName)

def registerFileTypes(*args):
    """ Convenience function for registerFileType, allows multiple Controller args """
    for Controller in args:
        registerFileType(Controller)

def registerPalettePage(paletteName, paletteTitle):
    """ Register a new page on the Palette"""
    if paletteName not in PaletteStore.paletteLists:
        PaletteStore.paletteLists[paletteName] = []
        PaletteStore.palette.append([paletteTitle, '', 
                                     PaletteStore.paletteLists[paletteName]])

def registerComponent(paletteName, Control, controlName, Companion):
    """ Registers a (design-time) component on the Palette """
    if paletteName is not None:
        PaletteStore.paletteLists[paletteName].append(Control)
    PaletteStore.compInfo[Control] = [controlName, Companion]

def registerComponents(paletteName, *components):
    """ Convenience function for registerComponent, allows multiple component tuples """
    for component in components:
        registerComponent(paletteName, *component)
    
def registerTool(name, func, bmp='-', key=''):
    """ Register an item in the Tools menu """
    EditorHelper.editorToolsReg.append( (name, func, bmp, key) )

def registerLanguageSTCStyle(name, lang, STCClass, stylesFile, insertPos=None):
    """ Register an STC mixin class and config file parameters that can be 
        configured under Preferences with the STC Style Editor """
    if insertPos is not None:
        ExplorerNodes.langStyleInfoReg.insert(insertPos, 
              (name, lang, STCClass, stylesFile ))
    else:
        ExplorerNodes.langStyleInfoReg.append(
              (name, lang, STCClass, stylesFile ))

def registerPreference(pluginName, prefName, defPrefValSrc, docs=[], info=''):
    """ Define a plug-in preference. Added to prefs.plug-ins.rc.py in needed """

    def addBlankLine(module, lineNo):
        module.addLine('', lineNo)
        return lineNo + 1
        
    Preferences.exportedPluginProps.append(prefName)
    # quick exit when name already exists
    if hasattr(Preferences, prefName):
        return 
    
    pluginPrefs = os.path.join(Preferences.rcPath, 'prefs.plug-ins.rc.py')
    lines = [l.rstrip() for l in open(pluginPrefs).readlines()]
    import moduleparse
    m = moduleparse.Module(pluginName, lines)
    if not m.globals.has_key(prefName):
        breakLineNames = m.break_lines.values()
        if pluginName not in breakLineNames:
            lineNo = addBlankLine(m, len(lines))
            lineNo = addBlankLine(m, lineNo)
            m.addLine('#-%s%s'%(pluginName, '-' * (80-2-len(pluginName))), lineNo)
            lineNo = addBlankLine(m, lineNo + 1)
        else:
            for l, n in m.break_lines.items():
                if pluginName == n:
                    lineNo = l + 1
                    break
            else:
                lineNo = len(lines)
                
        if docs:
            for doc in docs:
                m.addLine('# %s'%doc, lineNo); lineNo += 1
        if info:
            m.addLine('## %s'%info, lineNo); lineNo += 1
        
        try:
            value = eval(defPrefValSrc, Preferences.__dict__)
        except Exception, err:
            raise PluginError(
                  ('Could not create default value from "%s" for %s. (%s:%s)'%(
                  defPrefValSrc, prefName, err.__class__, err)))

        m.addLine('%s = %s'%(prefName, defPrefValSrc), lineNo)
        lineNo = addBlankLine(m, lineNo + 1)

        setattr(Preferences, prefName, value)
        open(pluginPrefs, 'wb').write(os.linesep.join(m.source))
    else:
        raise PluginError(
            '%s not in Preferences, but is defined in globals of '
            'prefs.plug-ins.rc.py'%prefName)