home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1475 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  8.1 KB  |  261 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import atexit
  5. import os
  6.  
  7. try:
  8.     set
  9. except NameError:
  10.     from sets import Set as set
  11.  
  12. import sys
  13. import threading
  14. import time
  15. import traceback as _traceback
  16. import warnings
  17.  
  18. class _StateEnum(object):
  19.     
  20.     class State(object):
  21.         name = None
  22.         
  23.         def __repr__(self):
  24.             return 'states.%s' % self.name
  25.  
  26.  
  27.     
  28.     def __setattr__(self, key, value):
  29.         if isinstance(value, self.State):
  30.             value.name = key
  31.         
  32.         object.__setattr__(self, key, value)
  33.  
  34.  
  35. states = _StateEnum()
  36. states.STOPPED = states.State()
  37. states.STARTING = states.State()
  38. states.STARTED = states.State()
  39. states.STOPPING = states.State()
  40. states.EXITING = states.State()
  41.  
  42. class Bus(object):
  43.     states = states
  44.     state = states.STOPPED
  45.     execv = False
  46.     
  47.     def __init__(self):
  48.         self.execv = False
  49.         self.state = states.STOPPED
  50.         self.listeners = []([ (channel, set()) for channel in ('start', 'stop', 'exit', 'graceful', 'log') ])
  51.         self._priorities = { }
  52.  
  53.     
  54.     def subscribe(self, channel, callback, priority = None):
  55.         if channel not in self.listeners:
  56.             self.listeners[channel] = set()
  57.         
  58.         self.listeners[channel].add(callback)
  59.         if priority is None:
  60.             priority = getattr(callback, 'priority', 50)
  61.         
  62.         self._priorities[(channel, callback)] = priority
  63.  
  64.     
  65.     def unsubscribe(self, channel, callback):
  66.         listeners = self.listeners.get(channel)
  67.         if listeners and callback in listeners:
  68.             listeners.discard(callback)
  69.             del self._priorities[(channel, callback)]
  70.         
  71.  
  72.     
  73.     def publish(self, channel, *args, **kwargs):
  74.         if channel not in self.listeners:
  75.             return []
  76.         exc = None
  77.         output = []
  78.         items = [ (self._priorities[(channel, listener)], listener) for listener in self.listeners[channel] ]
  79.         items.sort()
  80.         for priority, listener in items:
  81.             
  82.             try:
  83.                 output.append(listener(*args, **kwargs))
  84.             continue
  85.             except KeyboardInterrupt:
  86.                 []
  87.                 []
  88.                 []
  89.                 raise 
  90.                 continue
  91.                 channel not in self.listeners
  92.                 except SystemExit:
  93.                     e = None
  94.                     if exc and e.code == 0:
  95.                         e.code = 1
  96.                     
  97.                     raise 
  98.                     continue
  99.                     exc = sys.exc_info()[1]
  100.                     if channel == 'log':
  101.                         pass
  102.                     else:
  103.                         self.log('Error in %r listener %r' % (channel, listener), level = 40, traceback = True)
  104.                 
  105.             if exc:
  106.                 raise 
  107.             return output
  108.  
  109.  
  110.     
  111.     def _clean_exit(self):
  112.         if self.state != states.EXITING:
  113.             warnings.warn('The main thread is exiting, but the Bus is in the %r state; shutting it down automatically now. You must either call bus.block() after start(), or call bus.exit() before the main thread exits.' % self.state, RuntimeWarning)
  114.             self.exit()
  115.         
  116.  
  117.     
  118.     def start(self):
  119.         atexit.register(self._clean_exit)
  120.         self.state = states.STARTING
  121.         self.log('Bus STARTING')
  122.         
  123.         try:
  124.             self.publish('start')
  125.             self.state = states.STARTED
  126.             self.log('Bus STARTED')
  127.         except (KeyboardInterrupt, SystemExit):
  128.             raise 
  129.         except:
  130.             self.log('Shutting down due to error in start listener:', level = 40, traceback = True)
  131.             e_info = sys.exc_info()
  132.             
  133.             try:
  134.                 self.exit()
  135.             except:
  136.                 pass
  137.  
  138.             raise e_info[0], e_info[1], e_info[2]
  139.  
  140.  
  141.     
  142.     def exit(self):
  143.         
  144.         try:
  145.             self.stop()
  146.             self.state = states.EXITING
  147.             self.log('Bus EXITING')
  148.             self.publish('exit')
  149.             self.log('Bus EXITED')
  150.         except:
  151.             os._exit(70)
  152.  
  153.  
  154.     
  155.     def restart(self):
  156.         self.execv = True
  157.         self.exit()
  158.  
  159.     
  160.     def graceful(self):
  161.         self.log('Bus graceful')
  162.         self.publish('graceful')
  163.  
  164.     
  165.     def block(self, interval = 0.1):
  166.         
  167.         try:
  168.             self.wait(states.EXITING, interval = interval)
  169.         except (KeyboardInterrupt, IOError):
  170.             self.log('Keyboard Interrupt: shutting down bus')
  171.             self.exit()
  172.         except SystemExit:
  173.             self.log('SystemExit raised: shutting down bus')
  174.             self.exit()
  175.             raise 
  176.  
  177.         self.log('Waiting for child threads to terminate...')
  178.         for t in threading.enumerate():
  179.             if t != threading.currentThread() and t.isAlive():
  180.                 if hasattr(threading.Thread, 'daemon'):
  181.                     d = t.daemon
  182.                 else:
  183.                     d = t.isDaemon()
  184.                 if not d:
  185.                     t.join()
  186.                 
  187.             d
  188.         
  189.         if self.execv:
  190.             self._do_execv()
  191.         
  192.  
  193.     
  194.     def wait(self, state, interval = 0.1):
  195.         if isinstance(state, (tuple, list)):
  196.             states = state
  197.         else:
  198.             states = [
  199.                 state]
  200.         
  201.         def _wait():
  202.             while self.state not in states:
  203.                 time.sleep(interval)
  204.  
  205.         
  206.         try:
  207.             sys.modules['psyco'].cannotcompile(_wait)
  208.         except (KeyError, AttributeError):
  209.             (None, None, None)
  210.             (None, None, None)
  211.         except:
  212.             (None, None, None)
  213.  
  214.         _wait()
  215.  
  216.     
  217.     def _do_execv(self):
  218.         args = sys.argv[:]
  219.         self.log('Re-spawning %s' % ' '.join(args))
  220.         args.insert(0, sys.executable)
  221.         os.execv(sys.executable, args)
  222.  
  223.     
  224.     def stop(self):
  225.         self.state = states.STOPPING
  226.         self.log('Bus STOPPING')
  227.         self.publish('stop')
  228.         self.state = states.STOPPED
  229.         self.log('Bus STOPPED')
  230.  
  231.     
  232.     def start_with_callback(self, func, args = None, kwargs = None):
  233.         if args is None:
  234.             args = ()
  235.         
  236.         if kwargs is None:
  237.             kwargs = { }
  238.         
  239.         args = (func,) + args
  240.         
  241.         def _callback(func, *a, **kw):
  242.             self.wait(states.STARTED)
  243.             func(*a, **kw)
  244.  
  245.         t = threading.Thread(target = _callback, args = args, kwargs = kwargs)
  246.         t.setName('Bus Callback ' + t.getName())
  247.         t.start()
  248.         self.start()
  249.         return t
  250.  
  251.     
  252.     def log(self, msg = '', level = 20, traceback = False):
  253.         if traceback:
  254.             exc = sys.exc_info()
  255.             msg += '\n' + ''.join(_traceback.format_exception(*exc))
  256.         
  257.         self.publish('log', msg, level)
  258.  
  259.  
  260. bus = Bus()
  261.