Exemple #1
0
 def __init__(self, client):
     self.client = client
     self.s = QtNetwork.QLocalSocket()
     self.s.readyRead.connect(self.create)
     self.s2 = QtNetwork.QLocalSocket()
     self.s2.readyRead.connect(self.changeValue)
     self.l = kst.LineEdit(client, "", self.s2, 0.47, 0.975, 0.93, 0.025)
     self.b = kst.Button(client, "Go!", self.s, 0.97, 0.975, 0.05, 0.025)
     self.plot = client.new_plot((0.5, 0.4885), (0.9, 0.8))
     self.genVec = client.new_generated_vector(-100, 100, 1000)
    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 = QtNetwork.QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QtCore.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 = QtNetwork.QLocalServer(self)
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)
            self.NAM = QtNetwork.QNetworkAccessManager(self)
Exemple #3
0
 def firstWindow(self, fileNames):
     """Open first main window"""
     try:
         # check for existing TreeLine session
         socket = QtNetwork.QLocalSocket()
         socket.connectToServer('treeline-session',
                                QtCore.QIODevice.WriteOnly)
         # if found, send files to open and exit TreeLine
         if socket.waitForConnected(1000):
             socket.write(repr(fileNames))
             if socket.waitForBytesWritten(1000):
                 socket.close()
                 sys.exit(0)
         qApp = QtGui.QApplication.instance()
         # start local server to listen for attempt to start new session
         self.serverSocket = QtNetwork.QLocalServer()
         self.serverSocket.listen('treeline-session')
         qApp.connect(self.serverSocket, QtCore.SIGNAL('newConnection()'),
                      self.getSocket)
     except AttributeError:
         print 'Warning:  Could not create local socket'
     if fileNames:
         fileNames = [unicode(fileName, globalref.localTextEncoding) for
                      fileName in fileNames]
         self.openMultipleFiles(fileNames)
     else:
         win = treemainwin.TreeMainWin()
         self.windowList.append(win)
         self.updateWinMenu()
         self.autoOpen()
         win.show()
     globalref.setStatusBar(_('Ready'), 2000)
Exemple #4
0
    def __init__(self, guid, *argv):
        super(QtSingleApplication, self).__init__(*argv)
        self._id = guid
        self._activationWindow = None
        self._activateOnMessage = False

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

        if self._isRunning:
            # Yes, there is.
            self._outStream = QtCore.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 = QtNetwork.QLocalServer()
            self._server.listen(self._id)
            # noinspection PyUnresolvedReferences
            self._server.newConnection.connect(
                self._onNewConnection
            )  # PyCharm doesn't recognize newConnection.connect()...
Exemple #5
0
 def request(self, request):
     self.__request = request
     self.__socket = QtNetwork.QLocalSocket(self)
     self.__socket.connected.connect(self.__clientConnect)
     self.__socket.error.connect(self.__clientError)
     self.__socket.connectToServer(PIPE_NAME)
     return not self.__quitRequested
Exemple #6
0
    def __init__(self, argv):
        super(SingleApplication, self).__init__(argv)
        self.isSingle = True

        self.setApplicationName('HelloWord')
        serverName = self.applicationName()
        socket = QtNetwork.QLocalSocket()
        socket.connectToServer(serverName)
        if socket.waitForConnected(1000):
            # print u'已存在一个实例'
            self.isSingle = False
            return
        # print u'建立本地服务器'
        self.server = QtNetwork.QLocalServer(self)
        # self.server.listen(serverName)
        self.server.newConnection.connect(self.newLocalConnection)
        if not self.server.listen(serverName):
            #     print '听'
            # 防止程序崩溃时,残留进程服务,移除之
            # 确保监听成功
            if self.server.serverError() == QtNetwork.QAbstractSocket.AddressInUseError and \
                    QtCore.QFile.exists(self.server.serverName()):
                QtCore.QFile.remove(self.server.serverName())
        #       print u'什么情况?'
                self.server.listen(serverName)
Exemple #7
0
 def sendToInstance(self, data=''):
     socket = QtNetwork.QLocalSocket()
     socket.connectToServer(self.catalog, QIODevice.WriteOnly)
     if socket.waitForConnected(500):
         if len(data) > 0:
             socket.write(data)
             socket.flush()
         socket.close()
         return True
     return False
