示例#1
0
    def _send_to_running_instance(self, payload: bytes, pid: int) -> None:
        from PyQt5.QtCore import QByteArray
        from PyQt5.QtNetwork import QLocalSocket

        named_pipe = f"{BUNDLE_IDENTIFIER}.protocol.{pid}"
        log.debug(
            f"Opening a local socket to the running instance on {named_pipe} "
            f"(payload={self.redact_payload(payload)!r})"
        )
        client = QLocalSocket()
        try:
            client.connectToServer(named_pipe)

            if not client.waitForConnected():
                log.error(f"Unable to open client socket: {client.errorString()}")
                return

            client.write(QByteArray(payload))
            client.waitForBytesWritten()
            client.disconnectFromServer()
            if client.state() == QLocalSocket.ConnectedState:
                client.waitForDisconnected()
        finally:
            del client
        log.debug("Successfully closed client socket")
示例#2
0
    def _send_to_running_instance(self, payload: bytes, pid: int) -> None:
        from PyQt5.QtCore import QByteArray
        from PyQt5.QtNetwork import QLocalSocket

        named_pipe = f"{BUNDLE_IDENTIFIER}.protocol.{pid}"
        log.debug(
            f"Opening a local socket to the running instance on {named_pipe} "
            f"(payload={self.redact_payload(payload)})"
        )
        client = QLocalSocket()
        try:
            client.connectToServer(named_pipe)

            if not client.waitForConnected():
                log.error(f"Unable to open client socket: {client.errorString()}")
                return

            client.write(QByteArray(payload))
            client.waitForBytesWritten()
            client.disconnectFromServer()
            if client.state() == QLocalSocket.ConnectedState:
                client.waitForDisconnected()
        finally:
            del client
        log.debug("Successfully closed client socket")
示例#3
0
    def hasPrevious(self, name, args):
        socket = QLocalSocket()
        socket.connectToServer(name, QLocalSocket.ReadWrite)
        if socket.waitForConnected():
            if len(args) > 1:
                socket.write(args[1])

            socket.flush()
            return True
        return False
class connection(object):
	"""docstring for connection"""
	def __init__(self, servername):
		super(connection, self).__init__()
		self.servername = servername
	
	def connectAndSend(self, content):
		self.content = json.dumps(content)
		self.socket = QLocalSocket()
		self.socket.connectToServer(self.servername)
		# self.socket.connected.connect(self.ready)
		self.socket.write(self.content.encode('utf-8'))
		pass
示例#5
0
    def __init__(self, serverName, parent=None):
        SocketInterface.__init__(self, serverName, parent=parent)

        socket = QLocalSocket(parent)
        socket.readyRead.connect(self.receiveMessage)
        socket.connectToServer(serverName)
        if socket.waitForConnected(1000):
            socket.write("Hello {0}!".format(serverName).encode("utf-8"))
            socket.flush()
            socket.waitForBytesWritten(1000)
            self.conn = socket
        else:
            self.log("Could not connect to SocketServer.")
示例#6
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
示例#7
0
文件: main.py 项目: poyraz76/lilii
 def hasPrevious(self, name, args):
     print("önceki socket kontrol ediliyor...")
     socket = QLocalSocket()
     socket.connectToServer(name, QLocalSocket.ReadWrite)
     if socket.waitForConnected():
         print("Önceki instansa argümanlar gönderiliyor.")
         if len(args) > 1:
             socket.write(args[1])
         else:
             pass
         socket.flush()
         return True
     print(socket.errorString())
     return False
示例#8
0
 def sendNotification(self, message):
     if self.isRunning():
         socket = QLocalSocket(self)
         socket.connectToServer(self._key, QIODevice.WriteOnly)
         if not socket.waitForConnected(self._timeout):
             print(socket.errorString())
             return False
         if not isinstance(message, bytes):
             message = message.encode('utf-8')
         socket.write(message)
         if not socket.waitForBytesWritten(self._timeout):
             print(socket.errorString())
             return False
         socket.disconnectFromServer()
         return True
     return False
