本文整理汇总了Python中PyQt5.QtNetwork.QLocalServer.nextPendingConnection方法的典型用法代码示例。如果您正苦于以下问题:Python QLocalServer.nextPendingConnection方法的具体用法?Python QLocalServer.nextPendingConnection怎么用?Python QLocalServer.nextPendingConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtNetwork.QLocalServer
的用法示例。
在下文中一共展示了QLocalServer.nextPendingConnection方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Server
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class Server(QDialog):
def __init__(self, parent=None):
super(Server, self).__init__(parent)
statusLabel = QLabel()
statusLabel.setWordWrap(True)
quitButton = QPushButton("Quit")
quitButton.setAutoDefault(False)
self.fortunes = (
"You've been leading a dog's life. Stay off the furniture.",
"You've got to think about tomorrow.",
"You will be surprised by a loud noise.",
"You will feel hungry again in another hour.",
"You might have mail.",
"You cannot kill time without injuring eternity.",
"Computers are not intelligent. They only think they are.",
)
self.server = QLocalServer()
if not self.server.listen('fortune'):
QMessageBox.critical(self, "Fortune Server",
"Unable to start the server: %s." % self.server.errorString())
self.close()
return
statusLabel.setText("The server is running.\nRun the Fortune Client "
"example now.")
quitButton.clicked.connect(self.close)
self.server.newConnection.connect(self.sendFortune)
buttonLayout = QHBoxLayout()
buttonLayout.addStretch(1)
buttonLayout.addWidget(quitButton)
buttonLayout.addStretch(1)
mainLayout = QVBoxLayout()
mainLayout.addWidget(statusLabel)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)
self.setWindowTitle("Fortune Server")
def sendFortune(self):
block = QByteArray()
out = QDataStream(block, QIODevice.WriteOnly)
out.setVersion(QDataStream.Qt_4_0)
out.writeUInt16(0)
out.writeQString(random.choice(self.fortunes))
out.device().seek(0)
out.writeUInt16(block.size() - 2)
clientConnection = self.server.nextPendingConnection()
clientConnection.disconnected.connect(clientConnection.deleteLater)
clientConnection.write(block)
clientConnection.flush()
clientConnection.disconnectFromServer()
示例2: Server
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class Server(QObject):
dataReceived = pyqtSignal(list)
quit = pyqtSignal()
def __init__(self):
super().__init__()
self.conn = None
self.server = None
def create(self, name=piony.G_SOCKET_NAME):
QLocalServer.removeServer(name)
self.server = QLocalServer()
if not self.server.listen(name):
print("Error: server -- unable to start: {}."
.format(self.server.errorString()))
self.quit.emit()
self.server.newConnection.connect(self.notify)
def close(self):
self.server.close()
def notify(self):
logger.info("1 new conn")
# WARNING: when multiple connections, each will overwrite previous!
self.conn = self.server.nextPendingConnection()
self.conn.readyRead.connect(self.receiveData)
self.conn.disconnected.connect(self.conn.deleteLater)
def receiveData(self):
logger.info("waits for data")
ins = QDataStream(self.conn)
ins.setVersion(QDataStream.Qt_5_0)
if ins.atEnd():
return
argv = ins.readQVariant()
logger.info("reads '%s'", str(argv))
# Must be setted up on 'show' action. Move from beginning to appropriate.
action.search_dst_window()
self.dataReceived.emit(argv)
示例3: IPCServer
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
#.........这里部分代码省略.........
else:
raise ListenError(self._server)
if not self._socketopts_ok: # pragma: no cover
# If we use setSocketOptions on Unix with Qt < 5.4, we get a
# NameError while listening.
# (see b135569d5c6e68c735ea83f42e4baf51f7972281)
#
# Also, we don't get an AddressInUseError with Qt 5.5:
# https://bugreports.qt.io/browse/QTBUG-48635
#
# This means we only use setSocketOption on Windows...
os.chmod(self._server.fullServerName(), 0o700)
@pyqtSlot(int)
def on_error(self, err):
"""Raise SocketError on fatal errors."""
if self._socket is None:
# Sometimes this gets called from stale sockets.
log.ipc.debug("In on_error with None socket!")
return
self._timer.stop()
log.ipc.debug("Socket error {}: {}".format(self._socket.error(), self._socket.errorString()))
if err != QLocalSocket.PeerClosedError:
raise SocketError("handling IPC connection", self._socket)
@pyqtSlot()
def handle_connection(self):
"""Handle a new connection to the server."""
if self.ignored:
return
if self._socket is not None:
log.ipc.debug("Got new connection but ignoring it because we're " "still handling another one.")
return
socket = self._server.nextPendingConnection()
if socket is None:
log.ipc.debug("No new connection to handle.")
return
log.ipc.debug("Client connected.")
self._timer.start()
self._socket = socket
socket.readyRead.connect(self.on_ready_read)
if socket.canReadLine():
log.ipc.debug("We can read a line immediately.")
self.on_ready_read()
socket.error.connect(self.on_error)
if socket.error() not in (QLocalSocket.UnknownSocketError, QLocalSocket.PeerClosedError):
log.ipc.debug("We got an error immediately.")
self.on_error(socket.error())
socket.disconnected.connect(self.on_disconnected)
if socket.state() == QLocalSocket.UnconnectedState:
log.ipc.debug("Socket was disconnected immediately.")
self.on_disconnected()
@pyqtSlot()
def on_disconnected(self):
"""Clean up socket when the client disconnected."""
log.ipc.debug("Client disconnected.")
self._timer.stop()
if self._socket is None:
log.ipc.debug("In on_disconnected with None socket!")
else:
self._socket.deleteLater()
self._socket = None
# Maybe another connection is waiting.
self.handle_connection()
示例4: QtSingleApplication
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class QtSingleApplication(QApplication):
"""
This class makes sure that we can only start one Tribler application.
When a user tries to open a second Tribler instance, the current active one will be brought to front.
"""
messageReceived = pyqtSignal(unicode)
def __init__(self, win_id, *argv):
logfunc = logging.info
logfunc(sys._getframe().f_code.co_name + '()')
QApplication.__init__(self, *argv)
self._id = win_id
self._activation_window = None
self._activate_on_message = False
# Is there another instance running?
self._outSocket = QLocalSocket()
self._outSocket.connectToServer(self._id)
self._isRunning = self._outSocket.waitForConnected()
self._outStream = None
self._inSocket = None
self._inStream = None
self._server = None
if self._isRunning:
# Yes, there is.
self._outStream = QTextStream(self._outSocket)
self._outStream.setCodec('UTF-8')
else:
# No, there isn't, at least not properly.
# Cleanup any past, crashed server.
error = self._outSocket.error()
logfunc(LOGVARSTR % ('self._outSocket.error()', error))
if error == QLocalSocket.ConnectionRefusedError:
logfunc('received QLocalSocket.ConnectionRefusedError; ' + \
'removing server.')
self.close()
QLocalServer.removeServer(self._id)
self._outSocket = None
self._server = QLocalServer()
self._server.listen(self._id)
self._server.newConnection.connect(self._on_new_connection)
logfunc(sys._getframe().f_code.co_name + '(): returning')
def close(self):
logfunc = logging.info
logfunc(sys._getframe().f_code.co_name + '()')
if self._inSocket:
self._inSocket.disconnectFromServer()
if self._outSocket:
self._outSocket.disconnectFromServer()
if self._server:
self._server.close()
logfunc(sys._getframe().f_code.co_name + '(): returning')
def is_running(self):
return self._isRunning
def get_id(self):
return self._id
def activation_window(self):
return self._activation_window
def set_activation_window(self, activation_window, activate_on_message=True):
self._activation_window = activation_window
self._activate_on_message = activate_on_message
def activate_window(self):
if not self._activation_window:
return
self._activation_window.setWindowState(
self._activation_window.windowState() & ~Qt.WindowMinimized)
self._activation_window.raise_()
def send_message(self, msg):
if not self._outStream:
return False
self._outStream << msg << '\n'
self._outStream.flush()
return self._outSocket.waitForBytesWritten()
def _on_new_connection(self):
if self._inSocket:
self._inSocket.readyRead.disconnect(self._on_ready_read)
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._on_ready_read)
if self._activate_on_message:
self.activate_window()
#.........这里部分代码省略.........
示例5: IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
#.........这里部分代码省略.........
def showMessageStatus(self, msg):
QTimer.singleShot(1, Qt.PreciseTimer, lambda: self.statusBar().showMessage(msg))
# self.statusBar().showMessage(msg)
@classmethod
def select_current(cls, widget):
"""Show the widget with a 4px lightblue border line."""
widget.setProperty("highlight", True)
widget.style().unpolish(widget)
widget.style().polish(widget)
@classmethod
def unselect_current(cls, widget):
"""Remove the 4px lightblue border line from the widget."""
widget.setProperty("highlight", False)
widget.style().unpolish(widget)
widget.style().polish(widget)
def _close_tray_icon(self):
"""Close the System Tray Icon."""
self.trayIcon.hide()
self.trayIcon.deleteLater()
def _change_tab_index(self):
"""Change the tabs of the current TabWidget using alt+numbers."""
widget = QApplication.focusWidget()
shortcut_index = getattr(widget, 'shortcut_index', None)
if shortcut_index:
obj = self.sender()
shortcut_index(obj.index)
def _process_connection(self):
"""Read the ipc input from another instance of ninja."""
connection = self.s_listener.nextPendingConnection()
connection.waitForReadyRead()
data = connection.readAll()
connection.close()
if data:
files, projects = str(data).split(ipc.project_delimiter, 1)
files = [(x.split(':')[0], int(x.split(':')[1]))
for x in files.split(ipc.file_delimiter)]
projects = projects.split(ipc.project_delimiter)
self.load_session_files_projects(files, [], projects, None)
def fullscreen_mode(self):
"""Change to fullscreen mode."""
if self.isFullScreen():
self.showMaximized()
else:
self.showFullScreen()
def change_toolbar_visibility(self):
"""Switch the toolbar visibility"""
if self.toolbar.isVisible():
self.toolbar.hide()
else:
self.toolbar.show()
def load_external_plugins(self, paths):
"""Load external plugins, the ones added to ninja throw the cmd."""
for path in paths:
self.plugin_manager.add_plugin_dir(path)
#load all plugins!
self.plugin_manager.discover()
self.plugin_manager.load_all()
示例6: QtSingleApplication
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class QtSingleApplication(QApplication):
messageReceived = pyqtSignal(str)
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.show()
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)
示例7: MainForm
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
#.........这里部分代码省略.........
def itemClicked(self):
sender = self.sender()
if sender.item.folder:
self.setCurrentItem(sender.item)
self.refresh(False)
else:
flags = ['f', 'F', 'u', 'U', 'd', 'D', 'n', 'N', 'i', 'k', 'v', 'm']
command = sender.item.command
for i in flags:
command = command.replace('%' + i, '')
# %c needs a proper value in some cases
command = command.replace('%c', '"%s"' % sender.item.name)
working = sender.item.working
if not os.path.isdir(working):
working = None
# Need to redirect stdout and stderr so if the process writes something it won't fail
with open(os.path.devnull, 'w') as devnull:
Popen(command + '&', stdout=devnull, stderr=devnull, shell=True, cwd=working)
self.hideOrClose()
def backClicked(self):
if self.currentItem:
self.setCurrentItem(self.currentItem.parent)
self.refresh(False)
def setCurrentItem(self, item):
self.currentItem = item
if item != None:
self.currentLabel.setText(item.name)
if item.parent != None:
self.backButton.setText(item.parent.name)
else:
self.backButton.setText('Favorites')
else:
self.currentLabel.setText('')
self.backButton.setText('Favorites')
def settingsClicked(self):
form = SettingsForm(self)
form.quitCheck.setChecked(self.settings['quit'])
theme = self.settings.get('iconTheme')
if theme:
form.themeCombo.setCurrentIndex(form.themeCombo.findText(theme))
self.holdOpen = True
form.exec_()
self.checkMouse()
self.holdOpen = False
if form.accepted:
self.settings['quit'] = form.quitCheck.isChecked()
def firstRun(self):
QMessageBox.information(self, 'First Time?', 'Your menu is currently empty. It is recommended that you import an existing menu file.')
self.settingsClicked()
def connectToRunning(self):
self.socket = QLocalSocket()
self.socket.connectToServer('nemuSocket')
self.socket.waitForConnected(1000)
if self.socket.state() == QLocalSocket.ConnectedState:
print 'Server found'
if self.socket.waitForReadyRead(3000):
line = self.socket.readLine()
print line
else:
print self.socket.errorString()
sys.exit()
else:
print 'No server running'
def handleConnection(self):
import datetime
print "Got connection", datetime.datetime.now()
connection = self.server.nextPendingConnection()
connection.write('connected')
del connection
self.setCurrentItem(None)
self.filterBox.setText('')
self.refresh(False)
self.show()
print "Showed", datetime.datetime.now()
return
# Call periodically to keep data resident in memory (hopefully)
def keepalive(self):
if self.isHidden():
self.refresh(False)
示例8: IPCServer
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class IPCServer(QObject):
"""IPC server to which clients connect to.
Attributes:
ignored: Whether requests are ignored (in exception hook).
_timer: A timer to handle timeouts.
_server: A QLocalServer to accept new connections.
_socket: The QLocalSocket we're currently connected to.
"""
def __init__(self, parent=None):
"""Start the IPC server and listen to commands."""
super().__init__(parent)
self.ignored = False
self._remove_server()
self._timer = usertypes.Timer(self, 'ipc-timeout')
self._timer.setInterval(READ_TIMEOUT)
self._timer.timeout.connect(self.on_timeout)
self._server = QLocalServer(self)
ok = self._server.listen(SOCKETNAME)
if not ok:
raise IPCError("Error while listening to IPC server: {} "
"(error {})".format(self._server.errorString(),
self._server.serverError()))
self._server.newConnection.connect(self.handle_connection)
self._socket = None
def _remove_server(self):
"""Remove an existing server."""
ok = QLocalServer.removeServer(SOCKETNAME)
if not ok:
raise IPCError("Error while removing server {}!".format(
SOCKETNAME))
@pyqtSlot(int)
def on_error(self, error):
"""Convenience method which calls _socket_error on an error."""
self._timer.stop()
log.ipc.debug("Socket error {}: {}".format(
self._socket.error(), self._socket.errorString()))
if error != QLocalSocket.PeerClosedError:
_socket_error("handling IPC connection", self._socket)
@pyqtSlot()
def handle_connection(self):
"""Handle a new connection to the server."""
if self.ignored:
return
if self._socket is not None:
log.ipc.debug("Got new connection but ignoring it because we're "
"still handling another one.")
return
socket = self._server.nextPendingConnection()
if socket is None:
log.ipc.debug("No new connection to handle.")
return
log.ipc.debug("Client connected.")
self._timer.start()
self._socket = socket
socket.readyRead.connect(self.on_ready_read)
if socket.canReadLine():
log.ipc.debug("We can read a line immediately.")
self.on_ready_read()
socket.error.connect(self.on_error)
if socket.error() not in (QLocalSocket.UnknownSocketError,
QLocalSocket.PeerClosedError):
log.ipc.debug("We got an error immediately.")
self.on_error(socket.error())
socket.disconnected.connect(self.on_disconnected)
if socket.state() == QLocalSocket.UnconnectedState:
log.ipc.debug("Socket was disconnected immediately.")
self.on_disconnected()
@pyqtSlot()
def on_disconnected(self):
"""Clean up socket when the client disconnected."""
log.ipc.debug("Client disconnected.")
self._timer.stop()
self._socket.deleteLater()
self._socket = None
# Maybe another connection is waiting.
self.handle_connection()
@pyqtSlot()
def on_ready_read(self):
"""Read json data from the client."""
if self._socket is None:
# this happened once and I don't know why
log.ipc.warn("In on_ready_read with None socket!")
return
self._timer.start()
while self._socket is not None and self._socket.canReadLine():
data = bytes(self._socket.readLine())
log.ipc.debug("Read from socket: {}".format(data))
try:
decoded = data.decode('utf-8')
except UnicodeDecodeError:
log.ipc.error("Ignoring invalid IPC data.")
log.ipc.debug("invalid data: {}".format(
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class SingleInstance:
def __init__(self, application: QtApplication, files_to_open: Optional[List[str]]) -> None:
self._application = application
self._files_to_open = files_to_open
self._single_instance_server = None
# Starts a client that checks for a single instance server and sends the files that need to opened if the server
# exists. Returns True if the single instance server is found, otherwise False.
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
def startServer(self) -> None:
self._single_instance_server = QLocalServer()
if self._single_instance_server:
self._single_instance_server.newConnection.connect(self._onClientConnected)
self._single_instance_server.listen("ultimaker-cura")
else:
Logger.log("e", "Single instance server was not created.")
def _onClientConnected(self) -> None:
Logger.log("i", "New connection recevied on our single-instance server")
connection = None #type: Optional[QLocalSocket]
if self._single_instance_server:
connection = self._single_instance_server.nextPendingConnection()
if connection is not None:
connection.readyRead.connect(lambda c = connection: self.__readCommands(c))
def __readCommands(self, connection: QLocalSocket) -> None:
line = connection.readLine()
while len(line) != 0: # There is also a .canReadLine()
try:
payload = json.loads(str(line, encoding = "ascii").strip())
command = payload["command"]
# Command: Remove all models from the build plate.
if command == "clear-all":
self._application.callLater(lambda: self._application.deleteAll())
# Command: Load a model file
elif command == "open":
self._application.callLater(lambda f = payload["filePath"]: self._application._openFile(f))
# Command: Activate the window and bring it to the top.
elif command == "focus":
# Operating systems these days prevent windows from moving around by themselves.
# 'alert' or flashing the icon in the taskbar is the best thing we do now.
main_window = self._application.getMainWindow()
if main_window is not None:
self._application.callLater(lambda: main_window.alert(0)) # type: ignore # I don't know why MyPy complains here
# Command: Close the socket connection. We're done.
elif command == "close-connection":
connection.close()
else:
Logger.log("w", "Received an unrecognized command " + str(command))
except json.decoder.JSONDecodeError as ex:
Logger.log("w", "Unable to parse JSON command '%s': %s", line, repr(ex))
line = connection.readLine()
示例10: Eddy
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
#.........这里部分代码省略.........
self.openFile(filepath)
####################################################################################################################
# #
# EVENTS #
# #
####################################################################################################################
def event(self, event):
"""
Executed when an event is received.
:type event: T <= QEvent | QFileOpenEvent
"""
if event.type() == QEvent.FileOpen:
self.pendingOpen = [event.file()]
return True
return super().event(event)
####################################################################################################################
# #
# INTERFACE #
# #
####################################################################################################################
def activate(self):
"""
Activate the application by raising the main window.
"""
if self.mainwindow:
self.mainwindow.setWindowState((self.mainwindow.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive)
self.mainwindow.activateWindow()
self.mainwindow.raise_()
def openFile(self, filepath):
"""
Open the given file in the activation window.
:type filepath: str
:rtype: bool
"""
if self.mainwindow:
if not isEmpty(filepath) and os.path.isfile(filepath) and filepath.endswith(Filetype.Graphol.extension):
self.mainwindow.openFile(filepath)
return True
return False
def sendMessage(self, message):
"""
Send a message to the other alive Eddy's process.
:type message: str
:rtype: bool
"""
if self.outStream:
self.outStream = self.outStream << message << '\n'
self.outStream.flush()
return self.outSocket.waitForBytesWritten()
return False
####################################################################################################################
# #
# SLOTS #
# #
####################################################################################################################
@pyqtSlot()
def newConnection(self):
"""
Executed whenever a message is received.
"""
if self.inSocket:
# Disconnect previously connected signal slot.
disconnect(self.inSocket.readyRead, self.readyRead)
# Create a new socket.
self.inSocket = self.server.nextPendingConnection()
if self.inSocket:
self.inStream = QTextStream(self.inSocket)
self.inStream.setCodec('UTF-8')
connect(self.inSocket.readyRead, self.readyRead)
self.activate()
@pyqtSlot()
def readyRead(self):
"""
Executed whenever we need to read a message.
"""
while True:
message = self.inStream.readLine()
if isEmpty(message):
break
self.messageReceived.emit(message)
@pyqtSlot(str)
def readMessage(self, message):
"""
Read a received message.
:type message: str
"""
for filepath in message.split(' '):
self.openFile(filepath)
示例11: IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
#.........这里部分代码省略.........
# ds = self.data_settings()
# settings.PYTHON_EXEC = ds.value("ide/interpreter")
self.interpreter.load()
@classmethod
def select_current(cls, widget):
"""Show the widget with a 4px lightblue border line."""
widget.setProperty("highlight", True)
widget.style().unpolish(widget)
widget.style().polish(widget)
@classmethod
def unselect_current(cls, widget):
"""Remove the 4px lightblue border line from the widget."""
widget.setProperty("highlight", False)
widget.style().unpolish(widget)
widget.style().polish(widget)
def _close_tray_icon(self):
"""Close the System Tray Icon."""
self.trayIcon.hide()
self.trayIcon.deleteLater()
# def _change_tab_index(self):
# """Change the tabs of the current TabWidget using alt+numbers."""
# widget = QApplication.focusWidget()
# shortcut_index = getattr(widget, 'shortcut_index', None)
# if shortcut_index:
# obj = self.sender()
# shortcut_index(obj.index)
def _process_connection(self):
"""Read the ipc input from another instance of ninja."""
connection = self.s_listener.nextPendingConnection()
connection.waitForReadyRead()
data = connection.readAll()
connection.close()
if data:
files, projects = str(data).split(ipc.project_delimiter, 1)
files = [(x.split(':')[0], int(x.split(':')[1]))
for x in files.split(ipc.file_delimiter)]
projects = projects.split(ipc.project_delimiter)
self.load_session_files_projects(files, [], projects, None)
def fullscreen_mode(self):
"""Change to fullscreen mode."""
if self.isFullScreen():
self.showMaximized()
else:
self.showFullScreen()
def change_toolbar_visibility(self):
"""Switch the toolbar visibility"""
if self.toolbar.isVisible():
self.toolbar.hide()
else:
self.toolbar.show()
def change_toolsdock_visibility(self):
"""Switch the tools dock visibility"""
tools_dock = IDE.get_service("tools_dock").buttons_widget
if tools_dock.isVisible():
tools_dock.hide()
else:
tools_dock.show()
示例12: _s_IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class _s_IDE(QMainWindow):
###############################################################################
# SIGNALS
#
# goingDown()
###############################################################################
goingDown = pyqtSignal()
def __init__(self, start_server=False):
super(_s_IDE, self).__init__()
self.setWindowTitle('NINJA-IDE {Ninja-IDE Is Not Just Another IDE}')
self.setMinimumSize(700, 500)
#Load the size and the position of the main window
self.load_window_geometry()
self.__project_to_open = 0
#Start server if needed
self.s_listener = None
if start_server:
self.s_listener = QLocalServer()
self.s_listener.listen("ninja_ide")
self.s_listener.newConnection.connect(self._process_connection)
#Profile handler
self.profile = None
#Opacity
self.opacity = settings.MAX_OPACITY
#Define Actions object before the UI
self.actions = actions.Actions()
#StatusBar
self.status = status_bar.StatusBar(self)
self.status.hide()
self.setStatusBar(self.status)
#Main Widget - Create first than everything else
self.central = central_widget.CentralWidget(self)
self.load_ui(self.central)
self.setCentralWidget(self.central)
#ToolBar
self.toolbar = QToolBar(self)
self.toolbar.setToolTip(_translate("_s_IDE", "Press and Drag to Move"))
self.toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
self.addToolBar(settings.TOOLBAR_AREA, self.toolbar)
if settings.HIDE_TOOLBAR:
self.toolbar.hide()
#Install Shortcuts after the UI has been initialized
self.actions.install_shortcuts(self)
self.mainContainer.currentTabChanged[str].connect(self.actions.update_explorer)
#Menu
menubar = self.menuBar()
file_ = menubar.addMenu(_translate("_s_IDE", "&File"))
edit = menubar.addMenu(_translate("_s_IDE", "&Edit"))
view = menubar.addMenu(_translate("_s_IDE", "&View"))
source = menubar.addMenu(_translate("_s_IDE", "&Source"))
project = menubar.addMenu(_translate("_s_IDE", "&Project"))
self.pluginsMenu = menubar.addMenu(_translate("_s_IDE", "&Addins"))
about = menubar.addMenu(_translate("_s_IDE", "Abou&t"))
#The order of the icons in the toolbar is defined by this calls
self._menuFile = menu_file.MenuFile(file_, self.toolbar, self)
self._menuView = menu_view.MenuView(view, self.toolbar, self)
self._menuEdit = menu_edit.MenuEdit(edit, self.toolbar)
self._menuSource = menu_source.MenuSource(source)
self._menuProject = menu_project.MenuProject(project, self.toolbar)
self._menuPlugins = menu_plugins.MenuPlugins(self.pluginsMenu)
self._menuAbout = menu_about.MenuAbout(about)
self.load_toolbar()
#Plugin Manager
services = {
'editor': plugin_services.MainService(),
'toolbar': plugin_services.ToolbarService(self.toolbar),
'menuApp': plugin_services.MenuAppService(self.pluginsMenu),
'explorer': plugin_services.ExplorerService(),
'misc': plugin_services.MiscContainerService(self.misc)}
serviceLocator = plugin_manager.ServiceLocator(services)
self.plugin_manager = plugin_manager.PluginManager(resources.PLUGINS,
serviceLocator)
self.plugin_manager.discover()
#load all plugins!
self.plugin_manager.load_all()
#Tray Icon
self.trayIcon = updates.TrayIconUpdates(self)
self.trayIcon.show()
self._menuFile.openFile[str].connect(self.mainContainer.open_file)
self.mainContainer.fileSaved[str].connect(self.show_status_message)
self.mainContainer.recentTabsModified[list].connect(self._menuFile.update_recent_files)#'QStringList'
self.mainContainer.currentTabChanged[str].connect(self.actions.update_migration_tips)
self.mainContainer.updateFileMetadata.connect(self.actions.update_migration_tips)
self.mainContainer.migrationAnalyzed.connect(self.actions.update_migration_tips)
def _process_connection(self):
connection = self.s_listener.nextPendingConnection()
connection.waitForReadyRead()
data = connection.readAll()
#.........这里部分代码省略.........
示例13: SingleApplication
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import nextPendingConnection [as 别名]
class SingleApplication(QtWidgets.QApplication):
'''
Inheriting from QApplication, executing main App instead.
Watching whether the app is already running.
If so, quit befor execution.
'''
messageReceived = QtCore.pyqtSignal(str)
def __init__(self, id, *argv):
super(SingleApplication, self).__init__(*argv)
self._id = id
self._activationWindow = None
self._activateOnMessage = False
# Check if another instance is running?
self._outSocket = 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 = QLocalServer()
self._server.removeServer(self._id) # if existing after crash-exit
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() & ~QtCore.Qt.WindowMinimized)
self._activationWindow.show()
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 = QtCore.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)