Ejemplo n.º 1
0
def main():
    global win
    signal.signal(signal.SIGINT, exit)
    args = parse_arguments()
    appKey = "scudcloud.pid"
    socket = QLocalSocket()
    socket.connectToServer(appKey)
    if socket.isOpen():
        socket.close()
        socket.deleteLater()
        return 0
    socket.deleteLater()
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName(Resources.APP_NAME+' Slack_SSB')
    app.setWindowIcon(QtGui.QIcon(Resources.get_path('scudcloud.png')))

    try:
        settings_path = load_settings(args.confdir)
    except:
        print("Configuration directory " + args.confdir +\
              " could not be created! Exiting...")
        raise SystemExit()
    minimized = True if args.minimized is True else None
    urgent_hint = True if args.urgent_hint is True else None

    win = sca.ScudCloud(debug=args.debug, minimized=minimized, urgent_hint=urgent_hint, settings_path=settings_path)
    app.commitDataRequest.connect(win.setForceClose, type=QtCore.Qt.DirectConnection)

    server = QLocalServer()
    server.newConnection.connect(restore)
    server.listen(appKey)
    win.restore()
    if win.minimized is None:
        win.show()
    sys.exit(app.exec_())
Ejemplo n.º 2
0
def init():
    """Start listening to incoming connections."""
    global _server
    if _server is not None:
        return

    server = QLocalServer(None)

    # find a free socket name to use
    for name in ids():
        if server.listen(name):
            break
    else:
        # all names failed, try to contact and remove stale file if that fails
        socket = QLocalSocket()
        for name in ids():
            socket.connectToServer(name)
            if not socket.waitForConnected(10000):
                QLocalServer.removeServer(name)
                if server.listen(name):
                    break
            else:
                socket.disconnectFromServer()
        else:
            # no ids left, don't listen
            return
    app.aboutToQuit.connect(server.close)
    server.newConnection.connect(slot_new_connection)
    os.environ["FRESCOBALDI_SOCKET"] = name
    _server = server
Ejemplo n.º 3
0
def main():
    global win
    signal.signal(signal.SIGINT, exit)
    args = parse_arguments()
    appKey = "scudcloud.pid"
    socket = QLocalSocket()
    socket.connectToServer(appKey)
    if socket.isOpen():
        socket.close()
        socket.deleteLater()
        return 0
    socket.deleteLater()
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName(Resources.APP_NAME)
    app.setWindowIcon(QtGui.QIcon(Resources.get_path('scudcloud.png')))

    try:
        settings_path = load_settings(args.confdir)
    except:
        print("Configuration directory " + args.confdir +\
              " could not be created! Exiting...")
        raise SystemExit()
    minimized = True if args.minimized is True else None

    win = sca.ScudCloud(debug=args.debug, minimized=minimized, settings_path=settings_path)
    app.commitDataRequest.connect(win.setForceClose, type=QtCore.Qt.DirectConnection)

    server = QLocalServer()
    server.newConnection.connect(restore)
    server.listen(appKey)
    win.restore()
    if win.minimized is None:
        win.show()
    sys.exit(app.exec_())
Ejemplo n.º 4
0
def init():
    """Start listening to incoming connections."""
    global _server
    if _server is not None:
        return
    
    server = QLocalServer(None)
    
    # find a free socket name to use
    for name in ids():
        if server.listen(name):
            break
    else:
        # all names failed, try to contact and remove stale file if that fails
        socket = QLocalSocket()
        for name in ids():
            socket.connectToServer(name)
            if not socket.waitForConnected(10000):
                QLocalServer.removeServer(name)
                if server.listen(name):
                    break
            else:
                socket.disconnectFromServer()
        else:
            # no ids left, dont listen
            return
    app.aboutToQuit.connect(server.close)
    server.newConnection.connect(slot_new_connection)
    os.environ["FRESCOBALDI_SOCKET"] = ensure_bytes(name)
    _server = server
Ejemplo n.º 5
0
def is_running():
    local_socket = QLocalSocket()
    local_socket.connectToServer("ninja_ide")
    if local_socket.state():
        result = (True, local_socket)
    else:
        result = (False, local_socket)
    return result
Ejemplo n.º 6
0
def is_running():
    local_socket = QLocalSocket()
    local_socket.connectToServer("ninja_ide")
    if local_socket.state():
        result = (True, local_socket)
    else:
        result = (False, local_socket)
    return result
Ejemplo n.º 7
0
def get():
    """Return a remote Frescobaldi, or None if not available."""
    socket = QLocalSocket()
    name = os.environ.get("FRESCOBALDI_SOCKET")
    for name in (name, ) if name else ids():
        socket.connectToServer(name)
        if socket.waitForConnected(5000):
            from . import api
            return api.Remote(socket)
