Esempio n. 1
0
class e2midi(QtGui.QMainWindow, Ui_e2midi):

    def __init__(self, host, nb):
        QtGui.QWidget.__init__(self, None)
        self.setupUi(self)
        mixer.init()
        self.sock = QTcpSocket()
        self.sock.connectToHost(host, 2012)
        self.sock.readyRead.connect(self.listen)
        self.nb = nb
        self.bar = []
        self.central.setSpacing(500/nb)
        for i in range(nb):
            b = QtGui.QProgressBar()
            b.setOrientation(Qt.Qt.Vertical)
            b.setFormat("%d" % i)
            b.setValue(0)
            self.central.addWidget(b)
            self.bar.append(b)

    def handle_data(self, position):
        print position
        bar = self.bar[min(self.nb - 1, int(position * self.nb))]
        bar.setValue(100)
        QtCore.QTimer.singleShot(200, lambda: bar.setValue(0));

    def listen(self):
        data = self.sock.readAll()
        [self.handle_data(float(i)) for i in data.split('\n') if i != '']
Esempio n. 2
0
class QTcpTransport(Transport):
    '''A Transport connecting to a TCP server.
    
    Connect using .start().
    
    Received data is processed on the Qt mainloop thread.
    '''
    shorthand='qtcp'
    @classmethod
    def fromstring(cls, expression):
        '''qtcp:<host>:<port>'''
        _, host, port = expression.split(':')
        return cls(host=host, port=int(port), sendername=expression)

    def __init__(self, host, port, sendername='qtcp'):
        self.address = (host, port)
        self.sendername = sendername
        self.leftover = b''
        self.socket = QTcpSocket()
        self.socket.readyRead.connect(self.on_ready_read)
        self.socket.error.connect(self.on_error)
        self.socket.connected.connect(self.on_connect)

    def start(self):
        if self.socket.state() != QAbstractSocket.UnconnectedState:
            L().debug('start(): Socket is not in UnconnectedState, doing nothing')
            return
        L().debug('connecting to: %s'%(self.address,))
        self.socket.connectToHost(self.address[0], self.address[1])
        
    def stop(self):
        self.socket.flush()
        self.socket.disconnectFromHost()

    def send(self, data, receivers=None):
        if receivers is not None and self.sendername not in receivers:
            return
        L().debug('message to tcp server: %s'%data)
        self.socket.write(data.decode('utf8'))

    def on_ready_read(self):
        data = self.socket.readAll().data()
        pdata = data
        if len(pdata) > 100:
            pdata = pdata[:100] + b'...'
        #if pdata.startswith('{'):
        L().debug('message from tcp server: %s'%pdata)
        self.leftover = self.received(
            sender=self.sendername,
            data=self.leftover + data
        )
        
    def on_connect(self):
         L().info('QTcpSocket: Established connection to %s'%(self.address,))

    def on_error(self, error):
        L().info('QTcpSocket raised error: %s'%error)
Esempio n. 3
0
class QiVisClient(QtCore.QObject):
    def __init__(self, name, server, serverPort, x, y, width, height ):
        """__init__() -> None
        initializes the client class"""


        QtCore.QObject.__init__(self)

        self.timer = QtCore.QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.setInterval(1000)
        self.timer.start()
        self.socket = QTcpSocket()
        self.current_pipeline = None
        self.current_config_function = None  

        self.server = server # os.environ.get( 'DV3D_HW_SERVER_NAME', server )
        self.serverPort = int(serverPort)

        self.buffer = ""
        self.pipelineQueue = []
        current_pipeline = None

        self.deviceName = name
        self.currentTab = None
        self.mainWindow = None
        print " Init VisClient, server=%s, serverPort=%s, name=%s " % ( str(self.server), str(self.serverPort), str(name) )

        self.spreadsheetWindow = spreadsheetController.findSpreadsheetWindow( False )
        self.spreadsheetWindow.setWindowFlags( self.spreadsheetWindow.windowFlags() | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Window )
#        self.spreadsheetWindow.setWindowFlags( self.spreadsheetWindow.windowFlags() | QtCore.Qt.Window )
        self.spreadsheetWindow.activateWindow()
        self.spreadsheetWindow.showMaximized()
        
        self.dimensions = ( x, y, width, height )
        self.connectSignals()       
        
    def createTab( self,  displayWidth, displayHeight, fullScreenEnabled ):
        self.spreadsheetWindow.addTabController('DV3D')
        tabController = self.spreadsheetWindow.get_current_tab_controller()
        tabController.clearTabs()
        self.currentTab = DisplayWallSheetTab( tabController, self.dimensions[0], self.dimensions[1], self.dimensions[2], self.dimensions[3], displayWidth, displayHeight, fullScreenEnabled )
        tabController.addTabWidget(self.currentTab, self.deviceName)
        tabController.setCurrentWidget(self.currentTab)
        self.size = self.currentTab.getDimension()
        print " Startup VisClient, size=%s, dims=%s, fullScreen=%s " % ( str(self.size), str(self.dimensions), str(fullScreenEnabled) )

    def updateCurrentTab(self):
        if self.currentTab == None:
            tabController = self.spreadsheetWindow.get_current_tab_controller()            
