Ejemplo n.º 1
0
def main():
    pygame.init()
    if hasattr(eventmodule, 'init'):
        eventmodule.init()
    screen = pygame.display.set_mode((300, 300))

    # send an event when twisted wants attention
    reactor.interleave(postTwistedEvent)
    # make shouldQuit a True value when it's safe to quit
    # by appending a value to it.  This ensures that
    # Twisted gets to shut down properly.
    shouldQuit = []
    reactor.addSystemEventTrigger('after', 'shutdown', shouldQuit.append, True)

    for event in eventIterator():
        if event.type == TWISTEDEVENT:
            event.iterateTwisted()
            if shouldQuit:
                break
        elif event.type == QUIT:
            reactor.stop()
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            reactor.stop()

    pygame.quit()
Ejemplo n.º 2
0
    def finishLaunching(self):
        statusbar = NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(
            NSSquareStatusItemLength)

        self.icon = NSImage.alloc().initByReferencingFile_('icon.png')
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)

        self.iconHighlight = NSImage.alloc().initByReferencingFile_('icon-hi.png')
        self.iconHighlight.setSize_((20, 20))
        self.statusitem.setAlternateImage_(self.iconHighlight)

        self.statusitem.setHighlightMode_(1)

        menu = NSMenu.alloc().init()
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Quit', 'terminate:', '')
        menu.addItem_(menuitem)
        self.statusitem.setMenu_(menu)

        # Also start twisted
        reactor.interleave(AppHelper.callAfter)
        reactor.addSystemEventTrigger(
            'after', 'shutdown', AppHelper.stopEventLoop)
Ejemplo n.º 3
0
    def __init__(self):
        self.config = config.read('config.json')

        if not 'twitch_id' in self.config:
            raise config.ConfigurationError(
                'Setting twitch_id incorrectly configured in config.json')

        self.wx = wx.App()

        self.plugins = plugins.PluginManager()
        self.plugins.load('plugins/')

        twitch_id = self.config['twitch_id']

        login = self.config['services']['chat']['login']
        bot_id = login['id']
        bot_oauth = login['oauth']

        chat.connect(bot_id, bot_oauth, twitch_id)

        reactor.interleave(wx.CallAfter)
        
        pub.subscribe(self.quit, 'command.quit')

        self.icon = gui.Icon(self.plugins.plugins())
        self.menu = gui.Menu(self.plugins.plugins())

        self.wx.MainLoop()
Ejemplo n.º 4
0
def start_apaf():
    """
    Start the apaf.
    It gets called asyncronously by ApafAppWrapper didFinishLoading
    """
    base.main().addCallback(setup_complete).addErrback(setup_failed)
    reactor.interleave(AppHelper.callAfter)
Ejemplo n.º 5
0
def start_apaf():
    """
    Start the apaf.
    It gets called asyncronously by ApafAppWrapper didFinishLoading
    """
    base.main().addCallback(setup_complete).addErrback(setup_failed)
    reactor.interleave(AppHelper.callAfter)
Ejemplo n.º 6
0
    def finishLaunching(self):
        statusbar = NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(
            NSSquareStatusItemLength)

        self.icon = NSImage.alloc().initByReferencingFile_('icon.png')
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)

        self.iconHighlight = NSImage.alloc().initByReferencingFile_('icon-hi.png')
        self.iconHighlight.setSize_((20, 20))
        self.statusitem.setAlternateImage_(self.iconHighlight)

        self.statusitem.setHighlightMode_(1)

        menu = NSMenu.alloc().init()
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Quit', 'terminate:', '')
        menu.addItem_(menuitem)
        self.statusitem.setMenu_(menu)

        # Also start twisted
        reactor.interleave(AppHelper.callAfter)
        reactor.addSystemEventTrigger(
            'after', 'shutdown', AppHelper.stopEventLoop)
 def applicationDidFinishLaunching_(self, aNotification):
     """Create and display a new connection window
     """
     reactor.interleave(AppHelper.callAfter)
     reactor.addSystemEventTrigger("after", "shutdown",
                                   AppHelper.stopEventLoop)
     self.newConnectionAction_(None)
Ejemplo n.º 8
0
def main():
    pygame.init()
    if hasattr(eventmodule, 'init'):
        eventmodule.init()
    screen = pygame.display.set_mode((300, 300))

    # send an event when twisted wants attention
    reactor.interleave(postTwistedEvent)
    # make shouldQuit a True value when it's safe to quit
    # by appending a value to it.  This ensures that
    # Twisted gets to shut down properly.
    shouldQuit = []
    reactor.addSystemEventTrigger('after', 'shutdown', shouldQuit.append, True)

    for event in eventIterator():
        if event.type == TWISTEDEVENT:
            event.iterateTwisted()
            if shouldQuit:
                break
        elif event.type == QUIT:
            reactor.stop()
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            reactor.stop()

    pygame.quit()
 def applicationDidFinishLaunching_(self, aNotification):
     """Create and display a new connection window
     """
     reactor.interleave(AppHelper.callAfter)
     reactor.addSystemEventTrigger(
         'after', 'shutdown', AppHelper.stopEventLoop)
     self.newConnectionAction_(None)
Ejemplo n.º 10
0
 def applicationDidFinishLaunching_(self, aNotification):
     """
     Invoked by NSApplication once the app is done launching and
     immediately before the first pass through the main event
     loop.
     """
     self.messageTextField.setStringValue_("http://www.twistedmatrix.com/")
     reactor.interleave(AppHelper.callAfter)
Ejemplo n.º 11
0
 def applicationDidFinishLaunching_(self, aNotification):
     """
     Invoked by NSApplication once the app is done launching and
     immediately before the first pass through the main event
     loop.
     """
     self.messageTextField.setStringValue_("http://www.twistedmatrix.com/")
     reactor.interleave(AppHelper.callAfter)