Ejemplo n.º 8
0
def get():
    """Return a remote Frescobaldi, or None if not available."""
    socket = QLocalSocket()
    name = os.environ.get("FRESCOBALDI_SOCKET")
    for name in (name,) if name else ids():
        socket.connectToServer(name)
        if socket.waitForConnected(5000):
            from . import api
            return api.Remote(socket)
Ejemplo n.º 9
0
    def __isServerRun(self, servername):  # 判断是否有一个同名的服务器在运行
        #  用一个localsocket去连一下,
        #  如果能连上就说明 有一个在运行了
        ls = QLocalSocket()

        ls.connectToServer(servername)
        if (ls.waitForConnected(1000)):
            ls.disconnectFromServer()  # // 说明已经在运行了
            ls.close()
            return  True
        return False
Ejemplo n.º 10
0
 def send_message(self, message):
     if not self.is_running:
         raise Exception("Client cannot connect to IPC server. Not running.")
     socket = QLocalSocket(self)
     socket.connectToServer(self.socket_filename, QIODevice.WriteOnly)
     if not socket.waitForConnected(self.timeout):
         raise Exception(str(socket.errorString()))
     socket.write(pickle.dumps(message))
     if not socket.waitForBytesWritten(self.timeout):
         raise Exception(str(socket.errorString()))
     socket.disconnectFromServer()
Ejemplo n.º 11
0
    def __isServerRun(self, servername):  # 判断是否有一个同名的服务器在运行
        #  用一个localsocket去连一下,
        #  如果能连上就说明 有一个在运行了
        ls = QLocalSocket()

        ls.connectToServer(servername)
        if (ls.waitForConnected(1000)):
            ls.disconnectFromServer()  # // 说明已经在运行了
            ls.close()
            return True
        return False
Ejemplo n.º 12
0
 def send_message(self, message):
     if not self.is_running:
         raise Exception(
             "Client cannot connect to IPC server. Not running.")
     socket = QLocalSocket(self)
     socket.connectToServer(self.socket_filename, QIODevice.WriteOnly)
     if not socket.waitForConnected(self.timeout):
         raise Exception(str(socket.errorString()))
     socket.write(pickle.dumps(message))
     if not socket.waitForBytesWritten(self.timeout):
         raise Exception(str(socket.errorString()))
     socket.disconnectFromServer()
Ejemplo n.º 13
0
    def sendMessage(self, message):
        assert (self._isRunning)

        if self.isRunning():
            socket = QLocalSocket(self)
            socket.connectToServer(self._key, QIODevice.WriteOnly)
            if not socket.waitForConnected(self._timeout):
                return False
            socket.write(message.encode('utf-8'))
            if not socket.waitForBytesWritten(self._timeout):
                return False
            socket.disconnectFromServer()
            return True
        return False
Ejemplo n.º 14
0
    def sendMessage(self, message):
        assert(self._isRunning)

        if self.isRunning():
            socket = QLocalSocket(self)
            socket.connectToServer(self._key, QIODevice.WriteOnly)
            if not socket.waitForConnected(self._timeout):
                return False
            socket.write(message.encode('utf-8'))
            if not socket.waitForBytesWritten(self._timeout):
                return False
            socket.disconnectFromServer()
            return True
        return False
Ejemplo n.º 15
0
def testSingleInstanceOrExit():
    connected = False
    #try connect to QLocalServer
    local_sock = QLocalSocket()
    import sys
    QObject.connect(local_sock, SIGNAL('connected()'), sys.exit)
    connected = local_sock.connectToServer(qApp.applicationName())
    global LOCALSERVER
    if not connected:
        LOCALSERVER = QLocalServer()
        print 'setting up localserver', qApp.applicationName()
        ret = LOCALSERVER.listen(qApp.applicationName())
        if not ret:
            import os
            try:
                #todo not good way to remove /tmp/guiTimer.py
                os.remove('/tmp/' + qApp.applicationName())
                ret = LOCALSERVER.listen(qApp.applicationName())
            except:
                raise Exception(
                    'LOCALSERVER listen failed'
                    'you may need to remove /tmp/guiTimer.py manually')
        QObject.connect(LOCALSERVER, SIGNAL('newConnection()'), showMainWindow)
    else:
        print 'local socket connected'
        pass

    pass
Ejemplo n.º 16
0
def testSingleInstanceOrExit():
    connected = False
    #try connect to QLocalServer
    local_sock = QLocalSocket()
    import sys
    QObject.connect(local_sock, SIGNAL('connected()'), sys.exit)
    connected = local_sock.connectToServer(qApp.applicationName())
    global LOCALSERVER
    if not connected:
        LOCALSERVER = QLocalServer()
        print 'setting up localserver', qApp.applicationName()
        ret = LOCALSERVER.listen(qApp.applicationName())
        if not ret:
            import os
            try:
                #todo not good way to remove /tmp/guiTimer.py
                os.remove('/tmp/'+qApp.applicationName())
                ret = LOCALSERVER.listen(qApp.applicationName())
            except:
                raise Exception('LOCALSERVER listen failed'
                        'you may need to remove /tmp/guiTimer.py manually')
        QObject.connect(LOCALSERVER, SIGNAL('newConnection()'), showMainWindow)
    else:
        print 'local socket connected'
        pass

    pass