class InstanceHandler(QObject):
    """ Makes sure that only one instance of this application can be run. """

    received = pyqtSignal(str)

    def __init__(self, parent, name):
        super(__class__, self).__init__(parent)
        self._parent = parent
        self._name = name
        self._timeout = 1000
        self._socket = QLocalSocket(self)
        self._socket.connectToServer(self._name)
        self._is_already_running = self._socket.waitForConnected(self._timeout)
        if not self.isAlreadyRunning():
            self._server = QLocalServer(self)
            self._server.newConnection.connect(self._receive_data)
            self._server.removeServer(self._name)
            self._server.listen(self._name)

    def _send_data(self, data=None):
        """ Sends model to an server-application. """
        if not data:
            data = ""
        self._socket.write(data.encode())
        self._socket.waitForBytesWritten(self._timeout)
        self._socket.disconnectFromServer()

    def _receive_data(self):
        """ Receives model from an client-application. """
        socket = self._server.nextPendingConnection()
        if socket.waitForReadyRead(self._timeout):
            # Emit transmitted model.
            self.received.emit(socket.readAll().data().decode(
                "utf-8", "surrogateescape"))
        else:
            # When no model was transmitted just emit empty string.
            self.received.emit("")

    def newTab(self, input):
        """ Opens a new tab in an already running instance. """
        self._send_data(input)

    def isAlreadyRunning(self) -> bool:
        """ Returns True when an instance of the application is already running, otherwise False. """
        return self._is_already_running
示例#10
0
    def startClient(self) -> bool:
        Logger.log(
            "i",
            "Checking for the presence of an ready running Cura instance.")
        single_instance_socket = QLocalSocket(self._application)
        Logger.log("d", "Full single instance server name: %s",
                   single_instance_socket.fullServerName())
        single_instance_socket.connectToServer("ultimaker-cura")
        single_instance_socket.waitForConnected(
            msecs=3000)  # wait for 3 seconds

        if single_instance_socket.state() != QLocalSocket.ConnectedState:
            return False

        # We only send the files that need to be opened.
        if not self._files_to_open:
            Logger.log("i", "No file need to be opened, do nothing.")
            return True

        if single_instance_socket.state() == QLocalSocket.ConnectedState:
            Logger.log(
                "i",
                "Connection has been made to the single-instance Cura socket.")

            # Protocol is one line of JSON terminated with a carriage return.
            # "command" field is required and holds the name of the command to execute.
            # Other fields depend on the command.

            if self._application.getPreferences().getValue(
                    "cura/single_instance_clear_before_load"):
                payload = {"command": "clear-all"}
                single_instance_socket.write(
                    bytes(json.dumps(payload) + "\n", encoding="ascii"))

            payload = {"command": "focus"}
            single_instance_socket.write(
                bytes(json.dumps(payload) + "\n", encoding="ascii"))

            for filename in self._files_to_open:
                payload = {
                    "command": "open",
                    "filePath": os.path.abspath(filename)
                }
                single_instance_socket.write(
                    bytes(json.dumps(payload) + "\n", encoding="ascii"))

            payload = {"command": "close-connection"}
            single_instance_socket.write(
                bytes(json.dumps(payload) + "\n", encoding="ascii"))

            single_instance_socket.flush()
            single_instance_socket.waitForDisconnected()
        return True
示例#11
0
    def _send_to_running_instance(self, payload: bytes) -> bool:
        from PyQt5.QtCore import QByteArray
        from PyQt5.QtNetwork import QLocalSocket

        log.debug(
            f"Opening local socket to send to the running instance (payload={payload})"
        )
        client = QLocalSocket()
        client.connectToServer("com.nuxeo.drive.protocol")

        if not client.waitForConnected():
            log.error(f"Unable to open client socket: {client.errorString()}")
            return 0

        client.write(QByteArray(payload))
        client.waitForBytesWritten()
        client.disconnectFromServer()
        client.waitForDisconnected()
        del client
        log.debug("Successfully closed client socket")
