~ubuntu-branches/ubuntu/precise/kompozer/precise

« back to all changes in this revision

Viewing changes to mozilla/extensions/python/xpcom/server/loader.py

  • Committer: Bazaar Package Importer
  • Author(s): Anthony Yarusso
  • Date: 2007-08-27 01:11:03 UTC
  • Revision ID: james.westby@ubuntu.com-20070827011103-2jgf4s6532gqu2ka
Tags: upstream-0.7.10
ImportĀ upstreamĀ versionĀ 0.7.10

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# The contents of this file are subject to the Mozilla Public License Version
 
2
# 1.1 (the "License"); you may not use this file except in compliance with the
 
3
# License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
 
4
#
 
5
# Software distributed under the License is distributed on an "AS IS" basis,
 
6
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 
7
# the specific language governing rights and limitations under the License.
 
8
#
 
9
# The Original Code is the Python XPCOM language bindings.
 
10
#
 
11
# The Initial Developer of the Original Code is ActiveState Tool Corp.
 
12
# Portions created by ActiveState Tool Corp. are Copyright (C) 2000, 2001
 
13
# ActiveState Tool Corp.  All Rights Reserved.
 
14
#
 
15
# Contributor(s): Mark Hammond <MarkH@ActiveState.com> (original author)
 
16
#
 
17
 
 
18
import xpcom
 
19
from xpcom import components
 
20
 
 
21
import module
 
22
 
 
23
import glob, os, types
 
24
import traceback
 
25
 
 
26
from xpcom.client import Component
 
27
 
 
28
# Until we get interface constants.
 
29
When_Startup = 0
 
30
When_Component = 1
 
31
When_Timer = 2
 
32
 
 
33
def _has_good_attr(object, attr):
 
34
    # Actually allows "None" to be specified to disable inherited attributes.
 
35
    return getattr(object, attr, None) is not None
 
36
 
 
37
def FindCOMComponents(py_module):
 
38
    # For now, just run over all classes looking for likely candidates.
 
39
    comps = []
 
40
    for name, object in py_module.__dict__.items():
 
41
        if type(object)==types.ClassType and \
 
42
           _has_good_attr(object, "_com_interfaces_") and \
 
43
           _has_good_attr(object, "_reg_clsid_") and \
 
44
           _has_good_attr(object, "_reg_contractid_"):
 
45
            comps.append(object)
 
46
    return comps
 
47
 
 
48
def register_self(klass, compMgr, location, registryLocation, componentType):
 
49
    pcl = PythonComponentLoader
 
50
    from xpcom import _xpcom
 
51
    svc = _xpcom.GetGlobalServiceManager().getServiceByContractID("@mozilla.org/categorymanager;1", components.interfaces.nsICategoryManager)
 
52
    svc.addCategoryEntry("component-loader", pcl._reg_component_type_, pcl._reg_contractid_, 1, 1)
 
53
 
 
54
class PythonComponentLoader:
 
55
    _com_interfaces_ = components.interfaces.nsIComponentLoader
 
56
    _reg_clsid_ = "{63B68B1E-3E62-45f0-98E3-5E0B5797970C}" # Never copy these!
 
57
    _reg_contractid_ = "moz.pyloader.1"
 
58
    _reg_desc_ = "Python component loader"
 
59
    # Optional function which performs additional special registration
 
60
    # Appears that no special unregistration is needed for ComponentLoaders, hence no unregister function.
 
61
    _reg_registrar_ = (register_self,None)
 
62
    # Custom attributes for ComponentLoader registration.
 
63
    _reg_component_type_ = "script/python"
 
64
 
 
65
    def __init__(self):
 
66
        self.com_modules = {} # Keyed by module's FQN as obtained from nsIFile.path
 
67
        self.moduleFactory = module.Module
 
68
        self.num_modules_this_register = 0
 
69
 
 
70
    def _getCOMModuleForLocation(self, componentFile):
 
71
        fqn = componentFile.path
 
72
        mod = self.com_modules.get(fqn)
 
73
        if mod is not None:
 
74
            return mod
 
75
        import ihooks, sys
 
76
        base_name = os.path.splitext(os.path.basename(fqn))[0]
 
77
        loader = ihooks.ModuleLoader()
 
78
 
 
79
        module_name_in_sys = "component:%s" % (base_name,)
 
80
        stuff = loader.find_module(base_name, [componentFile.parent.path])
 
81
        assert stuff is not None, "Couldnt find the module '%s'" % (base_name,)
 
82
        py_mod = loader.load_module( module_name_in_sys, stuff )
 
83
 
 
84
        # Make and remember the COM module.
 
85
        comps = FindCOMComponents(py_mod)
 
86
        mod = self.moduleFactory(comps)
 
87
        
 
88
        self.com_modules[fqn] = mod
 
89
        return mod
 
90
        
 
91
    def getFactory(self, clsid, location, type):
 
92
        # return the factory
 
93
        assert type == self._reg_component_type_, "Being asked to create an object not of my type:%s" % (type,)
 
94
        file_interface = components.manager.specForRegistryLocation(location)
 
95
        # delegate to the module.
 
96
        m = self._getCOMModuleForLocation(file_interface)
 