Ejemplo n.º 17
0
class QSingleApplication(QApplication):
    def singleStart(self, mainWindow, pid):
        self.mainWindow = mainWindow
        self.pid = pid
        # Socket
        self.m_socket = QLocalSocket()
        self.m_socket.connected.connect(self.connectToExistingApp)
        self.m_socket.error.connect(self.startApplication)
        self.m_socket.connectToServer(pid, QIODevice.WriteOnly)

    def connectToExistingApp(self):
        if len(sys.argv) > 1 and sys.argv[1] is not None:
            self.m_socket.write(sys.argv[1])
            self.m_socket.bytesWritten.connect(self.quit)
        else:
            QMessageBox.warning(None, self.applicationName(),
                                self.tr("The program is already running."))
            # Quit application in 250 ms
            QTimer.singleShot(250, self.quit)

    def show(self):
        self.m_server.newConnection.connect(self.getNewConnection)
        if self.mainWindow.minimized is None:
            self.mainWindow.show()

    def startApplication(self):
        self.m_server = QLocalServer()
        if self.m_server.listen(self.pid):
            self.show()
        else:
            # Try one more time, now deleting the pid
            QLocalServer.removeServer(self.pid)
            if self.m_server.listen(self.pid):
                self.show()
            else:
                QMessageBox.critical(None, self.tr("Error"),
                                     self.tr("Error listening the socket."))

    def getNewConnection(self):
        self.new_socket = self.m_server.nextPendingConnection()
        self.new_socket.readyRead.connect(self.readSocket)

    def readSocket(self):
        f = self.new_socket.readLine()
        self.mainWindow.getArgsFromOtherInstance(str(f))
        self.mainWindow.activateWindow()
        self.mainWindow.show()
Ejemplo n.º 18
0
def main():
    global win
    signal.signal(signal.SIGINT, exit)
    args = parse_arguments()
    appKey = "scudcloud.pid"
    socket = QLocalSocket()
    socket.connectToServer(appKey)
    if socket.isOpen():
        socket.close()
        socket.deleteLater()
        return 0
    socket.deleteLater()
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName(Resources.APP_NAME + ' Slack_SSB')
    app.setWindowIcon(QtGui.QIcon(Resources.get_path('scudcloud.png')))

    try:
        settings_path, cache_path = load_settings(args.confdir, args.cachedir)
    except:
        print("Data directories " + args.confdir + " and " + args.cachedir +
              " could not be created! Exiting...")
        raise SystemExit()
    minimized = True if args.minimized is True else None
    urgent_hint = True if args.urgent_hint is True else None

    # Let's move the CSS to cachedir to enable additional actions
    copyfile(Resources.get_path('resources.css'),
             os.path.join(cache_path, 'resources.css'))

    win = sca.ScudCloud(debug=args.debug,
                        minimized=minimized,
                        urgent_hint=urgent_hint,
                        settings_path=settings_path,
                        cache_path=cache_path)
    app.commitDataRequest.connect(win.setForceClose,
                                  type=QtCore.Qt.DirectConnection)

    server = QLocalServer()
    server.newConnection.connect(restore)
    server.listen(appKey)
    win.restore()
    if win.minimized is None:
        win.show()
    sys.exit(app.exec_())
Ejemplo n.º 19
0
    def __init__(self, argv, key):
        QApplication.__init__(self, argv)

        self._key = key
        self._timeout = 1000

        socket = QLocalSocket(self)
        socket.connectToServer(self._key)
        if socket.waitForConnected(self._timeout):
            self._isRunning = True
            socket.abort()
            return
        socket.abort()

        self._isRunning = False
        self._server = QLocalServer(self)
        self._server.newConnection.connect(self.__onNewConnection)
        self._server.listen(self._key)

        self.aboutToQuit.connect(self.__onAboutToQuit)
Ejemplo n.º 20
0
    def __init__(self, argv, key):
        QApplication.__init__(self, argv)

        self._key = key
        self._timeout = 1000

        socket = QLocalSocket(self)
        socket.connectToServer(self._key)
        if socket.waitForConnected(self._timeout):
            self._isRunning = True
            socket.abort()
            return
        socket.abort()

        self._isRunning = False
        self._server = QLocalServer(self)
        self._server.newConnection.connect(self.__onNewConnection)
        self._server.listen(self._key)

        self.aboutToQuit.connect(self.__onAboutToQuit)