Ejemplo n.º 12
0
    def __init__(self, appUrl, name, size=None):
        '''
        Creates the shared application client, used for
        application service interaction, and opens a web browser
        for UI display.
        '''
        wx.App.__init__(self, False)

        reactor.interleave(wx.CallAfter)
        # Create shared application client
        self.sharedAppClient = SharedAppClient(name)
        self.log = self.sharedAppClient.InitLogging()

        # Get client profile
        try:
            clientProfileFile = os.path.join(
                UserConfig.instance().GetConfigDir(), "profile")
            clientProfile = ClientProfile(clientProfileFile)
        except:
            self.log.info(
                "SharedAppClient.Connect: Could not load client profile, set clientProfile = None"
            )
            clientProfile = None

        # Join the application session.
        self.sharedAppClient.Join(appUrl, clientProfile)

        # Register browse event callback
        self.sharedAppClient.RegisterEventCallback("browse",
                                                   self.BrowseCallback)

        # Create Browser Window
        self.frame = wx.Frame(None, -1, "SharedBrowser", size=size)
        if sys.platform != Platform.WIN:
            self.frame.CreateStatusBar()
        self.browser = WebBrowser(self.frame, -1, self.log, self.frame)

        # Add callback for local browsing
        self.browser.add_navigation_callback(self.IBrowsedCallback)

        # Browse to the current url, if exists
        currentUrl = self.sharedAppClient.GetData("url")

        if currentUrl and len(currentUrl) > 0:
            self.browser.navigate(currentUrl)
            try:
                self.sharedAppClient.SetParticipantStatus(currentUrl)
            except:
                self.log.exception(
                    "SharedBrowser:__init__: Failed to set participant status")

        self.frame.SetIcon(icons.getAGIconIcon())
        self.frame.Show(1)
        self.SetTopWindow(self.frame)
Ejemplo n.º 13
0
    def __init__(self, parent, name, appUrl, venueUrl, connectionId):
        wx.Panel.__init__(self, parent, -1)

        reactor.interleave(wx.CallAfter)
        
        # Create ActiveX interface to adobe acrobate reader
        self.pdf = PDFWindow(self)
        
        # Do UI layout
        self.__Layout()
    
        # Create UI events
        EVT_BUTTON(self, self.openButton.GetId(), self.OnOpenButton)
        EVT_BUTTON(self, self.prevButton.GetId(), self.OnPrevPageButton)
        EVT_BUTTON(self, self.nextButton.GetId(), self.OnNextPageButton)
        EVT_WINDOW_DESTROY(self, self.OnExit)

        # Create shared application client        
        self.sharedAppClient = SharedAppClient(name)
        self.log = self.sharedAppClient.InitLogging()
        self.log.debug("PdfViewer.__init__: Start pdf viewer, venueUrl: %s, appUrl: %s"%(venueUrl, appUrl))

        # Get client profile
        clientProfile = ClientProfile(UserConfig.instance().GetProfile())
       
        # Join the application session.
        self.sharedAppClient.Join(appUrl, clientProfile)
        self.id = self.sharedAppClient.GetPublicId()
                
        # Register callbacks for external events
        self.sharedAppClient.RegisterEventCallback("openFile", self.OpenCallback)
        self.sharedAppClient.RegisterEventCallback("changePage", self.ChangePageCallback)

        # Create data store interface
        self.dataStoreClient = GetVenueDataStore(venueUrl, connectionId)

        self.file = None
        self.pageNr = 1
        
        # Get current state
        self.file = str(self.sharedAppClient.GetData("file"))
        self.pageNr = int(self.sharedAppClient.GetData("page"))
        if not self.pageNr:
            self.pageNr = 1

        if self.file:
            try:
                self.dataStoreClient.Download(self.file, "tmp")
                self.pdf.LoadFile("tmp")
                self.pdf.setCurrentPage( int(self.pageNr))
            except:
                self.log.exception("PdfViewer.__init__: Download failed %s"%(self.file))
Ejemplo n.º 14
0
    def __init__(self, appURL, connectionID):
        """The constructor."""
        wx.App.__init__(self, False)
        reactor.interleave(wx.CallAfter)

        messaging = SharedAppMessaging("SharedPaint-3", appURL, connectionID)
        model = SharedPaintSession()
        frame = SharedPaintGUI(model)

        self.SetTopWindow(frame)

        controller = SharedPaintController(messaging, model, frame)
        controller.Run()
Ejemplo n.º 15
0
def install_twisted(interval=1, start_running=True):
    try:
        from twisted.internet import _threadedselect
        _threadedselect.install()

        def waker(func):
            sublime.set_timeout(func, interval)

        from twisted.internet import reactor
        reactor.interleave(waker)
    except ImportError:
        return False
    return True
Ejemplo n.º 16
0
    def __init__(self,
                 parent=None,
                 id=-1,
                 title='Parallel IPython Shell',
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.DEFAULT_FRAME_STYLE,
                 locals=None,
                 InterpClass=None,
                 *args,
                 **kwds):
        """Create ShellFrame instance."""
        frame.Frame.__init__(self, parent, id, title, pos, size, style)
        intro = 'Twisted Enabled PyShell for Parallel IPython'
        self.SetStatusText(intro.replace('\n', ', '))

        # Import twisted stuff
        from twisted.internet import threadedselectreactor
        threadedselectreactor.install()
        from twisted.internet import reactor
        from twisted.python import log
        self.reactor = reactor
        log.startLogging(sys.stdout)

        # Pass the reactor to the user namespace
        mylocals = locals
        if mylocals is None:
            mylocals = {'reactor': reactor}
        else:
            mylocals.update({'reactor': reactor})

        # Now creat a Shell object
        self.shell = Shell(parent=self,
                           id=-1,
                           introText=intro,
                           locals=mylocals,
                           InterpClass=InterpClass,
                           *args,
                           **kwds)

        # Override the shell so that status messages go to the status bar.
        self.shell.setStatusText = self.SetStatusText

        # Add a File->Exit event to shutdown the twisted reactor
        mb = self.GetMenuBar()
        m0 = mb.GetMenu(0)
        m0.Append(10101, "E&xit", "Exit")
        wx.EVT_MENU(self, 10101, self.DoExit)

        # Lastly interleave the twisted reactor with wx!
        reactor.interleave(wx.CallAfter)
Ejemplo n.º 17
0
        def __init__(self, parent, ID, title):
            wx.Frame.__init__(self, parent, ID,
                             title,
                             wx.DefaultPosition, # position
                             wx.Size(512,512))
            self.SetAutoLayout(1)
            self.CreateStatusBar()
            menuBar = wx.MenuBar()
            menu    = wx.Menu()
            menu.AppendSeparator()
            menu.Append(self.ID_EXIT, "E&xit", "Terminate the program")
            menuBar.Append(menu, "&File");
            self.SetMenuBar(menuBar)
            wx.EVT_MENU(self,self.ID_EXIT,self.TimeToQuit)
            
            sizer = wx.BoxSizer(wx.VERTICAL)
            self.SetSizer(sizer)
            
            # a logging window
            self.log = wx.TextCtrl(self,-1,style = wx.TE_MULTILINE)
            wx.Log_SetActiveTarget(wx.LogTextCtrl(self.log))
            sizer.Add(self.log,1,wx.EXPAND|wx.ALL,1)
            
            # trap characters
            wx.EVT_CHAR(self.log, self.OnChar)
            
            # start the event server thread
            eventHost = "localhost"
            channelId = group
            self.eventClient = venueEventClientClass((eventHost, eventPort), 1, channelId, groupMsgClientClassList=groupMsgClientClassList)
            self.eventClient.RegisterEventCallback("test", self.OnTest)
            self.eventClient.RegisterMadeConnectionCallback(self.MadeConnection)
            self.eventClient.RegisterLostConnectionCallback(self.LostConnection)
            self.eventClient.Start()

            #timeout = 3
            #timeStart = time.time()
            #while (not self.eventClient.IsConnected()) and (timeout > time.time() - timeStart):
            #    print "Waiting for connection"
            #    time.sleep(1)
            #self.eventClient.Send("connect", "")    
                        
            # cleanup
            wx.EVT_CLOSE(self, self.OnCloseWindow)
            
            self.show_status("Connecting to %s on port %d." % 
                             (eventHost, eventPort))

            from twisted.internet import reactor
            reactor.interleave(wx.CallAfter)
