VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/python/server/loader.py@ 82912

Last change on this file since 82912 was 59798, checked in by vboxsync, 9 years ago

re-applied the Python 3 changes which were backed out in r105674 sans the changes in .cpp

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette