Esempio n. 1
0
class TcpDevice(DataDevice):
    '''
    classdocs
    '''

    def __init__(self, params={}, parent=None):
        '''
        Constructor
        '''
        super(TcpDevice, self).__init__(params, parent)

        self.iodevice = QTcpSocket()
        self.reconnect = int(params.get('Reconnect', 1000))
        self.host = params.get('Host', None)
        self.port = int(params.get('Port', 2000))
        self.gpsdInit = bool(params.get('GpsdInit', False))
        self.iodevice.readyRead.connect(self.readyRead)
        self.iodevice.error.connect(self.socketError)
        self.iodevice.connected.connect(self.socketConnected)
        self.iodevice.disconnected.connect(self.socketDisconnected)

    @pyqtSlot(QAbstractSocket.SocketError)
    def socketError(self, error):
        if self.iodevice.state() != QAbstractSocket.BoundState:
            if self.reconnect > 0:
                QTimer.singleShot(self.reconnect, self.onReconnectTimer)

    def connectDevice(self):
        self.iodevice.connectToHost(self.host, self.port)

    def disconnectDevice(self):
        if self.iodevice.state() is QAbstractSocket.ConnectedState:
            self.iodevice.disconnectFromHost()

    def readData(self):
        size = self.iodevice.bytesAvailable()
        data = self.iodevice.read(size)
        return data

    def readLine(self):
        if self.iodevice.canReadLine():
            return str(self.iodevice.readLine())
        return ''

    @pyqtSlot()
    def socketConnected(self):
        self.deviceConnected.emit(True)
        if self.gpsdInit:
            self.iodevice.writeData('?WATCH={"class":"WATCH","nmea":true}')

    @pyqtSlot()
    def socketDisconnected(self):
        self.deviceDisconnected.emit(True)
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 SocketTcpClient(AbstractSocket):
    """Socket que envia e recebe dados via TcpSocket"""
    def __init__(self, portaResponder, parent=None):
        super().__init__(None, portaResponder, parent)

        self._socketClient = QTcpSocket(self)

        self._socketClient.readyRead.connect(self._lerDados)

    def _lerDados(self):
        if self._socketClient.bytesAvailable():
            host = self.ipServidor()
            data = self._socketClient.readData()

            self.dadosRecebidos.emit(host, data)
            
    def enviarDados(self, byteArray):
        self._socketClient.write(byteArray)
            
    def setPara(self, para):
        if self.getPara() != para: 
            super().setPara(para)
            self._conectarServidor(para)

    def _conectarServidor(self, ip):
        if self._socketClient.state() in (QAbstractSocket.ConnectedState, QAbstractSocket.ConnectingState):
            self._desconectarServidor()

        self._socketClient.connectToHost(QHostAddress(ip), self.getPortaResponder())

    def _desconectarServidor(self):
        if self._socketClient.state() == QAbstractSocket.UnconnectedState:
            return True
        
        self._socketClient.disconnectFromHost()
        return self._socketClient.waitForConnected(50)

    def ipServidor(self):
        return self._socketClient.peerAddress()

    def meuIP(self):
        return self._socketClient.localAddress()
Esempio n. 4
0
class TCPConnection(Connection):
    def __init__(self):
        Connection.__init__(self)

        # read all data in buffer before exiting self.read_data
        self.break_on_packet_found = False

    def begin(self, instrument):
        self.log = logging.getLogger('GDAIS.' + instrument.short_name +
                                     '.TCPConnection')
        self.instrument = instrument

        self.io_conn = QTcpSocket()
        self.io_conn.connected.connect(self.connected)
        self.io_conn.error.connect(self.connection_error)
        self.io_conn.connectToHost(instrument.connection.tcp_host,
                                   instrument.connection.tcp_port)

    def connected(self):
        self.io_conn.readyRead.connect(self.read_data)
        Connection.begin(self, self.instrument)

    def connection_error(self, socket_error):
        if socket_error == QTcpSocket.RemoteHostClosedError:
            self.log.info(self.io_conn.errorString())
        else:
            self.log.error(self.io_conn.errorString())
            self.error_occurred.emit()

    def quit(self):
        if self.io_conn and self.io_conn.state() == QTcpSocket.ConnectedState:
            loop = QEventLoop()
            self.io_conn.disconnected.connect(loop.quit)
            self.io_conn.disconnectFromHost()
            self.log.debug("Entered disconnect state...")
            if self.io_conn.state() == QTcpSocket.ConnectedState:
                loop.exec_()
            self.log.info("Done")
        Connection.quit(self)