Ejemplo n.º 18
0
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, -1, title,
                          style=wx.MINIMIZE_BOX | wx.CAPTION | wx.CLIP_CHILDREN,size=wx.Size(344, 534))
                        
        menu = wx.Menu()
        menu.Append(wx.ID_EXIT, "E&xit", "Terminate the program")
        menuBar = wx.MenuBar()
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)
        wx.EVT_MENU(self, wx.ID_EXIT,  self.DoExit)
        
        mmp = MyMainPanel(self,-1)

        reactor.interleave(wx.CallAfter)
Ejemplo n.º 19
0
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, -1, title,
                          style=wx.MINIMIZE_BOX | wx.CAPTION | wx.CLIP_CHILDREN,size=wx.Size(344, 534))
                        
        menu = wx.Menu()
        menu.Append(wx.ID_EXIT, "E&xit", "Terminate the program")
        menuBar = wx.MenuBar()
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)
        wx.EVT_MENU(self, wx.ID_EXIT,  self.DoExit)
        
        mmp = MyMainPanel(self,-1)

        reactor.interleave(wx.CallAfter)
Ejemplo n.º 20
0
    def __init__(self, appUrl, name, size=None):
        """
        Creates the shared application client, used for
        application service interaction, and opens a web browser
        for UI display.
        """
        wx.App.__init__(self, False)

        reactor.interleave(wx.CallAfter)
        # Create shared application client
        self.sharedAppClient = SharedAppClient(name)
        self.log = self.sharedAppClient.InitLogging()

        # Get client profile
        try:
            clientProfileFile = os.path.join(UserConfig.instance().GetConfigDir(), "profile")
            clientProfile = ClientProfile(clientProfileFile)
        except:
            self.log.info("SharedAppClient.Connect: Could not load client profile, set clientProfile = None")
            clientProfile = None

        # Join the application session.
        self.sharedAppClient.Join(appUrl, clientProfile)

        # Register browse event callback
        self.sharedAppClient.RegisterEventCallback("browse", self.BrowseCallback)

        # Create Browser Window
        self.frame = wx.Frame(None, -1, "SharedBrowser", size=size)
        if sys.platform != Platform.WIN:
            self.frame.CreateStatusBar()
        self.browser = WebBrowser(self.frame, -1, self.log, self.frame)

        # Add callback for local browsing
        self.browser.add_navigation_callback(self.IBrowsedCallback)

        # Browse to the current url, if exists
        currentUrl = self.sharedAppClient.GetData("url")

        if currentUrl and len(currentUrl) > 0:
            self.browser.navigate(currentUrl)
            try:
                self.sharedAppClient.SetParticipantStatus(currentUrl)
            except:
                self.log.exception("SharedBrowser:__init__: Failed to set participant status")

        self.frame.SetIcon(icons.getAGIconIcon())
        self.frame.Show(1)
        self.SetTopWindow(self.frame)
Ejemplo n.º 21
0
    def __init__(self, parent, id, title):

        # baseclass constructor
        WXBridge.__init__( self, parent, id, title)

        # configure menu bar (also sets the local onExit callback)
        self.SetMenuBar( MenuBar(self) )
        self.CreateStatusBar()

        # notebook with one tab per device type, e.g., 'Cameras', 'Projectors'
        log.write('Creating TabbedNotebook')
        self.notebook = DeviceNotebook(self, -1, self)

        self.Layout()

        # super-duper important ....
        reactor.interleave(wx.CallAfter)
Ejemplo n.º 22
0
    def runWithTwisted(self, verbose=False):
        if hasattr(eventmodule, 'init'):
            eventmodule.init()

        # send an event when twisted wants attention
        reactor.interleave(postTwistedEvent)

        # make shouldQuit a True value when it's safe to quit
        # by appending a value to it.  This ensures that
        # Twisted gets to shut down properly.
        shouldQuit = []
        reactor.addSystemEventTrigger('after', 'shutdown', shouldQuit.append,
                                      True)

        # Have our main "app" iteration called repeatedly
        #    pygame events are handled in the loop below, so also don't have
        #    the mainLoop iteration handle pygame events.
        reactor.callLater(
            .0, self.twistedOutside_mainLoopIterationDontHandleEvents)

        self._running = 1
        while self._running:
            #self._tickClock()
            #if not self._paused:
            #    self.updateObjects() # move
            # **** organize this so it integrates with non-twisted events.
            for event in self.eventIterator():  # this is an infinite loop
                if event.type == TWISTEDEVENT:
                    event.iterateTwisted()
                    if shouldQuit:
                        self._running = 0
                        break
                #elif event.type == QUIT:
                #    reactor.stop()
                else:  # *** should we instead pass all events and move this
                    #    handling into current event handling?
                    self.handleOneEvent(event)
            #self.renderer.draw()
            #pygame.display.flip()
        if verbose:
            print "mainloop in app.runWithTwisted done"
            pygame.quit()
            print "pygame.quit done"
        print "app.runWithTwisted done"
Ejemplo n.º 23
0
    def runWithTwisted(self, verbose=False):
        if hasattr(eventmodule, 'init'):
            eventmodule.init()

        # send an event when twisted wants attention
        reactor.interleave(postTwistedEvent)

        # make shouldQuit a True value when it's safe to quit 
        # by appending a value to it.  This ensures that
        # Twisted gets to shut down properly.
        shouldQuit=[]
        reactor.addSystemEventTrigger('after', 'shutdown', shouldQuit.append, True)

        # Have our main "app" iteration called repeatedly
        #    pygame events are handled in the loop below, so also don't have
        #    the mainLoop iteration handle pygame events.
        reactor.callLater(.0, self.twistedOutside_mainLoopIterationDontHandleEvents)

        self._running = 1
        while self._running:
            #self._tickClock()
            #if not self._paused:
            #    self.updateObjects() # move
            # **** organize this so it integrates with non-twisted events.
            for event in self.eventIterator():  # this is an infinite loop
                if event.type == TWISTEDEVENT:
                    event.iterateTwisted()
                    if shouldQuit:
                        self._running = 0
                        break
                #elif event.type == QUIT:
                #    reactor.stop()
                else:  # *** should we instead pass all events and move this
                       #    handling into current event handling?
                    self.handleOneEvent(event)
            #self.renderer.draw()
            #pygame.display.flip()
        if verbose:
            print "mainloop in app.runWithTwisted done"
            pygame.quit()
            print "pygame.quit done"
        print "app.runWithTwisted done"
