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()
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()
def main(): app = QApplication(sys.argv) app.setApplicationVersion("v1.3.1") app.setQuitOnLastWindowClosed(False) socket = QLocalSocket() socket.connectToServer("blender-launcher-server") is_running = socket.waitForConnected() if not is_running: socket.close() BlenderLauncher(app) app.exec_()
def main(): global win signal.signal(signal.SIGINT, exit) args = parse_arguments() appKey = "scudcloud.pid" socket = QLocalSocket() socket.connectToServer(appKey) if socket.isOpen(): socket.close() socket.deleteLater() return 0 socket.deleteLater() app = QtWidgets.QApplication(sys.argv) app.setApplicationName(Resources.APP_NAME + ' Slack') app.setWindowIcon(QtGui.QIcon(Resources.get_path('scudcloud.png'))) try: settings_path, cache_path = load_settings(args.confdir, args.cachedir) except: print("Data directories " + args.confdir + " and " + args.cachedir + " could not be created! Exiting...") raise SystemExit() minimized = True if args.minimized is True else None urgent_hint = True if args.urgent_hint is True else None # Let's move the CSS to cachedir to enable additional actions copyfile(Resources.get_path('resources.css'), os.path.join(cache_path, 'resources.css')) # If there is an qt4 config and not a qt5, let's copy the old one qt4_config = os.path.join(settings_path, 'scudcloud.cfg') qt5_config = os.path.join(settings_path, 'scudcloud_qt5.cfg') if os.path.exists(qt4_config) and not os.path.exists(qt5_config): copyfile(qt4_config, qt5_config) win = sca.ScudCloud(debug=args.debug, minimized=minimized, urgent_hint=urgent_hint, settings_path=settings_path, cache_path=cache_path) app.commitDataRequest.connect(win.setForceClose, type=QtCore.Qt.DirectConnection) server = QLocalServer() server.newConnection.connect(restore) server.listen(appKey) win.restore() if win.minimized is None: win.show() sys.exit(app.exec_())
def main(): if "-update" in sys.argv: platform = get_platform() temp = Path(tempfile.gettempdir()) cwd = Path.cwd() if platform == 'Windows': bl_exe = "Blender Launcher.exe" elif platform == 'Linux': bl_exe = "Blender Launcher" source = (temp / bl_exe).as_posix() dist = (cwd / bl_exe).as_posix() with open(source, 'rb') as f1, open(dist, 'wb') as f2: copyfileobj(f1, f2) if platform == 'Windows': _popen([dist]) elif platform == 'Linux': os.chmod(dist, 0o744) _popen('nohup "' + dist + '"') sys.exit(0) app = QApplication(sys.argv) app.setStyle('Fusion') app.setApplicationVersion(version) app.setQuitOnLastWindowClosed(False) socket = QLocalSocket() socket.connectToServer("blender-launcher-server") is_running = socket.waitForConnected() if not is_running: socket.close() BlenderLauncher(app) app.exec_()
def start(cls, path, image, widget=None, single=False, name=None, above=False, alignment=None, color=None): """ :param path: 客户端路径 :param image: 背景图片 :param widget: 自定义的UI层 :param single: 是否单实例,默认 False :param name: 单实例唯一名 :param above: 是否置顶 :param alignment: 文字对齐位置 :param color: 文本颜色 """ name = cls.getName(name) os.environ['SplashConnectName'] = name # 单实例检测 if single: s = QLocalSocket() s.connectToServer(name) if s.waitForConnected(): # 应用已经启动则退出 s.close() s.deleteLater() print('application is already running') sys.exit(0) app = QApplication(sys.argv) # 启动客户端并将参数传递 QProcess.startDetached(path, sys.argv[1:]) # 显示启动界面 w = SplashScreen(name, image, widget, above) w.setAlignment(alignment) w.setColor(color) w.show() sys.exit(app.exec_())
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()
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)
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)
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)