#            self.currentTab = tabController.tabWidgets[1]
            self.currentTab = tabController.widget ( 1 )
            if self.currentTab:
                self.dims = self.currentTab.getDimension()
                print " UpdateCurrentTab: ntabs=%d, dims=%s " % ( len( tabController.tabWidgets ), str( self.dims ) )
                return True
        return False
            
    def connectSignals(self):
        """connectSignals() -> None
        Connects all relevant signals to this class"""
        self.connect(self.socket, QtCore.SIGNAL("connected()"), self.connected)
        self.connect(self.socket, QtCore.SIGNAL("disconnected()"), self.disconnected)
        self.connect(self.socket, QtCore.SIGNAL("readyRead()"), self.readDataFromSocket)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.retryConnection)
        self.connect(self, QtCore.SIGNAL("executeNextPipeline()"), self.executeNextPipeline)

    def retryConnection(self):
        """retryConnection() -> None
        this method is called once everytime self.timer ticks. It
        tries to connect to the server again"""
        print "retryConnection"
        sys.stdout.flush()
        if self.socket.state()!=QTcpSocket.ConnectedState:
            if self.socket.state()==QTcpSocket.UnconnectedState:
                port = int( self.serverPort )
                print " HWClient connecting to server at %s:%d" % ( self.server, port )
                self.socket.connectToHost(self.server, port )
            self.timer.start()
        elif core.system.systemType in ['Windows', 'Microsoft']:
            self.socket.setSocketOption(QAbstractSocket.LowDelayOption, 1)

    def connected(self):
        """connected() -> None
        this method is called when self.socket emits the connected() signal. It means that a succesful connection
        has been established to the server"""
        sender = "displayClient"
        receiver = "server"
        tokens = MessageTokenSep.join( [ "dimensions", self.deviceName, str(self.dimensions[0]), str(self.dimensions[1]), str(self.dimensions[2]), str(self.dimensions[3]) ] )
        reply = sender + "-" + receiver + "-" + str(len(tokens)) + ":" + tokens
        print "   ****** Connected to server!  CellCoords = ( %d, %d ), reply: %s " % ( self.dimensions[0], self.dimensions[1], reply )
        self.socket.write(reply)

    def disconnected(self):
        """disconnected() -> None
        this method is called when self.socket emits disconnected(). It means that the socket is no longer connected to the server"""
        print "Disconnected from server"
        self.timer.start()

    def readDataFromSocket(self):
        """readDataFromSocket() -> None
        This method is called everytime the socket sends the readyRead() signal"""
        incoming = str(self.socket.readAll().data())
        while incoming != "":
            self.buffer += incoming
            while self.buffer != "":
                tokens = self.buffer.split(":")
                header = tokens[0]
                rest = ""
                for piece in tokens[1:]:
                    rest += piece+":"
                rest = rest[:-1]
                info = header.split("-")
                if len(info)<3:
                    break
                (sender, receiver, size) = (info[0], info[1], info[2])
                if int(size) > len(rest):
                    break
                tokens = rest[:int(size)]
                self.buffer = rest[int(size):]
#                print " ********* CLIENT--> gotMessage: %s %s %s ********* " % ( str( receiver ), str( sender ), str( tokens ) )
                sys.stdout.flush()

                if (receiver == "displayClient"):
                    reply = self.processMessage((sender, tokens), self.socket)

                    if reply != ("","",""):
                        reply = reply[0] + "-" + reply[1] + "-" + str(len(reply[2])) + ":" + reply[2]
                        self.socket.write(reply)
                
            incoming = str(self.socket.readAll().data())


    def processCommand(self, terms):
        print " -- processCommand: %s " % str( terms )
        if terms[0] == "reltimestep":
            relTimeValue = float( terms[1] )  
            relTimeIndex = float( terms[2] )  
            useTimeIndex = bool(terms[3]) 
            displayText =  terms[4] 
            if self.current_pipeline:
                for module in self.current_pipeline.module_list:
                    persistentCellModule = ModuleStore.getModule( module.id ) 
                    if persistentCellModule: persistentCellModule.updateAnimation( [ relTimeValue, relTimeIndex, useTimeIndex ], displayText  )
        elif terms[0] == "pipelineHelper":
            if self.current_config_function:
                if self.current_config_function.type == 'leveling':
                    range = list( self.current_config_function.range )
                    cmd_args = terms[1].split('-')
                    iRangeArg = int( cmd_args[1] )
                    range[ iRangeArg ] = float( terms[2] )
#                    print " --- PipelineHelper: set range = ", str( range )
                    self.current_config_function.broadcastLevelingData( range  )
                else:
                    pass
#                    print " --- PipelineHelper, config type: ", self.current_config_function.type
        else:
            if self.current_pipeline:
                for module in self.current_pipeline.module_list:
                    persistentCellModule = ModuleStore.getModule( module.id ) 
                    if persistentCellModule: persistentCellModule.updateConfigurationObserver( terms[0], terms[1:] )
#        if terms[0] == 'colormap':
#             cmapData = terms[1]
#             displayText =  terms[2]  
#             for module in self.current_pipeline.module_list:
#                persistentCellModule = ModuleStore.getModule( module.id ) 
#                persistentCellModule.setColormap( cmapData  )
#                persistentCellModule.updateTextDisplay( displayText )

    def processEvent(self, terms):
        """processEvent(message: String) -> None
        decodifies the event received by the server and posts it to QT's event handler. In order
        to do this, we must send three events: the first one disables this client's method that
        would send events to the server. The second is the actual event we want processed and the third
        reenables event sending to the server. This must be done to avoid a deadlock"""
        def decodeMouseEvent( event, screenDims ):
            """decodeMouseEvent(event: String) -> QtGui.QMouseEvent
            this method receives a string and returns the corresponding mouse event"""
            pos = ( int( float( event[2] ) * screenDims[0] ), int( float( event[3] ) * screenDims[1] ) )
            if event[1] == "left":
                button = QtCore.Qt.LeftButton
            elif event[1] == "right":
                button = QtCore.Qt.RightButton

            if event[0] == "singleClick": 
                t = QtCore.QEvent.MouseButtonPress
            elif event[0] == "mouseMove": 
                t = QtCore.QEvent.MouseMove
                button = QtCore.Qt.NoButton
            elif event[0] == "mouseRelease": 
                t = QtCore.QEvent.MouseButtonRelease

            button = QtCore.Qt.MouseButton(button)
            m = QtCore.Qt.NoModifier
            if event[4] == "shift": 
                m = QtCore.Qt.ShiftModifier
            elif event[4] == "ctrl": 
                m = QtCore.Qt.ControlModifier
            elif event[4] == "alt": 
                m = QtCore.Qt.AltModifier
#            print " Client process %s %s event: pos = %s, screenDims=%s " % ( button, event[0], str( pos ), str( screenDims ) )

            return QtGui.QMouseEvent(t, QtCore.QPoint(pos[0], pos[1]), button, button, m)

        def decodeKeyEvent(event):
            """decodeKeyEvent(event: String) -> QtGui.QKeyEvent
            this method receives a string and returns the corresponding Key event"""
            type = None
            if event[0] == "keyPress":
                type = QtCore.QEvent.KeyPress
            elif event[0] == "keyRelease":
                type = QtCore.QEvent.KeyRelease
                
            key = int( event[1] )
            
            m = QtCore.Qt.NoModifier
            if event[2] == "shift": 
                m = QtCore.Qt.ShiftModifier
            elif event[2] == "ctrl": 
                m = QtCore.Qt.ControlModifier
            elif event[2] == "alt": 
                m = QtCore.Qt.AltModifier
#            print " Client process key event: %s " % str( event )

            return QtGui.QKeyEvent( type, key, QtCore.Qt.KeyboardModifiers(m) )

        app = QtCore.QCoreApplication.instance()
        newTab = self.updateCurrentTab()
        widget = self.currentTab.getCellWidget( 0, 0 ) if self.currentTab else None
                  
#        print " ------------- QiVisClient.processEvent: %s  ---------------------" % ( str(terms) )
        sys.stdout.flush()
        
        if terms[2] == "interactionState":           
            if self.current_pipeline:
                state =   terms[3] if ( len(terms) > 3 ) else None
                altMode = terms[4] if ( len(terms) > 4 ) else None
                print " ~~~~~ Setting Client Interaction State: ", str(state), str(altMode)
                sys.stdout.flush()
                for module in self.current_pipeline.module_list:
                    persistentModule = ModuleStore.getModule( module.id ) 
                    if persistentModule:
                        cf = persistentModule.updateInteractionState( state, altMode ) 
                        if cf: self.current_config_function = cf  
                    else: print "Can't find client persistentModule: ", module.id        
        else: 
            newEvent = None      
            if terms[2] == "singleClick":
                cellModules = self.getCellModules()
                cpos = [ float(terms[i]) for i in range(7,10) ]
                cfol = [ float(terms[i]) for i in range(10,13) ]
                cup  = [ float(terms[i]) for i in range(13,16) ]
    #            print " >>> QiVisClient.cellModules: %s, modules: %s" % ( str( [ cellMod.id for cellMod in cellModules ] ), str( ModuleStore.getModuleIDs() ) )           
                for cellMod in cellModules:
                    persistentCellModule = ModuleStore.getModule( cellMod.id ) 
                    if persistentCellModule: persistentCellModule.syncCamera( cpos, cfol, cup )            
            if terms[2] in ["singleClick", "mouseMove", "mouseRelease"]:
                if self.currentTab:
                    screenRect = self.currentTab.getCellRect( 0, 0 )
                    screenDims = ( screenRect.width(), screenRect.height() )
                    newEvent = decodeMouseEvent( terms[2:], screenDims )
            elif terms[2] in ["keyPress", "keyRelease" ]:
                newEvent = decodeKeyEvent(terms[2:])
    
            if widget and newEvent: 
                cellWidget = widget.widget()
                app.postEvent( cellWidget, newEvent)
                cellWidget.setFocus()
                cellWidget.update()

    def executeNextPipeline(self):
        if len(self.pipelineQueue) == 0:
            return
        pipeline = self.pipelineQueue[-1]
        self.pipelineQueue.pop()
        self.executePipeline(pipeline)
        self.emit(QtCore.SIGNAL("executeNextPipeline()"))

    def getCellModules(self):
        cellModules = []
        if self.current_pipeline:
            for module in self.current_pipeline.module_list:
                if ( module.name == "MapCell3D" ): cellModules.append( module )
        return cellModules
        
    def getCurrentPipeline(self):
        return self.current_pipeline
    
    def setCellLocation(self):
        cellModule = None
        if self.current_pipeline:
            print " Executing Client Workflow, modules: "
            for module in self.current_pipeline.module_list:
                print str( module )
    #            if : cellModule = module


    def executePipeline(self,pipeline):
        from core.db.io import unserialize
        from core.vistrail.pipeline import Pipeline
        from core.interpreter.default import get_default_interpreter as getDefaultInterpreter
        from core.utils import DummyView
        import api

        tabController = self.spreadsheetWindow.get_current_tab_controller()
        pip = unserialize(str(pipeline), Pipeline)
#        print " **** Client-%s ---Received Pipeline--- modules:" % str( self.dimensions )
#        for module in pip.module_list:
#            print "     ", str(module.id)
        self.current_pipeline = pip
        interpreter = getDefaultInterpreter()
        kwargs = { "locator":           None,
                   "current_version":   None,
                   "view":              DummyView(),
                   "aliases":           {} }
        interpreter.execute( pip, **kwargs )
        print "Finished Executing Pipeline"

    def processMessage(self, message, socket):
        (sender, tokens) = message
#        print " ********* CLIENT--> processMessage: %s ********* " % str( tokens )
        tokens = tokens.split( MessageTokenSep )
        if ( len(tokens) < 4 ) or ( tokens[3] <> 'mouseMove' ): print " ********* CLIENT--> splitMessage: %s ********* " % str( tokens )
        if len(tokens) == 0: return
        
        if tokens[0] == "exit":
            print "Received shutdown message"
            sys.stdout.flush()
            socket.close()
            gui.application.get_vistrails_application().quit()
            gui.application.stop_application()
            sys.exit(0)

        if tokens[0] == "pipeline":
#            print " $$$$$$$$$$$ Client-- pipeline message: %s " % str(tokens)
            ### we must execute a pipeline
#            return ("", "", "")
            if len(tokens[2:]) != 0:
                for t in tokens[2:]:
                    tokens[1] += t + "@"
                tokens[1] = tokens[1][:-1]
            
            self.executePipeline(tokens[1])
        elif tokens[0] == "interaction":
            self.processEvent(tokens[1:])
            
        elif tokens[0] == "command":
            self.processCommand(tokens[3:])
            
        elif tokens[0] == "refresh":
            self.updateCurrentTab()
            if self.currentTab:
                widget = self.currentTab.getCell(int(tokens[1]), int(tokens[2]))
#                if widget:
#                    widget.swapBuffers()
        return ("", "", "")
Esempio n. 4
0
class QiVisClient(QtCore.QObject):
    def __init__(self, name, server, serverPort, x, y, width, height):
        """__init__() -> None
        initializes the client class"""

        QtCore.QObject.__init__(self)

        self.timer = QtCore.QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.setInterval(1000)
        self.timer.start()
        self.socket = QTcpSocket()
        self.current_pipeline = None
        self.current_config_function = None

        self.server = server  # os.environ.get( 'DV3D_HW_SERVER_NAME', server )
        self.serverPort = int(serverPort)

        self.buffer = ""
        self.pipelineQueue = []
        current_pipeline = None

        self.deviceName = name
        self.currentTab = None
        self.mainWindow = None
        print " Init VisClient, server=%s, serverPort=%s, name=%s " % (str(
            self.server), str(self.serverPort), str(name))

        self.spreadsheetWindow = spreadsheetController.findSpreadsheetWindow(
            False)
        self.spreadsheetWindow.setWindowFlags(
            self.spreadsheetWindow.windowFlags()
            | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Window)
        #        self.spreadsheetWindow.setWindowFlags( self.spreadsheetWindow.windowFlags() | QtCore.Qt.Window )
        self.spreadsheetWindow.activateWindow()
        self.spreadsheetWindow.showMaximized()

        self.dimensions = (x, y, width, height)
        self.connectSignals()

    def createTab(self, displayWidth, displayHeight, fullScreenEnabled):
        self.spreadsheetWindow.addTabController('DV3D')
        tabController = self.spreadsheetWindow.get_current_tab_controller()
        tabController.clearTabs()
        self.currentTab = DisplayWallSheetTab(tabController,
                                              self.dimensions[0],
                                              self.dimensions[1],
                                              self.dimensions[2],
                                              self.dimensions[3], displayWidth,
                                              displayHeight, fullScreenEnabled)
        tabController.addTabWidget(self.currentTab, self.deviceName)
        tabController.setCurrentWidget(self.currentTab)
        self.size = self.currentTab.getDimension()
        print " Startup VisClient, size=%s, dims=%s, fullScreen=%s " % (str(
            self.size), str(self.dimensions), str(fullScreenEnabled))

    def updateCurrentTab(self):
        if self.currentTab == None:
            tabController = self.spreadsheetWindow.get_current_tab_controller()
            #            self.currentTab = tabController.tabWidgets[1]
            self.currentTab = tabController.widget(1)
            if self.currentTab:
                self.dims = self.currentTab.getDimension()
                print " UpdateCurrentTab: ntabs=%d, dims=%s " % (len(
                    tabController.tabWidgets), str(self.dims))
                return True
        return False

    def connectSignals(self):
        """connectSignals() -> None
        Connects all relevant signals to this class"""
        self.connect(self.socket, QtCore.SIGNAL("connected()"), self.connected)
        self.connect(self.socket, QtCore.SIGNAL("disconnected()"),
                     self.disconnected)
        self.connect(self.socket, QtCore.SIGNAL("readyRead()"),
                     self.readDataFromSocket)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"),
                     self.retryConnection)
        self.connect(self, QtCore.SIGNAL("executeNextPipeline()"),
                     self.executeNextPipeline)

    def retryConnection(self):
        """retryConnection() -> None
        this method is called once everytime self.timer ticks. It
        tries to connect to the server again"""
        print "retryConnection"
        sys.stdout.flush()
        if self.socket.state() != QTcpSocket.ConnectedState:
            if self.socket.state() == QTcpSocket.UnconnectedState:
                port = int(self.serverPort)
                print " HWClient connecting to server at %s:%d" % (self.server,
                                                                   port)
                self.socket.connectToHost(self.server, port)
            self.timer.start()
        elif core.system.systemType in ['Windows', 'Microsoft']:
            self.socket.setSocketOption(QAbstractSocket.LowDelayOption, 1)

    def connected(self):
        """connected() -> None
        this method is called when self.socket emits the connected() signal. It means that a succesful connection
        has been established to the server"""
        sender = "displayClient"
        receiver = "server"
        tokens = MessageTokenSep.join([
            "dimensions", self.deviceName,
            str(self.dimensions[0]),
            str(self.dimensions[1]),
            str(self.dimensions[2]),
            str(self.dimensions[3])
        ])
        reply = sender + "-" + receiver + "-" + str(len(tokens)) + ":" + tokens
        print "   ****** Connected to server!  CellCoords = ( %d, %d ), reply: %s " % (
            self.dimensions[0], self.dimensions[1], reply)
        self.socket.write(reply)

    def disconnected(self):
        """disconnected() -> None
        this method is called when self.socket emits disconnected(). It means that the socket is no longer connected to the server"""
        print "Disconnected from server"
        self.timer.start()

    def readDataFromSocket(self):
        """readDataFromSocket() -> None
        This method is called everytime the socket sends the readyRead() signal"""
        incoming = str(self.socket.readAll().data())
        while incoming != "":
            self.buffer += incoming
            while self.buffer != "":
                tokens = self.buffer.split(":")
                header = tokens[0]
                rest = ""
                for piece in tokens[1:]:
                    rest += piece + ":"
                rest = rest[:-1]
                info = header.split("-")
                if len(info) < 3:
                    break
                (sender, receiver, size) = (info[0], info[1], info[2])
                if int(size) > len(rest):
                    break
                tokens = rest[:int(size)]
                self.buffer = rest[int(size):]
                #                print " ********* CLIENT--> gotMessage: %s %s %s ********* " % ( str( receiver ), str( sender ), str( tokens ) )
                sys.stdout.flush()

                if (receiver == "displayClient"):
                    reply = self.processMessage((sender, tokens), self.socket)

                    if reply != ("", "", ""):
                        reply = reply[0] + "-" + reply[1] + "-" + str(
                            len(reply[2])) + ":" + reply[2]
                        self.socket.write(reply)

            incoming = str(self.socket.readAll().data())

    def processCommand(self, terms):
        print " -- processCommand: %s " % str(terms)
        if terms[0] == "reltimestep":
            relTimeValue = float(terms[1])
            relTimeIndex = float(terms[2])
            useTimeIndex = bool(terms[3])
            displayText = terms[4]
            if self.current_pipeline:
                for module in self.current_pipeline.module_list:
                    persistentCellModule = ModuleStore.getModule(module.id)
                    if persistentCellModule:
                        persistentCellModule.updateAnimation(
                            [relTimeValue, relTimeIndex, useTimeIndex],
                            displayText)
        elif terms[0] == "pipelineHelper":
            if self.current_config_function:
                if self.current_config_function.type == 'leveling':
                    range = list(self.current_config_function.range)
                    cmd_args = terms[1].split('-')
                    iRangeArg = int(cmd_args[1])
                    range[iRangeArg] = float(terms[2])
                    #                    print " --- PipelineHelper: set range = ", str( range )
                    self.current_config_function.broadcastLevelingData(range)
                else:
                    pass