Ejemplo n.º 24
0
 def reactor_start(*args):
     '''Start the twisted reactor main loop
     '''
     Logger.info("Support: Starting twisted reactor")
     reactor.interleave(reactor_wake, **kwargs)
     Clock.schedule_interval(reactor_work, 0)
Ejemplo n.º 25
0
    def postEventWithCallback(self, callback, data=None):
        # if we're in main thread, just fire off callback
        if get_ident()==BaseQObject.MAIN_THREAD_ID:
            if data or type(data)==type(False): callback(data)
            else: callback()
        # send callback to main thread 
        else:
            event = QEvent(QEvent.User)
            event.callback = callback
            if data or type(data)==type(False): event.data = data
            qApp.postEvent(self, event)
            
class Interleaver(BaseQObject):
    def __init__(self):
        BaseQObject.__init__(self)

    def toInterleave(self, func, *args, **kwargs):
        #print('toInterleave(): %s'%(str(func)))
        self.postEventWithCallback(func)

if len( sys.argv ) > 1 :
    Pinger( sys.argv[1] )
    ii = Interleaver()
    reactor.interleave(ii.toInterleave)
    app = QApplication([])
    app.exec_loop()
else:
    reactor.listenTCP( PORT, pb.PBServerFactory( Ponger()))
    reactor.run()
Ejemplo n.º 26
0
    def __init__(self, parent, ID, title, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
        self.parent = parent
        import graphcanvas
        import graphcontext
        import config
        from pathhelper import resFile

        self.cursor2D = None
        self.timer = None
        # Load XML resources.
        self.xmlres = xrc.XmlResource(resFile("gluskap.xrc"))

        # Before we set up the frame, parse command line arguments.
        (self.cmdline_options, self.cmdline_args) = cmdline_opts()

        # Parse Port number
        try:
            portnum = int(self.cmdline_options.portnum)
        except:
            print "Port number needs to be a number. Using default: 12001."
            portnum = 12001

        if self.cmdline_options.highlight:
            config.current['global:highlight'] = True

        # Two-stage creation from an XRC frame.
        pre = wx.PreFrame()
        self.xmlres.LoadOnFrame(pre, parent, "NetcliWindow")
        self.PostCreate(pre)

        # Bind the onClose handler
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        # Bind the handlers for the interface widgets.
        XRCCTRL(self, 'RenderFPS').Bind(wx.EVT_SPINCTRL, self.OnSetFPS)
        XRCCTRL(self, 'RenderFPS').Bind(wx.EVT_TEXT, self.OnSetFPS)
        XRCCTRL(self, 'ButtonRender').Bind(wx.EVT_BUTTON, self.OnRenderOne)
        XRCCTRL(self, 'OptionEye').Bind(wx.EVT_CHOICE, self.OnEyeChoice)
        XRCCTRL(self, 'OptionFilter').Bind(wx.EVT_CHOICE, self.OnFilterChoice)

        # Bind the exit button to OnClose.
        XRCCTRL(self, 'wxID_EXIT').Bind(wx.EVT_BUTTON, self.OnClose)

        self.size = size
        self.pos = pos

        # The ContextList is all the graphs currently open
        # This will be overwritten...
        self.contexts = graphcontext.ContextList(parent=self)

        # The GraphCanvas is the GLCanvas the graph gets drawn on
        self.canvas = graphcanvas.GraphCanvas(self)

        self.xmlres.AttachUnknownControl("GLCanvas", self.canvas, self)

        self.CreateStatusBar(1)
        self.SetStatusText("Initializing...", 0)

        #wx.Image_AddHandler(wx.ICOHandler())
        log = wx.LogNull()
        self.icon = wx.Icon(resFile("GLuskap.ico"), wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)
        del log

        # Set up behaviour for when we successfully connect to the
        # remote display.
        import remoteobjs

        def deliver(x):
            self.contexts = x
            x.parent = self
            self.SetStatusText("Connected to remote context manager.", 0)

        self.handler = remoteobjs.Handler(reactor, deliver)

        factory = MyPBClientFactory()

        def onConnect():
            factory.getRootObject(
            ).addCallback(self.handler.getmaker
            ).addErrback(self.handler.error
            )
            wx.CallAfter(self.GoFullscreen)
            ConnectedNow()

        def onConnectFailed(reason):
            """
	    wx.CallAfter(wx.MessageBox,
		message = "GLuskap@%s:%d could not be contacted (%s)" % (
		    self.cmdline_options.remote_peer,
                    portnum,
		    reason.getErrorMessage(),
		),
		caption = 'Sorry',
		style = wx.ICON_ERROR,
	    )
            """
            wx.CallAfter(self.SetStatusText, "Connection to remote GLuskap failed... Trying again.")
            if isinstance(self.timer, wx.Timer):
                self.timer.Stop()
            self.timer = wx.Timer(owner=self)
            self.delay = 5000.0
            self.Bind(wx.EVT_TIMER, Connect)
            self.timer.Start(milliseconds=self.delay, oneShot=True)

        def OnConnectionLost(event):
            if isinstance(self.timer, wx.Timer):
                self.timer.Stop()
            self.contexts.active = None
            self.ShowFullScreen(False)
            self.canvas.Refresh()
            wx.CallAfter(self.SetStatusText, "Connection to remote GLuskap lost... Attempting to reconnect.")
            wx.SafeYield()
            Connect(None)

        def Connect(event):
            print "Trying to connect..."
            reactor.connectTCP(self.cmdline_options.remote_peer, portnum, factory)

        factory.setConnectionMadeHandler(onConnect)
        factory.setConnectionLost(OnConnectionLost)
        factory.setConnectionFailedHandler(onConnectFailed)

        Connect(None)
        reactor.interleave(wx.CallAfter)

        def ConnectedNow():
            # Start a timer that will refresh the GraphCanvas at 20fps.
            self.timer = wx.Timer(owner=self)
            self.fps = 20
            self.timer.Start(milliseconds=1000.0 / self.fps, oneShot=False)
            self.Bind(wx.EVT_TIMER, self.OnTick)
Ejemplo n.º 27
0
playlist_button = gui.ToggleButton((160,0),NOTEBOOK_BUTTON_SIZE,align="top",label="Playlist")
playlist_panel = playlist.PlaylistPanel(current_panel)

lib_button = gui.ToggleButton((310,0),NOTEBOOK_BUTTON_SIZE,align="topright",label="Library")
lib_panel = library.LibraryPanel(playlist_panel)

nb = gui.NoteBook([(lib_button,lib_panel),(playlist_button,playlist_panel),(current_button,current_panel)])
gui.get_root_widget().update(downwards=True)

#set up twisted
def setUp():
    control_point = ControlPoint(Coherence({'logmode':'warning'}),
                                 auto_client=['MediaRenderer', 'MediaServer'])
    control_point.connect(lib_panel.add_library, 'Coherence.UPnP.ControlPoint.MediaServer.detected')
    control_point.connect(current_panel.add_renderer, 'Coherence.UPnP.ControlPoint.MediaRenderer.detected')
    
from twisted.internet import reactor
reactor.callWhenRunning(setUp)
reactor.interleave(tingbot.main_run_loop.callAfter)
try:
    tingbot.run()
finally:
    print "closing server"
    reactor.stop()
    print "clearing the queue"
    for i in range(30):
        time.sleep(0.03)
        tingbot.main_run_loop.clearQueue()
    print "exiting"
Ejemplo n.º 28
0
    def __init__(self, parent, id, title, appUrl):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition,
                          wx.Size(800, 600))
        #wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(800, 600), wx.DEFAULT_FRAME_STYLE^(wx.RESIZE_BORDER | wx.MINIMIZE_BOX |wx.MAXIMIZE_BOX))
        #self.SetIcon(wx.Icon('ico/sharedpaint.ico', wx.BITMAP_TYPE_ICO))

        self.appUrl = appUrl

        # <AGtk code>
        reactor.interleave(wx.CallAfter)

        # Create shared application client
        self.sharedAppClient = SharedAppClient("SharedPaint")
        self.log = self.sharedAppClient.InitLogging()
        self.log.debug("GroupPaint.__init__: Started Group Paint")

        # Get client profile
        try:
            self.clientProfileFile = os.path.join(
                UserConfig.instance().GetConfigDir(), "profile")
            self.clientProfile = ClientProfile(self.clientProfileFile)

        except:
            self.log.info(
                "SharedQuestionTool.__init__: Could not load client profile, set clientProfile = None"
            )
            self.clientProfile = None

        # Join the application session
        self.sharedAppClient.Join(self.appUrl, self.clientProfile)
        self.publicId = self.sharedAppClient.GetPublicId()
        self.user = self.clientProfile.GetName()
        self.id = self.sharedAppClient.GetPublicId()

        # Register event callback
        self.sharedAppClient.RegisterEventCallback(events.CONSOLE_EVENT,
                                                   self.GetConsoleEventData)
        self.sharedAppClient.RegisterEventCallback(events.CLEAR_EVENT,
                                                   self.GetClearEvent)
        #self.sharedAppClient.RegisterEventCallback(events.SET_BG_EVENT, self.GetSetBGEvent)
        # </AGtk code>
        """
        Setting status bar
        """
        self.CreateStatusBar()

        workspace = wx.BoxSizer(wx.VERTICAL)
        imagePanel = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        """
        Painter
        """
        self.painter = DoodleWindow(imagePanel, -1, self.clientProfile,
                                    self.sharedAppClient)

        imageBox = wx.BoxSizer(wx.VERTICAL)
        imageBox.Add(self.painter, 1, wx.EXPAND | wx.ALL, 1)
        imagePanel.SetSizer(imageBox)
        """
        Console settings
        """
        consolePanel = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)

        self.console = wx.TextCtrl(consolePanel, -1, style=wx.TE_MULTILINE)
        self.console.SetEditable(0)

        consoleBox = wx.BoxSizer(wx.VERTICAL)
        consoleBox.Add(self.console, 1, wx.EXPAND | wx.ALL, 1)
        consolePanel.SetSizer(consoleBox)

        workspace.Add(imagePanel, 4, wx.EXPAND | wx.ALL, 1)
        workspace.Add(consolePanel, 1, wx.EXPAND | wx.ALL, 1)

        self.SetSizer(workspace)
 def applicationDidFinishLaunching_(self, aNotification):
     """Create and display a new connection window"""
     reactor.interleave(AppHelper.callAfter)
     self.newConnectionAction_(None)