Ejemplo n.º 21
0
class QSingleApplication(QApplication):
    def singleStart(self, mainWindow, pid):
        self.mainWindow = mainWindow
        self.pid = pid
        # Socket
        self.m_socket = QLocalSocket()
        self.m_socket.connected.connect(self.connectToExistingApp)
        self.m_socket.error.connect(self.startApplication)
        self.m_socket.connectToServer(pid, QIODevice.WriteOnly)
    def connectToExistingApp(self):
        if len(sys.argv)>1 and sys.argv[1] is not None:
            self.m_socket.write(sys.argv[1])
            self.m_socket.bytesWritten.connect(self.quit)
        else:
            QMessageBox.warning(None, self.applicationName(), self.tr("The program is already running."))
            # Quit application in 250 ms
            QTimer.singleShot(250, self.quit)
    def show(self):
        self.m_server.newConnection.connect(self.getNewConnection)
        if self.mainWindow.minimized is None:
            self.mainWindow.show()
    def startApplication(self):
        self.m_server = QLocalServer()
        if self.m_server.listen(self.pid):
            self.show()
        else:
            # Try one more time, now deleting the pid
            QLocalServer.removeServer(self.pid)
            if self.m_server.listen(self.pid):
                self.show()
            else:
                QMessageBox.critical(None, self.tr("Error"), self.tr("Error listening the socket."))
    def getNewConnection(self):
        self.new_socket = self.m_server.nextPendingConnection()
        self.new_socket.readyRead.connect(self.readSocket)
    def readSocket(self):
        f = self.new_socket.readLine()
        self.mainWindow.getArgsFromOtherInstance(str(f))
        self.mainWindow.activateWindow()
        self.mainWindow.show()
Ejemplo n.º 22
0
def main():
    app = QtGui.QApplication(sys.argv)
    ffstoreMainWin = FFStoreMainWindow()

    # set skin styleSheet
    # SkinHelper().setStyle(app, ':/qss/white_style.qss')
    SkinHelper().setStyle(app, ':/qss/dark_style.qss')

    # single QApplication solution
    # http://blog.csdn.net/softdzf/article/details/6704187
    serverName = 'FFStoreManagerServer'
    clientSocket = QLocalSocket()
    clientSocket.connectToServer(serverName)
    # 如果连接成功, 表明server 已经存在,当前已经有实例在运行, 将参数发送给服务端
    if clientSocket.waitForConnected(500):
        # print u'连接成功 arg = ', winOsArgv
        stream = QtCore.QTextStream(clientSocket)
        # for i in range(0, len(winOsArgv)):
        #     stream << winOsArgv[i]
        # 对于打开终端来说,所携带参数为第1位(打开文件的地址),第0位为本执行程序地址
        # close client socket
        clientSocket.close()
        return app.quit()
    # 如果没有实例执行,创建服务器
    localServer = QLocalServer()
    # 一直监听端口
    localServer.listen(serverName)
    # 初始化全局变量
    GlobalVar.init()
    try:
        showWindowLogic = ShowWindowLogic(mainWindow=ffstoreMainWin,
                                          localServer=localServer)
        showWindowLogic.show()
        # uiMainWidget.setupUi(mainWindow=ffstoreMainWin, localServer=localServer)
        # ffstoreMainWin.show()
        sys.exit(app.exec_())
    finally:
        localServer.close()
Ejemplo n.º 23
0
def main():
    app = QtGui.QApplication(sys.argv)
    androidToolsMainWin = AndroidToolsMainWindow()
    uiMainWidget = Ui_MainWidget()
    winOsArgv = WinCommandEnCoding.getOsArgv()
    # single QApplication solution
    # http://blog.csdn.net/softdzf/article/details/6704187
    serverName = 'AndroidToolsServer'
    clientSocket = QLocalSocket()
    clientSocket.connectToServer(serverName)
    QSettingsUtil.init()
    # 如果连接成功, 表明server 已经存在,当前已经有实例在运行, 将参数发送给服务端
    if clientSocket.waitForConnected(500):
        # print u'连接成功 arg = ', winOsArgv
        stream = QtCore.QTextStream(clientSocket)
        # for i in range(0, len(winOsArgv)):
        #     stream << winOsArgv[i]
        # 对于打开终端来说,所携带参数为第1位(打开文件的地址),第0位为本执行程序地址
        if len(winOsArgv) > 1:
            stream << winOsArgv[1]
            stream.setCodec('UTF-8')
            stream.flush()
            clientSocket.waitForBytesWritten()
        # close client socket
        clientSocket.close()
        return app.quit()
    # 如果没有实例执行,创建服务器
    localServer = QLocalServer()
    # 一直监听端口
    localServer.listen(serverName)
    # create db
    createDb()
    try:
        uiMainWidget.setupUi(androidToolsMainWin, localServer, winOsArgv)
        androidToolsMainWin.show()
        sys.exit(app.exec_())
    finally:
        localServer.close()