Esempio n. 5
0
File: pod.py Progetto: phch/one-loop
class TcpClient(QObject):
    packet = pyqtSignal(str)
    connected = pyqtSignal()
    disconnected = pyqtSignal()

    def __init__(self, host):
        super().__init__()
        self._sock = QTcpSocket()
        self._pending = None
        self._host = host
        self._log = logging.getLogger("tcp")
        self._sock.connected.connect(self.greet)
        self._sock.connected.connect(self.connected.emit)
        self._sock.disconnected.connect(self.disconnected.emit)
        self._sock.readyRead.connect(self.recv)

    def set_host(self, host):
        self._sock.disconnectFromHost()
        self._host = host

    def _cancel_pending(self):
        self._pending.stop()
        self._pending = None
        self._sock.connected.disconnect(self._connection_success)

    @pyqtSlot()
    def _connection_success(self):
        self._cancel_pending()
        self._log.debug("connection successful")

    @pyqtSlot()
    def _connection_failure(self):
        self._cancel_pending()
        self._log.debug("connection failed")

    def try_connect(self, port):
        if self._pending:
            self._cancel_pending()
        self._sock.disconnectFromHost()
        if self._sock.state() != QAbstractSocket.UnconnectedState:
            self._sock.waitForDisconnected()
        msg = "connecting to ({}:{})"
        msg = msg.format(self._host.toString(), port)
        self._log.debug(msg)
        self._pending = QTimer()
        self._pending.timeout.connect(self._connection_failure)
        self._pending.setSingleShot(True)
        self._sock.connected.connect(self._connection_success)
        self._pending.start(10000)
        self._sock.connectToHost(self._host, port)

    def greet(self):
        self.send(query_tag("port", "udp"), "")

    def recv(self):
        while self._sock.canReadLine():
            data = bytes(self._sock.readLine())  # handle QByteArray
            message = data.decode()
            self.packet.emit(message)

    def send(self, tag, payload):
        message = tag + ":" + payload + "\n"
        data = message.encode()
        self._sock.write(data)
