def write(self, tileset, fileName): file = QSaveFile(fileName) if (not file.open(QIODevice.WriteOnly | QIODevice.Text)): self.mError = self.tr("Could not open file for writing.") return False converter = MapToVariantConverter() variant = converter.toVariant(tileset, QFileInfo(fileName).dir()) writer = json try: result = writer.dumps(variant, indent=4) except: # This can only happen due to coding error self.mError = self.tr('Unknow error.') return False out = QTextStream(file) out << result out.flush() if (file.error() != QFile.NoError): self.mError = self.tr("Error while writing file:\n%1").arg(file.errorString()) return False if (not file.commit()): self.mError = file.errorString() return False return True
def save_qss(out_file: str, qss: str): flqss = QFile(out_file) flqss.open(QFile.WriteOnly) stream = QTextStream(flqss) stream << qss stream.flush() flqss.close()
def save(self, data, path=None): if path: self.filename = path self.is_new = False _file = QFile(self.filename) if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate): raise Exception(_file.errorString()) stream = QTextStream(_file) stream.setCodec(QTextCodec.codecForLocale()) stream << data stream.flush() _file.close() # Emit the signal self.fileSaved.emit(self.filename)
def save(self, data, path=None): if path: self.filename = path self.is_new = False _file = QFile(self.filename) if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate): raise Exception(_file.errorString()) stream = QTextStream(_file) stream.setCodec(QTextCodec.codecForLocale()) stream << data stream.flush() _file.close() # Emit the signal self.fileSaved.emit(self.filename)
def write(self, map, fileName): file = QSaveFile(fileName) if (not file.open(QIODevice.WriteOnly | QIODevice.Text)) : self.mError = self.tr("Could not open file for writing.") return False converter = MapToVariantConverter() variant = converter.toVariant(map, QFileInfo(fileName).dir()) writer = json try: result = writer.dumps(variant, indent=4) except: # This can only happen due to coding error self.mError = self.tr('Unknow error.') return False out = QTextStream(file) if self.mSubFormat == JsonMapFormat.SubFormat.JavaScript: # Trim and escape name nameWriter = json baseName = QFileInfo(fileName).baseName() baseNameResult = nameWriter.dumps(baseName) out << "(function(name,data){\n if(typeof onTileMapLoaded === 'undefined') {\n" out << " if(typeof TileMaps === 'undefined') TileMaps = {};\n" out << " TileMaps[name] = data;\n" out << " } else {\n" out << " onTileMapLoaded(name,data);\n" out << " }})(" + baseNameResult + ",\n" out << result if self.mSubFormat == JsonMapFormat.SubFormat.JavaScript: out << ");" out.flush() if (file.error() != QFile.NoError) : self.mError = self.tr("Error while writing file:\n%1").arg(file.errorString()) return False if (not file.commit()) : self.mError = file.errorString() return False return True
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() def _on_ready_read(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
class QtSingleApplication(QApplication): """ Adapted from https://stackoverflow.com/a/12712362/11038610 Published by Johan Rade under 2-clause BSD license, opensource.org/licenses/BSD-2-Clause """ message_received_event = pyqtSignal(str) def __init__(self, id, *argv): super().__init__(*argv) self._id = id # 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.removeServer(self._id) self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) def isRunning(self): return self._isRunning def id(self): return self._id 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) def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.message_received_event.emit(msg)
class SingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, appid, *argv): super(SingleApplication, self).__init__(*argv) self._appid = appid self._activationWindow = None self._activateOnMessage = False self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._appid) self._isRunning = self._outSocket.waitForConnected() self._outStream = None self._inSocket = None self._inStream = None self._server = None self.settings = QSettings(SingleApplication.getSettingsPath(), QSettings.IniFormat) self.singleInstance = self.settings.value('singleInstance', 'on', type=str) in {'on', 'true'} if self._isRunning and self.singleInstance: self._outStream = QTextStream(self._outSocket) for a in argv[0][1:]: a = os.path.join(os.getcwd(), a) if os.path.isfile(a): self.sendMessage(a) break sys.exit(0) else: error = self._outSocket.error() if error == QLocalSocket.ConnectionRefusedError: self.close() QLocalServer.removeServer(self._appid) self._outSocket = None self._server = QLocalServer() self._server.listen(self._appid) self._server.newConnection.connect(self._onNewConnection) def close(self): if self._inSocket: self._inSocket.disconnectFromServer() if self._outSocket: self._outSocket.disconnectFromServer() if self._server: self._server.close() @staticmethod def getSettingsPath() -> str: if sys.platform == 'win32': settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local', 'vidcutter') elif sys.platform == 'darwin': settings_path = os.path.join(QDir.homePath(), 'Library', 'Preferences', 'vidcutter') else: if QFileInfo(__file__).absolutePath().startswith('/app/'): settings_path = QProcessEnvironment.systemEnvironment().value( 'XDG_CONFIG_HOME', '') if not len(settings_path): settings_path = os.path.join(QDir.homePath(), '.var', 'app', vidcutter.__desktopid__, 'config') else: settings_path = os.path.join(QDir.homePath(), '.config', 'vidcutter') return os.path.join(settings_path, 'vidcutter.ini') def isRunning(self): return self._isRunning def appid(self): return self._appid 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, msg): if not self._outStream: return False # noinspection PyUnresolvedReferences 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._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)
class QtSingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, _id, _viewer_id, *argv): super(QtSingleApplication, self).__init__(*argv) self._id = _id self._viewer_id = _viewer_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(-1) if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') # Is there another viewer runnging? self._outSocketViewer = QLocalSocket() self._outSocketViewer.connectToServer(self._viewer_id) self._isRunningViewer = self._outSocketViewer.waitForConnected(-1) if self._isRunningViewer: self._outStreamViewer = QTextStream(self._outSocketViewer) self._outStreamViewer.setCodec('UTF-8') else: # app is running, we announce us as viewer app # First we remove existing servers of that name that might not have been properly closed as the server died QLocalServer.removeServer(self._viewer_id) self._outSocketViewer = None self._outStreamViewer = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._viewer_id) self._server.newConnection.connect(self._onNewConnection) else: self._isRunningViewer = False # No, there isn't. # First we remove existing servers of that name that might not have been properly closed as the server died QLocalServer.removeServer(self._id) 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 isRunningViewer(self): return self._isRunningViewer 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() @pyqtSlot() 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 and self._isRunning: self.activateWindow() @pyqtSlot() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
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(str) 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() def _on_ready_read(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
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)
class QtSingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, _id, _viewer_id, *argv): if sys.platform.startswith( "darwin") and mp.current_process().name == "WebLCDs": import AppKit info = AppKit.NSBundle.mainBundle().infoDictionary( ) # @UndefinedVariable info["LSBackgroundOnly"] = "1" super(QtSingleApplication, self).__init__(*argv) self._id = _id self._viewer_id = _viewer_id self._activationWindow = None self._activateOnMessage = False self._outSocket = None self._isRunning = False self._server = None # we exclude the WebLCDs parallel process from participating any Artisan inter-app communication if mp.current_process().name != "WebLCDs": # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected(-1) if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') # Is there another viewer running? self._outSocketViewer = QLocalSocket() self._outSocketViewer.connectToServer(self._viewer_id) self._isRunningViewer = self._outSocketViewer.waitForConnected( -1) if self._isRunningViewer: self._outStreamViewer = QTextStream(self._outSocketViewer) self._outStreamViewer.setCodec('UTF-8') else: # app is running, we announce us as viewer app # First we remove existing servers of that name that might not have been properly closed as the server died QLocalServer.removeServer(self._viewer_id) self._outSocketViewer = None self._outStreamViewer = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._viewer_id) self._server.newConnection.connect(self._onNewConnection) else: self._isRunningViewer = False # No, there isn't. # First we remove existing servers of that name that might not have been properly closed as the server died QLocalServer.removeServer(self._id) 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 isRunningViewer(self): return self._isRunningViewer 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() @pyqtSlot() 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 and self._isRunning: self.activateWindow() @pyqtSlot() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
class LogsReadThread(QThread): MAX_INITIAL_SIZE = 2*1024*1024 # 2Mb updateLogs = pyqtSignal() def __init__(self, parent): QThread.__init__(self, parent) self.fCloseNow = False self.fPurgeLogs = False self.fRealParent = parent # ------------------------------------------------------------- # Take some values from Logs Window self.LOG_FILE_JACK = LogsW.LOG_FILE_JACK self.LOG_FILE_A2J = LogsW.LOG_FILE_A2J self.LOG_FILE_LASH = LogsW.LOG_FILE_LASH self.LOG_FILE_LADISH = LogsW.LOG_FILE_LADISH # ------------------------------------------------------------- # Init logs if self.LOG_FILE_JACK is not None: self.fLogFileJACK = QFile(self.LOG_FILE_JACK) self.fLogFileJACK.open(QIODevice.ReadOnly) self.fLogStreamJACK = QTextStream(self.fLogFileJACK) self.fLogStreamJACK.setCodec("UTF-8") if self.fLogFileJACK.size() > self.MAX_INITIAL_SIZE: self.fLogStreamJACK.seek(self.fLogFileJACK.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_A2J is not None: self.fLogFileA2J = QFile(self.LOG_FILE_A2J) self.fLogFileA2J.open(QIODevice.ReadOnly) self.fLogStreamA2J = QTextStream(self.fLogFileA2J) self.fLogStreamA2J.setCodec("UTF-8") if self.fLogFileA2J.size() > self.MAX_INITIAL_SIZE: self.fLogStreamA2J.seek(self.fLogFileA2J.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_LASH is not None: self.fLogFileLASH = QFile(self.LOG_FILE_LASH) self.fLogFileLASH.open(QIODevice.ReadOnly) self.fLogStreamLASH = QTextStream(self.fLogFileLASH) self.fLogStreamLASH.setCodec("UTF-8") if self.fLogFileLASH.size() > self.MAX_INITIAL_SIZE: self.fLogStreamLASH.seek(self.fLogFileLASH.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_LADISH is not None: self.fLogFileLADISH = QFile(self.LOG_FILE_LADISH) self.fLogFileLADISH.open(QIODevice.ReadOnly) self.fLogStreamLADISH = QTextStream(self.fLogFileLADISH) self.fLogStreamLADISH.setCodec("UTF-8") if self.fLogFileLADISH.size() > self.MAX_INITIAL_SIZE: self.fLogStreamLADISH.seek(self.fLogFileLADISH.size() - self.MAX_INITIAL_SIZE) def closeNow(self): self.fCloseNow = True def purgeLogs(self): self.fPurgeLogs = True def run(self): # ------------------------------------------------------------- # Read logs and set text in main thread while not self.fCloseNow: if self.fPurgeLogs: if self.LOG_FILE_JACK: self.fLogStreamJACK.flush() self.fLogFileJACK.close() self.fLogFileJACK.open(QIODevice.WriteOnly) self.fLogFileJACK.close() self.fLogFileJACK.open(QIODevice.ReadOnly) if self.LOG_FILE_A2J: self.fLogStreamA2J.flush() self.fLogFileA2J.close() self.fLogFileA2J.open(QIODevice.WriteOnly) self.fLogFileA2J.close() self.fLogFileA2J.open(QIODevice.ReadOnly) if self.LOG_FILE_LASH: self.fLogStreamLASH.flush() self.fLogFileLASH.close() self.fLogFileLASH.open(QIODevice.WriteOnly) self.fLogFileLASH.close() self.fLogFileLASH.open(QIODevice.ReadOnly) if self.LOG_FILE_LADISH: self.fLogStreamLADISH.flush() self.fLogFileLADISH.close() self.fLogFileLADISH.open(QIODevice.WriteOnly) self.fLogFileLADISH.close() self.fLogFileLADISH.open(QIODevice.ReadOnly) self.fPurgeLogs = False else: if self.LOG_FILE_JACK: textJACK = fixLogText(self.fLogStreamJACK.readAll()).strip() else: textJACK = "" if self.LOG_FILE_A2J: textA2J = fixLogText(self.fLogStreamA2J.readAll()).strip() else: textA2J = "" if self.LOG_FILE_LASH: textLASH = fixLogText(self.fLogStreamLASH.readAll()).strip() else: textLASH = "" if self.LOG_FILE_LADISH: textLADISH = fixLogText(self.fLogStreamLADISH.readAll()).strip() else: textLADISH = "" self.fRealParent.setLogsText(textJACK, textA2J, textLASH, textLADISH) self.updateLogs.emit() if not self.fCloseNow: self.sleep(1) # ------------------------------------------------------------- # Close logs before closing thread if self.LOG_FILE_JACK: self.fLogFileJACK.close() if self.LOG_FILE_A2J: self.fLogFileA2J.close() if self.LOG_FILE_LASH: self.fLogFileLASH.close() if self.LOG_FILE_LADISH: self.fLogFileLADISH.close()
class QtSingleApplication(QApplication): unhandledExceptionCaught = pyqtSignal(QVariant, QVariant, QVariant, arguments=["except_type", "except_value", "traceback_obj"]) messageReceived = pyqtSignal(str) def __init__(self, id, *argv): super().__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.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)
class QtSingleApplication(QApplication): """ Adapted from https://stackoverflow.com/a/12712362/11038610 Copyright 2013 Johan Råde Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ message_received_event = pyqtSignal(str) def __init__(self, id, *argv): super().__init__(*argv) self._id = id # 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.removeServer(self._id) self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) def isRunning(self): return self._isRunning def id(self): return self._id 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) def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.message_received_event.emit(msg)
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) #################################################################################################################### # # # 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)
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) #################################################################################################################### # # # 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)
class QtSingleApplication(QApplication): """QApplication que permite solo una instancia de la aplicación. """ 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.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' # pylint: disable=W0104 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)