示例#12
0
class Client:
    def __init__(self):
        self.socket = QLocalSocket()
        self.socket.setServerName(piony.G_SOCKET_NAME)
        self.socket.error.connect(self.displayError)
        self.socket.disconnected.connect(self.socket.deleteLater)

    def _log_(self, text, *args):
        logger.info(self.__class__.__qualname__ + ': ' + text, *args)

    def connect(self):
        self.socket.abort()
        self._log_("connection attempt")
        self.socket.connectToServer()

    def send(self, argv):
        data = QByteArray()
        out = QDataStream(data, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_5_0)
        out.writeQVariant(argv)
        self._log_("writes: %s", str(data))
        self.socket.write(data)
        self.socket.flush()
        self.socket.disconnectFromServer()

    def displayError(self, err):
        msg = {
            QLocalSocket.ServerNotFoundError:
                "The host was not found. Check the host name and port.",
            QLocalSocket.ConnectionRefusedError:
                "The connection was refused by the peer. "
                "Check server is running, it's host and port.",
            QLocalSocket.PeerClosedError:
                "Peer was closed",  # None,
        }.get(err, "Client error: {}.".format(self.socket.errorString()))
        self._log_(msg)
示例#13
0
    def startClient(self) -> bool:
        Logger.log("i", "Checking for the presence of an ready running Cura instance.")
        single_instance_socket = QLocalSocket(self._application)
        Logger.log("d", "Full single instance server name: %s", single_instance_socket.fullServerName())
        single_instance_socket.connectToServer("ultimaker-cura")
        single_instance_socket.waitForConnected(msecs = 3000)  # wait for 3 seconds

        if single_instance_socket.state() != QLocalSocket.ConnectedState:
            return False

        # We only send the files that need to be opened.
        if not self._files_to_open:
            Logger.log("i", "No file need to be opened, do nothing.")
            return True

        if single_instance_socket.state() == QLocalSocket.ConnectedState:
            Logger.log("i", "Connection has been made to the single-instance Cura socket.")

            # Protocol is one line of JSON terminated with a carriage return.
            # "command" field is required and holds the name of the command to execute.
            # Other fields depend on the command.

            payload = {"command": "clear-all"}
            single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            payload = {"command": "focus"}
            single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            for filename in self._files_to_open:
                payload = {"command": "open", "filePath": os.path.abspath(filename)}
                single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            payload = {"command": "close-connection"}
            single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            single_instance_socket.flush()
            single_instance_socket.waitForDisconnected()
        return True
示例#14
0
class QSingleApplication(QApplication):
    # https://github.com/PyQt5/PyQt/blob/master/Demo/Lib/Application.py
    messageReceived = pyqtSignal(str)

    def __init__(self, *args, **kwargs):
        # logger.debug("{} init...".format(self.__class__.__name__))
        super(QSingleApplication, self).__init__(*args, **kwargs)
        # 使用路径作为appid
        # appid = QApplication.applicationFilePath().lower().split("/")[-1]
        # 使用固定的appid
        appid = "SHL_LHX_Wallet"
        # logger.debug("{} appid name: {}".format(self.__class__.__name__,appid))
        # self._socketName = "qtsingleapp-" + appid
        self._socketName = appid
        # print("socketName", self._socketName)
        self._activationWindow = None
        self._activateOnMessage = False
        self._socketServer = None
        self._socketIn = None
        self._socketOut = None
        self._running = False

        # 先尝试连接
        self._socketOut = QLocalSocket(self)
        self._socketOut.connectToServer(self._socketName)
        self._socketOut.error.connect(self.handleError)
        self._running = self._socketOut.waitForConnected()
        # logger.debug("local socket connect error: {}".format(self._socketOut.errorString()))

        if not self._running:  # 程序未运行
            # logger.debug("start init QLocalServer.")
            self._socketOut.close()
            del self._socketOut
            self._socketServer = QLocalServer(self)
            # 设置连接权限
            self._socketServer.setSocketOptions(QLocalServer.UserAccessOption)
            self._socketServer.listen(self._socketName)
            self._socketServer.newConnection.connect(self._onNewConnection)
            self.aboutToQuit.connect(self.removeServer)
            # logger.debug("QLocalServer finished init.")

    def handleError(self, message):
        print("handleError message: ", message)

    def isRunning(self):
        return self._running

    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()
        # 增加了显示功能。
        # self._activationWindow.show()

    def sendMessage(self, message, msecs=5000):
        if not self._socketOut:
            return False
        if not isinstance(message, bytes):
            message = str(message).encode()
        self._socketOut.write(message)
        if not self._socketOut.waitForBytesWritten(msecs):
            raise RuntimeError("Bytes not written within %ss" %
                               (msecs / 1000.))
        return True

    def _onNewConnection(self):
        if self._socketIn:
            self._socketIn.readyRead.disconnect(self._onReadyRead)
        self._socketIn = self._socketServer.nextPendingConnection()
        if not self._socketIn:
            return
        self._socketIn.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while 1:
            message = self._socketIn.readLine()
            if not message:
                break
            # print("Message received: ", message)
            self.messageReceived.emit(message.data().decode())

    def removeServer(self):
        if self._socketServer is not None:
            self._socketServer.close()
            self._socketServer.removeServer(self._socketName)