Esempio n. 6
0
class ClientDialog(QtGui.QDialog):

    STATUS = ["Not Connected",
              "Host Lookup",
              "Establishing connection",
              "Connected",
              "The socket is bound to an address and port",
              "For internal use only",
              "Socket is about to close"]
    
    def __init__(self, configdir, recentconndb):
        QtGui.QDialog.__init__(self)
        
        # Variables
        self.configdir = configdir
        self.recentconndb = recentconndb
        
        self.socket = QTcpSocket()
        self.status = self.STATUS[0]
        
        logging.info("Starting Client")

        # Properties        
        self.setModal(True)
        
        # Setup Widget
        self.layout = QtGui.QVBoxLayout()
        self.mainWidget = ControllerClientWidget()
        self.layout.addWidget(self.mainWidget)
        self.setLayout(self.layout)
          
        #Connections
        self.connect(self.socket, QtCore.SIGNAL('error(QAbstractSocket::SocketError)'), self.displayError)
        self.connect(self.socket, QtCore.SIGNAL('connected()'), self.connected)
        self.connect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'), self.connectToServer) 
        self.connect(self.mainWidget.hostEdit,  QtCore.SIGNAL('textChanged(QString)'), self.enableConnectButton)
        self.connect(self.mainWidget.portEdit,  QtCore.SIGNAL('textChanged(QString)'), self.enableConnectButton)
        self.connect(self.mainWidget.passEdit,  QtCore.SIGNAL('textChanged(QString)'), self.enableConnectButton)
        self.connect(self.mainWidget.recentConnList, QtCore.SIGNAL('doubleClicked(const QModelIndex &)'), self.recentListHandler)

        self.loadRecentConnDB()
        self.enableConnectButton()
        self.hide()
        
        # Translations
        self.current_language = "en_US"
        self.uiTranslator = QtCore.QTranslator()
        self.uiTranslator.load(":/languages/tr_en_US.qm")
        self.retranslate()
        self.updateStatus()
        
    ###
    ### Translation Related
    ###
    def retranslate(self, language=None):
        if language is not None:
            self.current_language = language
            
        self.uiTranslator.load(":/languages/tr_%s.qm" % self.current_language)
        
        self.setWindowTitle(self.uiTranslator.translate("ControllerClientApp", "Controller Client"))
        #
        # Reusable Strings
        #
        self.clientStatusString = self.uiTranslator.translate("ControllerClientApp", "Status")
        self.connectString = self.uiTranslator.translate("ControllerClientApp", "Connect")
        self.disconnectString = self.uiTranslator.translate("ControllerClientApp", "Disconnect")
        # --- End Reusable Strings
        
        #
        # Connection Settings
        #
        self.mainWidget.toolBox.setItemText(0, self.uiTranslator.translate("ControllerClientApp", "Connection Settings"))
        self.mainWidget.hostLabel.setText(self.uiTranslator.translate("ControllerClientApp", "Host name (or IP Address)"))
        self.mainWidget.portLabel.setText(self.uiTranslator.translate("ControllerClientApp", "Port"))
        self.mainWidget.passLabel.setText(self.uiTranslator.translate("ControllerClientApp", "Passphrase"))
        if self.status == self.STATUS[3]:
            self.mainWidget.connectButton.setText(self.uiTranslator.translate("ControllerClientApp", self.disconnectString))
        else:
            self.mainWidget.connectButton.setText(self.uiTranslator.translate("ControllerClientApp", self.connectString))
        self.updateStatus()
        # --- End Connection Settings
        
        #
        # Recent Connections
        #
        self.mainWidget.toolBox.setItemText(1, self.uiTranslator.translate("ControllerClientApp", "Recent Connections"))
        # --- End Recent Connections
        
    ##
    ## UI Related
    ##
    
    def enableConnectButton(self):
        if self.mainWidget.passEdit.text() == '' or self.mainWidget.hostEdit.text() == '' or self.mainWidget.portEdit.text() == '':
            self.mainWidget.connectButton.setEnabled(False)
        else:
            self.mainWidget.connectButton.setEnabled(True)
    
    def connected(self):
        caddr = self.socket.peerName()
        cport = self.socket.peerPort()
        logging.info("Connected to %s:%s" % (caddr, cport))
        
        self.sendPassphrase()
        self.mainWidget.connectButton.setText(self.disconnectString)
        self.disconnect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'), self.connectToServer) 
        self.disconnect(self.mainWidget.passEdit,  QtCore.SIGNAL('textChanged(QString)'), self.enableConnectButton)
        self.connect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'), self.disconnectFromHost)
        self.connect(self.socket, QtCore.SIGNAL("disconnected()"), self.disconnectedFromHost)
        
    '''
    This function is for updating the sockets status and the statusLabel. It's called when a stateChanged signal is triggered.
    '''
    def updateStatus(self):
        state = self.socket.state()
        self.status = self.STATUS[state]
        self.mainWidget.statusLabel.setText(self.clientStatusString + ": " + self.status)
        
    '''
    When there is a socket error this function is called to show the error in a QMessageBox
    '''    
    def displayError(self, socketError):
        messageBox = QtGui.QMessageBox.critical(self, QtCore.QString('Error!'), 
                                                   QtCore.QString(self.socket.errorString()))
        logging.error("Socket error %s" % self.socket.errorString())

    ##
    ## Connection Related
    ##
        
    '''
    Function that is called when connect button is pressed.
    '''
    def connectToServer(self):
        caddr = self.mainWidget.hostEdit.text()
        cport = int(self.mainWidget.portEdit.text())
        cpass = self.mainWidget.passEdit.text()
        
        self.connect(self.socket, QtCore.SIGNAL('stateChanged(QAbstractSocket::SocketState)'), self.updateStatus)

        logging.info("Connecting to %s:%s" % (caddr, cport))
        self.socket.connectToHost(caddr, cport)
        
        if not self.socket.waitForConnected(1000):
            logging.error("Socket error %s", self.socket.errorString())
        else:
            # Add to recent connections if connection is successful
            self.addToRecentConnections(caddr, cport, cpass)
    
    def disconnectFromHost(self):
        self.socket.disconnectFromHost()
        
    '''
    Function for disconnecting the client from the host.
    '''
    def disconnectedFromHost(self):
        logging.info("Disconnected from host")
        self.disconnect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'), self.disconnectFromHost)
        self.connect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'), self.connectToServer)
        self.connect(self.mainWidget.passEdit,  QtCore.SIGNAL('textChanged(QString)'), self.enableConnectButton)
        self.mainWidget.connectButton.setText(self.connectString)
      
    '''
    Function for sending message to the connected server
    '''  
    def sendMessage(self, message):
        logging.info("Sending message: %s", message)
        block = QtCore.QByteArray()
        block.append(message)
        self.socket.write(block)
        
    '''
    This function is for sending the passphrase to the server. It uses the sendMessage function
    '''
    def sendPassphrase(self):
        self.sendMessage(self.mainWidget.passEdit.text())
    
    '''
    This function is for reading message from the server
    '''
    def readMessage(self):
        message = self.socket.read(self.socket.bytesAvailable()) 
        logging("Server said:%s", message)  
        return message

    ##
    ## Recent Connections Related
    ##
    
    def loadRecentConnDB(self):
        model = self.recentconndb.get_recentconn_model()
        self.mainWidget.recentConnList.setModel(model)
        self.mainWidget.recentConnList.setColumnHidden(2, True) # Hide the passphrase column
                
    '''
    This function is for adding a new connection to the recent connections. It checks whether it exists in the database or not.
    '''   
    def addToRecentConnections(self, caddr, cport, cpass):
        self.recentconndb.insert_recentconn(caddr, cport, cpass)
        self.loadRecentConnDB()
        
    '''
    Handler for the recent connections list. When you click on a recent connection the details of the connection are loaded 
    '''
    def recentListHandler(self, connection):
        chost = connection.sibling(connection.row(), 0).data().toString()
        cport = int(connection.sibling(connection.row(), 1).data().toString())
        cpass = connection.sibling(connection.row(), 2).data().toString()
        self.mainWidget.hostEdit.setText(chost)
        self.mainWidget.portEdit.setValue(cport)
        self.mainWidget.passEdit.setText(cpass)
        self.mainWidget.toolBox.setCurrentWidget(self.mainWidget.connWidget)