Ejemplo n.º 30
0

# --- install and start the twisted reactor, if it hasn't already be started --- #
from twisted.internet.error import ReactorAlreadyInstalledError, ReactorAlreadyRunning, ReactorNotRestartable

reactorAlreadyInstalled = False
try:
    from twisted.internet import _threadedselect
    _threadedselect.install()
except ReactorAlreadyInstalledError:
    reactorAlreadyInstalled = True

from twisted.internet import reactor

try:
    reactor.interleave(callInSublimeLoop, installSignalHandlers=False)
except ReactorAlreadyRunning:
    reactorAlreadyInstalled = True
except ReactorNotRestartable:
    reactorAlreadyInstalled = True

if reactorAlreadyInstalled:
    logger.debug('twisted reactor already installed')
    if type(reactor) != _threadedselect.ThreadedSelectReactor:
        logger.warn(
            'unexpected reactor type installed: %s, it is best to use twisted.internet._threadedselect!'
            % type(reactor))
else:
    logger.debug('twisted reactor installed and running')
# --- --------------------------------------------------------------------- --- #
Ejemplo n.º 31
0
 def applicationDidFinishLaunching_(self, sender):
     reactor.interleave(AppHelper.callAfter)
     assert (reactor.running)
 def applicationDidFinishLaunching_(self, sender):
     reactor.interleave(AppHelper.callAfter)
     assert(reactor.running)
