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/
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.
9
# The Original Code is the Python XPCOM language bindings.
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.
15
# Contributor(s): Mark Hammond <MarkH@ActiveState.com> (original author)
19
from xpcom import components
23
import glob, os, types
26
from xpcom.client import Component
28
# Until we get interface constants.
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
37
def FindCOMComponents(py_module):
38
# For now, just run over all classes looking for likely candidates.
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_"):
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)
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"
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
70
def _getCOMModuleForLocation(self, componentFile):
71
fqn = componentFile.path
72
mod = self.com_modules.get(fqn)
76
base_name = os.path.splitext(os.path.basename(fqn))[0]
77
loader = ihooks.ModuleLoader()
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 )
84
# Make and remember the COM module.
85
comps = FindCOMComponents(py_mod)
86
mod = self.moduleFactory(comps)
88
self.com_modules[fqn] = mod
91
def getFactory(self, clsid, location, type):
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)
99
def init(self, comp_mgr, registry):
101
self.comp_mgr = comp_mgr
103
print "Python component loader init() called"
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):
110
print "Python component loader - onRegister() called"
112
def autoRegisterComponents (self, when, directory):
113
directory_path = directory.path
114
self.num_modules_this_register = 0
116
print "Auto-registering all Python components in", directory_path
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":
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,)
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)
141
# All other exceptions get the full traceback.
142
print "** Registration of '%s' failed!" % (entry.leafName,)
143
traceback.print_exc()
145
def autoRegisterComponent (self, when, componentFile):
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):
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.
160
from xpcom import _xpcom
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)
167
print "PyXPCOM loader failed to process site directory before component registration"
168
traceback.print_exc()
170
self.num_modules_this_register += 1
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)
179
def autoUnregisterComponent (self, when, componentFile):
181
# auto-unregister via the module.
182
m = self._getCOMModuleForLocation(componentFile)
183
loader_mgr = components.manager.queryInterface(components.interfaces.nsIComponentLoaderManager)
185
m.unregisterSelf(components.manager, componentFile)
187
loader_mgr.removeFileInfo(componentFile, None)
190
def registerDeferredComponents (self, when):
193
print "Python component loader - registerDeferred() called"
194
return 0 # no more to register
195
def unloadAll (self, when):
197
print "Python component loader being asked to unload all components!"
199
self.com_modules = {}
201
def MakePythonComponentLoaderModule(serviceManager, nsIFile):
203
return module.Module( [PythonComponentLoader] )