Esempio n. 7
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. 8
0
class TcpClient(QObject):
    packet = pyqtSignal(str)
    connected = pyqtSignal()
    disconnected = pyqtSignal()

    def __init__(self, host):
        super().__init__()
        self._sock = QTcpSocket()
        self._pending = None
        self._host = host
        self._log = logging.getLogger('tcp')
        self._sock.connected.connect(self.greet)
        self._sock.connected.connect(self.connected.emit)
        self._sock.disconnected.connect(self.disconnected.emit)
        self._sock.readyRead.connect(self.recv)

    def set_host(self, host):
        self._sock.disconnectFromHost()
        self._host = host

    def _cancel_pending(self):
        self._pending.stop()
        self._pending = None
        self._sock.connected.disconnect(self._connection_success)

    @pyqtSlot()
    def _connection_success(self):
        self._cancel_pending()
        self._log.debug('connection successful')

    @pyqtSlot()
    def _connection_failure(self):
        self._cancel_pending()
        self._log.debug('connection failed')

    def try_connect(self, port):
        if self._pending:
            self._cancel_pending()
        self._sock.disconnectFromHost()
        if self._sock.state() != QAbstractSocket.UnconnectedState:
            self._sock.waitForDisconnected()
        msg = 'connecting to ({}:{})'
        msg = msg.format(self._host.toString(), port)
        self._log.debug(msg)
        self._pending = QTimer()
        self._pending.timeout.connect(self._connection_failure)
        self._pending.setSingleShot(True)
        self._sock.connected.connect(self._connection_success)
        self._pending.start(10000)
        self._sock.connectToHost(self._host, port)

    def greet(self):
        self.send(query_tag('port', 'udp'), '')

    def recv(self):
        while self._sock.canReadLine():
            data = bytes(self._sock.readLine())  # handle QByteArray
            message = data.decode()
            self.packet.emit(message)

    def send(self, tag, payload):
        message = tag + ':' + payload + '\n'
        data = message.encode()
        self._sock.write(data)
