本文整理汇总了Python中PyQt5.QtNetwork.QLocalServer.listen方法的典型用法代码示例。如果您正苦于以下问题:Python QLocalServer.listen方法的具体用法?Python QLocalServer.listen怎么用?Python QLocalServer.listen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtNetwork.QLocalServer
的用法示例。
在下文中一共展示了QLocalServer.listen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_nxdrive_listener
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
def init_nxdrive_listener(self) -> None:
"""
Set up a QLocalServer to listen to nxdrive protocol calls.
On Windows, when an nxdrive:// URL is opened, it creates a new
instance of Nuxeo Drive. As we want the already running instance to
receive this call (particularly during the login process), we set
up a QLocalServer in that instance to listen to the new ones who will
send their data.
The Qt implementation of QLocalSocket on Windows makes use of named
pipes. We just need to connect a handler to the newConnection signal
to process the URLs.
"""
named_pipe = f"{BUNDLE_IDENTIFIER}.protocol.{os.getpid()}"
server = QLocalServer()
server.setSocketOptions(QLocalServer.WorldAccessOption)
server.newConnection.connect(self._handle_connection)
try:
server.listen(named_pipe)
log.info(f"Listening for nxdrive:// calls on {server.fullServerName()}")
except:
log.info(
f"Unable to start local server on {named_pipe}: {server.errorString()}"
)
self._nxdrive_listener = server
self.aboutToQuit.connect(self._nxdrive_listener.close)
示例2: init
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
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
示例3: Server
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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()
示例4: test_socket_options_address_in_use_problem
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
def test_socket_options_address_in_use_problem(qlocalserver, short_tmpdir):
"""Qt seems to ignore AddressInUseError when using socketOptions.
With this test we verify this bug still exists. If it fails, we can
probably start using setSocketOptions again.
"""
servername = str(short_tmpdir / 'x')
s1 = QLocalServer()
ok = s1.listen(servername)
assert ok
s2 = QLocalServer()
s2.setSocketOptions(QLocalServer.UserAccessOption)
ok = s2.listen(servername)
print(s2.errorString())
# We actually would expect ok == False here - but we want the test to fail
# when the Qt bug is fixed.
assert ok
示例5: Server
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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)
示例6: IPCServer
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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.
_socketname: The socketname to use.
_socketopts_ok: Set if using setSocketOptions is working with this
OS/Qt version.
_atime_timer: Timer to update the atime of the socket regularly.
Signals:
got_args: Emitted when there was an IPC connection and arguments were
passed.
got_args: Emitted with the raw data an IPC connection got.
got_invalid_data: Emitted when there was invalid incoming data.
"""
got_args = pyqtSignal(list, str, str)
got_raw = pyqtSignal(bytes)
got_invalid_data = pyqtSignal()
def __init__(self, socketname, parent=None):
"""Start the IPC server and listen to commands.
Args:
socketname: The socketname to use.
parent: The parent to be used.
"""
super().__init__(parent)
self.ignored = False
self._socketname = socketname
self._timer = usertypes.Timer(self, "ipc-timeout")
self._timer.setInterval(READ_TIMEOUT)
self._timer.timeout.connect(self.on_timeout)
if os.name == "nt": # pragma: no coverage
self._atime_timer = None
else:
self._atime_timer = usertypes.Timer(self, "ipc-atime")
self._atime_timer.setInterval(ATIME_INTERVAL)
self._atime_timer.timeout.connect(self.update_atime)
self._atime_timer.setTimerType(Qt.VeryCoarseTimer)
self._server = QLocalServer(self)
self._server.newConnection.connect(self.handle_connection)
self._socket = None
self._socketopts_ok = os.name == "nt"
if self._socketopts_ok: # pragma: no cover
# If we use setSocketOptions on Unix with Qt < 5.4, we get a
# NameError while listening...
log.ipc.debug("Calling setSocketOptions")
self._server.setSocketOptions(QLocalServer.UserAccessOption)
else: # pragma: no cover
log.ipc.debug("Not calling setSocketOptions")
def _remove_server(self):
"""Remove an existing server."""
ok = QLocalServer.removeServer(self._socketname)
if not ok:
raise Error("Error while removing server {}!".format(self._socketname))
def listen(self):
"""Start listening on self._socketname."""
log.ipc.debug("Listening as {}".format(self._socketname))
if self._atime_timer is not None: # pragma: no branch
self._atime_timer.start()
self._remove_server()
ok = self._server.listen(self._socketname)
if not ok:
if self._server.serverError() == QAbstractSocket.AddressInUseError:
raise AddressInUseError(self._server)
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:
#.........这里部分代码省略.........
示例7: QtSingleApplication
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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()
#.........这里部分代码省略.........
示例8: IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
#.........这里部分代码省略.........
'signal_name': 'openPreferences',#()
'slot': self.show_preferences},
{'target': 'main_container',
'signal_name': 'allTabsClosed',#()
'slot': self._last_tab_closed},
{'target': 'explorer_container',
'signal_name': 'changeWindowTitle',#(QString)
'slot': self.change_window_title},
{'target': 'explorer_container',
'signal_name': 'projectClosed',#(QString)
'slot': self.close_project},
)
self.register_signals('ide', connections)
# Central Widget MUST always exists
self.central = IDE.get_service('central_container')
print("self.central:", self.central)
self.setCentralWidget(self.central)
# Install Services
for service_name in self.__IDESERVICES:
self.install_service(service_name)
IDE.__created = True
# Place Status Bar
main_container = IDE.get_service('main_container')
status_bar = IDE.get_service('status_bar')
main_container.add_status_bar(status_bar)
# Load Menu Bar
menu_bar = IDE.get_service('menu_bar')
if menu_bar:
menu_bar.load_menu(self)
#These two are the same service, I think that's ok
menu_bar.load_toolbar(self)
#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)
@classmethod
def hasCreated(clss):
return clss.__created
@classmethod
def getInstance(clss):
return clss.__instance
@classmethod
def get_service(cls, service_name):
"""Return the instance of a registered service."""
return cls.__IDESERVICES.get(service_name, None)
def get_menuitems(self):
"""Return a dictionary with the registered menu items."""
return IDE.__IDEMENUS
def get_bar_categories(self):
"""Get the registered Categories for the Application menus."""
return IDE.__IDEBARCATEGORIES
def get_toolbaritems(self):
"""Return a dictionary with the registered menu items."""
return IDE.__IDETOOLBAR
@classmethod
示例9: QtSingleApplication
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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)
示例10: IPCServer
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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(
#.........这里部分代码省略.........
示例11: MainForm
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
class MainForm(QDialog):
def __init__(self, parent = None):
QDialog.__init__(self, parent)
# If a Nemu instance is already running, this is as far as we go
self.connectToRunning()
self.holdOpen = False
self.menuItems = []
self.allItems = []
self.favorites = []
self.currentItem = None
self.menuFile = os.path.expanduser('~/.nemu/menu')
self.favoritesFile = os.path.expanduser('~/.nemu/favorites')
# NOTE: If you change this, also update migrate-settings
self.settingsFile = os.path.expanduser('~/.nemu/settings')
self.initSettings()
self.server = QLocalServer()
self.server.newConnection.connect(self.handleConnection)
QLocalServer.removeServer('nemuSocket')
self.server.listen('nemuSocket')
self.configDir = os.path.expanduser('~/.nemu')
if not os.path.isdir(self.configDir):
os.mkdir(self.configDir)
self.menuItems = self.loadConfig(self.menuFile, self.menuItems)
self.favorites = self.loadConfig(self.favoritesFile, self.favorites)
# Don't load directly into self.settings so we can add new default values as needed
try:
tempSettings = self.loadConfig(self.settingsFile, self.settings)
for key, value in tempSettings.items():
self.settings[key] = value
except SystemError:
print('ERROR: Failed to load settings. You may need to run migrate-settings.')
raise
# This should never happen, but unfortunately bugs do, so clean up orphaned items.
# We need to do this because these items won't show up in the UI, but may interfere with
# merges if they duplicate something that is being merged in.
self.menuItems[:] = [i for i in self.menuItems if i.parent == None or i.parent in self.menuItems]
# Look for broken icon paths
needSave = False
for i in self.menuItems + self.favorites:
if not os.path.exists(i.icon):
i.findIcon()
needSave = True
if needSave:
self.saveMenu()
for i in self.menuItems:
if not hasattr(i, 'imported'):
i.imported = False
self.setupUI()
self.setContextMenuPolicy(Qt.ActionsContextMenu)
self.createMenu(self)
self.refresh(False)
if len(self.menuItems) == 0:
self.firstRun()
self.show()
self.keepaliveTimer = QTimer(self)
self.keepaliveTimer.timeout.connect(self.keepalive)
self.keepaliveTimer.start(60000)
def initSettings(self):
self.settings = dict()
self.settings['width'] = 400
self.settings['height'] = 400
self.settings['quit'] = False
self.settings['imported'] = []
self.settings['iconTheme'] = None
def loadConfig(self, filename, default):
if os.path.exists(filename):
with open(filename, 'rb') as f:
data = f.read().replace('PyQt4', 'PyQt5')
return cPickle.loads(data)
else:
return default
def setupUI(self):
self.resize(self.settings['width'], self.settings['height'])
self.setWindowFlags(Qt.FramelessWindowHint | Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint)
#self.setWindowFlags(Qt.X11BypassWindowManagerHint)
self.setWindowTitle('Nemu')
self.setMouseTracking(True)
iconPath = os.path.join(os.path.dirname(__file__), 'images')
iconPath = os.path.join(iconPath, 'nemu.png')
self.setWindowIcon(IconCache()[iconPath])
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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()
示例13: Eddy
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
class Eddy(QApplication):
"""
This class implements the main Qt application.
"""
messageReceived = pyqtSignal(str)
def __init__(self, argv):
"""
Initialize Eddy.
:type argv: list
"""
super().__init__(argv)
parser = ArgumentParser()
parser.add_argument('--nosplash', dest='nosplash', action='store_true')
parser.add_argument('--tests', dest='tests', action='store_true')
options, args = parser.parse_known_args(args=argv)
self.inSocket = None
self.inStream = None
self.outSocket = QLocalSocket()
self.outSocket.connectToServer(APPID)
self.outStream = None
self.isRunning = self.outSocket.waitForConnected()
self.mainwindow = None
self.pendingOpen = []
self.server = None
# We do not initialize a new instance of Eddy if there is a process running
# and we are not executing the tests suite: we'll create a socket instead so we can
# exchange messages between the 2 processes (this one and the already running one).
if self.isRunning and not options.tests:
self.outStream = QTextStream(self.outSocket)
self.outStream.setCodec('UTF-8')
else:
self.server = QLocalServer()
self.server.listen(APPID)
self.outSocket = None
self.outStream = None
connect(self.server.newConnection, self.newConnection)
connect(self.messageReceived, self.readMessage)
############################################################################################################
# #
# PERFORM EDDY INITIALIZATION #
# #
############################################################################################################
# Draw the splashscreen.
self.splashscreen = None
if not options.nosplash:
self.splashscreen = SplashScreen(min_splash_time=4)
self.splashscreen.show()
# Setup layout.
self.setStyle(Clean('Fusion'))
with open(expandPath('@eddy/ui/clean.qss')) as sheet:
self.setStyleSheet(sheet.read())
# Create the main window.
self.mainwindow = MainWindow()
# Close the splashscreen.
if self.splashscreen:
self.splashscreen.wait(self.splashscreen.remaining)
self.splashscreen.close()
# Display the mainwindow.
self.mainwindow.show()
if Platform.identify() is Platform.Darwin:
# On MacOS files being opened are handled as a QFileOpenEvent but since we don't
# have a Main Window initialized we store them locally and we open them here.
for filepath in self.pendingOpen:
self.openFile(filepath)
self.pendingOpen = []
else:
# Perform document opening if files have been added to sys.argv. This is not
# executed on Mac OS since this is already handled as a QFileOpenEvent instance.
for filepath in argv:
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)
#.........这里部分代码省略.........
示例14: IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [as 别名]
#.........这里部分代码省略.........
# connections = (
# {'target': 'main_container',
# 'signal_name': 'openPreferences()',
# 'slot': self.show_preferences},
# {'target': 'main_container',
# 'signal_name': 'allTabsClosed()',
# 'slot': self._last_tab_closed},
# {'target': 'explorer_container',
# 'signal_name': 'changeWindowTitle(QString)',
# 'slot': self.change_window_title},
# {'target': 'explorer_container',
# 'signal_name': 'projectClosed(QString)',
# 'slot': self.close_project},
# )
# Central Widget MUST always exists
self.central = IDE.get_service('central_container')
self.setCentralWidget(self.central)
# Install Services
for service_name in self.__IDESERVICES:
self.install_service(service_name)
IDE.__created = True
# Place Status Bar
main_container = IDE.get_service('main_container')
status_bar = IDE.get_service('status_bar')
main_container.add_status_bar(status_bar)
# Load Menu Bar
menu_bar = IDE.get_service('menu_bar')
if menu_bar:
# These two are the same service, I think that's ok
menu_bar.load_menu(self)
menu_bar.load_toolbar(self)
# 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)
# Load interpreters
self.load_interpreters()
IDE.__instance = self
def _change_item_in_project(self, filename):
project_explorer = IDE.get_service("projects_explorer")
if project_explorer is not None:
project_explorer.set_current_item(filename)
@classmethod
def get_service(cls, service_name):
"""Return the instance of a registered service."""
service = cls.__IDESERVICES.get(service_name, None)
if service is None:
logger.debug("Service '{}' unregistered".format(service_name))
return service
def get_menuitems(self):
"""Return a dictionary with the registered menu items."""
return IDE.__IDEMENUS #
def get_bar_categories(self):
"""Get the registered Categories for the Application menus."""
return IDE.__IDEBARCATEGORIES
示例15: _s_IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import listen [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()
#.........这里部分代码省略.........