Ejemplo n.º 33
0
    def finishLaunching(self):
        self.connection = False
        statusbar = AppKit.NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(AppKit.NSVariableStatusItemLength)

        self.icon = AppKit.NSImage.alloc().initByReferencingFile_(ICON_PATH)
        self.icon.setScalesWhenResized_(True)
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)

        self.menubarMenu = AppKit.NSMenu.alloc().init()

        self.open = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Open", "openui:", "")
        self.menubarMenu.addItem_(self.open)

        self.quit = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Quit", "terminate:", "")
        self.menubarMenu.addItem_(self.quit)

        self.statusitem.setMenu_(self.menubarMenu)
        self.statusitem.setToolTip_(APP_NAME)

        LBRYNotify("Starting LBRY")

        def getui():
            def download_ui(dest_dir):
                url = urlopen("https://rawgit.com/lbryio/lbry-web-ui/master/dist.zip")
                z = ZipFile(StringIO(url.read()))
                z.extractall(dest_dir)
                return defer.succeed(dest_dir)

            data_dir = user_data_dir("LBRY")
            version_dir = os.path.join(data_dir, "ui_version_history")

            git_version = subprocess.check_output("git ls-remote https://github.com/lbryio/lbry-web-ui.git | grep HEAD | cut -f 1", shell=True)

            if not os.path.isdir(data_dir):
                os.mkdir(data_dir)

            if not os.path.isdir(os.path.join(data_dir, "ui_version_history")):
                os.mkdir(version_dir)

            if not os.path.isfile(os.path.join(version_dir, git_version)):
                try:
                    f = open(os.path.join(version_dir, git_version), "w")
                    version_message = "Updating UI " + str(datetime.now())
                    f.write(version_message)
                    f.close()
                except:
                    LBRYNotify("You should have been notified to install xcode command line tools, once it's installed you can start LBRY")
                    sys.exit(0)

                if os.path.isdir(os.path.join(data_dir, "lbry-web-ui")):
                    os.rmdir(os.path.join(data_dir, "lbry-web-ui"))

            if os.path.isdir(os.path.join(data_dir, "lbry-web-ui")):
                return defer.succeed(os.path.join(data_dir, "lbry-web-ui"))
            else:
                return download_ui((os.path.join(data_dir, "lbry-web-ui")))

        def setupserver(ui_dir):
            root = LBRYindex(ui_dir)
            root.putChild("css", static.File(os.path.join(ui_dir, "css")))
            root.putChild("font", static.File(os.path.join(ui_dir, "font")))
            root.putChild("img", static.File(os.path.join(ui_dir, "img")))
            root.putChild("js", static.File(os.path.join(ui_dir, "js")))
            root.putChild("view", LBRYFileRender())
            return defer.succeed(root)

        def setupapi(root):
            daemon = LBRYDaemon()
            root.putChild(API_ADDRESS, daemon)
            reactor.listenTCP(API_PORT, server.Site(root), interface=API_INTERFACE)
            return daemon.setup(DEFAULT_WALLET, "False")

        d = getui()
        d.addCallback(setupserver)
        d.addCallback(setupapi)
        d.addCallback(lambda _: webbrowser.get("safari").open(UI_ADDRESS))

        reactor.interleave(AppHelper.callAfter)
Ejemplo n.º 34
0
 def applicationDidFinishLaunching_(self, notification):
     client = Client()
     client.app = Xierpa3App()
     site = server.Site(client)
     reactor.interleave(AppHelper.callAfter)  #@UndefinedVariable
     reactor.listenTCP(8060, site)  # @UndefinedVariable
Ejemplo n.º 35
0
    def __init__(self,
                 parent=None,
                 id=-1,
                 title='Parallel IPython Crust',
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.DEFAULT_FRAME_STYLE,
                 rootObject=None,
                 rootLabel=None,
                 rootIsNamespace=True,
                 locals=None,
                 InterpClass=None,
                 *args,
                 **kwds):
        """Create CrustFrame instance."""
        frame.Frame.__init__(self, parent, id, title, pos, size, style)
        intro = 'Twisted Enabled PyCrust for Parallel IPython'
        self.SetStatusText(intro.replace('\n', ', '))

        # Import twisted stuff
        from twisted.internet import threadedselectreactor
        threadedselectreactor.install()
        from twisted.internet import reactor
        from twisted.python import log
        self.reactor = reactor
        log.startLogging(sys.stdout)

        # Pass the reactor to the user namespace
        mylocals = locals
        if mylocals is None:
            mylocals = {'reactor': reactor}
        else:
            mylocals.update({'reactor': reactor})

        self.crust = Crust(parent=self,
                           intro=intro,
                           rootObject=rootObject,
                           rootLabel=rootLabel,
                           rootIsNamespace=rootIsNamespace,
                           locals=mylocals,
                           InterpClass=InterpClass,
                           *args,
                           **kwds)
        self.shell = self.crust.shell
        # Override the filling so that status messages go to the status bar.
        self.crust.filling.tree.setStatusText = self.SetStatusText
        # Override the shell so that status messages go to the status bar.
        self.shell.setStatusText = self.SetStatusText
        # Fix a problem with the sash shrinking to nothing.
        self.crust.filling.SetSashPosition(200)
        # Set focus to the shell editor.
        self.shell.SetFocus()

        # Add a File->Exit event to shutdown the twisted reactor
        mb = self.GetMenuBar()
        m0 = mb.GetMenu(0)
        m0.Append(10101, "E&xit", "Exit")
        wx.EVT_MENU(self, 10101, self.DoExit)

        # Lastly interleave the twisted reactor with wx!
        reactor.interleave(wx.CallAfter)
Ejemplo n.º 36
0
        # if we're in main thread, just fire off callback
        if get_ident() == BaseQObject.MAIN_THREAD_ID:
            if data or type(data) == type(False): callback(data)
            else: callback()
        # send callback to main thread
        else:
            event = QEvent(QEvent.User)
            event.callback = callback
            if data or type(data) == type(False): event.data = data
            qApp.postEvent(self, event)


class Interleaver(BaseQObject):
    def __init__(self):
        BaseQObject.__init__(self)

    def toInterleave(self, func, *args, **kwargs):
        #print('toInterleave(): %s'%(str(func)))
        self.postEventWithCallback(func)


if len(sys.argv) > 1:
    Pinger(sys.argv[1])
    ii = Interleaver()
    reactor.interleave(ii.toInterleave)
    app = QApplication([])
    app.exec_loop()
else:
    reactor.listenTCP(PORT, pb.PBServerFactory(Ponger()))
    reactor.run()
Ejemplo n.º 37
0
 def reactor_start(*_args):
     log.info('starting twisted reactor in ipython')
     reactor.interleave(reactor_wake)  # @UndefinedVariable
     inputhook.set_inputhook(reactor_work)
Ejemplo n.º 38
0
def start_apaf():
    base.main().addCallback(setup_complete).addErrback(base.setup_failed)
    reactor.interleave(win32gui.PumpMessages)
Ejemplo n.º 39
0
 def start(self):
     # start the reactor
     reactor.interleave(self.twistedQueue.put)
 def applicationDidFinishLaunching_(self, notification):
     client = Client()
     client.app = Xierpa3App()
     site = server.Site(client)
     reactor.interleave(AppHelper.callAfter) #@UndefinedVariable
     reactor.listenTCP(8060, site) # @UndefinedVariable
Ejemplo n.º 41
0
 def reactor_start(*args):
     '''Start the twisted reactor main loop
     '''
     Logger.info("Support: Starting twisted reactor")
     reactor.interleave(reactor_wake, **kwargs)
     Clock.schedule_interval(reactor_work, 0)