Esempio n. 9
0
class display_driver(PtDriver.PtDriver):
    def __init__(self,name=None):
        PtDriver.PtDriver.__init__(self,name=name)


    def open(self,options):
        self.options = options
        self.tcpSocket = QTcpSocket()
        # try to connect to the server
        self.tcpSocket.connectToHost(QHostAddress("0.0.0.0"), 5006)
        self.tcpSocket.waitForConnected(2000)

        if self.tcpSocket.state() != 3:
            self._launchWindow()
            #thread.start_new_thread(self._launchWindow,(xres,yres))
            QObject.connect(self.tcpSocket, SIGNAL("connected()"), self.tcpSocketConnected)

            #print "connecting now"
            while self.tcpSocket.state() != 3:
                self.tcpSocket.connectToHost(QHostAddress("0.0.0.0"), 5006)
                self.tcpSocket.waitForConnected(5000)


    def tcpSocketConnected(self):
        #txt = "Successfully connected to Server!!!"
        self.xres = self.options.xres.value
        self.yres = self.options.yres.value
        # send resolution
        txt = struct.pack("6sII","imgnfo",self.xres,self.yres)
        self.tcpSocket.write(QByteArray(txt))
        self.tcpSocket.waitForBytesWritten()
        

    def prepareBucket(self,bucket):
        bu = struct.pack("6sIIII","bucket",
                                    bucket.pos.x,
                                    bucket.pos.y,
                                    bucket.width,
                                    bucket.height)

        for i,p in enumerate(bucket.pixels):


            if i < bucket.width or \
            i > ((bucket.height * bucket.width) - bucket.width) or \
            (i % bucket.width) == 0 or\
            (((i+1) % bucket.width) + bucket.width) == bucket.width:
                bu += struct.pack("3I",255,255,0)
            else:
                bu += struct.pack("3I",0,0,0)

        self.tcpSocket.write(QByteArray(bu))
        self.tcpSocket.waitForBytesWritten()
    
    def writeBucket(self,bucket):
        bu = struct.pack("6sIIII","bucket",
                                    bucket.pos.x,
                                    bucket.pos.y,
                                    bucket.width,
                                    bucket.height)
        #print "wrote ",len(bucket.pixels)
        #print "x ",bucket.width," y ",bucket.height, " len ",len(bucket.pixels)
        #j = 0
        for i in bucket.pixels:
            #bu += struct.pack("3I",i.r,i.g,i.b)
            bu += struct.pack("3I",int(i.r),int(i.g),int(i.b))
            #j +=1
        #print "size sent ",j

        self.tcpSocket.write(QByteArray(bu))
        self.tcpSocket.waitForBytesWritten()

    def close(self):
        self.tcpSocket.close()

    def _launchWindow(self):
        file = os.path.dirname(__file__)
        cmd = "python %s"%os.path.join(file,"framebuffer.py")
        subprocess.Popen(cmd.split())