#                    print " --- PipelineHelper, config type: ", self.current_config_function.type
        else:
            if self.current_pipeline:
                for module in self.current_pipeline.module_list:
                    persistentCellModule = ModuleStore.getModule(module.id)
                    if persistentCellModule:
                        persistentCellModule.updateConfigurationObserver(
                            terms[0], terms[1:])
#        if terms[0] == 'colormap':
#             cmapData = terms[1]
#             displayText =  terms[2]
#             for module in self.current_pipeline.module_list:
#                persistentCellModule = ModuleStore.getModule( module.id )
#                persistentCellModule.setColormap( cmapData  )
#                persistentCellModule.updateTextDisplay( displayText )

    def processEvent(self, terms):
        """processEvent(message: String) -> None
        decodifies the event received by the server and posts it to QT's event handler. In order
        to do this, we must send three events: the first one disables this client's method that
        would send events to the server. The second is the actual event we want processed and the third
        reenables event sending to the server. This must be done to avoid a deadlock"""
        def decodeMouseEvent(event, screenDims):
            """decodeMouseEvent(event: String) -> QtGui.QMouseEvent
            this method receives a string and returns the corresponding mouse event"""
            pos = (int(float(event[2]) * screenDims[0]),
                   int(float(event[3]) * screenDims[1]))
            if event[1] == "left":
                button = QtCore.Qt.LeftButton
            elif event[1] == "right":
                button = QtCore.Qt.RightButton

            if event[0] == "singleClick":
                t = QtCore.QEvent.MouseButtonPress
            elif event[0] == "mouseMove":
                t = QtCore.QEvent.MouseMove
                button = QtCore.Qt.NoButton
            elif event[0] == "mouseRelease":
                t = QtCore.QEvent.MouseButtonRelease

            button = QtCore.Qt.MouseButton(button)
            m = QtCore.Qt.NoModifier
            if event[4] == "shift":
                m = QtCore.Qt.ShiftModifier
            elif event[4] == "ctrl":
                m = QtCore.Qt.ControlModifier
            elif event[4] == "alt":
                m = QtCore.Qt.AltModifier
#            print " Client process %s %s event: pos = %s, screenDims=%s " % ( button, event[0], str( pos ), str( screenDims ) )

            return QtGui.QMouseEvent(t, QtCore.QPoint(pos[0], pos[1]), button,
                                     button, m)

        def decodeKeyEvent(event):
            """decodeKeyEvent(event: String) -> QtGui.QKeyEvent
            this method receives a string and returns the corresponding Key event"""
            type = None
            if event[0] == "keyPress":
                type = QtCore.QEvent.KeyPress
            elif event[0] == "keyRelease":
                type = QtCore.QEvent.KeyRelease

            key = int(event[1])

            m = QtCore.Qt.NoModifier
            if event[2] == "shift":
                m = QtCore.Qt.ShiftModifier
            elif event[2] == "ctrl":
                m = QtCore.Qt.ControlModifier
            elif event[2] == "alt":
                m = QtCore.Qt.AltModifier