Ejemplo n.º 42
0
    def __init__(self, parent, ID, title, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
        self.parent = parent
        import tabbar, sidebar, mainmenu, graphcanvas, graphcontext
        import inputmanager
        from pathhelper import resFile

        wx.Frame.__init__(self, parent, ID, title, pos, size, style)

        # Before we set up the frame, parse command line arguments.
        (self.cmdline_options, self.cmdline_args) = cmdline_opts()

        # set the side by side 3D to False
        config.current['global:sideBySide3D']=False

        #Check Always highlight:
        if self.cmdline_options.alwaysHighlight:
            config.current['global:highlight'] = True

        # Set up anaglyph mode if requested
        if self.cmdline_options.anaglyph:
            config.current['global:enable-anaglyph'] = True
            #	    config.current['default:show-plane'] = False
            #	    config.current['default:plane-color'] = (0.0, 0.0, 0.0)
            config.current['default:background-color'] = (0.0, 0.0, 0.0)

        # Set up jitter control if specified
        if self.cmdline_options.jitter == 175.0:
            pass
        else:
            config.current['global:jitter'] = self.cmdline_options.jitter

        # Bind the onClose handler to prompt for saving before
        # app close
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.size = size
        self.pos = pos
        # Set Up Joystick
        try:
            self.js = wx.Joystick(0)
            if self.js.GetNumberJoysticks() > 0:
                self.haveJoystick = True
                print "Joystick Detected."
                self.xJoystickRotation = 0
                self.yJoystickRotation = 0
                self.JoystickB2 = False
                self.JoystickB4 = False
                self.pov = self.js.GetRudderMax()
            else:
                self.haveJoystick = False
        except NotImplementedError:
            print "wxJoystick not available."
            self.haveJoystick = False

        # Load Sounds:
        self.sound = EvtSounds()
        # Load Cursors:
        self.cursor2D = Cursor2D()

        # Load XML resources.
        self.xmlres = xrc.XmlResource(resFile("gluskap.xrc"))

        self.menu = mainmenu.MainMenu(self)

        # The ContextList is all the graphs currently open
        # The InteractiveCanvas is the GLCanvas the graph gets drawn on
        self.contexts = graphcontext.ContextList(parent=self)
        self.canvas = graphcanvas.InteractiveCanvas(parent=self, stereo=self.cmdline_options.stereo)

        # The Sidebar and Tabbar
        self.sidebar = sidebar.Sidebar(self)
        self.tabbar = tabbar.TabBar(self)

        boxGraphTabs = wx.BoxSizer(wx.VERTICAL)
        boxGraphTabs.Add(self.canvas, 1, wx.EXPAND)
        boxGraphTabs.Add(self.tabbar, 0, wx.EXPAND)

        boxAllControls = wx.BoxSizer(wx.HORIZONTAL)
        boxAllControls.Add(boxGraphTabs, 3, wx.EXPAND)
        boxAllControls.Add(self.sidebar, 1, wx.EXPAND)
        self.SetSizer(boxAllControls)
        self.SetAutoLayout(True)

        self.CreateStatusBar(1)
        self.SetStatusText("Welcome to GLuskap", 0)

        #this lines causes memory leeks. REmoving it seems to make everything better
        #it might be needed somewheres... but who knows?
        #wx.Image_AddHandler(wx.ICOHandler())

        log = wx.LogNull()
        self.icon = wx.Icon(resFile("GLuskap.ico"), wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)
        del log

        self.menuBar = wx.MenuBar()
        self.menuBar.Append(self.menu.mnuFile, "&File")
        self.menuBar.Append(self.menu.mnuEdit, "&Edit")
        self.menuBar.Append(self.menu.mnuView, "&View")
        self.menuBar.Append(self.menu.mnuTools, "&Tools")
        self.menuBar.Append(self.menu.mnuHelp, "&Help")
        self.SetMenuBar(self.menuBar)

        def startingFiles():
            if len(self.cmdline_args) > 0:
                for f in self.cmdline_args:
                    self.menu._FileOpen(filename=f)
            else:
                self.menu._FileNew()

        wx.CallAfter(startingFiles)

        # Start the reactor - only if twisted is available.
        if havetwisted:
            try:
                print "Converting", self.cmdline_options.portnum
                realport = int(self.cmdline_options.portnum)
            except:
                print "Port number needs to be a number."
                realport = 12001
            self.port = reactor.listenTCP(realport, pb.PBServerFactory(ContextServer(self.contexts)))
            reactor.interleave(wx.CallAfter)

        # Start a timer that will refresh the GraphCanvas.
        self.timer = wx.Timer(owner=self)
        self.fps = config.current['global:render-fps']
        XRCCTRL(self.sidebar, "CameraRenderFPS").SetValue(self.fps)
        self.timer.Start(milliseconds=1000.0 / self.fps, oneShot=False)
        self.Bind(wx.EVT_TIMER, self.OnTick)

        # Initialize the Animator
        from animate import Animator

        self.animator = Animator(parent=self)

        # Initialize the Input Manager - we need it for the Flock
        # and/or the Wanda
        self.inputmgr = inputmanager.InputManager(self, self.contexts)

        # Initialize flock control
        if self.cmdline_options.useFlock:
            import flock

            # Try to use the port as an integer (0-based indexing
            # for pySerial) - if not, pass it as a string
            try:
                port = int(self.cmdline_options.flockPort)
            except ValueError:
                port = self.cmdline_options.flockPort
            self.FOB = flock.FlockControl(port=port, nbirds=2, reportrate=4)

            def next():
                print "Flock init succeeded."
                # HEMI_FWD
                # HEMI_AFT
                # HEMI_UPPER
                # HEMI_LOWER
                self.FOB.SendCmd(flock.CMD_HEMISPHERE + flock.HEMI_UPPER)
                #		self.FOB.SendCmd(flock.CMD_HEMISPHERE+flock.HEMI_FWD)

                #XXX# untested!
                #XXX# self.FOB.SetLineFreq(50)

                # Bird 1: Wanda tracker (map to cursor)
                self.FOB.birds[0].SetReportFormat(flock.CMD_POSITION_MATRIX)
                self.FOB.birds[0].SetHandlers(position=self.inputmgr.cursorInputPos,
                                              matrix=self.inputmgr.cursorInputRot)
                # Bird 2: Headtracker
                self.FOB.birds[1].SetReportFormat(flock.CMD_POSITION_MATRIX)
                self.FOB.birds[1].SetHandlers(position=self.inputmgr.trackerInputPos)
                self.FOB.Start()
                wx.CallAfter(self.FOB.Update, 50)

            def fail():
                print "Flock init failed."
                config.current['global:flock'] = False

            self.FOB.Prestart(onSuccess=next, onFailure=fail)
        else:
            self.FOB = None

        # Initialize wanda control
        if self.cmdline_options.useWanda:
            import flock

            # Try to use the port as an integer (0-based indexing
            # for pySerial) - if not, pass it as a string
            try:
                port = int(self.cmdline_options.wandaPort)
            except ValueError:
                port = self.cmdline_options.wandaPort
            self.Wanda = flock.WandaControl(port=port)

            def printArgs(*args, **kwargs):
                print "args:", args, "kwargs:", kwargs

            #	    self.Wanda.SetHandlers(movement=printArgs,leftbutton=printArgs,rightbutton=printArgs,midbutton=printArgs)
            self.Wanda.SetHandlers(movement=self.inputmgr.wandaInput2D,
                                   leftbutton=self.inputmgr.wandaButtonLeft,
                                   rightbutton=self.inputmgr.wandaButtonRight,
                                   midbutton=self.inputmgr.wandaButtonMid)
            wx.CallAfter(self.Wanda.Update, 50)


        # Always call ContextList.setActive; that way menu disabling/enabling
        # happens properly.
        self.contexts.setActive(-1)
Ejemplo n.º 43
0
    sublime.set_timeout(funcToCall, 0)


from twisted.internet.error import ReactorAlreadyInstalledError, ReactorAlreadyRunning, ReactorNotRestartable

reactorAlreadyInstalled = False
try:
    # noinspection PyProtectedMember
    from twisted.internet import _threadedselect

    _threadedselect.install()
except ReactorAlreadyInstalledError:
    reactorAlreadyInstalled = True

from twisted.internet import reactor

try:
    # noinspection PyUnresolvedReferences
    reactor.interleave(callInSublimeLoop, installSignalHandlers=False)
except ReactorAlreadyRunning:
    reactorAlreadyInstalled = True
except ReactorNotRestartable:
    reactorAlreadyInstalled = True

if reactorAlreadyInstalled:
    log.msg('twisted reactor already installed', logLevel=logging.DEBUG)
    if type(reactor) != _threadedselect.ThreadedSelectReactor:
        log.msg('unexpected reactor type installed: %s, it is best to use twisted.internet._threadedselect!' % type(
            reactor), logLevel=logging.WARNING)
else:
    log.msg('twisted reactor installed and running', logLevel=logging.DEBUG)
Ejemplo n.º 44
0
 def start(self):
     # start the reactor
     reactor.interleave(self.twistedQueue.put)
 def applicationDidFinishLaunching_(self, aNotification):
     """Create and display a new connection window
     """
     reactor.interleave(AppHelper.callAfter)
     self.newConnectionAction_(None)
    def __init__(self, appName = 'example', checkRoom = None, suggest = False, options=None):
        splash = None

        FXUI.app = QtGui.QApplication(sys.argv)
        FXUI.app.setApplicationName("wallaby - " + appName)

        for s in ['16', '32', '64', '128', '256']:
            FXUI.app.setWindowIcon(QtGui.QIcon(QtGui.QPixmap(':/icons/images/wallaby_logo_' + s + '.png')))

        pixmap = QtGui.QPixmap(":/images/images/wallaby_splash.png")
        splash = QtGui.QSplashScreen(pixmap)
        splash.show()
        splash.raise_()
        FXUI.app.processEvents()

        if USES_PYSIDE or FXUI.qt4reactor:
            print "Install qt4reactor. USES_PYSIDE =", USES_PYSIDE
            import wallaby.frontends.qt.reactor.qt4reactor as qtreactor
            qtreactor.install()
        else:
            threadedselect.install()
             
            from twisted.internet import reactor
            ii = Interleaver()
            reactor.interleave(ii.toInterleave)
            reactor.suggestThreadPoolSize(50)

        FXUI.mineIcon = QtGui.QIcon(':/icons/images/mine.png')
        FXUI.theirsIcon = QtGui.QIcon(':/icons/images/theirs.png')

        tapp = twisted.application.service.Application("gui")
        service  = FXLogger('wallaby.log')
        service.setServiceParent(tapp)
        service.startService()

        FX.appModule = 'wallaby.apps.' + appName

        try:
            from twisted.plugin import getCache
            pkg = __import__(FX.appModule, globals(), locals(), ["*"], 0)
            if pkg is not None and len(pkg.__path__) > 0 and os.path.exists(pkg.__path__[0]):
                FX.appPath = pkg.__path__[0]
            else:
                FX.appPath = os.path.join(".", "wallaby", "apps", appName)
        except:
            FX.appPath = os.path.join(".", "wallaby", "apps", appName)

        FXUI.css = None

        try:
            print "importing", options.module, "from", FX.appModule
            if options.module == "WallabyApp2" and os.path.exists(os.path.join(FX.appPath, "mainWindow.py")):
                mod = FX.imp(FX.appModule + '.mainWindow', False)
                if os.path.exists(os.path.join(FX.appPath, "mainWindow.css")):
                    FXUI.css = open(os.path.join(FX.appPath, "mainWindow.css")).read()
            else:
                module = options.module
                module = module[0].lower() + module[1:]
                mod = FX.imp(FX.appModule + '.' + module, False)

                if os.path.exists(os.path.join(FX.appPath, module + ".css")):
                    FXUI.css = open(os.path.join(FX.appPath, module + ".css")).read()
        except:
            mod = None

        if mod == None:
            FX.crit('Module', FX.appModule, 'not found')
            reactor.callWhenRunning(self.myQuit)
            if USES_PYSIDE or FXUI.qt4reactor: reactor.runReturn()
            FXUI.app.exec_()
            return

        try:
            FXUI.mainWindow = mod.MainWindow(self.myQuit, options)
            if FXUI.css is not None:
                FXUI.app.setStyle("plastique")
                FXUI.mainWindow.setStyleSheet(FXUI.css)
        except Exception as e:
            import traceback
            traceback.print_exc(file=sys.stdout)

            from twisted.internet import reactor
            reactor.callWhenRunning(self.myQuit)
            if USES_PYSIDE or FXUI.qt4reactor: reactor.runReturn()
            FXUI.app.exec_()
            return

        FXUI.mainWindow.setSplash(splash)

        from twisted.internet import reactor
        reactor.callWhenRunning(self.run, mod, options, checkRoom)

        FXUI.mainWindow.enabled = False
        FXUI.mainWindow.configure()
        FXUI.mainWindow.show()
        FXUI.mainWindow.raise_()

        signal.signal(signal.SIGINT, self.sigint_handler)
        signal.signal(signal.SIGTERM, self.sigint_handler)

        # self.gc = GarbageCollector(FXUI.mainWindow, True)

        if USES_PYSIDE or FXUI.qt4reactor: reactor.runReturn()
        FXUI.app.exec_()