Esempio n. 10
0
class ClientDialog(QtGui.QDialog):

    STATUS = [
        "Not Connected", "Host Lookup", "Establishing connection", "Connected",
        "The socket is bound to an address and port", "For internal use only",
        "Socket is about to close"
    ]

    def __init__(self, configdir, recentconndb):
        QtGui.QDialog.__init__(self)

        # Variables
        self.configdir = configdir
        self.recentconndb = recentconndb

        self.socket = QTcpSocket()
        self.status = self.STATUS[0]

        log.info("Starting Client")

        # Properties
        self.setModal(True)

        # Setup Widget
        self.layout = QtGui.QVBoxLayout()
        self.mainWidget = ControllerClientWidget()
        self.layout.addWidget(self.mainWidget)
        self.setLayout(self.layout)

        #Connections
        self.connect(self.socket,
                     QtCore.SIGNAL('error(QAbstractSocket::SocketError)'),
                     self.displayError)
        self.connect(self.socket, QtCore.SIGNAL('connected()'), self.connected)
        self.connect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'),
                     self.connectToServer)
        self.connect(self.mainWidget.hostEdit,
                     QtCore.SIGNAL('textChanged(QString)'),
                     self.enableConnectButton)
        self.connect(self.mainWidget.portEdit,
                     QtCore.SIGNAL('textChanged(QString)'),
                     self.enableConnectButton)
        self.connect(self.mainWidget.passEdit,
                     QtCore.SIGNAL('textChanged(QString)'),
                     self.enableConnectButton)
        self.connect(self.mainWidget.recentConnList,
                     QtCore.SIGNAL('doubleClicked(const QModelIndex &)'),
                     self.recentListHandler)

        self.loadRecentConnDB()
        self.enableConnectButton()
        self.hide()

        # Translations
        self.app = QtGui.QApplication.instance()
        self.current_language = "en_US"
        self.uiTranslator = QtCore.QTranslator()
        self.uiTranslator.load(":/languages/tr_en_US.qm")
        self.retranslate()
        self.updateStatus()

    ###
    ### Translation Related
    ###
    def retranslate(self, language=None):
        if language is not None:
            self.current_language = language

        self.uiTranslator.load(":/languages/tr_%s.qm" % self.current_language)

        self.setWindowTitle(
            self.app.translate("ControllerClientApp", "Controller Client"))
        #
        # Reusable Strings
        #
        self.clientStatusString = self.app.translate("ControllerClientApp",
                                                     "Status")
        self.connectString = self.app.translate("ControllerClientApp",
                                                "Connect")
        self.disconnectString = self.app.translate("ControllerClientApp",
                                                   "Disconnect")
        # --- End Reusable Strings

        #
        # Connection Settings
        #
        self.mainWidget.toolBox.setItemText(
            0, self.app.translate("ControllerClientApp",
                                  "Connection Settings"))
        self.mainWidget.hostLabel.setText(
            self.app.translate("ControllerClientApp",
                               "Host name (or IP Address)"))
        self.mainWidget.portLabel.setText(
            self.app.translate("ControllerClientApp", "Port"))
        self.mainWidget.passLabel.setText(
            self.app.translate("ControllerClientApp", "Passphrase"))
        if self.status == self.STATUS[3]:
            self.mainWidget.connectButton.setText(
                self.app.translate("ControllerClientApp",
                                   self.disconnectString))
        else:
            self.mainWidget.connectButton.setText(
                self.app.translate("ControllerClientApp", self.connectString))
        self.updateStatus()
        # --- End Connection Settings

        #
        # Recent Connections
        #
        self.mainWidget.toolBox.setItemText(
            1, self.app.translate("ControllerClientApp", "Recent Connections"))
        # --- End Recent Connections

    ##
    ## UI Related
    ##

    def enableConnectButton(self):
        if self.mainWidget.passEdit.text(
        ) == '' or self.mainWidget.hostEdit.text(
        ) == '' or self.mainWidget.portEdit.text() == '':
            self.mainWidget.connectButton.setEnabled(False)
        else:
            self.mainWidget.connectButton.setEnabled(True)

    def connected(self):
        caddr = self.socket.peerName()
        cport = self.socket.peerPort()
        log.info("Connected to %s:%s" % (caddr, cport))

        self.sendPassphrase()
        self.mainWidget.connectButton.setText(self.disconnectString)
        self.disconnect(self.mainWidget.connectButton,
                        QtCore.SIGNAL('pressed()'), self.connectToServer)
        self.disconnect(self.mainWidget.passEdit,
                        QtCore.SIGNAL('textChanged(QString)'),
                        self.enableConnectButton)
        self.connect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'),
                     self.disconnectFromHost)
        self.connect(self.socket, QtCore.SIGNAL("disconnected()"),
                     self.disconnectedFromHost)

    '''
    This function is for updating the sockets status and the statusLabel. It's called when a stateChanged signal is triggered.
    '''

    def updateStatus(self):
        state = self.socket.state()
        self.status = self.STATUS[state]
        self.mainWidget.statusLabel.setText(self.clientStatusString + ": " +
                                            self.status)

    '''
    When there is a socket error this function is called to show the error in a QMessageBox
    '''

    def displayError(self, socketError):
        messageBox = QtGui.QMessageBox.critical(
            self, QtCore.QString('Error!'),
            QtCore.QString(self.socket.errorString()))
        log.error("Socket error %s" % self.socket.errorString())

    ##
    ## Connection Related
    ##
    '''
    Function that is called when connect button is pressed.
    '''

    def connectToServer(self):
        caddr = self.mainWidget.hostEdit.text()
        cport = int(self.mainWidget.portEdit.text())
        cpass = self.mainWidget.passEdit.text()

        self.connect(
            self.socket,
            QtCore.SIGNAL('stateChanged(QAbstractSocket::SocketState)'),
            self.updateStatus)

        log.info("Connecting to %s:%s" % (caddr, cport))
        self.socket.connectToHost(caddr, cport)

        if not self.socket.waitForConnected(1000):
            log.error("Socket error %s", self.socket.errorString())
        else:
            # Add to recent connections if connection is successful
            self.addToRecentConnections(caddr, cport, cpass)

    def disconnectFromHost(self):
        self.socket.disconnectFromHost()

    '''
    Function for disconnecting the client from the host.
    '''

    def disconnectedFromHost(self):
        log.info("Disconnected from host")
        self.disconnect(self.mainWidget.connectButton,
                        QtCore.SIGNAL('pressed()'), self.disconnectFromHost)
        self.connect(self.mainWidget.connectButton, QtCore.SIGNAL('pressed()'),
                     self.connectToServer)
        self.connect(self.mainWidget.passEdit,
                     QtCore.SIGNAL('textChanged(QString)'),
                     self.enableConnectButton)
        self.mainWidget.connectButton.setText(self.connectString)

    '''
    Function for sending message to the connected server
    '''

    def sendMessage(self, message):
        log.info("Sending message: %s", message)
        block = QtCore.QByteArray()
        block.append(message)
        self.socket.write(block)

    '''
    This function is for sending the passphrase to the server. It uses the sendMessage function
    '''

    def sendPassphrase(self):
        self.sendMessage(self.mainWidget.passEdit.text())

    '''
    This function is for reading message from the server
    '''

    def readMessage(self):
        message = self.socket.read(self.socket.bytesAvailable())
        log.info("Server said: %s", message)
        return message

    ##
    ## Recent Connections Related
    ##

    def loadRecentConnDB(self):
        model = self.recentconndb.get_recentconn_model()
        self.mainWidget.recentConnList.setModel(model)
        self.mainWidget.recentConnList.setColumnHidden(
            2, True)  # Hide the passphrase column

    '''
    This function is for adding a new connection to the recent connections. It checks whether it exists in the database or not.
    '''

    def addToRecentConnections(self, caddr, cport, cpass):
        self.recentconndb.insert_recentconn(caddr, cport, cpass)
        self.loadRecentConnDB()

    '''
    Handler for the recent connections list. When you click on a recent connection the details of the connection are loaded
    '''

    def recentListHandler(self, connection):
        chost = connection.sibling(connection.row(), 0).data().toString()
        cport = int(connection.sibling(connection.row(), 1).data().toString())
        cpass = connection.sibling(connection.row(), 2).data().toString()
        self.mainWidget.hostEdit.setText(chost)
        self.mainWidget.portEdit.setValue(cport)
        self.mainWidget.passEdit.setText(cpass)
        self.mainWidget.toolBox.setCurrentWidget(self.mainWidget.connWidget)
Esempio n. 11
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 ("", "", "")