示例#15
0
class SingleApplicationClient(object):
    """
    Class implementing the single application client base class.
    """
    def __init__(self, name):
        """
        Constructor
        
        @param name name of the local server to connect to (string)
        """
        self.name = name
        self.connected = False
        
    def connect(self, timeout=10000):
        """
        Public method to connect the single application client to its server.
        
        @param timeout connection timeout value in milliseconds
        @type int
        @return value indicating success or an error number. Value is one of:
            <table>
                <tr><td>0</td><td>No application is running</td></tr>
                <tr><td>1</td><td>Application is already running</td></tr>
            </table>
        """
        self.sock = QLocalSocket()
        self.sock.connectToServer(self.name)
        if self.sock.waitForConnected(timeout):
            self.connected = True
            return 1
        else:
            err = self.sock.error()
            if err == QLocalSocket.ServerNotFoundError:
                return 0
            else:
                return -err
        
    def disconnect(self):
        """
        Public method to disconnect from the Single Appliocation server.
        """
        self.sock.disconnectFromServer()
        self.connected = False
    
    def processArgs(self, args):
        """
        Public method to process the command line args passed to the UI.
        
        <b>Note</b>: This method must be overridden by subclasses.
        
        @param args command line args (list of strings)
        @exception RuntimeError raised to indicate that this method must be
            implemented by a subclass
        """
        raise RuntimeError("'processArgs' must be overridden")
    
    def sendCommand(self, command, arguments):
        """
        Public method to send the command to the application server.
        
        @param command command to be sent to the server
        @type str
        @param arguments list of command arguments
        @type list of str
        """
        if self.connected:
            commandDict = {
                "command": command,
                "arguments": arguments,
            }
            self.sock.write(QByteArray(
                "{0}\n".format(json.dumps(commandDict)).encode()
            ))
            self.sock.flush()
        
    def errstr(self):
        """
        Public method to return a meaningful error string for the last error.
        
        @return error string for the last error (string)
        """
        return self.sock.errorString()