Ejemplo n.º 24
0
class QSingleton(QApplication):
    messageReceived = pyqtSignal()  # Señal de mensaje recibido

    #==================================================================================================================
    # CONSTRUCTOR DE LA CLASE
    #==================================================================================================================
    def __init__(self, appID, argv):
        #--------------------------------------------------------------------------------------------------------------
        # INICIAR LA CLASE
        #--------------------------------------------------------------------------------------------------------------
        super(QSingleton, self).__init__(argv)

        #--------------------------------------------------------------------------------------------------------------
        # CONFIGURACIONES INICIALES
        #--------------------------------------------------------------------------------------------------------------

        self.appID = appID
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self.appID)
        self._isRunning = self._outSocket.waitForConnected()

        # Si hay instancias previas corriendo
        if self._isRunning:
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')

        # Si es la primera instancia
        else:
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self.appID)
            self._server.newConnection.connect(self._onNewConnection)

    #==================================================================================================================
    # MÉTODOS
    #==================================================================================================================

    # Método para saber si hay instancias previas ejecutandose
    def isRunning(self):
        return self._isRunning

    # Método para crear una nueva conexión
    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)

    # Método para lectura del socket
    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg: break
            self.messageReceived.emit(msg)
Ejemplo n.º 25
0
class LivePlotClient(object):
    def __init__(self, timeout=2000, size=2**20):
        self.app = QCoreApplication.instance()
        if self.app is None:
            self.app = QCoreApplication([])
        self.sock = QLocalSocket()
        self.sock.connectToServer("LivePlot")
        if not self.sock.waitForConnected():
            raise EnvironmentError("Couldn't find LivePlotter instance")
        self.sock.disconnected.connect(self.disconnect_received)

        key = str(uuid.uuid4())
        self.shared_mem = QSharedMemory(key)
        if not self.shared_mem.create(size):
            raise Exception("Couldn't create shared memory %s" %
                            self.shared_mem.errorString())
        logging.debug('Memory created with key %s and size %s' %
                      (key, self.shared_mem.size()))
        self.sock.write(key)
        self.sock.waitForBytesWritten()

        self.is_connected = True
        self.timeout = timeout

        atexit.register(self.close)

    def close(self):
        self.shared_mem.detach()

    def send_to_plotter(self, meta, arr=None):
        if not self.is_connected:
            return

        if meta["name"] is None:
            meta["name"] = "*"
        if arr is not None:
            arrbytes = bytearray(arr)
            arrsize = len(arrbytes)
            if arrsize > self.shared_mem.size():
                raise ValueError("Array too big %s > %s" %
                                 (arrsize, self.shared_mem.size()))
            meta['arrsize'] = arrsize
            meta['dtype'] = str(arr.dtype)
            meta['shape'] = arr.shape
        else:
            meta['arrsize'] = 0
        meta_bytes = json.dumps(meta).ljust(200)
        if len(meta_bytes) > 200:
            raise ValueError("meta object is too large (> 200 char)")

        if arr is None:
            self.sock.write(meta_bytes)
        else:
            if not self.sock.bytesAvailable():
                self.sock.waitForReadyRead()
            self.sock.read(2)
            self.shared_mem.lock()
            self.sock.write(meta_bytes)
            region = self.shared_mem.data()
            region[:arrsize] = arrbytes
            self.shared_mem.unlock()

    def plot_y(self, name, arr, extent=None, start_step=None):
        arr = np.array(arr)
        if extent is not None and start_step is not None:
            raise ValueError(
                'extent and start_step provide the same info and are thus mutually exclusive'
            )
        if extent is not None:
            x0, x1 = extent
            nx = len(arr)
            start_step = x0, float(x1 - x0) / nx
        meta = {
            'name': name,
            'operation': 'plot_y',
            'start_step': start_step,
            'rank': 1,
        }
        self.send_to_plotter(meta, arr)

    def plot_z(self, name, arr, extent=None, start_step=None):
        '''
        extent is ((initial x, final x), (initial y, final y))
        start_step is ((initial x, delta x), (initial_y, final_y))
        '''
        arr = np.array(arr)
        if extent is not None and start_step is not None:
            raise ValueError(
                'extent and start_step provide the same info and are thus mutually exclusive'
            )
        if extent is not None:
            (x0, x1), (y0, y1) = extent
            nx, ny = arr.shape
            start_step = (x0, float(x1 - x0) / nx), (y0, float(y1 - y0) / ny)
        meta = {
            'name': name,
            'operation': 'plot_z',
            'rank': 2,
            'start_step': start_step,
        }
        self.send_to_plotter(meta, arr)

    def plot_xy(self, name, xs, ys):
        arr = np.array([xs, ys])
        meta = {
            'name': name,
            'operation': 'plot_xy',
            'rank': 1,
        }
        self.send_to_plotter(meta, np.array([xs, ys]))

    def append_y(self, name, point, start_step=None):
        self.send_to_plotter({
            'name': name,
            'operation': 'append_y',
            'value': point,
            'start_step': start_step,
            'rank': 1,
        })

    def append_xy(self, name, x, y):
        self.send_to_plotter({
            'name': name,
            'operation': 'append_xy',
            'value': (x, y),
            'rank': 1,
        })

    def append_z(self, name, arr, start_step=None):
        arr = np.array(arr)
        meta = {
            'name': name,
            'operation': 'append_z',
            'rank': 2,
            'start_step': start_step,
        }
        self.send_to_plotter(meta, arr)

    def clear(self, name=None):
        self.send_to_plotter({'name': name, 'operation': 'clear'})

    def hide(self, name=None):
        self.send_to_plotter({'name': name, 'operation': 'close'})

    def remove(self, name=None):
        self.send_to_plotter({'name': name, 'operation': 'remove'})

    def disconnect_received(self):
        self.is_connected = False
        warnings.warn(
            'Disconnected from LivePlotter server, plotting has been disabled')
