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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
|
#
# THIS FILE IS PART OF THE JOKOSHER PROJECT AND LICENSED UNDER THE GPL. SEE
# THE 'COPYING' FILE FOR DETAILS
#
# ExtensionManager.py
#
# This module defines the ExtensionManager class which is
# responsible for controlling extensions to Jokosher
#
#-------------------------------------------------------------------------------
import Globals
import Extension
import pkg_resources
import os.path
import imp
import gtk
import shutil
#=========================================================================
class ExtensionManager:
"""
The ExtensionManager class handles the installation and running of
Extensions. It also controls their disabling and removal.
"""
#_____________________________________________________________________
def __init__(self, mainapp):
"""
Creates a new Instance of ExtensionManager.
Parameters:
parent -- the parent MainApp Jokosher window.
"""
self.mainapp = mainapp
self.loadedExtensions = []
self.API = Extension.ExtensionAPI(mainapp)
self.LoadAllExtensions()
#_____________________________________________________________________
def register(self, extension, filename, directory, local):
"""
Called from Extension.LoadAllExtensions afer the Extensions
module has been imported (and the class instantiated in the case
of extensions that are eggs).
Parameters:
extension -- a reference to the Extension. Either a module
or in the case of an Extension imported from an
egg, an instance object.
filename -- the name of the file containing the Extension.
directory -- full path to the directory containing the file.
local -- True = the extension is to be copied to the
local extension directory after checking
False = don't copy the Extension.
Returns:
True -- the Extension was successfully registered.
False -- an error ocurred while trying to register the Extension,
or the Extension has been disabled via the ExtensionManagerDialog.
"""
name = None
preferences = False
# check if the necessary attributes EXTENSION_NAME, EXTENSION_VERSION
# and EXTENSION_DESCRIPTION are present and
# refuse to start the extension if they are missing.
requiredAttributes = ("EXTENSION_NAME", "EXTENSION_VERSION",
"EXTENSION_DESCRIPTION", "startup", "shutdown")
missingAttrs = []
for attr in requiredAttributes:
if not hasattr(extension, attr):
missingAttrs.append(attr)
if missingAttrs:
Globals.debug("\t" + filename, "missing", ", ".join(missingAttrs))
return False
else:
name = extension.EXTENSION_NAME
version = extension.EXTENSION_VERSION
description = extension.EXTENSION_DESCRIPTION
# check for preferences attribute
if hasattr(extension, "preferences"):
preferences = True
# check extension is not already loaded
for testExtension in self.loadedExtensions:
if testExtension["name"] == name:
Globals.debug(filename + " extension '" + name + "' already present")
return False
# find full file name of extension
extensionFile = os.path.join(directory, filename)
# if we are installing locally first check the file doesn't exist and
# then try and copy it
if local:
extensionFile = os.path.join(Globals.JOKOSHER_DATA_HOME, "extensions", filename)
if os.path.exists(extensionFile):
Globals.debug("Filename " + extensionFile + " already exists")
return False
else:
try:
shutil.copy(os.path.join(directory, filename), extensionFile)
except Exception, e:
Globals.debug(filename + "Failed copying file: " + str(e))
return False
# check if extension's requirements are met (only if the extension requires it)
testResults = (True, "")
try:
if hasattr(extension, "check_dependencies"):
testResults = extension.check_dependencies()
except Exception, e:
Globals.debug(name + " extension could not check its dependencies")
Globals.debug(e)
return False
# if the system doesn't provide what the extension needs,
# fail loading this plugin and set the error message
if testResults[0] == False:
#TODO: inform the user of the error
Globals.debug(name + ": "+testResults[1])
return False
# check if the extension is blacklisted, if so, mark it as disabled
enabled = True
if name in Globals.settings.extensions['extensions_blacklist']:
enabled = False
# add details to loadedExtensions list
self.loadedExtensions.append(
{"name":name,
"description":description,
"version":version,
"extension":extension,
"enabled":enabled,
"preferences":preferences,
"filename":extensionFile })
return True
#_____________________________________________________________________
def GetExtensions(self):
"""
Obtain a generator for iterating the list of loadedExtensions.
Returns:
a generator with the list of loadedExtensions.
"""
return iter(self.loadedExtensions)
#_____________________________________________________________________
def LoadExtensionFromFile(self, filename, directory, local=False):
"""
Tries to load an Extension fron a given file.
Parameters:
filename -- the name of the file containing the Extension.
directory -- full path to the directory containing the file.
local -- True = the extension is to be copied to the
local extension directory after checking
False = don't copy the Extension.
Returns:
True -- the Extension was successfully loaded.
False -- an error ocurred while trying to load the Extension,
or the Extension has been disabled via the ExtensionManagerDialog.
"""
Globals.debug("\timporting extension", filename)
extension = None
if filename.endswith(".py"):
# for a python module try and import it
extension = None
fn = os.path.splitext(filename)[0]
exten_file, filename, description = imp.find_module(fn, [directory])
try:
extension = imp.load_module(fn, exten_file, filename, description)
except Exception, e:
Globals.debug("\t\t...failed.")
Globals.debug(e)
if exten_file:
exten_file.close()
return False
if exten_file:
exten_file.close()
elif filename.endswith(".egg"):
# for an egg, add it to working_set and then try and
# load it and pick out the entry points
fullName = os.path.join(directory, filename)
pkg_resources.working_set.add_entry(fullName)
dist_generator = pkg_resources.find_distributions(fullName)
for dist in dist_generator:
try:
extension_class = dist.load_entry_point("jokosher.extensions", "extension")
# create an instance of the class
extension = extension_class()
except Exception, e :
Globals.debug("\t\t...failed.")
Globals.debug(e)
return False
else:
# any other file extension is wrong
Globals.debug("Invalid extension file suffix for", filename)
return False
# try and register the extension - quit if failed
if not self.register(extension, filename, directory, local):
return False
# if we're still here then start the extension, if its not in the extensions_blacklist
if extension.EXTENSION_NAME not in Globals.settings.extensions['extensions_blacklist']:
dir
if not self.StartExtension(self.loadedExtensions[len(self.loadedExtensions)-1]["filename"]):
return False
return True
#_____________________________________________________________________
def LoadExtensionsFromEggs(self, directory):
"""
Tries to load Extensions fron a given directory.
Parameters:
directory -- full path to the directory containing Eggs.
Returns:
True -- the Extension was successfully loaded.
False -- an error ocurred while trying to load the Extension,
or the Extension has been disabled via the ExtensionManagerDialog.
"""
Globals.debug("\timporting extensions from directory", directory)
pkg_resources.working_set.add_entry(directory)
dist_generator = pkg_resources.find_distributions(directory)
for dist in dist_generator:
try:
extension_class = dist.load_entry_point("jokosher.extensions", "extension")
# create an instance of the class
extension = extension_class()
filename = dist.egg_name()
except Exception, e :
Globals.debug("\t\t...failed.")
Globals.debug(e)
return False
# try and register the extension - continue if failed
if not self.register(extension, filename, directory, False):
Globals.debug("\tcannot register extension ", filename)
continue
# if we're still here then start the extension, if its not in the extensions_blacklist
if extension.EXTENSION_NAME not in Globals.settings.extensions['extensions_blacklist']:
if not self.StartExtension(self.loadedExtensions[len(self.loadedExtensions)-1]["filename"]):
continue
return True
#_____________________________________________________________________
def StopExtension(self, filename):
"""
Stops the given Extension.
Considerations:
This method executes the shutdown() function of the Extension.
This is mainly for disabling Extensions on the fly, but is also
used for removing them.
Parameters:
filename -- the name of the file containing the Extension.
Returns:
True -- the Extension was successfully stopped.
False -- an error ocurred while trying to stop the Extension.
"""
for extension in self.GetExtensions():
if extension['filename'] == filename:
try:
extension['extension'].shutdown()
except Exception, e:
Globals.debug(filename + " extension failed to shut down")
Globals.debug(e)
return False
return True
#_____________________________________________________________________
def StartExtension(self, filename):
"""
Starts the given Extension.
Considerations:
This method executes the startup() function of the Extension
This is mainly for enabling an Extension on the fly without
loading another instance.
Parameters:
filename -- the name of the file containing the Extension.
Returns:
True -- the Extension was successfully started.
False -- an error ocurred while trying to start the Extension.
"""
for extension in self.GetExtensions():
if extension['filename'] == filename:
try:
extension['extension'].startup(self.API)
except Exception, e:
Globals.debug(filename + " extension failed to start")
Globals.debug(e)
return False
return True
#_____________________________________________________________________
def RemoveExtension(self, filename):
"""
Removes the given Extension.
Considerations:
This function "unloads" the Extension. It executes the shutdown()
function of the Extension and then removes it from loadedExtensions.
Parameters:
filename -- the name of the file containing the Extension.
Returns:
True -- the Extension was successfully removed.
False -- an error ocurred while trying to remove the Extension.
"""
self.StopExtension(filename)
index = -1
for extension in self.GetExtensions():
index += 1
if extension['filename'] == filename:
try:
os.remove(filename)
self.loadedExtensions.pop(index)
except Exception, e:
Globals.debug("Failed to remove " + filename)
Globals.debug(e)
return False
return True
#_____________________________________________________________________
def ExtensionPreferences(self, filename):
"""
Loads the preferences() function of an Extension.
Parameters:
filename -- the name of the file containing the Extension.
Returns:
True -- the Extension's preferences were successfully loaded.
False -- an error ocurred while trying to load the Extension's
preferences.
"""
for extension in self.GetExtensions():
if extension['filename'] == filename:
try:
extension['extension'].preferences()
except:
Globals.debug("Someone screwed up their preferences function")
return False
return True
#_____________________________________________________________________
def LoadAllExtensions(self):
"""
Load all the Extensions found in EXTENSION_PATHS and import every .py
and .egg file found.
"""
Globals.debug("Loading extensions:")
for exten_dir in Globals.EXTENSION_PATHS:
if not os.path.isdir(exten_dir):
continue
for filename in os.listdir(exten_dir):
if filename.endswith('.py'):
self.LoadExtensionFromFile(filename, exten_dir)
# don't block the gui when loading many extensions
while gtk.events_pending():
gtk.main_iteration()
# handle Eggs (zipped or unpacked) here
self.LoadExtensionsFromEggs(exten_dir)
# don't block the gui when loading many extensions
while gtk.events_pending():
gtk.main_iteration()
#_____________________________________________________________________
#=========================================================================
|