Exemple #8
0
    def checkConnection(self):
        from PyQt4 import QtNetwork

        self.socket = QtNetwork.QLocalSocket(self)
        self.connect(self.socket, QtCore.SIGNAL('connected()'),
                     self.onSocketConnected)
        self.socket.connectToServer(self.serverName)
        if not self.socket.waitForConnected(1000):
            self.isServer = True

        if self.isServer:
            self.server = QtNetwork.QLocalServer()
            self.connect(self.server, QtCore.SIGNAL('newConnection()'),
                         self.onNewConnection)
            QtNetwork.QLocalServer.removeServer(self.serverName)
 def send_message(self, message):
     """
     Message sending function. Connected to local socket specified by shared key and if successful writes the message to it and returns.
     """
     if self.is_running():
         socket = QtNetwork.QLocalSocket(self)
         socket.connectToServer(self._key, QtCore.QIODevice.WriteOnly)
         if not socket.waitForConnected(self._timeout):
             self.log.error(socket.errorString())
             return False
         socket.write(str(message).encode("utf-8"))
         if not socket.waitForBytesWritten(self._timeout):
             self.log.error(socket.errorString())
             return False
         socket.disconnectFromServer()
         return True
     self.log.debug(self.translate("logs", "Attempted to send message when commotion client application was not currently running."))
     return False
Exemple #10
0
def check_running(settings):
    """Check for a valid socket of an already running instance, and if so,
    connect to it and send the input file names."""
    if settings.NEW_GUI_INSTANCE:
        return False

    files = os.listdir(SOCKET_DIR)
    for f in files:
        if f.startswith(SOCKET_NAME_PREFIX):
            pid = int(f.split("-")[-1])
            try:
                os.kill(pid, 0)
                sys.stderr.write(
                    "Found a running instance with pid %d. Trying to connect... "
                    % pid)
                # Signal handler did not raise an error, so the pid is running. Try to connect
                sock = QtNetwork.QLocalSocket()
                sock.connectToServer(os.path.join(SOCKET_DIR, f),
                                     QIODevice.WriteOnly)
                if not sock.waitForConnected(1000):
                    continue

                # Encode the filenames as a QStringList and pass them over the socket
                block = QByteArray()
                stream = QDataStream(block, QIODevice.WriteOnly)
                stream.setVersion(QDataStream.Qt_4_0)
                stream.writeQStringList(
                    [os.path.abspath(f) for f in settings.INPUT])
                sock.write(block)
                ret = sock.waitForBytesWritten(1000)
                sock.disconnectFromServer()

                # If we succeeded in sending stuff, we're done. Otherwise, if
                # there's another possibly valid socket in the list we'll try
                # again the next time round in the loop.
                if ret:
                    sys.stderr.write("Success!\n")
                    return True
                else:
                    sys.stderr.write("Error!\n")
            except OSError:
                # os.kill raises OSError if the pid does not exist
                pass
    return False
Exemple #11
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.blockSize = 0
        self.currentFortune = None

        hostLabel = QtGui.QLabel("&Server name:")
        self.hostLineEdit = QtGui.QLineEdit("fortune")
        hostLabel.setBuddy(self.hostLineEdit)

        self.statusLabel = QtGui.QLabel(
            "This examples requires that you run the Fortune Server "
            "example as well.")
        self.statusLabel.setWordWrap(True)

        self.getFortuneButton = QtGui.QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)

        quitButton = QtGui.QPushButton("Quit")
        buttonBox = QtGui.QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton,
                            QtGui.QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QtGui.QDialogButtonBox.RejectRole)

        self.socket = QtNetwork.QLocalSocket()

        self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.socket.readyRead.connect(self.readFortune)
        self.socket.error.connect(self.displayError)

        mainLayout = QtGui.QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostLineEdit, 0, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Client")
        self.hostLineEdit.setFocus()
