def save(self): if self.filename.startswith("Unnamed"): filename, filetype = QFileDialog.getSaveFileName( self, "Text Editor -- Save File As", self.filename, "Text files (*.txt *.*)") if not filename: 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 readTextFromFile(self, fileName=None, encoding=None): previousFileName = self._fileName if fileName: self._fileName = fileName # Only try to detect encoding if it is not specified if encoding is None and globalSettings.detectEncoding: encoding = self.detectFileEncoding(self._fileName) # TODO: why do we open the file twice: for detecting encoding # and for actual read? Can we open it just once? openfile = QFile(self._fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) # If encoding is specified or detected, we should save the file with # the same encoding self.editBox.document().setProperty("encoding", encoding) text = stream.readAll() openfile.close() if previousFileName != self._fileName: self.updateActiveMarkupClass() self.editBox.setPlainText(text) self.editBox.document().setModified(False) cssFileName = self.getBaseName() + '.css' self.cssFileExists = QFile.exists(cssFileName) if previousFileName != self._fileName: self.fileNameChanged.emit()
def overseek(self): outdatar = "" CONFIGPATH = os.path.join( sys.path[0], "plugins\\ResolutionExtension\\Resolution.txt") if QFile(CONFIGPATH).exists() == False: #Default outdatar = outdatar + self.overread(QSize(70, 70)) outdatar = outdatar + self.overread(QSize(95, 80)) outdatar = outdatar + self.overread(QSize(95, 95)) outdatar = outdatar + self.overread(QSize(160, 140)) outdatar = outdatar + self.overread(QSize(200, 200)) else: fh = QFile(CONFIGPATH) fh.open(QIODevice.ReadOnly) stream = QTextStream(fh) stream.setCodec(CODEC) while stream.atEnd() == False: tem = stream.readLine() if tem[0] == '#': continue tems = tem.split(",") if len(tems) == 2 and tems[0].isdigit() and tems[1].isdigit(): outdatar = outdatar + self.overread( QSize(int(tems[0]), int(tems[1]))) fh.close() return outdatar
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) as error: exception = error finally: if filehandle is not None: filehandle.close() if exception is not None: raise exception
def exportToTxt(self, fname): error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.WriteOnly): raise IOError(fh.errorString()) htmlTags = re.compile(r"<[^>]+?>") nonDigits = re.compile("[., ]") stream = QTextStream(fh) stream.setCodec(CODEC) for row in range(self.rowCount()): name = self.data(self.index(row, NAME)) owner = self.data(self.index(row, OWNER)) country = self.data(self.index(row, COUNTRY)) teu = self.data(self.index(row, TEU)) teu = int(nonDigits.sub("", teu)) description = self.data(self.index(row, DESCRIPTION)) description = htmlTags.sub("", description) stream << name << "|" << owner << "|" << country \ << "|" << teu << "|" << description << '\r\n' except Exception as e: error = "Failed to save: {}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error return True, "Saved {} ship records to {}".format( len(self.ships), QFileInfo(fname).fileName())
def saveQTextStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(unicode(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 (IOError, OSError) 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(self, content, path=None): """ Write a temporary 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 is not None: 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.willSave.emit(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 is not None: if new_path: # FIXME: what? # 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(unicode(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 (IOError, OSError) 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) as ioError: exception = ioError finally: if filehandle is not None: filehandle.close() for plugin in filter_plugins_by_capability('afterFileSave',self.enabled_plugins): plugin.do_afterFileSave(self) if exception is not None: raise exception
def __openByStream(self, fileName): ##用QTextStream打开文件 fileDevice = QFile(fileName) if not fileDevice.exists(): #判断文件是否存在 return False if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text): return False try: fileStream = QTextStream(fileDevice) fileStream.setAutoDetectUnicode(True) #自动检测Unicode fileStream.setCodec("utf-8") #必须设置编码,否则不能正常显示汉字 # 一次性全部读出 ## text=fileStream.readAll() #读取出来就是str ## self.ui.textEdit.setPlainText(text) #逐行读取方式 self.ui.textEdit.clear() while not fileStream.atEnd(): lineStr = fileStream.readLine() #读取文件的一行,读取出来就是str self.ui.textEdit.appendPlainText(lineStr) #添加到文本框显示 finally: fileDevice.close() #关闭文件 return True
def test3(): file = QFile("TopTitleUi.qss") file.open(QIODevice.ReadOnly | QIODevice.Text) fin = QTextStream(file) fin.setCodec("UTF-8") print(fin.readAll()) file.close()
def __readDepartmentsData(self): department_list = [] # of Department for file_name in MainWindow.dep_file_name_list: count = 0 file = QFile(':/stuff/' + file_name + '.txt') if not file.open(QIODevice.ReadOnly | QIODevice.Text): raise FileNotFoundError(file_name) stream = QTextStream(file) stream.setCodec('UTF-8') dep_name = stream.readLine() if dep_name[-1] != ':': raise Exception('resource ' + file_name + ' with no department mark') dep_name = dep_name[:-1] new_dep_obj = Department(dep_name) while not stream.atEnd(): count += 1 (n, s) = stream.readLine().split() if count == 1: new_dep_obj.setBoss(Employee(n, s)) else: new_dep_obj.addEmployee(Employee(n, s)) if count == 0: raise Exception('resource ' + file_name + ' has no items') department_list.append(new_dep_obj) return department_list
def test2(): file = QFile("ansi.txt") file.open(QIODevice.ReadOnly | QIODevice.Text) fin = QTextStream(file) fin.setCodec("UTF-8") print(fin.readAll()) file.close()
def test1(): file = QFile("utf8.txt") file.open(QIODevice.ReadOnly) fin = QTextStream(file) fin.setCodec("UTF-8") print(fin.readAll()) file.close()
def readTextFromFile(self, fileName=None, encoding=None): previousFileName = self._fileName if fileName: self._fileName = fileName # Only try to detect encoding if it is not specified if encoding is None and globalSettings.detectEncoding: encoding = self.detectFileEncoding(self._fileName) # TODO: why do we open the file twice: for detecting encoding # and for actual read? Can we open it just once? openfile = QFile(self._fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) # If encoding is specified or detected, we should save the file with # the same encoding self.editBox.document().setProperty("encoding", encoding) text = stream.readAll() openfile.close() self.editBox.setPlainText(text) self.editBox.document().setModified(False) if previousFileName != self._fileName: self.updateActiveMarkupClass() self.fileNameChanged.emit()
def writeTextToFile(self, fileName=None): # Just writes the text to file, without any changes to tab object # Used directly for e.g. export extensions # Get text from the cursor to avoid tweaking special characters, # see https://bugreports.qt.io/browse/QTBUG-57552 and # https://github.com/retext-project/retext/issues/216 cursor = self.editBox.textCursor() cursor.select(QTextCursor.SelectionType.Document) text = cursor.selectedText().replace('\u2029', '\n') savefile = QFile(fileName or self._fileName) result = savefile.open(QFile.OpenModeFlag.WriteOnly) if result: savestream = QTextStream(savefile) # Save the file with original encoding encoding = self.editBox.document().property("encoding") encoding = encoding or globalSettings.defaultCodec if encoding is not None: savestream.setCodec(encoding) savestream << text savefile.close() return result
def readTextFromFile(self, fileName=None, encoding=None): previousFileName = self._fileName if fileName: self._fileName = fileName openfile = QFile(self._fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) # Only try to detect encoding if it is not specified if encoding is None and globalSettings.detectEncoding: encoding = self.detectFileEncoding(fileName) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) # If encoding is specified or detected, we should save the file with # the same encoding self.editBox.document().setProperty("encoding", encoding) text = stream.readAll() openfile.close() self.editBox.setPlainText(text) self.editBox.document().setModified(False) if previousFileName != self._fileName: self.updateActiveMarkupClass() self.fileNameChanged.emit()
def do_snap(self,gfile): img = Snapshot.snapshot(width = 200, height = 200).scaled(200,200,Qt.IgnoreAspectRatio, Qt.SmoothTransformation) outdata = "" outdata = outdata + self.overseek() outdata = outdata + "; bigtree thumbnail end\r\n\r\n" outdata = outdata + self.material_usage() fh = QFile(gfile) fh.open(QIODevice.ReadOnly) stream = QTextStream(fh) stream.setCodec(CODEC) fg = stream.readAll() + "\r\n" if self.extruder_M2O() == True: fg = fg.replace("M104 T0",";M104 T0") fg = fg.replace("M104 T1",";M104 T1") fg = fg.replace("M109 T0",";M109 T0") fg = fg.replace("M109 T1",";M109 T1") fh.close() bigtree3dfile = os.path.splitext(gfile)[0]+"[Bigtree].gcode" fh = QFile(bigtree3dfile) fh.open(QIODevice.WriteOnly) stream = QTextStream(fh) stream.setCodec(CODEC) stream << outdata stream << fg fh.close() os.remove(gfile)
def save(self): if "Unnamed" in self.filename: filename = QFileDialog.getSaveFileName( self, "G.R.O.M. Editor -- Save File As", self.filename, "MD files (*.mdp *.itp *.top *.*)") print('filename is ', filename) if len(filename[0]) == 0: return self.filename = filename[0] 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): if "Unnamed" in self.filename: filename = QFileDialog.getSaveFileName(self, "G.R.O.M. Editor -- Save File As", self.filename, "MD files (*.mdp *.itp *.top *.*)") print('filename is ', filename) if len(filename[0]) == 0: return self.filename = filename[0] 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, content, path=None): """ Write a temporary 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 is not None: 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.willSave.emit(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 is not None: 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 reader(file_path): file = QFile(file_path) file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) stream.setCodec("UTF-8") content = stream.readAll() file.close() return content
def readFile(self, path, coding="UTF-8"): """读取文件""" file = QFile(path) file.open(QIODevice.ReadOnly | QIODevice.Text) fin = QTextStream(file) fin.setCodec(coding) data = fin.readAll() file.close() return data
def __readDefaultSchedule(self, num_of_days): file_name = 'default' file = QFile(':/schedule/' + file_name + '.txt') if not file.open(QIODevice.ReadOnly | QIODevice.Text): raise FileNotFoundError(file_name) stream = QTextStream(file) stream.setCodec('UTF-8') Matrix = [[[] for i in range(0, num_of_days)] for j in range(0, 9)] days_of_week = [ '', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье' ] while not stream.atEnd(): week_day = stream.readLine()[:-1] line = stream.readLine() while line: params_of_event = line.split(',') time = int(params_of_event[0].replace(':', '')) duration = int(params_of_event[1]) title = params_of_event[2] location = params_of_event[3] department = params_of_event[4] start_day_number = days_of_week.index(week_day) days_list = [ k for k in range(start_day_number, num_of_days, 7) ] type = ScheduleEvent.Type.HEAD if department == 'Руководство' else ScheduleEvent.Type.DEP participants_list = [] if type == ScheduleEvent.Type.HEAD: participants_list.append(self.firm.getBoss()) for dep in self.checked_departments: participants_list.append(dep.getBoss()) elif type == ScheduleEvent.Type.DEP: for dep in self.checked_departments: if dep.getName() == department: participants_list.extend(dep.getEmployeeList()) else: raise Exception( 'Error while processing default schedule data: TYPE') for day in days_list: if len(participants_list) != 0: Matrix[int(time / 100) - 10][day - 1].append( ScheduleEvent(time=time, duration=duration, title=title, location=location, type=type, part_list=participants_list, day=day)) line = stream.readLine() self.Matrix = Matrix
def readFile(self, path, coding = "UTF-8"): """读取文件""" file = QFile(path) file.open(QIODevice.ReadOnly | QIODevice.Text) fin = QTextStream(file) fin.setCodec(coding) data = fin.readAll() file.close() return data
def save_project(doc: QDomDocument, file_name="./test.xml"): file = QFile(file_name) if not file.open(QIODevice.ReadWrite): return False out = QTextStream(file) out.setCodec("UTF-8") doc.save(out, 4, QDomNode.EncodingFromTextStream) file.close() return True
def readData(path): file=QFile(path) if not file.open(QIODevice.ReadOnly): log.warn("读取样式文件失败") return '' stream=QTextStream(file) stream.setCodec(QTextCodec.codecForName('utf-8')) data=stream.readAll() del stream return data
def updateTextEdit(self): mib = self.encodingComboBox.itemData(self.encodingComboBox.currentIndex()) codec = QTextCodec.codecForMib(mib) data = QTextStream(self.encodedData) data.setAutoDetectUnicode(False) data.setCodec(codec) self.decodedStr = data.readAll() self.textEdit.setPlainText(self.decodedStr)
def initSkin(self): skin = QFile("resources/themes/default.qss") if not skin.exists() or not skin.open(QFile.ReadOnly | QFile.Text): del skin else: qts = QTextStream(skin) qts.setCodec("UTF-8") data = qts.readAll() skin.close() del skin self.setStyleSheet(data)
def readData(path): """red file data""" file = QFile(path) if not file.open(QIODevice.ReadOnly): return stream = QTextStream(file) stream.setCodec(QTextCodec.codecForName('UTF-8')) data = stream.readAll() file.close() del stream return data
def readText(self, path): file = QFile(path) if not file.open(QIODevice.ReadOnly): return '' stream = QTextStream(file) # 下面这句设置编码根据文件的编码自行确定 stream.setCodec(QTextCodec.codecForName('UTF-8')) data = stream.readAll() file.close() del stream return data
def loadFile(self): fh = QFile(self.filename) print("fh is ", fh) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") # self.setPlainText("Hello World") self.preParse = (stream.readAll()) # Here lies the problem how to fix it? PyQt 3.4.2 Works Fine print(self.preParse) self.parseOutputData(self.preParse)
def writeTextToFile(self, fileName=None): # Just writes the text to file, without any changes to tab object # Used directly for i.e. export extensions savefile = QFile(fileName or self._fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBox.toPlainText() savefile.close() return result
def writeFile(self): file = QFile("./doc/test.txt") #写文件第一步首先创建文件对象 #file.setFileName("./doc/test.txt") #第二步将文件路径与文件关联,有2中方式,一是在创建文件对象时指定路径,二是通过setFileName指定 isok = file.open(QIODevice.WriteOnly) #第三步打开文件,返回值为True/False if isok: stream = QTextStream(file) #创建文本流并且与打开的文件相关联,向文本流读写数据相当于从文件读写数据 stream.setCodec("gbk") school = "nenu102" num = 52 stream << school << num #向文本流中写入数据通过<<操作符 file.close() #文本流操作结束后,关闭文件
def read(self): """ Reads the file and returns the content """ _file = QFile(self.filename) if not _file.open(QIODevice.ReadOnly | QIODevice.Text): raise Exception(_file.errorString()) # Codec codec = QTextCodec.codecForLocale() stream = QTextStream(_file) stream.setCodec(codec) return stream.readAll()
def saveFileCore(self, fn): self.fileSystemWatcher.removePath(fn) savefile = QFile(fn) result = savefile.open(QIODevice.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBoxes[self.ind].toPlainText() savefile.close() self.fileSystemWatcher.addPath(fn) return result
def writeTextToFile(self, fileName=None): # Just writes the text to file, without any changes to tab object # Used directly for i.e. export extensions savefile = QFile(fileName or self._fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBox.toPlainText() savefile.close() return result
def readTextFromFile(self, encoding=None): openfile = QFile(self.fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) text = stream.readAll() openfile.close() markupClass = get_markup_for_file_name(self.fileName, return_class=True) self.setMarkupClass(markupClass) modified = bool(encoding) and (self.editBox.toPlainText() != text) self.editBox.setPlainText(text) self.editBox.document().setModified(modified)
def save(self): fileName, _ = QFileDialog.getSaveFileName(self) if fileName: outFile = QFile(fileName) if not outFile.open(QFile.WriteOnly|QFile.Text): QMessageBox.warning(self, "Codecs", "Cannot write file %s:\n%s" % (fileName, outFile.errorString())) return action = self.sender() codecName = action.data() out = QTextStream(outFile) out.setCodec(codecName) out << self.textEdit.toPlainText()
def saveHtml(self, fileName): if not QFileInfo(fileName).suffix(): fileName += ".html" try: htmltext = self.currentTab.getHtml(includeStyleSheet=False, webenv=True) except Exception: return self.printError() htmlFile = QFile(fileName) htmlFile.open(QIODevice.WriteOnly) html = QTextStream(htmlFile) if globalSettings.defaultCodec: html.setCodec(globalSettings.defaultCodec) html << htmltext htmlFile.close()
def saveTextToFile(self, fileName=None, addToWatcher=True): if fileName is None: fileName = self.fileName self.p.fileSystemWatcher.removePath(fileName) savefile = QFile(fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBox.toPlainText() savefile.close() if result and addToWatcher: self.p.fileSystemWatcher.addPath(fileName) return result
def writeTextToFile(self, fileName=None): # Just writes the text to file, without any changes to tab object # Used directly for i.e. export extensions savefile = QFile(fileName or self._fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) # Save the file with original encoding encoding = self.editBox.document().property("encoding") if encoding is not None: savestream.setCodec(encoding) savestream << self.editBox.toPlainText() savefile.close() return result
def save(self, data, path=None): if path: self.filename = path self.is_new = False _file = QFile(self.filename) if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate): raise Exception(_file.errorString()) stream = QTextStream(_file) stream.setCodec(QTextCodec.codecForLocale()) stream << data stream.flush() _file.close() # Emit the signal self.fileSaved.emit(self.filename)
def __init__(self, subtitle, encoding="UTF-8"): super().__init__() subtitlefile = QFile(subtitle) if not subtitlefile.open(QIODevice.ReadOnly | QIODevice.Text): return text = QTextStream(subtitlefile) text.setCodec(encoding) subtitletext = text.readAll() # ('sıra', 'saat', 'dakika', 'saniye', 'milisaniye', 'saat', 'dakika', 'saniye', 'milisaniye', 'birincisatır', 'ikincisatır') compile = re.compile(r"(\d.*)\n(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})\n(\W.*|\w.*)\n(\w*|\W*|\w.*|\W.*)\n") self.sublist = compile.findall(subtitletext)
def load(self): # Windows crash buty why exception = None fh = None print("Hello Load Text File") # Looks like there's bug in windows try: fh = QFile(self.filename) print("fh is ", fh) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") # self.setPlainText("Hello World") self.setPlainText(stream.readAll()) # Here lies the problem how to fix it? PyQt 3.4.2 Works Fine self.document().setModified(False) except EnvironmentError as e: exception = e
def saveHtml(self, fileName): if not QFileInfo(fileName).suffix(): fileName += ".html" try: _, htmltext, _ = self.currentTab.getDocumentForExport(includeStyleSheet=False, webenv=True) except Exception: return self.printError() htmlFile = QFile(fileName) result = htmlFile.open(QIODevice.WriteOnly) if not result: QMessageBox.warning(self, '', self.tr("Cannot save to file because it is read-only!")) return html = QTextStream(htmlFile) if globalSettings.defaultCodec: html.setCodec(globalSettings.defaultCodec) html << htmltext htmlFile.close()
def readTextFromFile(self, fileName=None, encoding=None): previousFileName = self._fileName if fileName: self._fileName = fileName openfile = QFile(self._fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) text = stream.readAll() openfile.close() modified = bool(encoding) and (self.editBox.toPlainText() != text) self.editBox.setPlainText(text) self.editBox.document().setModified(modified) if previousFileName != self._fileName: self.updateActiveMarkupClass() self.fileNameChanged.emit()
def openFileMain(self, encoding=None): openfile = QFile(self.currentTab.fileName) openfile.open(QIODevice.ReadOnly) stream = QTextStream(openfile) if encoding: stream.setCodec(encoding) elif globalSettings.defaultCodec: stream.setCodec(globalSettings.defaultCodec) text = stream.readAll() openfile.close() markupClass = markups.get_markup_for_file_name( self.currentTab.fileName, return_class=True) self.currentTab.highlighter.docType = (markupClass.name if markupClass else '') self.currentTab.markup = self.getMarkup() if self.defaultMarkup: self.currentTab.highlighter.docType = self.defaultMarkup.name editBox = self.currentTab.editBox modified = bool(encoding) and (editBox.toPlainText() != text) editBox.setPlainText(text) self.setCurrentFile() editBox.document().setModified(modified) self.setWindowModified(modified)
def saveTextToFile(self, fileName=None, addToWatcher=True): previousFileName = self._fileName if fileName: self._fileName = fileName self.p.fileSystemWatcher.removePath(previousFileName) savefile = QFile(self._fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBox.toPlainText() savefile.close() self.editBox.document().setModified(False) if result and addToWatcher: self.p.fileSystemWatcher.addPath(self._fileName) if previousFileName != self._fileName: self.updateActiveMarkupClass() self.fileNameChanged.emit() return result
def writeTextToFile(self, fileName=None): # Just writes the text to file, without any changes to tab object # Used directly for e.g. export extensions # Get text from the cursor to avoid tweaking special characters, # see https://bugreports.qt.io/browse/QTBUG-57552 and # https://github.com/retext-project/retext/issues/216 cursor = self.editBox.textCursor() cursor.select(QTextCursor.Document) text = cursor.selectedText().replace('\u2029', '\n') savefile = QFile(fileName or self._fileName) result = savefile.open(QFile.WriteOnly) if result: savestream = QTextStream(savefile) # Save the file with original encoding encoding = self.editBox.document().property("encoding") if encoding is not None: savestream.setCodec(encoding) savestream << text savefile.close() return result
def write(self, map, fileName): file = QSaveFile(fileName) if (not file.open(QFile.WriteOnly | QFile.Text)): self.mError = self.tr("Could not open file for writing.") return False out = QTextStream(file) out.setCodec("UTF-8") mapWidth = map.width() mapHeight = map.height() # write [header] out << "[header]\n" out << "width=" << str(mapWidth) << "\n" out << "height=" << str(mapHeight) << "\n" out << "tilewidth=" << str(map.tileWidth()) << "\n" out << "tileheight=" << str(map.tileHeight()) << "\n" out << "orientation=" << str(orientationToString(map.orientation())) << "\n" # write all properties for this map for it in map.properties().__iter__(): out << it[0] << "=" << it[1] << "\n" out << "\n" mapDir = QFileInfo(fileName).absoluteDir() out << "[tilesets]\n" for tileset in map.tilesets(): imageSource = tileset.imageSource() source = mapDir.relativeFilePath(imageSource) out << "tileset=" << source \ << "," << str(tileset.tileWidth()) \ << "," << str(tileset.tileHeight()) \ << "," << str(tileset.tileOffset().x()) \ << "," << str(tileset.tileOffset().y()) \ << "\n" out << "\n" gidMapper = GidMapper(map.tilesets()) # write layers for layer in map.layers(): tileLayer = layer.asTileLayer() if tileLayer: out << "[layer]\n" out << "type=" << layer.name() << "\n" out << "data=\n" for y in range(0, mapHeight): for x in range(0, mapWidth): t = tileLayer.cellAt(x, y) id = 0 if (t.tile): id = gidMapper.cellToGid(t) out << id if (x < mapWidth - 1): out << "," if (y < mapHeight - 1): out << "," out << "\n" out << "\n" group = layer.asObjectGroup() if group: for o in group.objects(): if o.type() != '': out << "[" << group.name() << "]\n" # display object name as comment if o.name() != '': out << "# " << o.name() << "\n" out << "type=" << o.type() << "\n" x,y,w,h = 0 if (map.orientation() == Map.Orthogonal): x = o.x()/map.tileWidth() y = o.y()/map.tileHeight() w = o.width()/map.tileWidth() h = o.height()/map.tileHeight() else : x = o.x()/map.tileHeight() y = o.y()/map.tileHeight() w = o.width()/map.tileHeight() h = o.height()/map.tileHeight() out << "location=" << x << "," << y out << "," << w << "," << h << "\n" # write all properties for this object for it in o.properties().__iter__(): out << it[0] << "=" << it[1] << "\n" out << "\n" if not file.commit(): self.mError = file.errorString() return False return True
class QtSingleApplication(QApplication): """ This class makes sure that we can only start one Tribler application. When a user tries to open a second Tribler instance, the current active one will be brought to front. """ messageReceived = pyqtSignal(unicode) def __init__(self, win_id, *argv): logfunc = logging.info logfunc(sys._getframe().f_code.co_name + '()') QApplication.__init__(self, *argv) self._id = win_id self._activation_window = None self._activate_on_message = False # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected() self._outStream = None self._inSocket = None self._inStream = None self._server = None if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') else: # No, there isn't, at least not properly. # Cleanup any past, crashed server. error = self._outSocket.error() logfunc(LOGVARSTR % ('self._outSocket.error()', error)) if error == QLocalSocket.ConnectionRefusedError: logfunc('received QLocalSocket.ConnectionRefusedError; ' + \ 'removing server.') self.close() QLocalServer.removeServer(self._id) self._outSocket = None self._server = QLocalServer() self._server.listen(self._id) self._server.newConnection.connect(self._on_new_connection) logfunc(sys._getframe().f_code.co_name + '(): returning') def close(self): logfunc = logging.info logfunc(sys._getframe().f_code.co_name + '()') if self._inSocket: self._inSocket.disconnectFromServer() if self._outSocket: self._outSocket.disconnectFromServer() if self._server: self._server.close() logfunc(sys._getframe().f_code.co_name + '(): returning') def is_running(self): return self._isRunning def get_id(self): return self._id def activation_window(self): return self._activation_window def set_activation_window(self, activation_window, activate_on_message=True): self._activation_window = activation_window self._activate_on_message = activate_on_message def activate_window(self): if not self._activation_window: return self._activation_window.setWindowState( self._activation_window.windowState() & ~Qt.WindowMinimized) self._activation_window.raise_() def send_message(self, msg): if not self._outStream: return False self._outStream << msg << '\n' self._outStream.flush() return self._outSocket.waitForBytesWritten() def _on_new_connection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._on_ready_read) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec('UTF-8') self._inSocket.readyRead.connect(self._on_ready_read) if self._activate_on_message: self.activate_window() def _on_ready_read(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
class LogsReadThread(QThread): MAX_INITIAL_SIZE = 2*1024*1024 # 2Mb updateLogs = pyqtSignal() def __init__(self, parent): QThread.__init__(self, parent) self.fCloseNow = False self.fPurgeLogs = False self.fRealParent = parent # ------------------------------------------------------------- # Take some values from Logs Window self.LOG_FILE_JACK = LogsW.LOG_FILE_JACK self.LOG_FILE_A2J = LogsW.LOG_FILE_A2J self.LOG_FILE_LASH = LogsW.LOG_FILE_LASH self.LOG_FILE_LADISH = LogsW.LOG_FILE_LADISH # ------------------------------------------------------------- # Init logs if self.LOG_FILE_JACK is not None: self.fLogFileJACK = QFile(self.LOG_FILE_JACK) self.fLogFileJACK.open(QIODevice.ReadOnly) self.fLogStreamJACK = QTextStream(self.fLogFileJACK) self.fLogStreamJACK.setCodec("UTF-8") if self.fLogFileJACK.size() > self.MAX_INITIAL_SIZE: self.fLogStreamJACK.seek(self.fLogFileJACK.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_A2J is not None: self.fLogFileA2J = QFile(self.LOG_FILE_A2J) self.fLogFileA2J.open(QIODevice.ReadOnly) self.fLogStreamA2J = QTextStream(self.fLogFileA2J) self.fLogStreamA2J.setCodec("UTF-8") if self.fLogFileA2J.size() > self.MAX_INITIAL_SIZE: self.fLogStreamA2J.seek(self.fLogFileA2J.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_LASH is not None: self.fLogFileLASH = QFile(self.LOG_FILE_LASH) self.fLogFileLASH.open(QIODevice.ReadOnly) self.fLogStreamLASH = QTextStream(self.fLogFileLASH) self.fLogStreamLASH.setCodec("UTF-8") if self.fLogFileLASH.size() > self.MAX_INITIAL_SIZE: self.fLogStreamLASH.seek(self.fLogFileLASH.size() - self.MAX_INITIAL_SIZE) if self.LOG_FILE_LADISH is not None: self.fLogFileLADISH = QFile(self.LOG_FILE_LADISH) self.fLogFileLADISH.open(QIODevice.ReadOnly) self.fLogStreamLADISH = QTextStream(self.fLogFileLADISH) self.fLogStreamLADISH.setCodec("UTF-8") if self.fLogFileLADISH.size() > self.MAX_INITIAL_SIZE: self.fLogStreamLADISH.seek(self.fLogFileLADISH.size() - self.MAX_INITIAL_SIZE) def closeNow(self): self.fCloseNow = True def purgeLogs(self): self.fPurgeLogs = True def run(self): # ------------------------------------------------------------- # Read logs and set text in main thread while not self.fCloseNow: if self.fPurgeLogs: if self.LOG_FILE_JACK: self.fLogStreamJACK.flush() self.fLogFileJACK.close() self.fLogFileJACK.open(QIODevice.WriteOnly) self.fLogFileJACK.close() self.fLogFileJACK.open(QIODevice.ReadOnly) if self.LOG_FILE_A2J: self.fLogStreamA2J.flush() self.fLogFileA2J.close() self.fLogFileA2J.open(QIODevice.WriteOnly) self.fLogFileA2J.close() self.fLogFileA2J.open(QIODevice.ReadOnly) if self.LOG_FILE_LASH: self.fLogStreamLASH.flush() self.fLogFileLASH.close() self.fLogFileLASH.open(QIODevice.WriteOnly) self.fLogFileLASH.close() self.fLogFileLASH.open(QIODevice.ReadOnly) if self.LOG_FILE_LADISH: self.fLogStreamLADISH.flush() self.fLogFileLADISH.close() self.fLogFileLADISH.open(QIODevice.WriteOnly) self.fLogFileLADISH.close() self.fLogFileLADISH.open(QIODevice.ReadOnly) self.fPurgeLogs = False else: if self.LOG_FILE_JACK: textJACK = fixLogText(self.fLogStreamJACK.readAll()).strip() else: textJACK = "" if self.LOG_FILE_A2J: textA2J = fixLogText(self.fLogStreamA2J.readAll()).strip() else: textA2J = "" if self.LOG_FILE_LASH: textLASH = fixLogText(self.fLogStreamLASH.readAll()).strip() else: textLASH = "" if self.LOG_FILE_LADISH: textLADISH = fixLogText(self.fLogStreamLADISH.readAll()).strip() else: textLADISH = "" self.fRealParent.setLogsText(textJACK, textA2J, textLASH, textLADISH) self.updateLogs.emit() if not self.fCloseNow: self.sleep(1) # ------------------------------------------------------------- # Close logs before closing thread if self.LOG_FILE_JACK: self.fLogFileJACK.close() if self.LOG_FILE_A2J: self.fLogFileA2J.close() if self.LOG_FILE_LASH: self.fLogFileLASH.close() if self.LOG_FILE_LADISH: self.fLogFileLADISH.close()
class QtSingleApplication(QApplication): messageReceived = pyqtSignal(str) def __init__(self, id, *argv): super(QtSingleApplication, self).__init__(*argv) self._id = id self._activationWindow = None self._activateOnMessage = False # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected() if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec("UTF-8") else: # No, there isn't. self._outSocket = None self._outStream = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) def isRunning(self): return self._isRunning def id(self): return self._id def activationWindow(self): return self._activationWindow def setActivationWindow(self, activationWindow, activateOnMessage=True): self._activationWindow = activationWindow self._activateOnMessage = activateOnMessage def activateWindow(self): if not self._activationWindow: return self._activationWindow.show() self._activationWindow.setWindowState(self._activationWindow.windowState() & ~Qt.WindowMinimized) self._activationWindow.raise_() self._activationWindow.activateWindow() def sendMessage(self, msg): if not self._outStream: return False self._outStream << msg << "\n" self._outStream.flush() return self._outSocket.waitForBytesWritten() def _onNewConnection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._onReadyRead) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec("UTF-8") self._inSocket.readyRead.connect(self._onReadyRead) if self._activateOnMessage: self.activateWindow() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg)
class Eddy(QApplication): """ This class implements the main Qt application. """ messageReceived = pyqtSignal(str) def __init__(self, argv): """ Initialize Eddy. :type argv: list """ super().__init__(argv) parser = ArgumentParser() parser.add_argument('--nosplash', dest='nosplash', action='store_true') parser.add_argument('--tests', dest='tests', action='store_true') options, args = parser.parse_known_args(args=argv) self.inSocket = None self.inStream = None self.outSocket = QLocalSocket() self.outSocket.connectToServer(APPID) self.outStream = None self.isRunning = self.outSocket.waitForConnected() self.mainwindow = None self.pendingOpen = [] self.server = None # We do not initialize a new instance of Eddy if there is a process running # and we are not executing the tests suite: we'll create a socket instead so we can # exchange messages between the 2 processes (this one and the already running one). if self.isRunning and not options.tests: self.outStream = QTextStream(self.outSocket) self.outStream.setCodec('UTF-8') else: self.server = QLocalServer() self.server.listen(APPID) self.outSocket = None self.outStream = None connect(self.server.newConnection, self.newConnection) connect(self.messageReceived, self.readMessage) ############################################################################################################ # # # PERFORM EDDY INITIALIZATION # # # ############################################################################################################ # Draw the splashscreen. self.splashscreen = None if not options.nosplash: self.splashscreen = SplashScreen(min_splash_time=4) self.splashscreen.show() # Setup layout. self.setStyle(Clean('Fusion')) with open(expandPath('@eddy/ui/clean.qss')) as sheet: self.setStyleSheet(sheet.read()) # Create the main window. self.mainwindow = MainWindow() # Close the splashscreen. if self.splashscreen: self.splashscreen.wait(self.splashscreen.remaining) self.splashscreen.close() # Display the mainwindow. self.mainwindow.show() if Platform.identify() is Platform.Darwin: # On MacOS files being opened are handled as a QFileOpenEvent but since we don't # have a Main Window initialized we store them locally and we open them here. for filepath in self.pendingOpen: self.openFile(filepath) self.pendingOpen = [] else: # Perform document opening if files have been added to sys.argv. This is not # executed on Mac OS since this is already handled as a QFileOpenEvent instance. for filepath in argv: self.openFile(filepath) #################################################################################################################### # # # EVENTS # # # #################################################################################################################### def event(self, event): """ Executed when an event is received. :type event: T <= QEvent | QFileOpenEvent """ if event.type() == QEvent.FileOpen: self.pendingOpen = [event.file()] return True return super().event(event) #################################################################################################################### # # # INTERFACE # # # #################################################################################################################### def activate(self): """ Activate the application by raising the main window. """ if self.mainwindow: self.mainwindow.setWindowState((self.mainwindow.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive) self.mainwindow.activateWindow() self.mainwindow.raise_() def openFile(self, filepath): """ Open the given file in the activation window. :type filepath: str :rtype: bool """ if self.mainwindow: if not isEmpty(filepath) and os.path.isfile(filepath) and filepath.endswith(Filetype.Graphol.extension): self.mainwindow.openFile(filepath) return True return False def sendMessage(self, message): """ Send a message to the other alive Eddy's process. :type message: str :rtype: bool """ if self.outStream: self.outStream = self.outStream << message << '\n' self.outStream.flush() return self.outSocket.waitForBytesWritten() return False #################################################################################################################### # # # SLOTS # # # #################################################################################################################### @pyqtSlot() def newConnection(self): """ Executed whenever a message is received. """ if self.inSocket: # Disconnect previously connected signal slot. disconnect(self.inSocket.readyRead, self.readyRead) # Create a new socket. self.inSocket = self.server.nextPendingConnection() if self.inSocket: self.inStream = QTextStream(self.inSocket) self.inStream.setCodec('UTF-8') connect(self.inSocket.readyRead, self.readyRead) self.activate() @pyqtSlot() def readyRead(self): """ Executed whenever we need to read a message. """ while True: message = self.inStream.readLine() if isEmpty(message): break self.messageReceived.emit(message) @pyqtSlot(str) def readMessage(self, message): """ Read a received message. :type message: str """ for filepath in message.split(' '): self.openFile(filepath)