def _editTemplate(self, templatePath, newName): """ Updates the template document to use the new name. """ templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Open Operation Error"), \ "{0}\n{1}".format( QApplication.translate("TemplateDocumentSelector", "Cannot read template file."), \ templateFile.errorString() )) return (False, "") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerElement = templateDoc.documentElement() titleAttr = composerElement.attributeNode("_title") if not titleAttr.isNull(): titleAttr.setValue(newName) # Try remove file status = templateFile.remove() if not status: return (False, "") # Create new file newTemplatePath = self._composerTemplatesPath() + "/" + newName + ".sdt" newTemplateFile = QFile(newTemplatePath) if not newTemplateFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector", "Could not save template file."), \ newTemplateFile.errorString() )) return (False, "") if newTemplateFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Error"), \ QApplication.translate("TemplateDocumentSelector", "Could not save template file.")) return (False, "") newTemplateFile.close() return (True, newTemplatePath)
def saveQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MovieContainer.MAGIC_NUMBER) stream.writeInt32(MovieContainer.FILE_VERSION) stream.setVersion(QDataStream.Qt_4_2) for key, movie in self.__movies: stream << movie.title stream.writeInt16(movie.year) stream.writeInt16(movie.minutes) stream << movie.acquired << movie.notes 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 load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) magic = stream.readInt32() if magic != MAGIC_NUMBER: raise IOError, "unrecognized file type" fileVersion = stream.readInt16() if fileVersion != FILE_VERSION: raise IOError, "unrecognized file type version" self.ships = [] while not stream.atEnd(): name = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, e: exception = e
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 loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related controls. """ if not QFile.exists(filePath): QMessageBox.critical(self.composerView(), QApplication.translate("OpenTemplateConfig","Open Template Error"), \ QApplication.translate("OpenTemplateConfig","The specified template does not exist.")) return templateFile = QFile(filePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Open Operation Error"), \ "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Cannot read template file."), \ templateFile.errorString() )) return templateDoc = QDomDocument() if templateDoc.setContent(templateFile): #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) self.clearWidgetMappings() #Load data controls composerDS = ComposerDataSource.create(templateDoc) self._configureDataControls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig)
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) magic = stream.readInt32() if magic != MAGIC_NUMBER: raise IOError, "unrecognized file type" fileVersion = stream.readInt16() if fileVersion != FILE_VERSION: raise IOError, "unrecognized file type version" self.ships = [] while not stream.atEnd(): name = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, err: exception = err
def saveQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MovieContainer.MAGIC_NUMBER) stream.writeInt32(MovieContainer.FILE_VERSION) stream.setVersion(QDataStream.Qt_4_2) for key, movie in self.__movies: stream << movie.title stream.writeInt16(movie.year) stream.writeInt16(movie.minutes) stream << movie.acquired << movie.location \ << movie.notes 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 loadConfig(self): """Load configuration combobox with configurations stored in XML configuration file.""" XMLFile = QFile(self.plugin_dir + '/' + self.configFileName) if not XMLFile.open(QFile.ReadOnly | QFile.Text): QMessageBox.warning( self.iface.mainWindow(), "XML Configuration", "Cannot read file %s:\n%s." % (self.plugin_dir + '/' + self.configFileName, XMLFile.errorString()), QMessageBox.Ok) return False ok, errorStr, errorLine, errorColumn = self.configXML.setContent( XMLFile, True) if not ok: QMessageBox.information( self.iface.mainWindow(), "XML Configuration", "Parse error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr)) return False root = self.configXML.documentElement() configs = root.elementsByTagName('config') for index in range(configs.count()): if configs.at(index).hasAttributes(): nodeAttributes = configs.at(index).attributes() self.dlg.cbxConfig.addItem( nodeAttributes.namedItem('name').nodeValue(), nodeAttributes.namedItem('id').nodeValue()) self.setCurrentConfig( self.dlg.cbxConfig.itemData(self.dlg.cbxConfig.currentIndex())) return True
def changeResolution(self): fileName = QFileDialog.getOpenFileName( self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open', QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadWrite): QMessageBox.warning( self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) headerVersion = data.readInt32() xdpi = data.readInt32() ydpi = data.readInt32() dialog = ChangeResolutionDialog(xdpi, ydpi, self) if dialog.exec_(): file.seek(4) data.writeInt32(dialog.sbXdpi.value()) data.writeInt32(dialog.sbYdpi.value()) self.status.showMessage("Resolution changed successful", 7000) file.close()
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 importDOM(self, fname): dom = QDomDocument() error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) if not dom.setContent(fh): raise ValueError("could not parse XML") except (IOError, OSError, ValueError) as e: error = "Failed to import: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error try: self.populateFromDOM(dom) except ValueError as e: return False, "Failed to import: {0}".format(e) self.__fname = QString() self.__dirty = True return True, "Imported {0} movie records from {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 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, 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): 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 save(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError("no filename specified for saving") fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MAGIC_NUMBER) stream.writeInt16(FILE_VERSION) stream.setVersion(QDataStream.Qt_4_1) for ship in self.ships: stream << ship.name << ship.owner << ship.country \ << ship.description stream.writeInt32(ship.teu) self.dirty = False except IOError as e: exception = e finally: if fh is not None: fh.close() if exception is not None: raise exception
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 open(self): self.offerSave() path = (QFileInfo(self.filename).path() if not self.filename.isEmpty() else ".") fname = QFileDialog.getOpenFileName(self, "Page Designer - Open", path, "Page Designer Files (*.pgd)") if fname.isEmpty(): return self.filename = fname fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) items = self.scene.items() while items: item = items.pop() self.scene.removeItem(item) del item self.addBorders() stream = QDataStream(fh) stream.setVersion(QDataStream.Qt_4_2) magic = stream.readInt32() if magic != MagicNumber: raise IOError, "not a valid .pgd file" fileVersion = stream.readInt16() if fileVersion != FileVersion: raise IOError, "unrecognised .pgd file version" while not fh.atEnd(): self.readItemFromStream(stream) except IOError, e: QMessageBox.warning(self, "Page Designer -- Open Error", "Failed to open {0}: {1}".format(self.filename, e))
def escribir_archivo(nombre_de_archivo, contenido): """ Se escribe en el archivo, si el nombre no tiene extensión se agrega .c """ extension = (os.path.splitext(nombre_de_archivo)[-1])[1:] if not extension: nombre_de_archivo += '.c' try: f = QFile(nombre_de_archivo) if not f.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning("Guardar", "No se escribio en %s: %s" % ( nombre_de_archivo, f.errorString())) return False flujo = QTextStream(f) encode_flujo = flujo.codec().fromUnicode(contenido) f.write(encode_flujo) f.flush() f.close() except: pass return os.path.abspath(nombre_de_archivo)
def loadTemplate(self,filePath): """ Loads a document template into the view and updates the necessary STDM-related controls. """ if not QFile.exists(filePath): QMessageBox.critical(self.composerView(), QApplication.translate("OpenTemplateConfig","Open Template Error"), \ QApplication.translate("OpenTemplateConfig","The specified template does not exist.")) return templateFile = QFile(filePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Open Operation Error"), \ "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Cannot read template file."), \ templateFile.errorString() )) return templateDoc = QDomDocument() if templateDoc.setContent(templateFile): #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) self.clearWidgetMappings() #Load data controls composerDS = ComposerDataSource.create(templateDoc) self._configureDataControls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create(templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig)
def read_project(settings, openFileName): """ Toplevel reader routine. """ status = None handle = None try: handle = QFile(openFileName) if not handle.open(QIODevice.ReadOnly): raise IOError(handle.errorString()) stream = QDataStream(handle) # check header magic = stream.readInt32() if magic != MAGIC_NUMBER: status = ("Unrecognized file type - \n{0}\nis not " "a sconcho spf file!").format(openFileName) raise IOError(status) version = stream.readInt32() stream.setVersion(QDataStream.Qt_4_5) # initialize API specific entries repeatLegends = {} rowRepeats = [] textItems = [] rowLabels = {} columnLabels = {} if version == 1: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats) = read_API_1_version(stream, settings) elif version == 2: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems) = \ read_API_2_version(stream, settings) elif version == 3: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels) = \ read_API_3_version(stream, settings) else: raise IOError("unsupported API version") except (IOError, OSError) as e: status = "Failed to open %s: %s " % (openFileName, e) finally: if handle is not None: handle.close() if status is not None: return (False, status, None, None, None, None, None, None, None, None) return (True, None, patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels)
def _editTemplate(self,templatePath,newName): """ Updates the template document to use the new name. """ templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Open Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Cannot read template file."), \ templateFile.errorString() )) return (False,"") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerElement = templateDoc.documentElement() titleAttr = composerElement.attributeNode("_title") if not titleAttr.isNull(): titleAttr.setValue(newName) #Try remove file status = templateFile.remove() if not status: return (False,"") #Create new file newTemplatePath = self._composerTemplatesPath() + "/" + newName + ".sdt" newTemplateFile = QFile(newTemplatePath) if not newTemplateFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Could not save template file."), \ newTemplateFile.errorString() )) return (False,"") if newTemplateFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Error"), \ QApplication.translate("TemplateDocumentSelector","Could not save template file.")) return (False,"") newTemplateFile.close() return (True,newTemplatePath)
def httpDownload(theManager, theUrl, theOutPath, theProgressDlg=None): """ Download file from theUrl. Params: * theManager - a QNetworkManager instance * theUrl - url of file * theOutPath - output path * theProgressDlg - progress dialog widget Returns: True if success, otherwise return a tuple with format like this (QNetworkReply.NetworkError, error_message) Raises: * IOError - when cannot create theOutPath """ # prepare output path myFile = QFile(theOutPath) if not myFile.open(QFile.WriteOnly): raise IOError(myFile.errorString()) # slot to write data to file def writeData(): myFile.write(myReply.readAll()) myRequest = QNetworkRequest(QUrl(theUrl)) myReply = theManager.get(myRequest) myReply.readyRead.connect(writeData) if theProgressDlg: # progress bar def progressEvent(theReceived, theTotal): QCoreApplication.processEvents() theProgressDlg.setLabelText("%s / %s" % (theReceived, theTotal)) theProgressDlg.setMaximum(theTotal) theProgressDlg.setValue(theReceived) # cancel def cancelAction(): myReply.abort() myReply.downloadProgress.connect(progressEvent) theProgressDlg.canceled.connect(cancelAction) # wait until finished while not myReply.isFinished(): QCoreApplication.processEvents() myFile.close() myResult = myReply.error() if myResult == QNetworkReply.NoError: return True else: return (myResult, str(myReply.errorString()))
def save_project(canvas, colors, activeSymbol, settings, saveFileName): """ Toplevel writer routine. """ # prepare data structures patternGridItems = get_patternGridItems(canvas) legendItems = canvas.gridLegend.values() patternRepeats = get_patternRepeats(canvas) repeatLegends = canvas.repeatLegend rowRepeats = canvas.rowRepeatTracker rowLabels = canvas.rowLabels columnLabels = canvas.columnLabels textItems = canvas.canvasTextBoxes assert(len(patternRepeats) == len(repeatLegends)) status = None handle = None try: handle = QFile(saveFileName) if not handle.open(QIODevice.WriteOnly | QIODevice.Truncate): raise IOError(unicode(handle.errorString())) stream = QDataStream(handle) # write header stream.writeInt32(MAGIC_NUMBER) stream.writeInt32(API_VERSION) stream.setVersion(QDataStream.Qt_4_5) # write content write_patternGridItems(stream, patternGridItems) write_legendItems(stream, legendItems) write_colors(stream, colors) write_active_symbol(stream, activeSymbol) write_patternRepeats(stream, patternRepeats) write_repeatLegends(stream, repeatLegends) write_rowRepeats(stream, rowRepeats) write_textItems(stream, textItems) write_row_labels(stream, rowLabels) write_column_labels(stream, columnLabels) write_settings(stream, settings) except (IOError, OSError) as e: status = "Failed to save: %s " % e finally: if handle is not None: handle.close() if status is not None: return (False, status) return (True, None)
def __init__(self, settings, name, filename, plain_text=False, parent=None): super().__init__(parent=parent) splitty = QSplitter(self) self.setWidget(splitty) self.setWindowTitle(os.path.basename(name)) self.setFloating(True) self.setAttribute(Qt.WA_DeleteOnClose) self.plain_text = plain_text self.notePath = settings.notePath fh = QFile(filename) try: if not fh.open(QIODevice.ReadOnly): raise IOError(fh.errorString()) except IOError as e: QMessageBox.warning(self, self.tr("Read Error"), self.tr("Failed to open %s: %s") % (filename, e)) finally: if fh is not None: noteBody = QTextStream(fh).readAll() fh.close() self.tocw = TocTree(self) splitty.addWidget(self.tocw) strip_math_for_header_parsing = False strip_fence_for_header_parsing = False self.tocw.itemClicked.connect(self.tocNavigate) if 'asciimathml' in settings.extensions: stuff=JSCRIPT_TPL.format(settings.mathjax) strip_math_for_header_parsing = True else: stuff='' if 'fenced_code' in settings.extensions or 'extra' in settings.extensions: strip_fence_for_header_parsing = True if plain_text: note_view = QPlainTextEdit(self) qfnt = QFont() qfnt.setFamily('monospace') note_view.setFont(qfnt) note_view.setPlainText(noteBody) else: note_view = QWebView(self) note_view.setHtml(settings.md.reset().convert(noteBody)+stuff) note_view.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) note_view.linkClicked.connect(self.linkClicked) note_view.settings().setUserStyleSheetUrl( QUrl('file://'+self.parent().settings.cssfile)) self.note_view = note_view splitty.addWidget(note_view) self.tocw.updateToc(os.path.basename(name), parseHeaders(noteBody, strip_fenced_block=strip_fence_for_header_parsing, strip_ascii_math=strip_math_for_header_parsing))
def save_project(canvas, colors, activeSymbol, settings, saveFileName): """ Toplevel writer routine. """ # prepare data structures patternGridItems = get_patternGridItems(canvas) legendItems = canvas.gridLegend.values() patternRepeats = get_patternRepeats(canvas) repeatLegends = canvas.repeatLegend rowRepeats = canvas.rowRepeatTracker rowLabels = canvas.rowLabels columnLabels = canvas.columnLabels textItems = canvas.canvasTextBoxes assert (len(patternRepeats) == len(repeatLegends)) status = None handle = None try: handle = QFile(saveFileName) if not handle.open(QIODevice.WriteOnly | QIODevice.Truncate): raise IOError(unicode(handle.errorString())) stream = QDataStream(handle) # write header stream.writeInt32(MAGIC_NUMBER) stream.writeInt32(API_VERSION) stream.setVersion(QDataStream.Qt_4_5) # write content write_patternGridItems(stream, patternGridItems) write_legendItems(stream, legendItems) write_colors(stream, colors) write_active_symbol(stream, activeSymbol) write_patternRepeats(stream, patternRepeats) write_repeatLegends(stream, repeatLegends) write_rowRepeats(stream, rowRepeats) write_textItems(stream, textItems) write_row_labels(stream, rowLabels) write_column_labels(stream, columnLabels) write_settings(stream, settings) except (IOError, OSError) as e: status = "Failed to save: %s " % e finally: if handle is not None: handle.close() if status is not None: return (False, status) return (True, None)
def saveTemplate(self): """ Creates and saves a new document template. """ #Validate if the user has specified the data source if self.selectedDataSource() == "": QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \ QApplication.translate("ComposerWrapper","Please specify the " \ "data source name for the document composition.")) return #If it is a new unsaved document template then prompt for the document name. docFile = self.documentFile() if docFile == None: docName,ok = QInputDialog.getText(self.composerView(), \ QApplication.translate("ComposerWrapper","Template Name"), \ QApplication.translate("ComposerWrapper","Please enter the template name below"), \ ) if ok and docName != "": templateDir = self._composerTemplatesPath() if templateDir == None: QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \ QApplication.translate("ComposerWrapper","Directory for document templates could not be found.")) return absPath = templateDir + "/" + docName + ".sdt" docFile = QFile(absPath) else: return docFileInfo = QFileInfo(docFile) if not docFile.open(QIODevice.WriteOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Could not save template file."), \ docFile.errorString() )) return templateDoc = QDomDocument() self._writeXML(templateDoc, docFileInfo.completeBaseName()) if docFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Error"), \ QApplication.translate("ComposerWrapper","Could not save template file.")) return docFile.close() self.setDocumentFile(docFile)
def saveTemplate(self): """ Creates and saves a new document template. """ #Validate if the user has specified the data source if self.selectedDataSource() == "": QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \ QApplication.translate("ComposerWrapper","Please specify the " \ "data source name for the document composition.")) return #If it is a new unsaved document template then prompt for the document name. docFile = self.documentFile() if docFile == None: docName,ok = QInputDialog.getText(self.composerView(), \ QApplication.translate("ComposerWrapper","Template Name"), \ QApplication.translate("ComposerWrapper","Please enter the template name below"), \ ) if ok and docName != "": templateDir = self._composerTemplatesPath() if templateDir == None: QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Error"), \ QApplication.translate("ComposerWrapper","Directory for document templates could not be found.")) return absPath = templateDir + "/" + docName + ".sdt" docFile= QFile(absPath) else: return docFileInfo = QFileInfo(docFile) if not docFile.open(QIODevice.WriteOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Could not save template file."), \ docFile.errorString() )) return templateDoc = QDomDocument() self._writeXML(templateDoc,docFileInfo.completeBaseName()) if docFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Save Error"), \ QApplication.translate("ComposerWrapper","Could not save template file.")) return docFile.close() self.setDocumentFile(docFile)
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_plot(self, which=0): file_name = QFileDialog.getSaveFileName( None, 'Zapisz wykres jako...', "../saved_plots", '.PNG File (*.png);;All Files (*)")') if len(file_name) == 0: return plot_file = QFile(file_name) if not plot_file.open(QIODevice.WriteOnly): QMessageBox.about(self, "Nie uda\u0142o si\u0119 otworzy\u0107 pliku", plot_file.errorString()) return self.plot_canvases[which].save_plot_canvas(plot_file)
def loadQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) magic = stream.readInt32() if magic != MovieContainer.MAGIC_NUMBER: raise IOError("unrecognized file type") version = stream.readInt32() if version < MovieContainer.OLD_FILE_VERSION: raise IOError("old and unreadable file format") elif version > MovieContainer.FILE_VERSION: raise IOError("new and unreadable file format") old = False if version == MovieContainer.OLD_FILE_VERSION: old = True stream.setVersion(QDataStream.Qt_4_2) self.clear(False) while not stream.atEnd(): title = QString() acquired = QDate() location = QString() notes = QString() stream >> title year = stream.readInt16() minutes = stream.readInt16() if old: stream >> acquired >> notes else: stream >> acquired >> location >> notes self.add(Movie(title, year, minutes, acquired, location, notes)) except EnvironmentError as e: error = "Failed to load: {0}".format(e) 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())
def __init__(self, species=None, parent=None): super(CharacterSheetDocument, self).__init__(parent) self.__species = species ## Lade Datei mit Stylesheet-Informationen cssFile = QFile(":stylesheets/sheet.css") if not cssFile.open(QIODevice.ReadOnly): raise ErrFileNotOpened( "Wile opening file \"{}\", the error \"{}\" occured.".format( item, cssFile.errorString()), filename=item) cssStream = QTextStream(cssFile) cssContent = cssStream.readAll() cssFile.close() self.setDefaultStyleSheet(cssContent)
def __init__(self, species=None, parent=None): super(CharacterSheetDocument, self).__init__( parent) self.__species = species ## Lade Datei mit Stylesheet-Informationen cssFile = QFile(":stylesheets/sheet.css") if not cssFile.open(QIODevice.ReadOnly): raise ErrFileNotOpened( "Wile opening file \"{}\", the error \"{}\" occured.".format( item, cssFile.errorString() ), filename=item ) cssStream = QTextStream(cssFile) cssContent = cssStream.readAll() cssFile.close() self.setDefaultStyleSheet(cssContent)
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 save(self, pageName, filePath): fh = QFile(filePath) try: if not fh.open(QIODevice.WriteOnly): raise IOError(fh.errorString()) except IOError as e: QMessageBox.warning(self, 'Save Error', 'Failed to save %s: %s' % (pageName, e)) finally: if fh is not None: savestream = QTextStream(fh) savestream << self.toPlainText() fh.close() self.document().setModified(False) # Fork a process to update index, which benefit responsiveness. p = Process(target=self.updateIndex, args=( pageName, self.toPlainText(),)) p.start()
def run(self): fh = QFile(self.filename) fhlen = self._file_len(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) self.data_block = {} stream = QDataStream(fh) stream.setVersion(QDataStream.Qt_4_2) magic = stream.readInt32() if magic != gMAGICNUM: raise IOError, "not a valid .jd file" fileVersion = stream.readInt16() if fileVersion != gFILEVERSION: raise IOError, "unrecognised .jd file version" while not fh.atEnd(): self._ReadItemFromStream(stream) self.emit(SIGNAL("PROJECTLOADERDONE(PyQt_PyObject)"), self.data_block)
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 openFile(self, filename): fh = QFile(filename) try: if not fh.open(QIODevice.ReadOnly): raise IOError(fh.errorString()) except IOError as e: QMessageBox.warning(self, 'Read Error', 'Failed to open %s: %s' % (filename, e)) finally: if fh is not None: noteBody = QTextStream(fh).readAll() fh.close() self.notesEdit.setPlainText(noteBody) self.notesView.scrollPosition = QPoint(0, 0) # self.actionSave.setEnabled(False) self.notesEdit.document().setModified(False) self.notesView.updateView() self.setCurrentNote() self.updateRecentViewedNotes()
def save(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for saving" fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) stream.writeInt32(MAGIC_NUMBER) stream.writeInt16(FILE_VERSION) stream.setVersion(QDataStream.Qt_4_1) for ship in self.ships.values(): stream << ship.name << ship.owner << ship.country stream << ship.description stream.writeInt32(ship.teu) self.dirty = False except IOError, err: exception = err
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 save(self, item): pageName = self.parent.notesTree.itemToPage(item) filePath = self.parent.notesTree.itemToFile(item) htmlFile = self.parent.notesTree.itemToHtmlFile(item) fh = QFile(filePath) try: if not fh.open(QIODevice.WriteOnly): raise IOError(fh.errorString()) except IOError as e: QMessageBox.warning(self, "Save Error", "Failed to save %s: %s" % (pageName, e)) raise finally: if fh is not None: savestream = QTextStream(fh) savestream << self.toPlainText() fh.close() self.document().setModified(False) # Fork a process to update index, which benefit responsiveness. Process(target=self.updateIndex).start()
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, item): pageName = self.parent.notesTree.itemToPage(item) filePath = self.parent.notesTree.itemToFile(item) htmlFile = self.parent.notesTree.itemToHtmlFile(item) fh = QFile(filePath) try: if not fh.open(QIODevice.WriteOnly): raise IOError(fh.errorString()) except IOError as e: QMessageBox.warning(self, 'Save Error', 'Failed to save %s: %s' % (pageName, e)) raise finally: if fh is not None: savestream = QTextStream(fh) savestream << self.toPlainText() fh.close() self.document().setModified(False) # Fork a process to update index, which benefit responsiveness. Thread(target=self.updateIndex).start()
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 = ""