示例#16
0
    def __init__(self, pathObjects, parent=None):
        """Initialize the main tree controls

        Arguments:
            pathObjects -- a list of file objects to open
            parent -- the parent QObject if given
        """
        super().__init__(parent)
        self.localControls = []
        self.activeControl = None
        self.trayIcon = None
        self.isTrayMinimized = False
        self.configDialog = None
        self.sortDialog = None
        self.numberingDialog = None
        self.findTextDialog = None
        self.findConditionDialog = None
        self.findReplaceDialog = None
        self.filterTextDialog = None
        self.filterConditionDialog = None
        self.basicHelpView = None
        self.passwords = {}
        globalref.mainControl = self
        self.allActions = {}
        try:
            # check for existing TreeLine session
            socket = QLocalSocket()
            socket.connectToServer('treeline3-session', QIODevice.WriteOnly)
            # if found, send files to open and exit TreeLine
            if socket.waitForConnected(1000):
                socket.write(
                    bytes(repr([str(path) for path in pathObjects]), 'utf-8'))
                if socket.waitForBytesWritten(1000):
                    socket.close()
                    sys.exit(0)
            # start local server to listen for attempt to start new session
            self.serverSocket = QLocalServer()
            self.serverSocket.listen('treeline3-session')
            self.serverSocket.newConnection.connect(self.getSocket)
        except AttributeError:
            print(_('Warning:  Could not create local socket'))
        mainVersion = '.'.join(__version__.split('.')[:2])
        globalref.genOptions = options.Options('general', 'TreeLine',
                                               mainVersion, 'bellz')
        optiondefaults.setGenOptionDefaults(globalref.genOptions)
        globalref.miscOptions = options.Options('misc')
        optiondefaults.setMiscOptionDefaults(globalref.miscOptions)
        globalref.histOptions = options.Options('history')
        optiondefaults.setHistOptionDefaults(globalref.histOptions)
        globalref.toolbarOptions = options.Options('toolbar')
        optiondefaults.setToolbarOptionDefaults(globalref.toolbarOptions)
        globalref.keyboardOptions = options.Options('keyboard')
        optiondefaults.setKeyboardOptionDefaults(globalref.keyboardOptions)
        try:
            globalref.genOptions.readFile()
            globalref.miscOptions.readFile()
            globalref.histOptions.readFile()
            globalref.toolbarOptions.readFile()
            globalref.keyboardOptions.readFile()
        except IOError:
            errorDir = options.Options.basePath
            if not errorDir:
                errorDir = _('missing directory')
            QMessageBox.warning(
                None, 'TreeLine',
                _('Error - could not write config file to {}').format(
                    errorDir))
            options.Options.basePath = None
        iconPathList = self.findResourcePaths('icons', iconPath)
        globalref.toolIcons = icondict.IconDict(
            [path / 'toolbar' for path in iconPathList],
            ['', '32x32', '16x16'])
        globalref.toolIcons.loadAllIcons()
        windowIcon = globalref.toolIcons.getIcon('treelogo')
        if windowIcon:
            QApplication.setWindowIcon(windowIcon)
        globalref.treeIcons = icondict.IconDict(iconPathList, ['', 'tree'])
        icon = globalref.treeIcons.getIcon('default')
        qApp.setStyle(QStyleFactory.create('Fusion'))
        setThemeColors()
        self.recentFiles = recentfiles.RecentFileList()
        if globalref.genOptions['AutoFileOpen'] and not pathObjects:
            recentPath = self.recentFiles.firstPath()
            if recentPath:
                pathObjects = [recentPath]
        self.setupActions()
        self.systemFont = QApplication.font()
        self.updateAppFont()
        if globalref.genOptions['MinToSysTray']:
            self.createTrayIcon()
        qApp.focusChanged.connect(self.updateActionsAvail)
        if pathObjects:
            for pathObj in pathObjects:
                self.openFile(pathObj, True)
        else:
            self.createLocalControl()
示例#17
0
class QSingleApplication(QApplication):

    messageReceived = pyqtSignal(str)

    def __init__(self, *args, **kwargs):
        super(QSingleApplication, self).__init__(*args, **kwargs)
        appid = QApplication.applicationFilePath().lower().split("/")[-1]
        self._socketName = "qtsingleapp-" + appid
        print("socketName", self._socketName)
        self._activationWindow = None
        self._activateOnMessage = False
        self._socketServer = None
        self._socketIn = None
        self._socketOut = None
        self._running = False

        # 先尝试连接
        self._socketOut = QLocalSocket(self)
        self._socketOut.connectToServer(self._socketName)
        self._socketOut.error.connect(self.handleError)
        self._running = self._socketOut.waitForConnected()

        if not self._running:  # 程序未运行
            self._socketOut.close()
            del self._socketOut
            self._socketServer = QLocalServer(self)
            self._socketServer.listen(self._socketName)
            self._socketServer.newConnection.connect(self._onNewConnection)
            self.aboutToQuit.connect(self.removeServer)

    def handleError(self, message):
        print("handleError message: ", message)

    def isRunning(self):
        return self._running

    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, message, msecs=5000):
        if not self._socketOut:
            return False
        if not isinstance(message, bytes):
            message = str(message).encode()
        self._socketOut.write(message)
        if not self._socketOut.waitForBytesWritten(msecs):
            raise RuntimeError("Bytes not written within %ss" %
                               (msecs / 1000.))
        return True

    def _onNewConnection(self):
        if self._socketIn:
            self._socketIn.readyRead.disconnect(self._onReadyRead)
        self._socketIn = self._socketServer.nextPendingConnection()
        if not self._socketIn:
            return
        self._socketIn.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while 1:
            message = self._socketIn.readLine()
            if not message:
                break
            print("Message received: ", message)
            self.messageReceived.emit(message.data().decode())

    def removeServer(self):
        self._socketServer.close()
        self._socketServer.removeServer(self._socketName)