Ejemplo n.º 26
0
class LivePlotClient(object):
    def __init__(self, timeout=2000, size=2**20):
        self.app = QCoreApplication.instance()
        if self.app is None:
            self.app = QCoreApplication([])
        self.sock = QLocalSocket()
        self.sock.connectToServer("LivePlot")
        if not self.sock.waitForConnected():
            raise EnvironmentError("Couldn't find LivePlotter instance")
        self.sock.disconnected.connect(self.disconnect_received)

        key = str(uuid.uuid4())
        self.shared_mem = QSharedMemory(key)
        if not self.shared_mem.create(size):
            raise Exception("Couldn't create shared memory %s" % self.shared_mem.errorString())
        logging.debug('Memory created with key %s and size %s' % (key, self.shared_mem.size()))
        self.sock.write(key)
        self.sock.waitForBytesWritten()

        self.is_connected = True
        self.timeout = timeout

        atexit.register(self.close)

    def close(self):
        self.shared_mem.detach()

    def send_to_plotter(self, meta, arr=None):
        if not self.is_connected:
            return

        if meta["name"] is None:
            meta["name"] = "*";
        if arr is not None:
            arrbytes = bytearray(arr)
            arrsize = len(arrbytes)
            if arrsize > self.shared_mem.size():
                raise ValueError("Array too big %s > %s" % (arrsize, self.shared_mem.size()))
            meta['arrsize'] = arrsize
            meta['dtype'] = str(arr.dtype)
            meta['shape'] = arr.shape
        else:
            meta['arrsize'] = 0
        meta_bytes = json.dumps(meta).ljust(200)
        if len(meta_bytes) > 200:
            raise ValueError("meta object is too large (> 200 char)")

        if arr is None:
            self.sock.write(meta_bytes)
        else:
            if not self.sock.bytesAvailable():
                self.sock.waitForReadyRead()
            self.sock.read(2)
            self.shared_mem.lock()
            self.sock.write(meta_bytes)
            region = self.shared_mem.data()
            region[:arrsize] = arrbytes
            self.shared_mem.unlock()

    def plot_y(self, name, arr, extent=None, start_step=None):
        arr = np.array(arr)
        if extent is not None and start_step is not None:
            raise ValueError('extent and start_step provide the same info and are thus mutually exclusive')
        if extent is not None:
            x0, x1 = extent
            nx = len(arr)
            start_step = x0, float(x1 - x0)/nx
        meta = {
            'name': name,
            'operation':'plot_y',
            'start_step': start_step,
            'rank': 1,
        }
        self.send_to_plotter(meta, arr)

    def plot_z(self, name, arr, extent=None, start_step=None):
        '''
        extent is ((initial x, final x), (initial y, final y))
        start_step is ((initial x, delta x), (initial_y, final_y))
        '''
        arr = np.array(arr)
        if extent is not None and start_step is not None:
            raise ValueError('extent and start_step provide the same info and are thus mutually exclusive')
        if extent is not None:
            (x0, x1), (y0, y1) = extent
            nx, ny = arr.shape
            start_step = (x0, float(x1 - x0)/nx), (y0, float(y1 - y0)/ny)
        meta = {
            'name': name,
            'operation':'plot_z',
            'rank': 2,
            'start_step': start_step,
        }
        self.send_to_plotter(meta, arr)

    def plot_xy(self, name, xs, ys):
        arr = np.array([xs, ys])
        meta = {
            'name': name,
            'operation':'plot_xy',
            'rank': 1,
        }
        self.send_to_plotter(meta, np.array([xs, ys]))

    def append_y(self, name, point, start_step=None):
        self.send_to_plotter({
            'name': name,
            'operation': 'append_y',
            'value': point,
            'start_step': start_step,
            'rank': 1,
        })

    def append_xy(self, name, x, y):
        self.send_to_plotter({
            'name': name,
            'operation': 'append_xy',
            'value': (x, y),
            'rank': 1,
        })

    def append_z(self, name, arr, start_step=None):
        arr = np.array(arr)
        meta = {
            'name': name,
            'operation':'append_z',
            'rank': 2,
            'start_step': start_step,
            }
        self.send_to_plotter(meta, arr)

    def clear(self, name=None):
        self.send_to_plotter({
            'name': name,
            'operation': 'clear'
        })

    def hide(self, name=None):
        self.send_to_plotter({
            'name': name,
            'operation': 'close'
        })

    def remove(self, name=None):
        self.send_to_plotter({
            'name': name,
            'operation': 'remove'
        })

    def disconnect_received(self):
            self.is_connected = False
            warnings.warn('Disconnected from LivePlotter server, plotting has been disabled')
