home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2012 January / maximum-cd-2012-01.iso / DiscContents / digsby_setup.exe / lib / singleinstance.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-10-05  |  8.2 KB  |  286 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. from contextlib import closing
  6. import sys
  7. import socket
  8. import wx
  9. import logging
  10. import threading
  11. from traceback import print_exc
  12.  
  13. def log(msg):
  14.     pass
  15.  
  16.  
  17. class SingleInstanceApp(wx.App):
  18.     
  19.     def __init__(self, appname, *args, **kws):
  20.         appname = '%s-%s' % (appname, wx.GetUserId())
  21.         mgr = InstanceChecker(appname, 'localhost', InstanceChecker.default_port)
  22.         self.instance_checker = mgr
  23.         
  24.         try:
  25.             should_quit = self._check_and_raise_other()
  26.             if should_quit:
  27.                 log('instance already running. quitting!')
  28.                 self._do_quit()
  29.         except Exception:
  30.             print_exc()
  31.  
  32.         wx.App.__init__(self, *args, **kws)
  33.  
  34.     
  35.     def start_server(self):
  36.         if self.instance_checker.isServerRunning():
  37.             return None
  38.         port_taken = self.instance_checker.startServer()
  39.         if port_taken:
  40.             if self._check_and_raise_other():
  41.                 self._do_quit()
  42.             
  43.         
  44.  
  45.     
  46.     def _do_quit(self):
  47.         sys.exit(0)
  48.  
  49.     
  50.     def _check_and_raise_other(self):
  51.         another = self.instance_checker.isAnotherRunning()
  52.         log('another instance running: %r' % another)
  53.         if another:
  54.             sent_raise = self.instance_checker.sendRaisePreviousFrameCommand()
  55.             log('sent raise command: %r' % sent_raise)
  56.         
  57.         if another and sent_raise:
  58.             return True
  59.  
  60.     
  61.     def StopSingleInstanceServer(self):
  62.         return self.instance_checker.stopServer()
  63.  
  64.     
  65.     def SetTopWindow(self, w):
  66.         wx.App.SetTopWindow(self, w)
  67.         self.instance_checker.setFrame(w)
  68.         self.start_server()
  69.  
  70.     
  71.     def MainLoop(self, *args, **kws):
  72.         if not hasattr(self, 'instance_checker'):
  73.             raise AssertionError('must call SetTopWindow on this app first')
  74.         hasattr(self, 'instance_checker')
  75.         
  76.         try:
  77.             wx.App.MainLoop(self, *args, **kws)
  78.         finally:
  79.             self.instance_checker.stopServer()
  80.  
  81.  
  82.  
  83. SERVER_NOT_STARTED = 0
  84. SERVER_STARTED = 1
  85. SERVER_PORT_TAKEN = 2
  86.  
  87. class ServerThread(threading.Thread):
  88.     backlog = 5
  89.     
  90.     def __init__(self, host, port, function, timeout = None, cv = None):
  91.         threading.Thread.__init__(self, name = self.__class__.__name__ + '-' + host + ':' + str(port))
  92.         self.host = host
  93.         self.port = port
  94.         self.function = function
  95.         self.die = False
  96.         if not timeout:
  97.             pass
  98.         self.timeout = 1
  99.         self.cv = cv
  100.         self.status = SERVER_NOT_STARTED
  101.  
  102.     
  103.     def _notify_status(self, status):
  104.         pass
  105.  
  106.     
  107.     def run(self):
  108.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  109.         
  110.         try:
  111.             s.bind((self.host, self.port))
  112.         except socket.error:
  113.             e = None
  114.             self._notify_status(SERVER_PORT_TAKEN)
  115.             return None
  116.  
  117.         self._notify_status(SERVER_STARTED)
  118.         s.listen(self.backlog)
  119.         s.settimeout(self.timeout)
  120.         while not self.die:
  121.             
  122.             try:
  123.                 (client, address) = s.accept()
  124.                 if self.die:
  125.                     break
  126.                 
  127.                 
  128.                 try:
  129.                     log('accepted a single instance ping, sending "ok"')
  130.                     client.sendall('ok')
  131.                 finally:
  132.                     client.close()
  133.  
  134.                 
  135.                 try:
  136.                     self.function()
  137.                 except Exception:
  138.                     print_exc()
  139.  
  140.             continue
  141.             except socket.timeout:
  142.                 e = None
  143.                 if self.die:
  144.                     log('singleinstance s.accept()')
  145.                     break
  146.                 
  147.                 self.die
  148.             
  149.  
  150.             None<EXCEPTION MATCH>socket.timeout
  151.         
  152.         try:
  153.             s.close()
  154.         except:
  155.             pass
  156.  
  157.  
  158.     
  159.     def isRunning(self):
  160.         return not (self.die)
  161.  
  162.     
  163.     def stop(self):
  164.         self.die = True
  165.  
  166.  
  167.  
  168. def poke_client_port(host, port):
  169.     
  170.     try:
  171.         log('connecting to (%r, %r)' % (host, port))
  172.         
  173.         try:
  174.             s = _[1]
  175.             s.connect((host, port))
  176.             data = s.recv(512)
  177.             log('received bytes from other digsby process: %r' % (data,))
  178.             if data != 'ok':
  179.                 return False
  180.         finally:
  181.             pass
  182.  
  183.     except Exception:
  184.         print_exc()
  185.         return False
  186.  
  187.     return True
  188.  
  189.  
  190. class InstanceChecker(object):
  191.     default_port = 8791
  192.     
  193.     def __init__(self, name, host, port, frame = None, func = None):
  194.         self.name = name
  195.         self.frame = frame
  196.         self.port = port
  197.         self.host = host
  198.         self.logger = logging.getLogger('')
  199.         if not func:
  200.             
  201.             self.func = lambda : wx.CallAfter(self._InstanceChecker__raiseFrame)
  202.         
  203.         self.s_checker = wx.SingleInstanceChecker(self.name)
  204.  
  205.     
  206.     def startServer(self):
  207.         self.logger.info('Server stuff')
  208.         self._quit_cv = threading.Condition()
  209.         self.server = ServerThread(self.host, self.port, self.func, cv = self._quit_cv)
  210.         
  211.         try:
  212.             self._quit_cv.__enter__()
  213.             
  214.             try:
  215.                 self.server.start()
  216.                 while self.server.status == SERVER_NOT_STARTED:
  217.                     self._quit_cv.wait()
  218.                     continue
  219.                     self._quit_cv.__exit__
  220.                 if self.server.status == SERVER_PORT_TAKEN:
  221.                     self.logger.info('instance checker port was already taken, quitting')
  222.                     return True
  223.             finally:
  224.                 pass
  225.  
  226.         except Exception:
  227.             e = None
  228.             self.logger.error("Couldn't start single instance checker server because: %r", e)
  229.             raise e
  230.  
  231.  
  232.     
  233.     def sendRaisePreviousFrameCommand(self):
  234.         self.logger.info('Poking IPC loopback connection')
  235.         return poke_client_port(self.host, self.port)
  236.  
  237.     
  238.     def isServerRunning(self):
  239.         if hasattr(self, 'server'):
  240.             pass
  241.         return self.server.isRunning()
  242.  
  243.     
  244.     def stopServer(self):
  245.         if hasattr(self, 's_checker'):
  246.             del self.s_checker
  247.         
  248.         if hasattr(self, 'server') and self.server.isRunning():
  249.             self.server.stop()
  250.             return True
  251.         self.logger.warning("Tried to stop a server that wasn't running")
  252.         return False
  253.  
  254.     
  255.     def setFrame(self, f):
  256.         self.frame = f
  257.  
  258.     
  259.     def setFunc(self, func):
  260.         self.func = func
  261.  
  262.     
  263.     def __raiseFrame(self):
  264.         if self.frame is None:
  265.             log('wxApp.SetTopWindow was not called, cannot raise frame')
  266.             return None
  267.         self.frame.Show(True)
  268.         self.frame.Iconize(False)
  269.         self.frame.Raise()
  270.         if hasattr(self.frame, 'ComeBackFromAutoHide'):
  271.             self.frame.ComeBackFromAutoHide()
  272.         
  273.  
  274.     
  275.     def isAnotherRunning(self):
  276.         return self.s_checker.IsAnotherRunning()
  277.  
  278.  
  279. if __name__ == '__main__':
  280.     app = SingleInstanceApp(0)
  281.     f = wx.Frame(None, -1, 'This app only runs once!')
  282.     f.Show(True)
  283.     app.SetTopWindow(f)
  284.     app.MainLoop()
  285.  
  286.