示例#18
0
class LivePlotClient(object):
    def __init__(self, timeout=2000, size=2**28):
        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.encode())
        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(300)
        if len(meta_bytes) > 300:
            raise ValueError("meta object is too large (> 300 char)")

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

    def plot_y(self, name, arr, extent=None, start_step=(0, 1), label=''):
        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,
            'label': label,
        }
        self.send_to_plotter(meta, arr.astype('float64'))
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def plot_z(self, name, arr, extent=None, start_step=None, xname='X axis',\
     xscale='arb. u.', yname='Y axis', yscale='arb. u.', zname='Y axis', zscale='arb. u.'):
        '''
        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,
            'X': xscale,
            'Y': yscale,
            'Z': zscale,
            'Xname': xname,
            'Yname': yname,
            'Zname': zname,
        }
        self.send_to_plotter(meta, arr.astype('float64'))
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def plot_xy(self, name, xs, ys, label='', xname='X axis', xscale='arb. u.',\
     yname='Y axis', yscale='arb. u.', scatter='False', timeaxis='False'):
        arr = np.array([xs, ys])
        meta = {
            'name': name,
            'operation': 'plot_xy',
            'rank': 1,
            'label': label,
            'X': xscale,
            'Y': yscale,
            'Xname': xname,
            'Yname': yname,
            'Scatter': scatter,
            'TimeAxis': timeaxis
        }
        self.send_to_plotter(meta, np.array([xs, ys]).astype('float64'))
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def append_y(self, name, point, start_step=(0, 1), label='', xname='X axis',\
     xscale='arb. u.', yname='Y axis', yscale='arb. u.',scatter='False', timeaxis='False'):
        self.send_to_plotter({
            'name': name,
            'operation': 'append_y',
            'value': point,
            'start_step': start_step,
            'rank': 1,
            'label': label,
            'X': xscale,
            'Y': yscale,
            'Xname': xname,
            'Yname': yname,
            'Scatter': scatter,
            'TimeAxis': timeaxis
        })
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def append_xy(self, name, x, y, label=''):
        self.send_to_plotter({
            'name': name,
            'operation': 'append_xy',
            'value': (x, y),
            'rank': 1,
            'label': label,
        })
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def append_z(self, name, arr, start_step=None, xname='X axis',\
     xscale='arb. u.', yname='Y axis', yscale='arb. u.', zname='Y axis', zscale='arb. u.'):
        arr = np.array(arr)
        meta = {
            'name': name,
            'operation': 'append_z',
            'rank': 2,
            'start_step': start_step,
            'X': xscale,
            'Y': yscale,
            'Z': zscale,
            'Xname': xname,
            'Yname': yname,
            'Zname': zname,
        }
        self.send_to_plotter(meta, arr.astype('float64'))
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def label(self, name, text):
        self.send_to_plotter({
            'name': name,
            'operation': 'label',
            'value': text
        })
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    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'})
        self.send_to_plotter({
            'name': 'none',
            'operation': 'none'
        }, np.array([0.]))

    def disconnect_received(self):
        self.is_connected = False
        warnings.warn(
            'Disconnected from LivePlotter server, plotting has been disabled')
示例#19
0
class SingleApplicationClient(object):
    """
    Class implementing the single application client base class.
    """
    def __init__(self, name):
        """
        Constructor
        
        @param name name of the local server to connect to (string)
        """
        self.name = name
        self.connected = False
        
    def connect(self):
        """
        Public method to connect the single application client to its server.
        
        @return value indicating success or an error number. Value is one of:
            <table>
                <tr><td>0</td><td>No application is running</td></tr>
                <tr><td>1</td><td>Application is already running</td></tr>
            </table>
        """
        self.sock = QLocalSocket()
        self.sock.connectToServer(self.name)
        if self.sock.waitForConnected(10000):
            self.connected = True
            return 1
        else:
            err = self.sock.error()
            if err == QLocalSocket.ServerNotFoundError:
                return 0
            else:
                return -err
        
    def disconnect(self):
        """
        Public method to disconnect from the Single Appliocation server.
        """
        self.sock.disconnectFromServer()
        self.connected = False
    
    def processArgs(self, args):
        """
        Public method to process the command line args passed to the UI.
        
        <b>Note</b>: This method must be overridden by subclasses.
        
        @param args command line args (list of strings)
        @exception RuntimeError raised to indicate that this method must be
            implemented by a subclass
        """
        raise RuntimeError("'processArgs' must be overridden")
    
    def sendCommand(self, cmd):
        """
        Public method to send the command to the application server.
        
        @param cmd command to be sent (string)
        """
        if self.connected:
            self.sock.write(cmd)
            self.sock.flush()
        
    def errstr(self):
        """
        Public method to return a meaningful error string for the last error.
        
        @return error string for the last error (string)
        """
        return self.sock.errorString()
示例#20
0
class QSingleApplication(QApplication):
    messageReceived = pyqtSignal(str)

    def __init__(self, name, *args, **kwargs):
        super(QSingleApplication, self).__init__(*args, **kwargs)

        self._socketName = name
        self._activationWindow = None
        self._socketServer = None
        self._socketIn = None
        self._socketOut = None
        self._running = False

        # 先尝试连接
        self._socketOut = QLocalSocket(self)
        self._socketOut.connectToServer(self._socketName)
        self._socketOut.error.connect(self.handleError)
        self._running = self._socketOut.waitForConnected()

        if not self._running:  # 程序未运行
            self._socketOut.close()
            del self._socketOut
            # 创建本地server
            self._socketServer = QLocalServer(self)
            self._socketServer.listen(self._socketName)
            self._socketServer.newConnection.connect(self._onNewConnection)
            self.aboutToQuit.connect(self.removeServer)

    def handleError(self, message):
        print("handleError message: ", message)

    def isRunning(self):
        return self._running

    def setActivationWindow(self, activationWindow):
        # 设置当前窗口
        self._activationWindow = activationWindow

    def activateWindow(self):
        # 激活当前窗口
        try:
            self._activationWindow.setWindowState(
                self._activationWindow.windowState() & ~Qt.WindowMinimized)
            #self._activationWindow.raise_() # 提升窗口到最上面
            self._activationWindow.showNormal()
            self._activationWindow.activateWindow()
        except Exception as e:
            print(e)

    def sendMessage(self, message, msecs=5000):
        if not self._socketOut:
            return False
        if not isinstance(message, bytes):
            message = str(message).encode()
        self._socketOut.write(message)
        if not self._socketOut.waitForBytesWritten(msecs):
            raise Exception("Bytes not written within %ss" % (msecs / 1000.))
        return True

    def _onNewConnection(self):
        if self._socketIn:
            self._socketIn.readyRead.disconnect(self._onReadyRead)
        self._socketIn = self._socketServer.nextPendingConnection()
        if not self._socketIn:
            return
        self._socketIn.readyRead.connect(self._onReadyRead)

    def _onReadyRead(self):
        while 1:
            message = self._socketIn.readLine()
            if not message:
                break
            if message == b'show':
                self.activateWindow()
            self.messageReceived.emit(message.data().decode())

    def removeServer(self):
        self._socketServer.close()
        self._socketServer.removeServer(self._socketName)