Ejemplo n.º 27
0
class DoorbotGUI(QWidget, Ui_BotGUI):
    def __init__(self):
        QWidget.__init__(self)

        self.setupUi(self)

        self.accessDialog = AccessDialog(self)
        self.accessDialog.hide()

        self.dispatchTable = {
            'time': self.respTime,
            'schedule': self.respSchedule,
            'bulletin': self.respBulletin,
            'readstatus': self.respReadStatus,
            'access': self.respAccess
        }

        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(1000)

        self.reconnectTimer = QTimer()
        self.reconnectTimer.timeout.connect(self.onReconnect)
        self.reconnectTimer.stop()

        self.socket = QLocalSocket()
        self.socket.connected.connect(self.onConnect)
        self.socket.disconnected.connect(self.onDisconnect)
        self.socket.readyRead.connect(self.onReadyRead)
        self.socket.error.connect(self.onError)
        self.socket.connectToServer('doorbotgui')

        self.setCursor(Qt.BlankCursor)
        self.showFullScreen()
        self.show()

    def tick(self):
        pass

    def onReconnect(self):
        self.reconnectTimer.stop()
        self.labelHealth.setText('Reconnecting to backend.')
        self.socket.connectToServer('doorbotgui')

    def onConnect(self):
        self.labelHealth.setText('Connected to backend.')

    def onDisconnect(self):
        self.labelHealth.setText('Disconnected from backend.')
        self.reconnectTimer.start(2000)

    def onError(self, err):
        self.labelHealth.setText('Backend connect error ' +
                                 self.socket.errorString() + '.')
        self.reconnectTimer.start(2000)

    def onReadyRead(self):
        while self.socket.canReadLine():
            rx = self.socket.readLine(2048).decode('utf-8')
            try:
                pkt = json.loads(rx)
                print(pkt)

                cmd = pkt['cmd']

                if cmd in self.dispatchTable:
                    self.dispatchTable[cmd](pkt)
            except ValueError:
                print('could not decode json')

            except:
                print('could not dispatch: %s', sys.exc_info())

    def respTime(self, pkt):
        self.labelTime.setText(pkt['time'])

    def respSchedule(self, pkt):
        desc = pkt['description']
        self.labelSchedule.setText(desc)

    def respBulletin(self, pkt):
        source = pkt['source']

        self.textBrowser.setSource(QUrl(source))
        self.textBrowser.reload()

    def respReadStatus(self, pkt):
        status = pkt['status']

        if status == 'Status.INIT':
            statusText = 'Initializing System.'
        elif status == 'Status.READY':
            statusText = 'Please scan your tag below.'
        elif status == 'Status.READING':
            statusText = 'Reading tag...'
        elif status == 'Status.DENIED':
            statusText = 'Access denied.'
        elif status == 'Status.ALLOWED' or status == 'Status.LATCHED':
            statusText = 'Access granted.'
        elif status == 'Status.UNKNOWN':
            statusText = 'Tag not recognized.'
        elif status == 'Status.ERROR':
            statusText = 'An unexpected error has occurred.  Contact [email protected].'
        else:
            statusText = 'Unexpected status: %s' % status

        self.labelReadStatus.setText(statusText)

    def respAccess(self, pkt):
        result = pkt['result']
        member = pkt['member']

        self.accessDialog.memberAccess(result, member)
Ejemplo n.º 28
0
                        self.lblfull.setToolTip(
                            'Open mitmproxy full inspection capture for %s' %
                            self.appname)
                        self.lblfull.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                    else:
                        self.lblfull.setToolTip('')
                        self.lblfull.setCursor(QCursor())


if __name__ == '__main__':
    app = QApplication(sys.argv)

    # self.qtappname = 'Tapioca'
    socket = QLocalSocket()
    socket.connectToServer('Tapioca')
    if socket.isOpen():
        socket.close
        socket.deleteLater()
        sys.exit(0)

    example = Example(app)

    socket.deleteLater()
    server = QLocalServer()
    server.newConnection.connect(example.restore)
    ok = server.listen('Tapioca')
    if not ok:
        if server.serverError() == QAbstractSocket.AddressInUseError:
            #print('Socket in use!')
            server.removeServer('Tapioca')
Ejemplo n.º 29
0
#!/usr/bin/python

import pyatspi
from PyQt4.QtNetwork import QLocalSocket
from os.path import expanduser

homeDir = expanduser("~")
connected = False
socket = QLocalSocket()
socket.connectToServer(homeDir + "/.eta-keyboard")