#            print " Client process key event: %s " % str( event )

            return QtGui.QKeyEvent(type, key, QtCore.Qt.KeyboardModifiers(m))

        app = QtCore.QCoreApplication.instance()
        newTab = self.updateCurrentTab()
        widget = self.currentTab.getCellWidget(0,
                                               0) if self.currentTab else None

        #        print " ------------- QiVisClient.processEvent: %s  ---------------------" % ( str(terms) )
        sys.stdout.flush()

        if terms[2] == "interactionState":
            if self.current_pipeline:
                state = terms[3] if (len(terms) > 3) else None
                altMode = terms[4] if (len(terms) > 4) else None
                print " ~~~~~ Setting Client Interaction State: ", str(
                    state), str(altMode)
                sys.stdout.flush()
                for module in self.current_pipeline.module_list:
                    persistentModule = ModuleStore.getModule(module.id)
                    if persistentModule:
                        cf = persistentModule.updateInteractionState(
                            state, altMode)
                        if cf: self.current_config_function = cf
                    else:
                        print "Can't find client persistentModule: ", module.id
        else:
            newEvent = None
            if terms[2] == "singleClick":
                cellModules = self.getCellModules()
                cpos = [float(terms[i]) for i in range(7, 10)]
                cfol = [float(terms[i]) for i in range(10, 13)]
                cup = [float(terms[i]) for i in range(13, 16)]
                #            print " >>> QiVisClient.cellModules: %s, modules: %s" % ( str( [ cellMod.id for cellMod in cellModules ] ), str( ModuleStore.getModuleIDs() ) )
                for cellMod in cellModules:
                    persistentCellModule = ModuleStore.getModule(cellMod.id)
                    if persistentCellModule:
                        persistentCellModule.syncCamera(cpos, cfol, cup)
            if terms[2] in ["singleClick", "mouseMove", "mouseRelease"]:
                if self.currentTab:
                    screenRect = self.currentTab.getCellRect(0, 0)
                    screenDims = (screenRect.width(), screenRect.height())
                    newEvent = decodeMouseEvent(terms[2:], screenDims)
            elif terms[2] in ["keyPress", "keyRelease"]:
                newEvent = decodeKeyEvent(terms[2:])

            if widget and newEvent:
                cellWidget = widget.widget()
                app.postEvent(cellWidget, newEvent)
                cellWidget.setFocus()
                cellWidget.update()

    def executeNextPipeline(self):
        if len(self.pipelineQueue) == 0:
            return
        pipeline = self.pipelineQueue[-1]
        self.pipelineQueue.pop()
        self.executePipeline(pipeline)
        self.emit(QtCore.SIGNAL("executeNextPipeline()"))

    def getCellModules(self):
        cellModules = []
        if self.current_pipeline:
            for module in self.current_pipeline.module_list:
                if (module.name == "MapCell3D"): cellModules.append(module)
        return cellModules

    def getCurrentPipeline(self):
        return self.current_pipeline

    def setCellLocation(self):
        cellModule = None
        if self.current_pipeline:
            print " Executing Client Workflow, modules: "
            for module in self.current_pipeline.module_list:
                print str(module)

    #            if : cellModule = module

    def executePipeline(self, pipeline):
        from core.db.io import unserialize
        from core.vistrail.pipeline import Pipeline
        from core.interpreter.default import get_default_interpreter as getDefaultInterpreter
        from core.utils import DummyView
        import api

        tabController = self.spreadsheetWindow.get_current_tab_controller()
        pip = unserialize(str(pipeline), Pipeline)
        #        print " **** Client-%s ---Received Pipeline--- modules:" % str( self.dimensions )
        #        for module in pip.module_list:
        #            print "     ", str(module.id)
        self.current_pipeline = pip
        interpreter = getDefaultInterpreter()
        kwargs = {
            "locator": None,
            "current_version": None,
            "view": DummyView(),
            "aliases": {}
        }
        interpreter.execute(pip, **kwargs)
        print "Finished Executing Pipeline"

    def processMessage(self, message, socket):
        (sender, tokens) = message
        #        print " ********* CLIENT--> processMessage: %s ********* " % str( tokens )
        tokens = tokens.split(MessageTokenSep)
        if (len(tokens) < 4) or (tokens[3] <> 'mouseMove'):
            print " ********* CLIENT--> splitMessage: %s ********* " % str(
                tokens)
        if len(tokens) == 0: return

        if tokens[0] == "exit":
            print "Received shutdown message"
            sys.stdout.flush()
            socket.close()
            gui.application.get_vistrails_application().quit()
            gui.application.stop_application()
            sys.exit(0)

        if tokens[0] == "pipeline":
            #            print " $$$$$$$$$$$ Client-- pipeline message: %s " % str(tokens)
            ### we must execute a pipeline
            #            return ("", "", "")
            if len(tokens[2:]) != 0:
                for t in tokens[2:]:
                    tokens[1] += t + "@"
                tokens[1] = tokens[1][:-1]

            self.executePipeline(tokens[1])
        elif tokens[0] == "interaction":
            self.processEvent(tokens[1:])

        elif tokens[0] == "command":
            self.processCommand(tokens[3:])

        elif tokens[0] == "refresh":
            self.updateCurrentTab()
            if self.currentTab:
                widget = self.currentTab.getCell(int(tokens[1]),
                                                 int(tokens[2]))
