home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / python2.4 / site-packages / deskbar / ModuleLoader.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2006-08-31  |  8.7 KB  |  253 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. import os
  5. import sys
  6. import pydoc
  7. from os.path import abspath, expanduser, join, basename
  8. import traceback
  9. import gtk
  10. import gobject
  11. import deskbar
  12. import deskbar.Handler as deskbar
  13. import deskbar.Categories as deskbar
  14. from deskbar.Watcher import DirWatcher
  15. from deskbar.ModuleContext import ModuleContext
  16.  
  17. class ModuleLoader(gobject.GObject):
  18.     '''An auxilary class to ModuleList. Create an instance of ModuleLoader by
  19. \tspecifying the which directories to search and what extension to accept.
  20. \tThe load_all() method will load all qualified modules into the ModuleList
  21. \tspecified in the constructor.
  22. \t
  23. \tMost methods have a _async variant. These methods emits signals that is handled
  24. \tby the mainloop.
  25. \t\t\t
  26. \tHint: If you pass None as the dirs argument the ModuleLoader will not search
  27. \tfor modules at all. This is useful if you want to reload a single module for
  28. \twhich you know the path.
  29. \t'''
  30.     __gsignals__ = {
  31.         'module-loaded': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
  32.             gobject.TYPE_PYOBJECT]),
  33.         'modules-loaded': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []),
  34.         'module-initialized': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
  35.             gobject.TYPE_PYOBJECT]),
  36.         'module-not-initialized': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
  37.             gobject.TYPE_PYOBJECT]),
  38.         'module-stopped': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
  39.             gobject.TYPE_PYOBJECT]) }
  40.     
  41.     def __init__(self, dirs, extension = '.py'):
  42.         '''
  43. \t\tdirs: A list of directories to search. Relative pathnames and paths
  44. \t\t\t  containing ~ will be expanded. If dirs is None the 
  45. \t\t\t  ModuleLoader will not search for modules.
  46. \t\textension: What extension should this ModuleLoader accept (string).
  47. \t\t'''
  48.         gobject.GObject.__init__(self)
  49.         self.ext = extension
  50.         self.watcher = DirWatcher()
  51.         self.watch_id = self.watcher.connect('changed', self._on_handler_file_changed)
  52.  
  53.     
  54.     def _on_handler_file_changed(self, watcher, f):
  55.         if f in self.filelist or not self.is_module(f):
  56.             return None
  57.         
  58.         self.load(f)
  59.         self.filelist.append(f)
  60.  
  61.     
  62.     def build_filelist(self):
  63.         '''Returns a list containing the filenames of all qualified modules.
  64. \t\tThis method is automatically invoked by the constructor.
  65. \t\t'''
  66.         res = []
  67.         for d in self.dirs:
  68.             
  69.             try:
  70.                 if not os.path.exists(d):
  71.                     continue
  72.                 
  73.                 for m in os.listdir(d):
  74.                     if self.is_module(m):
  75.                         continue
  76.                     _[1][join(d, m)]
  77.             continue
  78.             except OSError:
  79.                 err = None
  80.                 print >>sys.stderr, 'Error reading directory %s, skipping.' % d
  81.                 traceback.print_exc()
  82.                 continue
  83.             
  84.  
  85.         
  86.         self.filelist = res
  87.  
  88.     
  89.     def is_module(self, filename):
  90.         '''Tests whether the filename has the appropriate extension.'''
  91.         return filename[-len(self.ext):] == self.ext
  92.  
  93.     
  94.     def import_module(self, filename):
  95.         '''Tries to import the specified file. Returns the python module on succes.
  96. \t\tPrimarily for internal use.'''
  97.         
  98.         try:
  99.             mod = pydoc.importfile(filename)
  100.         except Exception:
  101.             print >>sys.stderr, 'Error loading the file: %s.' % filename
  102.             traceback.print_exc()
  103.             return None
  104.  
  105.         
  106.         try:
  107.             if mod.HANDLERS:
  108.                 pass
  109.         except AttributeError:
  110.             print >>sys.stderr, 'The file %s is not a valid module. Skipping.' % filename
  111.             print >>sys.stderr, 'A module must have the variable HANDLERS defined as a dictionary.'
  112.             traceback.print_exc()
  113.             return None
  114.  
  115.         if mod.HANDLERS == None:
  116.             if not hasattr(mod, 'ERROR'):
  117.                 mod.ERROR = 'Unspecified Reason'
  118.             
  119.             print >>sys.stderr, '*** The file %s decided to not load itself: %s' % (filename, mod.ERROR)
  120.             return None
  121.         
  122.         for handler, infos in mod.HANDLERS.items():
  123.             if hasattr(getattr(mod, handler), 'initialize') and 'name' in infos:
  124.                 pass
  125.             else:
  126.                 print >>sys.stderr, "Class %s in file %s does not have an initialize(self) method or does not define a 'name' attribute. Skipping." % (handler, filename)
  127.                 return None
  128.             if 'requirements' in infos:
  129.                 (status, msg, callback) = infos['requirements']()
  130.                 if status == deskbar.Handler.HANDLER_IS_NOT_APPLICABLE:
  131.                     print >>sys.stderr, '***'
  132.                     print >>sys.stderr, '*** The file %s (%s) decided to not load itself: %s' % (filename, handler, msg)
  133.                     print >>sys.stderr, '***'
  134.                     return None
  135.                 
  136.             status == deskbar.Handler.HANDLER_IS_NOT_APPLICABLE
  137.         
  138.         return mod
  139.  
  140.     
  141.     def load(self, filename):
  142.         """Loads the given file as a module and emits a 'module-loaded' signal
  143. \t\tpassing a corresponding ModuleContext as argument.
  144. \t\t"""
  145.         mod = self.import_module(filename)
  146.         if mod is None:
  147.             return None
  148.         
  149.         for handler, infos in mod.HANDLERS.items():
  150.             print "Loading module '%s' from file %s." % (infos['name'], filename)
  151.             mod_instance = getattr(mod, handler)()
  152.             context = ModuleContext(mod_instance.get_icon(), False, mod_instance, filename, handler, infos)
  153.             self.emit('module-loaded', context)
  154.         
  155.         return context
  156.  
  157.     
  158.     def load_all(self):
  159.         """Tries to load all qualified modules detected by the ModuleLoader.
  160. \t\tEach time a module is loaded it will emit a 'module-loaded' signal
  161. \t\tpassing a corresponding module context.
  162. \t\t"""
  163.         if self.dirs is None:
  164.             print >>sys.stderr, 'The ModuleLoader at %s has no filelist!' % str(id(self))
  165.             print >>sys.stderr, 'It was probably initialized with dirs=None.'
  166.             return None
  167.         
  168.         for f in self.filelist:
  169.             self.load(f)
  170.         
  171.         self.emit('modules-loaded')
  172.  
  173.     
  174.     def initialize_module(self, context):
  175.         """
  176. \t\tInitializes the module in the given context. Emits a 'module-initialized' signal
  177. \t\twhen done, passing the (now enabled) contextas argument.
  178. \t\tIf module is already initialized, do nothing.
  179. \t\t"""
  180.         if context.enabled:
  181.             return None
  182.         
  183.         print 'Initializing %s' % context.infos['name']
  184.         if context.infos.has_key('requirements'):
  185.             (status, message, callback) = context.infos['requirements']()
  186.             if status == deskbar.Handler.HANDLER_HAS_REQUIREMENTS or status == deskbar.Handler.HANDLER_IS_NOT_APPLICABLE:
  187.                 print 'Error while initializing %s. Requirements not met.' % context.infos['name']
  188.                 print message
  189.                 context.enabled = False
  190.                 self.emit('module-not-initialized', context)
  191.                 return None
  192.             
  193.         
  194.         
  195.         try:
  196.             context.module.initialize()
  197.             if 'categories' in context.infos:
  198.                 for catname, catinfo in context.infos['categories'].items():
  199.                     deskbar.Categories.CATEGORIES[catname] = catinfo
  200.                 
  201.         except Exception:
  202.             msg = None
  203.             print 'Error while initializing %s: %s' % (context.infos['name'], msg)
  204.             traceback.print_exc()
  205.             context.enabled = False
  206.             self.emit('module-not-initialized', context)
  207.             return None
  208.  
  209.         context.enabled = True
  210.         self.emit('module-initialized', context)
  211.  
  212.     
  213.     def stop_module(self, context):
  214.         """
  215. \t\tStops the module an sets context.enabled = False. Furthermore the context.module
  216. \t\tinstance is also set to None. Emits a 'context-stopped' signal when done passing
  217. \t\tthe stopped context as argument.
  218. \t\t"""
  219.         print 'Stopping %s' % context.infos['name']
  220.         context.module.stop()
  221.         if 'category' in context.infos:
  222.             (catname, catinfo) = context.infos['category']
  223.             del deskbar.Categories.CATEGORIES[catname]
  224.         
  225.         context.enabled = False
  226.         self.emit('module-stopped', context)
  227.  
  228.     
  229.     def load_all_async(self):
  230.         '''
  231. \t\tSame as load_all() except the loading is done in an idle mainloop call.
  232. \t\t'''
  233.         gobject.idle_add(self.load_all)
  234.  
  235.     
  236.     def initialize_module_async(self, context):
  237.         '''
  238. \t\tInvokes initialize_module in an idle mainloop call.
  239. \t\t'''
  240.         gobject.idle_add(self.initialize_module, context)
  241.  
  242.     
  243.     def stop_module_async(self, context):
  244.         '''
  245. \t\tInvokes stop_module in an idle mainloop call.
  246. \t\t'''
  247.         gobject.idle_add(self.stop_module, context)
  248.  
  249.  
  250. if gtk.pygtk_version < (2, 8, 0):
  251.     gobject.type_register(ModuleLoader)
  252.  
  253.