if socket.waitForConnected(3000) == False:
    connected = False
    print("Client , cannot connect to Server")
else:
    connected = True

show_data_signal = "1:0:python"
hide_data_signal = "2:0:python"
show_passwd_signal = "1:1:python"


def onFocusChanged(e):
    global connected
    try:
        if connected == True:
            atspiRole = e.source.getRole()
            print(atspiRole)

            if (atspiRole == pyatspi.ROLE_TEXT) | (e.source.getRole() == pyatspi.ROLE_ENTRY):
                try:
Ejemplo n.º 30
0
#coding=utf-8

from time import sleep
from PyQt4.QtCore import QTextStream,QString
from PyQt4.QtNetwork import QLocalSocket
import random
import os

if __name__ == "__main__":

    pid = os.getpid()
    ls = QLocalSocket()
    ls.connectToServer("localserver-test")
    if ls.waitForConnected():
        print "连接成功"
        while True:
            try:
                ts = QTextStream(ls)
                ts << QString.number(random.randrange(1000)) + "\nTTTTTTTTTT" + "\n PID = " + QString.number(pid) + "\n"
                ts.flush()
                print "werite :", ls.waitForBytesWritten()
                print pid
                sleep(1)
            except Exception as e:
                print e.message

Ejemplo n.º 31
0
class DoorbotGUI(QWidget, Ui_BotGUI):
    
    def __init__(self):
        QWidget.__init__(self)

        self.setupUi(self)

        self.accessDialog = AccessDialog(self)
        self.accessDialog.hide()
        
        self.dispatchTable = {
            'time' : self.respTime,
            'schedule' : self.respSchedule,
            'bulletin' : self.respBulletin,
            'readstatus' : self.respReadStatus,
            'access' : self.respAccess
        }
        
        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(1000)

        self.reconnectTimer = QTimer()
        self.reconnectTimer.timeout.connect(self.onReconnect)
        self.reconnectTimer.stop()

        self.socket = QLocalSocket()
        self.socket.connected.connect(self.onConnect)
        self.socket.disconnected.connect(self.onDisconnect)
        self.socket.readyRead.connect(self.onReadyRead)
        self.socket.error.connect(self.onError)
        self.socket.connectToServer('doorbotgui')

        
        self.setCursor(Qt.BlankCursor)
        self.showFullScreen()
        self.show()

    def tick(self):
        pass

    def onReconnect(self):
        self.reconnectTimer.stop()
        self.labelHealth.setText('Reconnecting to backend.')
        self.socket.connectToServer('doorbotgui')
        
    def onConnect(self):
        self.labelHealth.setText('Connected to backend.')
        
    def onDisconnect(self):
        self.labelHealth.setText('Disconnected from backend.')
        self.reconnectTimer.start(2000)

    def onError(self, err):
        self.labelHealth.setText('Backend connect error ' + self.socket.errorString() + '.' )
        self.reconnectTimer.start(2000)
        
    def onReadyRead(self):
        while self.socket.canReadLine():
            rx = self.socket.readLine(2048).decode('utf-8')
            try:
                pkt = json.loads(rx)
                print(pkt)

                cmd = pkt['cmd']

                if cmd in self.dispatchTable:
                    self.dispatchTable[cmd](pkt)                    
            except ValueError:
                print('could not decode json')

            except:
                print('could not dispatch: %s', sys.exc_info())

    def respTime(self, pkt):
        self.labelTime.setText(pkt['time'])

    def respSchedule(self, pkt):
        desc = pkt['description']
        self.labelSchedule.setText(desc)

    def respBulletin(self, pkt):
        source = pkt['source']

        self.textBrowser.setSource(QUrl(source))
        self.textBrowser.reload()

    def respReadStatus(self, pkt):
        status = pkt['status']

        if status == 'Status.INIT':
            statusText = 'Initializing System.'
        elif status == 'Status.READY':
            statusText = 'Please scan your tag below.'
        elif status == 'Status.READING':
            statusText = 'Reading tag...'
        elif status == 'Status.DENIED':
            statusText = 'Access denied.'
        elif status == 'Status.ALLOWED' or status == 'Status.LATCHED':
            statusText = 'Access granted.'
        elif status == 'Status.UNKNOWN':
            statusText = 'Tag not recognized.'
        elif status == 'Status.ERROR':
            statusText = 'An unexpected error has occurred.  Contact [email protected].'
        else:
            statusText = 'Unexpected status: %s' % status
        
        self.labelReadStatus.setText(statusText)
        
        
    def respAccess(self, pkt):
        result = pkt['result']
        member = pkt['member']

        self.accessDialog.memberAccess(result, member)
Ejemplo n.º 32
0
class QtSingleApplication(QApplication):

    messageReceived = pyqtSignal(unicode)

    def __init__(self, id, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage = True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return
        self._activationWindow.setWindowState(
            self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg: break
            self.messageReceived.emit(msg)