97
        return m.getClassObject(components.manager, clsid, components.interfaces.nsIFactory)
 
98
 
 
99
    def init(self, comp_mgr, registry):
 
100
        # void
 
101
        self.comp_mgr = comp_mgr
 
102
        if xpcom.verbose:
 
103
            print "Python component loader init() called"
 
104
 
 
105
     # Called when a component of the appropriate type is registered,
 
106
     # to give the component loader an opportunity to do things like
 
107
     # annotate the registry and such.
 
108
    def onRegister (self, clsid, type, className, proId, location, replace, persist):
 
109
        if xpcom.verbose:
 
110
            print "Python component loader - onRegister() called"
 
111
 
 
112
    def autoRegisterComponents (self, when, directory):
 
113
        directory_path = directory.path
 
114
        self.num_modules_this_register = 0
 
115
        if xpcom.verbose:
 
116
            print "Auto-registering all Python components in", directory_path
 
117
 
 
118
        # ToDo - work out the right thing here
 
119
        # eg - do we recurse?
 
120
        # - do we support packages?
 
121
        entries = directory.directoryEntries
 
122
        while entries.HasMoreElements():
 
123
            entry = entries.GetNext(components.interfaces.nsIFile)
 
124
            if os.path.splitext(entry.path)[1]==".py":
 
125
                try:
 
126
                    self.autoRegisterComponent(when, entry)
 
127
                # Handle some common user errors
 
128
                except xpcom.COMException, details:
 
129
                    from xpcom import nsError
 
130
                    # If the interface name does not exist, suppress the traceback
 
131
                    if details.errno==nsError.NS_ERROR_NO_INTERFACE:
 
132
                        print "** Registration of '%s' failed\n %s" % (entry.leafName,details.message,)
 
133
                    else:
 
134
                        print "** Registration of '%s' failed!" % (entry.leafName,)
 
135
                        traceback.print_exc()
 
136
                except SyntaxError, details:
 
137
                    # Syntax error in source file - no useful traceback here either.
 
138
                    print "** Registration of '%s' failed!" % (entry.leafName,)
 
139
                    traceback.print_exception(SyntaxError, details, None)
 
140
                except:
 
141
                    # All other exceptions get the full traceback.
 
142
                    print "** Registration of '%s' failed!" % (entry.leafName,)
 
143
                    traceback.print_exc()
 
144
 
 
145
    def autoRegisterComponent (self, when, componentFile):
 
146
        # bool return
 
147
        
 
148
        # Check if we actually need to do anything
 
149
        modtime = componentFile.lastModifiedTime
 
150
        loader_mgr = components.manager.queryInterface(components.interfaces.nsIComponentLoaderManager)
 
151
        if not loader_mgr.hasFileChanged(componentFile, None, modtime):
 
152
            return 1
 
153
 
 
154
        if self.num_modules_this_register == 0:
 
155
            # New components may have just installed new Python
 
156
            # modules into the main python directory (including new .pth files)
 
157
            # So we ask Python to re-process our site directory.
 
158
            # Note that the pyloader does the equivalent when loading.
 
159
            try:
 
160
                from xpcom import _xpcom
 
161
                import site
 
162
                NS_XPCOM_CURRENT_PROCESS_DIR="XCurProcD"
 
163
                dirname = _xpcom.GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR)
 
164
                dirname.append("python")
 
165
                site.addsitedir(dirname.path)
 
166
            except:
 
167
                print "PyXPCOM loader failed to process site directory before component registration"
 
168
                traceback.print_exc()
 
169
 
 
170
        self.num_modules_this_register += 1
 
171
 
 
172
        # auto-register via the module.
 
173
        m = self._getCOMModuleForLocation(componentFile)
 
174
        m.registerSelf(components.manager, componentFile, None, self._reg_component_type_)
 
175
        loader_mgr = components.manager.queryInterface(components.interfaces.nsIComponentLoaderManager)
 
176
        loader_mgr.saveFileInfo(componentFile, None, modtime)
 
177
        return 1
 
178
 
 
179
    def autoUnregisterComponent (self, when, componentFile):
 
180
        # bool return
 
181
        # auto-unregister via the module.
 
182
        m = self._getCOMModuleForLocation(componentFile)
 
183
        loader_mgr = components.manager.queryInterface(components.interfaces.nsIComponentLoaderManager)
 
184
        try:
 
185
            m.unregisterSelf(components.manager, componentFile)
 
186
        finally:
 
187
            loader_mgr.removeFileInfo(componentFile, None)
 
188
        return 1
 
189
 
 
190
    def registerDeferredComponents (self, when):
 
191
        # bool return
 
192
        if xpcom.verbose:
 
193
            print "Python component loader - registerDeferred() called"
 
194
        return 0 # no more to register
 
195
    def unloadAll (self, when):
 
196
        if xpcom.verbose:
 
197
            print "Python component loader being asked to unload all components!"
 
198
        self.comp_mgr = None
 
199
        self.com_modules = {}
 
200
 
 
201
def MakePythonComponentLoaderModule(serviceManager, nsIFile):
 
202
    import module
 
203
    return module.Module( [PythonComponentLoader] )