Exemple #12
0
def exec_script(script):
    """Executes the given script in the associated MIFit session"""
    global socketId
    result = QtCore.QString()
    sock = QtNetwork.QLocalSocket()
    sock.connectToServer(socketId)
    if sock.waitForConnected():

        stream = QtCore.QDataStream(sock)
        stream.setVersion(QtCore.QDataStream.Qt_4_5)

        data = QtCore.QByteArray()
        out = QtCore.QDataStream(data, QtCore.QIODevice.WriteOnly)
        out.setVersion(QtCore.QDataStream.Qt_4_5)
        out.writeUInt32(0)
        out << QtCore.QString(script)
        out.device().seek(0)
        out.writeUInt32(data.size() - 8)
        sock.write(data)
        sock.flush()

        moreInput = True
        dataSize = 0
        while moreInput:
            QtGui.qApp.processEvents()
            if dataSize == 0:
                if sock.bytesAvailable() < 8:
                    continue
                dataSize = stream.readUInt32()
            if sock.bytesAvailable() < dataSize:
                continue
            stream >> result
            moreInput = False

        sock.close()
    else:
        print 'error connecting to local socket', socketId
    sock = None
    return result
Exemple #13
0
    def __init__(self, appid, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = appid
        self._activation_window = None
        self._activateOnMessage = False

        self._outSocket = QtNetwork.QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            self._outStream = QtCore.QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QtNetwork.QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._on_new_connection)
Exemple #14
0
 def __init__(self):
     self.cl = QtNetwork.QLocalSocket()
Exemple #15
0
    def __init__(self, filePaths, parent=None):
        """Initialize the main tree controls

        Arguments:
            filePaths -- a list of files to open
            parent -- the parent QObject if given
        """
        super().__init__(parent)
        self.localControls = []
        self.activeControl = None
        self.pluginInterface = None
        self.pluginInstances = []
        self.pluginDescriptions = []
        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.serverSocket = None
        self.passwords = {}
        globalref.mainControl = self
        try:
            # check for existing TreeLine session
            socket = QtNetwork.QLocalSocket()
            socket.connectToServer('treeline2-session',
                                   QtCore.QIODevice.WriteOnly)
            # if found, send files to open and exit TreeLine
            if socket.waitForConnected(1000):
                socket.write(bytes(repr(filePaths), 'utf-8'))
                if socket.waitForBytesWritten(1000):
                    socket.close()
                    sys.exit(0)
            # start local server to listen for attempt to start new session
            self.serverSocket = QtNetwork.QLocalServer()
            self.serverSocket.listen('treeline2-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', 'GmEdit',
                                               mainVersion, 'gmedit')
        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()
            recentfiles.setRecentOptionDefaults()
            globalref.histOptions.readFile()
            globalref.toolbarOptions.readFile()
            globalref.keyboardOptions.readFile()
        except IOError:
            QtGui.QMessageBox.warning(
                QtGui.QApplication.activeWindow(), 'GmEdit',
                _('Error - could not write config file to {}').format(
                    options.Options.basePath))
        iconPathList = self.findResourcePaths('icons', iconPath)
        globalref.toolIcons = icondict.IconDict(
            [os.path.join(path, 'toolbar') for path in iconPathList],
            ['', '32x32', '16x16'])
        globalref.toolIcons.loadAllIcons()
        windowIcon = globalref.toolIcons.getIcon('gm_logo')
        if windowIcon:
            QtGui.QApplication.setWindowIcon(windowIcon)
        globalref.treeIcons = icondict.IconDict(iconPathList, ['', 'tree'])
        self.recentFiles = recentfiles.RecentFileList()
        if globalref.genOptions.getValue('AutoFileOpen') and not filePaths:
            recentPath = self.recentFiles.firstPath()
            if recentPath:
                filePaths = [recentPath]
        self.allActions = {}
        self.setupActions()
        QtGui.qApp.focusChanged.connect(self.updateActionsAvail)
        if filePaths:
            for path in filePaths:
                self.openFile(path)
        else:
            self.createLocalControl()
        self.setupPlugins()
Exemple #16
0
import sip
sip.setapi('QString', 1)
import pykst as kst
import sys
import random
from PyQt4 import QtCore, QtNetwork, QtGui


class Magic:
    def __init__(self, client):
        self.client = client

    def test(self):
        self.client = client
        random.seed()
        client.new_circle(
            (random.random(), random.random()),
            random.random() / 10.0, "#" + str(random.randint(0, 9)) +
            str(random.randint(0, 9)) + str(random.randint(0, 9)))


client = kst.Client("testbutton")
app = QtGui.QApplication(sys.argv)
m = Magic(client)

s = QtNetwork.QLocalSocket()
s.readyRead.connect(m.test)
b = kst.Button(client, "Click Here", s, 0.5, 0.5, 0.2, 0.1)
app.exec_()