def save(self): if self.filename.startsWith("Unnamed"): filename = QFileDialog.getSaveFileName(self, "Text Editor -- Save File As", self.filename, "Text files (*.txt *.*)") if filename.isEmpty(): return self.filename = filename self.setWindowTitle(QFileInfo(self.filename).fileName()) exception = None fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) except EnvironmentError as e: exception = e finally: if fh is not None: fh.close() if exception is not None: raise exception
def exportXml(self, fname): error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='{0}'?>\n" "<!DOCTYPE MOVIES>\n" "<MOVIES VERSION='1.0'>\n".format(CODEC)) for key, movie in self.__movies: stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' " "ACQUIRED='{2}'>\n".format(movie.year, movie.minutes, movie.acquired.toString(Qt.ISODate))) \ << "<TITLE>" << Qt.escape(movie.title) \ << "</TITLE>\n<NOTES>" if not movie.notes.isEmpty(): stream << "\n" << Qt.escape( encodedNewlines(movie.notes)) stream << "\n</NOTES>\n</MOVIE>\n" stream << "</MOVIES>\n" except EnvironmentError as e: error = "Failed to export: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Exported {0} movie records to {1}".format( len(self.__movies), QFileInfo(fname).fileName())
def save(self, new): fh = QFile("tools/" + self.name + ".tool") if new and fh.exists(): return False if fh.open(QIODevice.WriteOnly): stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='%s'?>\n<!DOCTYPE TOOL>\n<TOOL\n" % CODEC) stream << ( "TIPDIAM='%s'\nSYRDIAM='%s'\nPATHWIDTH='%s'\nPATHHEIGHT='%s'\nJOGSPEED='%s'\nSUCKBACK='%s'\nPUSHOUT='%s'\n" "PATHSPEED='%s'\nPAUSEPATHS='%s'\nCLEARANCE='%s'\nDEPOSITIONRATE='%s'\n>" % ( self.tipDiam, self.syrDiam, self.pathWidth, self.pathHeight, self.jogSpeed, self.suckback, self.pushout, self.pathSpeed, self.pausePaths, self.clearance, self.depRate, ) ) stream << ("\n</TOOL>") fh.close() return True
def save(self, content, path=None): """ Write a temprorary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File #FIXME: Where to locate addExtension, does not fit here """ new_path = False if path: self.attach_to_path(path) new_path = True save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = "%s.nsp" % save_path # If we have a file system watcher, remove the file path # from its watch list until we are done making changes. if self.__watcher: self.__watcher.removePath(save_path) flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() #SIGNAL: Will save (temp, definitive) to warn folder to do something self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path, save_path) self.__mtime = os.path.getmtime(swap_save_path) shutil.move(swap_save_path, save_path) self.reset_state() # If we have a file system watcher, add the saved path back # to its watch list, otherwise create a watcher and start # watching if self.__watcher: if new_path: self.__watcher.removePath(self.__watcher.files()[0]) self.__watcher.addPath(self._file_path) else: self.__watcher.addPath(save_path) else: self.start_watching() return self
def exportXml(self, fname): error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='{0}'?>\n" "<!DOCTYPE MOVIES>\n" "<MOVIES VERSION='1.0'>\n".format(CODEC)) for key, movie in self.__movies: stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' " "ACQUIRED='{2}'>\n".format(movie.year, movie.minutes, movie.acquired.toString(Qt.ISODate))) \ << "<TITLE>" << Qt.escape(movie.title) \ << "</TITLE>\n<NOTES>" if not movie.notes.isEmpty(): stream << "\n" << Qt.escape(encodedNewlines(movie.notes)) stream << "\n</NOTES>\n</MOVIE>\n" stream << "</MOVIES>\n" except EnvironmentError as e: error = "Failed to export: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Exported {0} movie records to {1}".format( len(self.__movies), QFileInfo(fname).fileName())
def save(self): """Hum ... just save ...""" if self.filename.startswith("Unnamed"): filename = self.parent().parent().parent().saveAsFile() if not (filename == ''): return self.filename = filename self.setWindowTitle(QFileInfo(self.filename).fileName()) exception = None filehandle = None try: #Before FileSave plugin hook for plugin in filter_plugins_by_capability('beforeFileSave', self.enabled_plugins): plugin.do_beforeFileSave(self) filehandle = QFile(self.filename) if not filehandle.open(QIODevice.WriteOnly): raise IOError, unicode(filehandle.errorString()) stream = QTextStream(filehandle) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) RecentFiles().append(self.filename) except (IOError, OSError), ioError: exception = ioError
def saveQTextStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) for key, movie in self.__movies: stream << "{{MOVIE}} " << movie.title << "\n" \ << movie.year << " " << movie.minutes << " " \ << movie.acquired.toString(Qt.ISODate) \ << "\n{NOTES}" if not movie.notes.isEmpty(): stream << "\n" << movie.notes stream << "\n{{ENDMOVIE}}\n" except EnvironmentError as e: error = "Failed to save: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Saved {0} movie records to {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def save_file(self): """ Saving file to the path where getting from QFileDialog """ fileobject = None if self.path is "": self.path = QFileDialog.getSaveFileName(self, "TextEditor", self.tr("unnamed")) try: fileobject = QFile(self.path) if not fileobject.open(QIODevice.WriteOnly): raise IOError, unicode(fileobject.errorString()) textstream = QTextStream(fileobject) textstream.setCodec("UTF-8") textstream << self.textEdit.toPlainText() self.textEdit.document().setModified(False) self.setWindowTitle("%s - TextEditor" % QFileInfo(self.path).fileName()) except (IOError, OSError), error: QMessageBox.warning(self, self.tr("TextEditor - Save Error"), self.tr("Unable to save {0}:{1}".format( self.path, error))) self.path = ""
def save(self): """Hum ... just save ...""" if self.filename.startswith("Unnamed"): filename = self.parent().parent().parent().saveAsFile() if not (filename == ''): return self.filename = filename self.setWindowTitle( QFileInfo(self.filename).fileName()) exception = None filehandle = None try: #Before FileSave plugin hook for plugin in filter_plugins_by_capability('beforeFileSave',self.enabled_plugins): plugin.do_beforeFileSave(self) filehandle = QFile(self.filename) if not filehandle.open( QIODevice.WriteOnly): raise IOError, unicode(filehandle.errorString()) stream = QTextStream(filehandle) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) RecentFiles().append(self.filename) except (IOError, OSError), ioError: exception = ioError
def load(self): exception = None fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QTextStream(fh) stream.setCodec("UTF-8") self.setPlainText(stream.readAll()) self.document().setModified(False) except (IOError, OSError), e: exception = e
def save(self, content, path=None): """ Write a temprorary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File #FIXME: Where to locate addExtension, does not fit here """ if path and self._file_path: created_file = NFile(path).save(content) self.emit(SIGNAL("savedAsNewFile(PyQt_PyObject, QString, QString)"), created_file, self._file_path, path) return created_file elif path and not self._file_path: self.attach_to_path(path) save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = u"%s.nsp" % save_path flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() #SIGNAL: Will save (temp, definitive) to warn folder to do something self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path, save_path) shutil.move(swap_save_path, save_path) self.reset_state() return self
def load(self): exception = None fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") self.setPlainText(stream.readAll()) self.document().setModified(False) except EnvironmentError as e: exception = e finally: if fh is not None: fh.close() if exception is not None: raise exception
def __init__(self, parent=None ): super(helpDisplay, self).__init__(parent) # make page unmodifiable self.page().setContentEditable(False) # initialize settings # Find out the nearest font to Palatino qf = QFont() qf.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch) qf.setStyleHint(QFont.Serif) qf.setFamily(QString(u'Palatino')) qfi = QFontInfo(qf) # set the default font to that serif font self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family()) self.settings().setFontSize(QWebSettings.DefaultFontSize, 16) self.settings().setFontSize(QWebSettings.MinimumFontSize, 6) self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6) self.textZoomFactor = 1.0 self.setTextSizeMultiplier(self.textZoomFactor) self.settings().setAttribute(QWebSettings.JavascriptEnabled, False) self.settings().setAttribute(QWebSettings.JavaEnabled, False) self.settings().setAttribute(QWebSettings.PluginsEnabled, False) self.settings().setAttribute(QWebSettings.ZoomTextOnly, True) #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False) self.userFindText = QString() # Look for pqHelp.html in the app folder and copy its text into # a local buffer. If it isn't found, put a message there instead. # We need to keep it in order to implement the "back" function. helpPath = os.path.join(IMC.appBasePath,u'pqHelp.html') helpFile = QFile(helpPath) if not helpFile.exists(): self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p> <p>Looking in {0}'''.format(helpPath) ) elif not helpFile.open(QIODevice.ReadOnly) : self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p> <p>Looking in {0}</p><p>Error code {1}</p>'''.format(helpPath, helpFile.error()) ) else: helpStream = QTextStream(helpFile) helpStream.setCodec('ISO8859-1') self.HTMLstring = helpStream.readAll() self.setHtml(self.HTMLstring)
def load(self): """Load ?""" exception = None filehandle = None try: filehandle = QFile(self.filename) if not filehandle.open( QIODevice.ReadOnly): raise IOError, unicode(filehandle.errorString()) stream = QTextStream(filehandle) stream.setCodec("UTF-8") QApplication.processEvents() self.setPlainText(stream.readAll()) self.document().setModified(False) self.setWindowTitle( QFileInfo(self.filename).fileName()) self.loadHighlighter(self.filename) for plugin in filter_plugins_by_capability('afterFileOpen',self.enabled_plugins): plugin.do_afterFileOpen(self) except (IOError, OSError), error: exception = error
def func_Save_config(self): if (self.box_warn.isChecked()): conf_warn = "true" else: conf_warn = "false" if (self.box_1inst.isChecked()): conf_1inst = "true" else: conf_1inst = "false" if (self.box_systray.isChecked()): conf_systray = "true" else: conf_systray = "false" if (self.box_min.isChecked()): conf_min = "true" else: conf_min = "false" if (self.box_close.isChecked()): conf_close = "true" else: conf_close = "false" filename = QFile(os.getenv("HOME") + "/.qtsixa2/conf.xml") if not filename.open(QIODevice.WriteOnly): QMessageBox.critical( self, self.tr("QtSixA - Error"), self.tr("Cannot write QtSixA configuration file!")) raise IOError, unicode(filename.errorString()) stream = QTextStream(filename) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE QTSIXA>\n" "<QTSIXA VERSION='1.5.1'>\n" " <Configuration>\n" " <Main>\n" " <Show-Warnings>%s</Show-Warnings>\n" " <Only-One-Instance>%s</Only-One-Instance>\n" " </Main>\n" " <Systray>\n" " <Enable>%s</Enable>\n" " <Start-Minimized>%s</Start-Minimized>\n" " <Close-to-Tray>%s</Close-to-Tray>\n" " </Systray>\n" " </Configuration>\n" "</QTSIXA>\n" % (conf_warn, conf_1inst, conf_systray, conf_min, conf_close)) shared.Globals.show_warnings = self.box_warn.isChecked() shared.Globals.only_one_instance = self.box_1inst.isChecked() shared.Globals.systray_enabled = self.box_systray.isChecked() shared.Globals.start_minimized = self.box_min.isChecked() shared.Globals.close_to_tray = self.box_close.isChecked()
def __init__(self, parent=None): super(helpDisplay, self).__init__(parent) # make page unmodifiable self.page().setContentEditable(False) # initialize settings # Find out the nearest font to Palatino qf = QFont() qf.setStyleStrategy(QFont.PreferAntialias + QFont.PreferMatch) qf.setStyleHint(QFont.Serif) qf.setFamily(QString(u'Palatino')) qfi = QFontInfo(qf) # set the default font to that serif font self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family()) self.settings().setFontSize(QWebSettings.DefaultFontSize, 16) self.settings().setFontSize(QWebSettings.MinimumFontSize, 6) self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6) self.textZoomFactor = 1.0 self.setTextSizeMultiplier(self.textZoomFactor) self.settings().setAttribute(QWebSettings.JavascriptEnabled, False) self.settings().setAttribute(QWebSettings.JavaEnabled, False) self.settings().setAttribute(QWebSettings.PluginsEnabled, False) self.settings().setAttribute(QWebSettings.ZoomTextOnly, True) #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False) self.userFindText = QString() # Look for pqHelp.html in the app folder and copy its text into # a local buffer. If it isn't found, put a message there instead. # We need to keep it in order to implement the "back" function. helpPath = os.path.join(IMC.appBasePath, u'pqHelp.html') helpFile = QFile(helpPath) if not helpFile.exists(): self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p> <p>Looking in {0}'''.format(helpPath)) elif not helpFile.open(QIODevice.ReadOnly): self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p> <p>Looking in {0}</p><p>Error code {1}</p>'''.format( helpPath, helpFile.error())) else: helpStream = QTextStream(helpFile) helpStream.setCodec('ISO8859-1') self.HTMLstring = helpStream.readAll() self.setHtml(self.HTMLstring)
def load(self): """Load ?""" exception = None filehandle = None try: filehandle = QFile(self.filename) if not filehandle.open(QIODevice.ReadOnly): raise IOError, unicode(filehandle.errorString()) stream = QTextStream(filehandle) stream.setCodec("UTF-8") QApplication.processEvents() self.setPlainText(stream.readAll()) self.document().setModified(False) self.setWindowTitle(QFileInfo(self.filename).fileName()) self.loadHighlighter(self.filename) for plugin in filter_plugins_by_capability('afterFileOpen', self.enabled_plugins): plugin.do_afterFileOpen(self) except (IOError, OSError), error: exception = error
def save(self, new): fh = QFile('config/' + self.name + '.printer') if new and fh.exists(): return False if fh.open(QIODevice.WriteOnly): stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='%s'?>\n<!DOCTYPE PRINTER>\n<PRINTER\n" % CODEC) stream << ("UPDATEPERIOD='%s'\nJOGSPEED='%s'\nMAXTOOLS='%s'\nTOOLLIMIT='%s'\nMAXACCEL='%s'\n" "XMAX='%s'\nYMAX='%s'\nZMAX='%s'\n>\n" % (self.updatePeriod, self.jogSpeed, self.maxTools, self.toolLimit, self.maxAccel, self.xMax, self.yMax, self.zMax)) now = self.base stream << ("<BASE\nDIRECTION='%s'\nMOTOR='%s'\nRANGE='%s'\nLIMITS='%s'\nINCREMENT='%s'\n>\n" % (now.direction, now.motor, now.arange, now.limits, now.increment)) stream << ("</BASE>\n") now = self.x stream << ("<XAXIS\nDIRECTION='%s'\nMOTOR='%s'\nRANGE='%s'\nLIMITS='%s'\nINCREMENT='%s'\n>\n" % (now.direction, now.motor, now.arange, now.limits, now.increment)) stream << ("</XAXIS>\n") now = self.y stream << ("<YAXIS\nDIRECTION='%s'\nMOTOR='%s'\nRANGE='%s'\nLIMITS='%s'\nINCREMENT='%s'\n>\n" % (now.direction, now.motor, now.arange, now.limits, now.increment)) stream << ("</YAXIS>\n") now = self.z stream << ("<ZAXIS\nDIRECTION='%s'\nMOTOR='%s'\nRANGE='%s'\nLIMITS='%s'\nINCREMENT='%s'\n>\n" % (now.direction, now.motor, now.arange, now.limits, now.increment)) stream << ("</ZAXIS>\n") now = self.u stream << ("<UAXIS\nDIRECTION='%s'\nMOTOR='%s'\nRANGE='%s'\nLIMITS='%s'\nINCREMENT='%s'\n>\n" % (now.direction, now.motor, now.arange, now.limits, now.increment)) stream << ("</UAXIS>\n") if self.maxTools > 1: now = self.v stream << ("<VAXIS\nDIRECTION='%s'\nMOTOR='%s'\nRANGE='%s'\nLIMITS='%s'\nINCREMENT='%s'\n>\n" % (now.direction, now.motor, now.arange, now.limits, now.increment)) stream << ("</VAXIS>\n") stream << ("</PRINTER>\n") fh.close() return True
def write_description_content(handle, data): """ This function generates the xml content of the description file. """ stream = QTextStream(handle) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<sconcho>\n" " <knittingSymbol>\n" " <svgName>%s</svgName>\n" " <category>%s</category>\n" " <symbolName>%s</symbolName>\n" " <symbolDescription>%s</symbolDescription>\n" " <symbolWidth>%d</symbolWidth>\n" " </knittingSymbol>\n" "</sconcho>\n" % (Qt.escape(data["svgName"]), Qt.escape(data["category"]), Qt.escape(data["name"]), Qt.escape(data["description"]), data["width"]))
def func_Save_config(self): if (self.box_warn.isChecked()): conf_warn = "true" else: conf_warn = "false" if (self.box_1inst.isChecked()): conf_1inst = "true" else: conf_1inst = "false" if (self.box_systray.isChecked()): conf_systray = "true" else: conf_systray = "false" if (self.box_min.isChecked()): conf_min = "true" else: conf_min = "false" if (self.box_close.isChecked()): conf_close = "true" else: conf_close = "false" filename = QFile(os.getenv("HOME")+"/.qtsixa2/conf.xml") if not filename.open(QIODevice.WriteOnly): QMessageBox.critical(self, self.tr("QtSixA - Error"), self.tr("Cannot write QtSixA configuration file!")) raise IOError, unicode(filename.errorString()) stream = QTextStream(filename) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE QTSIXA>\n" "<QTSIXA VERSION='1.5.0'>\n" " <Configuration>\n" " <Main>\n" " <Show-Warnings>%s</Show-Warnings>\n" " <Only-One-Instance>%s</Only-One-Instance>\n" " </Main>\n" " <Systray>\n" " <Enable>%s</Enable>\n" " <Start-Minimized>%s</Start-Minimized>\n" " <Close-to-Tray>%s</Close-to-Tray>\n" " </Systray>\n" " </Configuration>\n" "</QTSIXA>\n" % ( conf_warn, conf_1inst, conf_systray, conf_min, conf_close ) ) shared.Globals.show_warnings = self.box_warn.isChecked() shared.Globals.only_one_instance = self.box_1inst.isChecked() shared.Globals.systray_enabled = self.box_systray.isChecked() shared.Globals.start_minimized = self.box_min.isChecked() shared.Globals.close_to_tray = self.box_close.isChecked()
def exportDocument(self, task, fileName, format): """ :type task: QUrl :type fileName: str :type format: self.ExportFormat :return: bool """ fileOut = QFile(fileName) if not fileOut.open(QIODevice.WriteOnly | QIODevice.Text): return False taskMap = self.__parseTask(task) text = self.__documentContent(taskMap, format) streamFileOut = QTextStream(fileOut) streamFileOut.setCodec("UTF-8") streamFileOut << text streamFileOut.flush() fileOut.close() return True
def load_file(self): """ Loading a text file to the self.textEdit """ self.ready_to_go() fileobject = None self.path = QFileDialog.getOpenFileName(self, "TextEditor", "") try: fileobject = QFile(self.path) if not fileobject.open(QIODevice.ReadOnly): raise IOError, unicode(fileobject.errorString()) textstream = QTextStream(fileobject) textstream.setCodec("UTF-8") self.textEdit.setPlainText(textstream.readAll()) self.textEdit.document().setModified(False) print self.textEdit.document().isModified() self.setWindowTitle("%s - TextEditor" % QFileInfo(self.path).fileName()) except (IOError, OSError), error: QMessageBox.warning( self, self.tr("TextEditor - Load Error"), self.tr("Unable to load {0} : {1}".format(self.path, error))) self.path = ""
def save_file(self): """ Saving file to the path where getting from QFileDialog """ fileobject = None if self.path is "": self.path = QFileDialog.getSaveFileName(self, "TextEditor", self.tr("unnamed")) try: fileobject = QFile(self.path) if not fileobject.open(QIODevice.WriteOnly): raise IOError, unicode(fileobject.errorString()) textstream = QTextStream(fileobject) textstream.setCodec("UTF-8") textstream << self.textEdit.toPlainText() self.textEdit.document().setModified(False) self.setWindowTitle("%s - TextEditor" % QFileInfo(self.path).fileName()) except (IOError, OSError), error: QMessageBox.warning( self, self.tr("TextEditor - Save Error"), self.tr("Unable to save {0}:{1}".format(self.path, error))) self.path = ""
def load_file(self): """ Loading a text file to the self.textEdit """ self.ready_to_go() fileobject = None self.path = QFileDialog.getOpenFileName(self, "TextEditor","") try: fileobject = QFile(self.path) if not fileobject.open(QIODevice.ReadOnly): raise IOError, unicode(fileobject.errorString()) textstream = QTextStream(fileobject) textstream.setCodec("UTF-8") self.textEdit.setPlainText(textstream.readAll()) self.textEdit.document().setModified(False) print self.textEdit.document().isModified() self.setWindowTitle("%s - TextEditor" % QFileInfo(self.path).fileName()) except(IOError, OSError), error: QMessageBox.warning(self, self.tr("TextEditor - Load Error"), self.tr("Unable to load {0} : {1}".format(self.path, error))) self.path = ""
from PyQt4.QtGui import (QApplication, QFileDialog, QMainWindow) import pqIMC IMC = pqIMC.tricorder() # create inter-module communicator app = QApplication(sys.argv) # create an app import pqMsgs pqMsgs.IMC = IMC import pqLists IMC.charCensus = pqLists.vocabList() CP = charsPanel() # create the widget with the table view and model MW = QMainWindow() MW.setCentralWidget(CP) IMC.statusBar = MW.statusBar() MW.show() utname = QFileDialog.getOpenFileName(MW, "UNIT TEST DATA FOR CHARS", ".") utfile = QFile(utname) if not utfile.open(QIODevice.ReadOnly): raise IOError, unicode(utfile.errorString()) CP.docWillChange() utstream = QTextStream(utfile) utstream.setCodec("UTF-8") utqs = utstream.readAll() for i in range(utqs.count()): qc = utqs.at(i) cat = qc.category() IMC.charCensus.count(QString(qc), cat) CP.docHasChanged() app.exec_()
def init_config(self): if not os.path.exists(os.getenv("HOME")+"/.qtsixa2/"): os.mkdir(os.getenv("HOME")+"/.qtsixa2/") if not os.path.exists(os.getenv("HOME")+"/.qtsixa2/profiles"): os.mkdir(os.getenv("HOME")+"/.qtsixa2/profiles") if not os.path.exists(os.getenv("HOME")+"/.qtsixa2/conf.xml"): filename = QFile(os.getenv("HOME")+"/.qtsixa2/conf.xml") if not filename.open(QIODevice.WriteOnly): QMessageBox.critical(self, self.tr("QtSixA - Error"), self.tr("Cannot write QtSixA configuration file!")) raise IOError, unicode(filename.errorString()) stream = QTextStream(filename) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE QTSIXA>\n" "<QTSIXA VERSION='1.5.1'>\n" " <Configuration>\n" " <Main>\n" " <Show-Warnings>true</Show-Warnings>\n" " <Only-One-Instance>true</Only-One-Instance>\n" " </Main>\n" " <Systray>\n" " <Enable>true</Enable>\n" " <Start-Minimized>false</Start-Minimized>\n" " <Close-to-Tray>false</Close-to-Tray>\n" " </Systray>\n" " </Configuration>\n" "</QTSIXA>\n" ) Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False else: # Set Default Values, only change them if the config says so Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False # Read configuration file xml = QDomDocument() filename = QFile(os.getenv("HOME")+"/.qtsixa2/conf.xml") if not filename.open(QIODevice.ReadOnly): print "error here, 1" if not xml.setContent(filename): print "error here, 2" filename.close() # Check if project file is not corrupted content = xml.documentElement() if (content.tagName() != "QTSIXA"): print "error here, 3" # Get values from XML - the big code node = content.firstChild() while not node.isNull(): if (node.toElement().tagName() == "Configuration"): configuration = node.toElement().firstChild() while not configuration.isNull(): conf_tag = configuration.toElement().tagName() if (conf_tag == "Main"): conf_tag_main = configuration.toElement().firstChild() while not conf_tag_main.isNull(): name = conf_tag_main.toElement().tagName() text = conf_tag_main.toElement().text() if (name == "Show-Warnings"): if (text == "0" or text == "false" or text == "False"): Globals.show_warnings = False elif (name == "Only-One-Instance"): if (text == "0" or text == "false" or text == "False"): Globals.only_one_instance = False conf_tag_main = conf_tag_main.nextSibling() elif (conf_tag == "Systray"): conf_tag_systray = configuration.toElement().firstChild() while not conf_tag_systray.isNull(): name = conf_tag_systray.toElement().tagName() text = conf_tag_systray.toElement().text() if (name == "Enable"): if (text == "0" or text == "false" or text == "False"): Globals.systray_enabled = False elif (name == "Start-Minimized"): if (text == "1" or text == "true" or text == "True"): Globals.start_minimized = True elif (name == "Close-to-Tray"): if (text == "1" or text == "true" or text == "True"): Globals.close_to_tray = True conf_tag_systray = conf_tag_systray.nextSibling() configuration = configuration.nextSibling() node = node.nextSibling()
def loadQTextStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) self.clear(False) lino = 0 while not stream.atEnd(): title = year = minutes = acquired = notes = None line = stream.readLine() lino += 1 if not line.startsWith("{{MOVIE}}"): raise ValueError("no movie record found") else: title = line.mid(len("{{MOVIE}}")).trimmed() if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 parts = line.split(" ") if parts.count() != 3: raise ValueError("invalid numeric data") year = intFromQStr(parts[0]) minutes = intFromQStr(parts[1]) ymd = parts[2].split("-") if ymd.count() != 3: raise ValueError("invalid acquired date") acquired = QDate(intFromQStr(ymd[0]), intFromQStr(ymd[1]), intFromQStr(ymd[2])) if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 if line != "{NOTES}": raise ValueError("notes expected") notes = QString() while not stream.atEnd(): line = stream.readLine() lino += 1 if line == "{{ENDMOVIE}}": if (title is None or year is None or minutes is None or acquired is None or notes is None): raise ValueError("incomplete record") self.add( Movie(title, year, minutes, acquired, notes.trimmed())) break else: notes += line + "\n" else: raise ValueError("missing endmovie marker") except (IOError, OSError, ValueError) as e: error = "Failed to load: {0} on line {1}".format(e, lino) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Loaded {0} movie records from {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
class Dialog(QDialog): TotalBytes = 50 * 1024 * 1024 PayloadSize = 65536 def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.settings = QSettings('settings.ini', QSettings.IniFormat) self.tcpServer = QTcpServer() self.chBox = QCheckBox("Print log to window") self.text = QPlainTextEdit() self.serverStatusLabel = QLabel("Server ready") self.lblFileName = QLabel("Choose file before start!") self.saveButton = QPushButton("&Choose file...") self.startButton = QPushButton("&Start") self.stopButton = QPushButton("S&top") self.quitButton = QPushButton("&Quit") self.file = None self.tcpServerConnection = None self._lineCounter = 0 self._lineBuf = '' buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) clearButon = QPushButton('&Clear') self.saveButton.clicked.connect(self.savedlg) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stopClicked) self.quitButton.clicked.connect(self.close) clearButon.clicked.connect(self.text.clear) self.tcpServer.newConnection.connect(self.acceptConnection) saveLayout = QHBoxLayout() saveLayout.addWidget(self.lblFileName) saveLayout.addStretch(1) saveLayout.addWidget(self.saveButton) topTextLayout = QHBoxLayout() topTextLayout.addWidget(self.chBox) topTextLayout.addStretch(1) topTextLayout.addWidget(clearButon) mainLayout = QVBoxLayout() mainLayout.addLayout(saveLayout) mainLayout.addLayout(topTextLayout) mainLayout.addWidget(self.text) mainLayout.addWidget(self.serverStatusLabel) # mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.title = "Simple Logger" self.ver = '1.0' self.setWindowIcon(QIcon('./icon.png')) self.setWindowTitle("{} {}".format(self.title, self.ver)) def start(self): if self.file is None: QMessageBox.critical( self, self.title, "Unable open log file.\nPlease, select another file.") return self.startButton.setEnabled(False) while not self.tcpServer.isListening() and not self.tcpServer.listen( port=9112): ret = QMessageBox.critical( self, self.title, "Unable to start the test: %s." % self.tcpServer.errorString(), QMessageBox.Retry | QMessageBox.Cancel) if ret == QMessageBox.Cancel: return self.serverStatusLabel.setText("Waiting connection ...") def acceptConnection(self): self.tcpServerConnection = self.tcpServer.nextPendingConnection() self.tcpServerConnection.readyRead.connect(self.updateLog) self.tcpServerConnection.error.connect(self.displayError) self.file = QFile(self.filename) if not self.file.open(QFile.Append): QMessageBox.warning( self, self.title, "Unable to write file {}:\n{}.".format( self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.serverStatusLabel.setText("Logging ...") self.tcpServer.close() def savedlg(self): self.filename = QFileDialog.getSaveFileName( self, "Log Filename", self.settings.value('directories/dir_save', QDir.currentPath()), "Text (*.log *.txt);;All (*)") if not self.filename: return self.file = QFile(self.filename) self.lblFileName.setText(self.filename) if not self.file.open(QFile.WriteOnly): QMessageBox.warning( self, self.title, "Unable to write file {}:\n{}.".format( self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.settings.setValue('directories/dir_save', QFileInfo(self.file).path()) self.file.close() def updateLog(self): if self.tcpServerConnection.bytesAvailable(): data = self.tcpServerConnection.readAll() line = "{}".format(str(data.data().decode())) if self.chBox.isChecked(): self._lineCounter += 1 self._lineBuf += line if self._lineCounter > 10: self.text.appendPlainText(self._lineBuf) self._lineCounter = 0 self._lineBuf = '' self.textStream << line self.file.flush() # self.serverStatusLabel.setText(line) def closeEvent(self, event): if self.file is not None: self.file.flush() self.file.close() def stopClicked(self): if self.tcpServerConnection is not None: self.tcpServerConnection.close() self.file.close() self.startButton.setEnabled(True) self.serverStatusLabel.setText("Logger ready") def displayError(self, socketError): if socketError == QTcpSocket.RemoteHostClosedError: return QMessageBox.information( self, "Network error", "The following error occured: %s." % self.tcpServer.errorString()) self.tcpServer.close() self.file.close() self.serverStatusLabel.setText("Logger ready") self.startButton.setEnabled(True)
class Dialog(QDialog): TotalBytes = 50 * 1024 * 1024 PayloadSize = 65536 def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.settings = QSettings('settings.ini', QSettings.IniFormat) self.tcpServer = QTcpServer() self.chBox = QCheckBox("Print log to window") self.text = QPlainTextEdit() self.serverStatusLabel = QLabel("Server ready") self.lblFileName = QLabel("Choose file before start!") self.saveButton = QPushButton("&Choose file...") self.startButton = QPushButton("&Start") self.stopButton = QPushButton("S&top") self.quitButton = QPushButton("&Quit") self.file = None self.tcpServerConnection = None self._lineCounter = 0 self._lineBuf = '' buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.stopButton, QDialogButtonBox.RejectRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) clearButon = QPushButton('&Clear') self.saveButton.clicked.connect(self.savedlg) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stopClicked) self.quitButton.clicked.connect(self.close) clearButon.clicked.connect(self.text.clear) self.tcpServer.newConnection.connect(self.acceptConnection) saveLayout = QHBoxLayout() saveLayout.addWidget(self.lblFileName) saveLayout.addStretch(1) saveLayout.addWidget(self.saveButton) topTextLayout = QHBoxLayout() topTextLayout.addWidget(self.chBox) topTextLayout.addStretch(1) topTextLayout.addWidget(clearButon) mainLayout = QVBoxLayout() mainLayout.addLayout(saveLayout) mainLayout.addLayout(topTextLayout) mainLayout.addWidget(self.text) mainLayout.addWidget(self.serverStatusLabel) # mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.title = "Simple Logger" self.ver = '1.0' self.setWindowIcon(QIcon('./icon.png')) self.setWindowTitle("{} {}".format(self.title, self.ver)) def start(self): if self.file is None: QMessageBox.critical(self, self.title, "Unable open log file.\nPlease, select another file.") return self.startButton.setEnabled(False) while not self.tcpServer.isListening() and not self.tcpServer.listen(port=9112): ret = QMessageBox.critical(self, self.title, "Unable to start the test: %s." % self.tcpServer.errorString(), QMessageBox.Retry | QMessageBox.Cancel) if ret == QMessageBox.Cancel: return self.serverStatusLabel.setText("Waiting connection ...") def acceptConnection(self): self.tcpServerConnection = self.tcpServer.nextPendingConnection() self.tcpServerConnection.readyRead.connect(self.updateLog) self.tcpServerConnection.error.connect(self.displayError) self.file = QFile(self.filename) if not self.file.open(QFile.Append): QMessageBox.warning(self, self.title, "Unable to write file {}:\n{}.".format(self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.serverStatusLabel.setText("Logging ...") self.tcpServer.close() def savedlg(self): self.filename = QFileDialog.getSaveFileName(self, "Log Filename", self.settings.value('directories/dir_save', QDir.currentPath()), "Text (*.log *.txt);;All (*)") if not self.filename: return self.file = QFile(self.filename) self.lblFileName.setText(self.filename) if not self.file.open(QFile.WriteOnly): QMessageBox.warning(self, self.title, "Unable to write file {}:\n{}.".format(self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.settings.setValue('directories/dir_save', QFileInfo(self.file).path()) self.file.close() def updateLog(self): if self.tcpServerConnection.bytesAvailable(): data = self.tcpServerConnection.readAll() line = "{}".format(str(data.data().decode())) if self.chBox.isChecked(): self._lineCounter += 1 self._lineBuf += line if self._lineCounter > 10: self.text.appendPlainText(self._lineBuf) self._lineCounter = 0 self._lineBuf = '' self.textStream << line self.file.flush() # self.serverStatusLabel.setText(line) def closeEvent(self, event): if self.file is not None: self.file.flush() self.file.close() def stopClicked(self): if self.tcpServerConnection is not None: self.tcpServerConnection.close() self.file.close() self.startButton.setEnabled(True) self.serverStatusLabel.setText("Logger ready") def displayError(self, socketError): if socketError == QTcpSocket.RemoteHostClosedError: return QMessageBox.information(self, "Network error", "The following error occured: %s." % self.tcpServer.errorString()) self.tcpServer.close() self.file.close() self.serverStatusLabel.setText("Logger ready") self.startButton.setEnabled(True)
#!/usr/bin/env python # -*- coding: utf-8 from PyQt4.QtGui import QApplication from login import Login from Main import MainWindow from PyQt4.QtGui import QDialog if __name__ == '__main__': import sys from PyQt4.QtCore import QFile, QIODevice, QTextStream, QTextCodec import myfile cssfile = QFile(':/main.css') if not cssfile.open(QIODevice.ReadOnly): sys.exit(u'未读取到资源文件') stream = QTextStream(cssfile) stream.setCodec(QTextCodec.codecForName('UTF-8')) cssdata = stream.readAll() cssfile.close() del stream app = QApplication(sys.argv) app.setStyle('Fusion') # with open('main.css', 'r') as css: # StyleSheet = css.read() app.setStyleSheet(cssdata) if Login().exec_() == QDialog.Accepted: window = MainWindow() window.show() sys.exit(app.exec_())
def loadQTextStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) self.clear(False) lino = 0 while not stream.atEnd(): title = year = minutes = acquired = notes = None line = stream.readLine() lino += 1 if not line.startsWith("{{MOVIE}}"): raise ValueError("no movie record found") else: title = line.mid(len("{{MOVIE}}")).trimmed() if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 parts = line.split(" ") if parts.count() != 3: raise ValueError("invalid numeric data") year = intFromQStr(parts[0]) minutes = intFromQStr(parts[1]) ymd = parts[2].split("-") if ymd.count() != 3: raise ValueError("invalid acquired date") acquired = QDate(intFromQStr(ymd[0]), intFromQStr(ymd[1]), intFromQStr(ymd[2])) if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 if line != "{NOTES}": raise ValueError("notes expected") notes = QString() while not stream.atEnd(): line = stream.readLine() lino += 1 if line == "{{ENDMOVIE}}": if (title is None or year is None or minutes is None or acquired is None or notes is None): raise ValueError("incomplete record") self.add(Movie(title, year, minutes, acquired, notes.trimmed())) break else: notes += line + "\n" else: raise ValueError("missing endmovie marker") except (IOError, OSError, ValueError) as e: error = "Failed to load: {0} on line {1}".format(e, lino) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Loaded {0} movie records from {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
from PyQt4.QtGui import (QApplication,QPlainTextEdit,QFileDialog,QMainWindow) import pqIMC app = QApplication(sys.argv) # create an app IMC = pqIMC.tricorder() # create inter-module communicator pqMsgs.IMC = IMC IMC.bookType = QString(u"html") M = QMainWindow() pqMsgs.makeBarIn(M.statusBar()) utname = QFileDialog.getOpenFileName(M, "UNIT TEST DATA FOR FLOW", ".") utfile = QFile(utname) if not utfile.open(QIODevice.ReadOnly): raise IOError, unicode(utfile.errorString()) utinfo = QFileInfo(utfile) IMC.bookDirPath = utinfo.absolutePath() utstream = QTextStream(utfile) utstream.setCodec("UTF-8") utqs = utstream.readAll() IMC.editWidget = QPlainTextEdit() IMC.editWidget.setPlainText(utqs) IMC.editWidget.show() W = htmlPreview() M.setCentralWidget(W) M.show() W.docWillChange() W.docHasChanged() #t = unicode(W.getSimpleText()) #print(t) #W.doneWithText() app.exec_()
IMC.fontFamily = QString(u"Courier") IMC.editWidget = QPlainTextEdit() IMC.pageTable = pagedb() widj = pagesPanel() MW = QMainWindow() IMC.mainWindow = MW MW.setCentralWidget(widj) MW.setWinModStatus = setWinModStatus MW.show() fn = QFileDialog.getOpenFileName(None, "Select a Test Book") print(fn) fh = QFile(fn) if not fh.open(QFile.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QTextStream(fh) stream.setCodec("UTF-8") IMC.editWidget.setPlainText(stream.readAll()) # load the editor doc widj.docWillChange() # Code from pqEdit to parse a doc by lines and extract page seps. reLineSep = QRegExp( u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*', Qt.CaseSensitive) qtb = IMC.editWidget.document().begin() # first text block IMC.pageTable.clear() while qtb != IMC.editWidget.document().end(): # up to end of document qsLine = qtb.text() # text of line as qstring if reLineSep.exactMatch(qsLine): # a page separator qsfilenum = reLineSep.capturedTexts()[1] qsproofers = reLineSep.capturedTexts()[2] # proofer names can contain spaces, replace with en-space char qsproofers.replace(QChar(" "), QChar(0x2002))
def __save__(self, qgis_project_file=None): """ Save the currect project. Because the normal project.write loses :param qgis_project_file: str :return: None """ f, fn = os.path.split(self.qprjf) temp_prj_n = fn + '.tmp' out_filet = os.path.join(f, temp_prj_n) out_file = qgis_project_file or self.qprjf outf_info = QFileInfo(out_filet) if os.path.exists(out_filet): os.remove(out_filet) logger.debug('Saving project to %s' % out_file) assert self.qprj.write( outf_info), 'failed to save QGIS project to file %s ' % out_filet doc = QDomDocument() doc.setContent(xml_jano.etree.tostring( xml_jano.etree.parse(out_filet))) qgisNode = doc.documentElement() os.remove(out_filet) # canvas bridge for layer order in new style (after 2.4 version) self.canvas_bridge.writeProject(doc) # and it seesm there is old style legend order (before 2.4 version ) so I add this element as well for compatibility if self.canvas_bridge.hasCustomLayerOrder(): logger.debug( '...creating legend element for old style (<2.4 version) projects to specifiy layer order ' ) clorder = self.canvas_bridge.customLayerOrder() lelem = QgsLayerTreeUtils.writeOldLegend( doc, self.qprj.layerTreeRoot(), self.canvas_bridge.hasCustomLayerOrder(), clorder) qgisNode.appendChild(lelem) # now the composers for composer_name in self.composers: logger.debug('...creating composer %s' % composer_name) lxml_composer_el = self.qpath_extract_element( qpath='Composer[@title="%s"]' % composer_name) title = lxml_composer_el.get('title') visible = lxml_composer_el.get('visible') qt_composer_doc = QDomDocument() qt_composer_doc.setContent( '<Composer title="%s" visible="%s"></Composer>' % (title, visible)) composer_el = qt_composer_doc.documentElement() # print qt_composer_doc.toString() composition = self.get_composition_object( composer_name=composer_name) assert composition.writeXML( composer_el, qt_composer_doc), 'Failed to write composer %s' % composer_name qgisNode.appendChild(qt_composer_doc.documentElement()) # and finally save it fh = QFile(out_file) qts = QTextStream(fh) if not fh.open(QIODevice.WriteOnly): raise IOError, unicode(fh.errorString()) qts.setCodec('UTF-8') doc.save(qts, 2)
def save(self, qgis_project_file=None): """ :param qgis_project_file: :return: """ out_file = qgis_project_file or self.qprjf logger.info('Saving %s to %s ' % (self.qprjf, out_file)) logger.debug('...creating main "qgis" element') #root with attrs doc = QDomDocument() qgisNode = doc.createElement('qgis') qgisNode.setAttribute('projectname', self.qprj.title()) qgisNode.setAttribute('version', QGis.QGIS_VERSION) doc.appendChild(qgisNode) #title title_node = doc.createElement('title') titleText = doc.createTextNode(self.qprj.title()) title_node.appendChild(titleText) qgisNode.appendChild(title_node) logger.debug('...creating transaction element') #transaction, added in 2.16 transactionNode = doc.createElement('autotransaction') try: transactionNode.setAttribute('active', int(self.qprj.autoTransaction())) except AttributeError: # qgis version < 2.16 transactionNode.setAttribute('active', 0) qgisNode.appendChild(transactionNode) logger.debug('...creating evaluateDefaultValues element') #evaluate defaults evaluateDefaultValuesNode = doc.createElement('evaluateDefaultValues') try: evaluateDefaultValuesNode.setAttribute( 'active', int(self.qprj.evaluateDefaultValues())) except AttributeError: evaluateDefaultValuesNode.setAttribute('active', 0) qgisNode.appendChild(evaluateDefaultValuesNode) #layer tree element logger.debug('...creating layer tree element') util.introspect(self.canvas, namefilter='legend') self.qprj.layerTreeRoot().writeXML(qgisNode) #relations, logger.debug('...creating relations element') relations_el = doc.createElement('relations') for rn, r in self.qprj.relationManager().relations().items(): r.writeXML(relations_el, doc) qgisNode.appendChild(relations_el) logger.debug('...creating map canvas/map settings element') #now map canvas self.canvas.writeProject(doc) logger.debug( '...creating layer order element for new (>2.4 version) projects ') #canvas bridge for layer order in new style (after 2.4 version) self.canvas_bridge.writeProject(doc) #and it seesm there is old style legend order (before 2.4 version ) so I add this element as well for compatibility if self.canvas_bridge.hasCustomLayerOrder(): logger.debug( '...creating legend element for old style (<2.4 version) projects to specifiy layer order ' ) clorder = self.canvas_bridge.defaultLayerOrder() lelem = QgsLayerTreeUtils.writeOldLegend( doc, self.qprj.layerTreeRoot(), self.canvas_bridge.hasCustomLayerOrder(), clorder) qgisNode.appendChild(lelem) # now the composers for composer_name in self.composers: logger.debug('...creating composer %s' % composer_name) lxml_composer_el = self.qpath_extract_element( qpath='Composer[@title="%s"]' % composer_name) title = lxml_composer_el.get('title') visible = lxml_composer_el.get('visible') qt_composer_doc = QDomDocument() qt_composer_doc.setContent( '<Composer title="%s" visible="%s"></Composer>' % (title, visible)) composer_el = qt_composer_doc.documentElement() #print qt_composer_doc.toString() composition = self.get_composition_object( composer_name=composer_name) assert composition.writeXML( composer_el, qt_composer_doc), 'Failed to write composer %s' % composer_name qgisNode.appendChild(qt_composer_doc.documentElement()) #util.introspect(self.qprj.layerTreeRoot(), namefilter='layer') projectLayersNode = doc.createElement('projectlayers') logger.debug('...creating project layers element') for ml in self.canvas.layers(): maplayerElem = doc.createElement('maplayer') ml.writeLayerXML(maplayerElem, doc) self.qprj.emit(QtCore.SIGNAL('writeMapLayer'), ml, maplayerElem, doc) projectLayersNode.appendChild(maplayerElem) qgisNode.appendChild(projectLayersNode) #TODO find out how to read all the properties logger.debug('...creating project properties') prop_content = self.__fetch_properties__() prop_doc = QDomDocument() prop_doc.setContent(prop_content) qgisNode.appendChild(prop_doc.documentElement()) # util.introspect(self.qprj ) # print xml.etree.tostring(self.qpath_extract_element('/properties')) # print self.qprj.entryList('Digitizing', '') # print self.qprj.entryList('/', '') # print self.qprj.readEntry('Digitizing', 'SnappingMode') # print self.qprj.property('Digitizing') self.qprj.visibilityPresetCollection().writeXML(doc) # and finally save it fh = QFile(out_file) qts = QTextStream(fh) if not fh.open(QIODevice.WriteOnly): raise IOError, unicode(fh.errorString()) qts.setCodec('UTF-8') doc.save(qts, 2)
IMC.fontFamily = QString(u"Courier") IMC.editWidget = QPlainTextEdit() IMC.pageTable = pagedb() widj = pagesPanel() MW = QMainWindow() IMC.mainWindow = MW MW.setCentralWidget(widj) MW.setWinModStatus = setWinModStatus MW.show() fn = QFileDialog.getOpenFileName(None,"Select a Test Book") print(fn) fh = QFile(fn) if not fh.open(QFile.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QTextStream(fh) stream.setCodec("UTF-8") IMC.editWidget.setPlainText(stream.readAll()) # load the editor doc widj.docWillChange() # Code from pqEdit to parse a doc by lines and extract page seps. reLineSep = QRegExp(u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*',Qt.CaseSensitive) qtb = IMC.editWidget.document().begin() # first text block IMC.pageTable.clear() while qtb != IMC.editWidget.document().end(): # up to end of document qsLine = qtb.text() # text of line as qstring if reLineSep.exactMatch(qsLine): # a page separator qsfilenum = reLineSep.capturedTexts()[1] qsproofers = reLineSep.capturedTexts()[2] # proofer names can contain spaces, replace with en-space char qsproofers.replace(QChar(" "),QChar(0x2002)) tcursor = QTextCursor(IMC.editWidget.document()) tcursor.setPosition(qtb.position())
class QSingleton(QApplication): messageReceived = pyqtSignal() # Señal de mensaje recibido #================================================================================================================== # CONSTRUCTOR DE LA CLASE #================================================================================================================== def __init__(self, appID, argv): #-------------------------------------------------------------------------------------------------------------- # INICIAR LA CLASE #-------------------------------------------------------------------------------------------------------------- super(QSingleton, self).__init__(argv) #-------------------------------------------------------------------------------------------------------------- # CONFIGURACIONES INICIALES #-------------------------------------------------------------------------------------------------------------- self.appID = appID self._outSocket = QLocalSocket() self._outSocket.connectToServer(self.appID) self._isRunning = self._outSocket.waitForConnected() # Si hay instancias previas corriendo if self._isRunning: self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') # Si es la primera instancia else: self._outSocket = None self._outStream = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self.appID) self._server.newConnection.connect(self._onNewConnection) #================================================================================================================== # MÉTODOS #================================================================================================================== # Método para saber si hay instancias previas ejecutandose def isRunning(self): return self._isRunning # Método para crear una nueva conexión 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) # Método para lectura del socket def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
def init_config(self): if not os.path.exists(os.getenv("HOME") + "/.qtsixa2/"): os.mkdir(os.getenv("HOME") + "/.qtsixa2/") if not os.path.exists(os.getenv("HOME") + "/.qtsixa2/profiles"): os.mkdir(os.getenv("HOME") + "/.qtsixa2/profiles") if not os.path.exists(os.getenv("HOME") + "/.qtsixa2/conf.xml"): filename = QFile(os.getenv("HOME") + "/.qtsixa2/conf.xml") if not filename.open(QIODevice.WriteOnly): QMessageBox.critical( self, self.tr("QtSixA - Error"), self.tr("Cannot write QtSixA configuration file!")) raise IOError, unicode(filename.errorString()) stream = QTextStream(filename) stream.setCodec("UTF-8") stream << ("<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE QTSIXA>\n" "<QTSIXA VERSION='1.5.1'>\n" " <Configuration>\n" " <Main>\n" " <Show-Warnings>true</Show-Warnings>\n" " <Only-One-Instance>true</Only-One-Instance>\n" " </Main>\n" " <Systray>\n" " <Enable>true</Enable>\n" " <Start-Minimized>false</Start-Minimized>\n" " <Close-to-Tray>false</Close-to-Tray>\n" " </Systray>\n" " </Configuration>\n" "</QTSIXA>\n") Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False else: # Set Default Values, only change them if the config says so Globals.show_warnings = True Globals.only_one_instance = True Globals.systray_enabled = True Globals.start_minimized = False Globals.close_to_tray = False # Read configuration file xml = QDomDocument() filename = QFile(os.getenv("HOME") + "/.qtsixa2/conf.xml") if not filename.open(QIODevice.ReadOnly): print "error here, 1" if not xml.setContent(filename): print "error here, 2" filename.close() # Check if project file is not corrupted content = xml.documentElement() if (content.tagName() != "QTSIXA"): print "error here, 3" # Get values from XML - the big code node = content.firstChild() while not node.isNull(): if (node.toElement().tagName() == "Configuration"): configuration = node.toElement().firstChild() while not configuration.isNull(): conf_tag = configuration.toElement().tagName() if (conf_tag == "Main"): conf_tag_main = configuration.toElement().firstChild() while not conf_tag_main.isNull(): name = conf_tag_main.toElement().tagName() text = conf_tag_main.toElement().text() if (name == "Show-Warnings"): if (text == "0" or text == "false" or text == "False"): Globals.show_warnings = False elif (name == "Only-One-Instance"): if (text == "0" or text == "false" or text == "False"): Globals.only_one_instance = False conf_tag_main = conf_tag_main.nextSibling() elif (conf_tag == "Systray"): conf_tag_systray = configuration.toElement( ).firstChild() while not conf_tag_systray.isNull(): name = conf_tag_systray.toElement().tagName() text = conf_tag_systray.toElement().text() if (name == "Enable"): if (text == "0" or text == "false" or text == "False"): Globals.systray_enabled = False elif (name == "Start-Minimized"): if (text == "1" or text == "true" or text == "True"): Globals.start_minimized = True elif (name == "Close-to-Tray"): if (text == "1" or text == "true" or text == "True"): Globals.close_to_tray = True conf_tag_systray = conf_tag_systray.nextSibling() configuration = configuration.nextSibling() node = node.nextSibling()
class LogsReadThread(QThread): MAX_INITIAL_SIZE = 2*1024*1024 # 2Mb 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.emit(SIGNAL("updateLogs()")) 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): messageReceived = pyqtSignal(unicode) 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' 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)