#                if widget:
#                    widget.swapBuffers()
        return ("", "", "")
Esempio n. 5
0
class GopherReply(QNetworkReply):
    def __init__(self, url):

        QNetworkReply.__init__(self)
        self.gopher = QTcpSocket()
        self.gopher.bytesWritten.connect(self.writeGopherData)
        self.gopher.readyRead.connect(self.readGopherData)
        self.gopher.connected.connect(self.getResource)
        self.gopher.disconnected.connect(self.setContent)

        self.input = ""
        self.output = ""

        self.content = ""
        self.offset = 0

        self.setUrl(url)
        self.gopher.connectToHost(url.host(), 70)

    def getResource(self):

        path = self.url().path()
        if path.isEmpty() or path == u"/":
            self.output = "\r\n"
        else:
            self.output = str(path) + "\r\n"

        self.writeGopherData()

    def readGopherData(self):

        self.input += str(self.gopher.readAll())

    def writeGopherData(self, written=0):

        self.output = self.output[written:]
        if self.output:
            self.gopher.write(self.output)

    def html(self, text):

        return (text).replace(u"&", u"&amp;").replace(u"<", u"&lt;").replace(
            u">", u"&gt;")

    def setContent(self):

        if self.url().hasQueryItem(u"type"):
            self.setContentData()
        else:
            self.setContentList()

    def setContentData(self):

        self.open(self.ReadOnly | self.Unbuffered)
        if self.url().queryItemValue(u"type") == u"text":
            self.setHeader(QNetworkRequest.ContentTypeHeader,
                           QVariant("text/plain"))

        self.content = self.input
        self.setHeader(QNetworkRequest.ContentLengthHeader,
                       QVariant(len(self.content)))
        self.readyRead.emit()
        self.finished.emit()

    def setContentList(self):

        url = QUrl(self.url())
        if not url.path().endsWith(u"/"):
            url.setPath(url.path() + u"/")

        base_url = self.url().toString()
        base_path = (url.path())

        self.open(self.ReadOnly | self.Unbuffered)
        content = (u"<html>\n"
                   u"<head>\n"
                   u"  <title>" + self.html(base_url) + u"</title>\n"
                   u'  <style type="text/css">\n'
                   u"  th { background-color: #aaaaaa;\n"
                   u"       color: black }\n"
                   u"  table { border: solid 1px #aaaaaa }\n"
                   u"  tr.odd { background-color: #dddddd;\n"
                   u"           color: black\n }\n"
                   u"  tr.even { background-color: white;\n"
                   u"           color: black\n }\n"
                   u"  </style>\n"
                   u"</head>\n\n"
                   u"<body>\n"
                   u"<h1>Listing for " + base_path + u"</h1>\n\n")

        lines = self.input.splitlines()

        for line in lines:

            pieces = line.split("\t")
            if pieces == ["."]:
                break
            try:
                type, path, host, port = pieces[:4]
            except ValueError:
                # This isn't a listing. Let's try returning data instead.
                self.setContentData()
                return

            if type[0] == "i":
                content += u"<p>" + self.html(type[1:]) + u"</p>"
            elif type[0] == "h" and path.startswith(u"URL:"):
                content += u"<p><a href=\"" + path[4:] + u"\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "0":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=text\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "1":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "4":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=binhex\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "5":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=dos\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "6":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=uuencoded\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "9":
                content += u"<p><a href=\"gopher://" + host + u":" + port + path + u"?type=binary\">" + self.html(
                    type[1:]) + u"</a></p>"
            elif type[0] == "g":
                content += u"<img src=\"gopher://" + host + u":" + port + path + u"?type=binary\">" + self.html(
                    type[1:]) + u"</img>"
            elif type[0] == "I":
                content += u"<img src=\"gopher://" + host + u":" + port + path + u"?type=binary\">" + self.html(
                    type[1:]) + u"</img>"

        content += (u"</body>\n" u"</html>\n")

        self.content = content.encode("utf-8")

        self.setHeader(QNetworkRequest.ContentTypeHeader,
                       QVariant("text/html; charset=UTF-8"))
        self.setHeader(QNetworkRequest.ContentLengthHeader,
                       QVariant(len(self.content)))
        self.readyRead.emit()
        self.finished.emit()

    # QIODevice methods

    def abort(self):
        pass

    def bytesAvailable(self):
        return len(self.content) - self.offset

    def isSequential(self):
        return True

    def readData(self, maxSize):

        if self.offset < len(self.content):
            end = min(self.offset + maxSize, len(self.content))
            data = self.content[self.offset:end]
            self.offset = end
            return data