Esempio n. 1
0
    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()
Esempio n. 2
0
 def writeTemplates(self, filename=None):
     """
     Public method to write the templates data to an XML file (.e4c).
     
     @param filename name of a templates file to read (string)
     @return flag indicating success (boolean)
     """
     if filename is None:
         filename = os.path.join(
             Utilities.getConfigDir(), "eric6templates.e4c")
     f = QFile(filename)
     ok = f.open(QIODevice.WriteOnly)
     if not ok:
         E5MessageBox.critical(
             self,
             self.tr("Save templates"),
             self.tr(
                 "<p>The templates file <b>{0}</b> could not be"
                 " written.</p>")
             .format(filename))
         return False
     
     from E5XML.TemplatesWriter import TemplatesWriter
     TemplatesWriter(f, self).writeXML()
     f.close()
     
     return True
Esempio n. 3
0
    def load_file(self, fname, check_for_changes=True):
        """
        load a file's content into the application.

        Parameters
        ----------
        fname : str
                full file path and name of the file to load
        check_for_changes : bool
                flag to check for save prompt if file has unsaved changes
        Returns
        -------
        None
        """

        if check_for_changes:
            changed = self.check_for_changes()
            if changed == "Cancel":
                return changed

        self.file_watcher = QFileSystemWatcher([fname])
        self.file_watcher.fileChanged.connect(self.file_updated)
        self.last_updated = time.time()

        self.clear_validation()

        # check that we have read write access to the file
        file = QFile(fname)
        if not file.open(QFile.ReadOnly | QFile.Text):
            msg = "Cannot read file %s:\n%s." % (fname, file.errorString())
            QMessageBox.warning(self, "Recent Files", msg)
            return
        file.close()

        self.load_file_content(fname)
Esempio n. 4
0
 def _load_qwebchannel(self):
     qwebchannel_js = QFile('src/js/qwebchannel.min.js')
     if qwebchannel_js.open(QIODevice.ReadOnly):
         content = qwebchannel_js.readAll()
         qwebchannel_js.close()
         self.page().runJavaScript(content.data().decode())
     self._set_web_channel()
Esempio n. 5
0
    def __openByIODevice(self, fileName):  ##用QFile打开文件
        fileDevice = QFile(fileName)
        if not fileDevice.exists():  #判断文件是否存在
            return False

        if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
            return False

###整个文件一次性读取的方式,可行
##      qtBytes=fileDevice.readAll() #返回QByteArray类型
##      pyBytes=bytes(qtBytes.data())  # 将QByteArray转换为bytes类型
##      text=pyBytes.decode("utf-8")  #用utf-8编码为字符串
##      self.ui.textEdit.setPlainText(text)

##  逐行读取方式,可行
        try:
            self.ui.textEdit.clear()
            while not fileDevice.atEnd():
                qtBytes = fileDevice.readLine()  # 返回QByteArray类型
                pyBytes = bytes(qtBytes.data())  # QByteArray转换为bytes类型
                lineStr = pyBytes.decode("utf-8")  #bytes转换为str型
                lineStr = lineStr.strip()  #去除结尾增加的空行
                self.ui.textEdit.appendPlainText(lineStr)
        finally:
            fileDevice.close()

        return True
Esempio n. 6
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setupUi(self)

        headers = ("Title", "Description")

        file = QFile(':/default.txt')
        file.open(QIODevice.ReadOnly)
        model = TreeModel(headers, file.readAll())
        file.close()

        self.view.setModel(model)
        for column in range(model.columnCount()):
            self.view.resizeColumnToContents(column)

        self.exitAction.triggered.connect(QApplication.instance().quit)

        self.view.selectionModel().selectionChanged.connect(self.updateActions)

        self.actionsMenu.aboutToShow.connect(self.updateActions)
        self.insertRowAction.triggered.connect(self.insertRow)
        self.insertColumnAction.triggered.connect(self.insertColumn)
        self.removeRowAction.triggered.connect(self.removeRow)
        self.removeColumnAction.triggered.connect(self.removeColumn)
        self.insertChildAction.triggered.connect(self.insertChild)

        self.updateActions()
Esempio n. 7
0
    def openFile(self, path=None):
        if not path:
            path, _ = QFileDialog.getOpenFileName(self, "Choose a data file",
                                                  '', '*.cht')

        if path:
            f = QFile(path)

            if f.open(QFile.ReadOnly | QFile.Text):
                stream = QTextStream(f)

                self.model.removeRows(0, self.model.rowCount(QModelIndex()),
                                      QModelIndex())

                row = 0
                line = stream.readLine()
                while line:
                    self.model.insertRows(row, 1, QModelIndex())

                    pieces = line.split(',')
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                       pieces[0])
                    self.model.setData(self.model.index(row, 1, QModelIndex()),
                                       float(pieces[1]))
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                       QColor(pieces[2]), Qt.DecorationRole)

                    row += 1
                    line = stream.readLine()

                f.close()
                self.statusBar().showMessage("Loaded %s" % path, 2000)
Esempio n. 8
0
    def openFile(self, path=None):
        if not path:
            path, _ = QFileDialog.getOpenFileName(self, "Choose a data file",
                    '', '*.cht')

        if path:
            f = QFile(path)

            if f.open(QFile.ReadOnly | QFile.Text):
                stream = QTextStream(f)

                self.model.removeRows(0, self.model.rowCount(QModelIndex()),
                        QModelIndex())

                row = 0
                line = stream.readLine()
                while line:
                    self.model.insertRows(row, 1, QModelIndex())

                    pieces = line.split(',')
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                pieces[0])
                    self.model.setData(self.model.index(row, 1, QModelIndex()),
                                float(pieces[1]))
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                QColor(pieces[2]), Qt.DecorationRole)

                    row += 1
                    line = stream.readLine()

                f.close()
                self.statusBar().showMessage("Loaded %s" % path, 2000)
Esempio n. 9
0
 def __saveImage(self, fileName):
     """
     Private method to save the snapshot.
     
     @param fileName name of the file to save to (string)
     @return flag indicating success (boolean)
     """
     if QFileInfo(fileName).exists():
         res = E5MessageBox.yesNo(
             self,
             self.tr("Save Snapshot"),
             self.tr("<p>The file <b>{0}</b> already exists."
                     " Overwrite it?</p>").format(fileName),
             icon=E5MessageBox.Warning)
         if not res:
             return False
     
     file = QFile(fileName)
     if not file.open(QFile.WriteOnly):
         E5MessageBox.warning(
             self, self.tr("Save Snapshot"),
             self.tr("Cannot write file '{0}:\n{1}.")
             .format(fileName, file.errorString()))
         return False
     
     ok = self.__snapshot.save(file)
     file.close()
     
     if not ok:
         E5MessageBox.warning(
             self, self.tr("Save Snapshot"),
             self.tr("Cannot write file '{0}:\n{1}.")
             .format(fileName, file.errorString()))
     
     return ok
Esempio n. 10
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setupUi(self)

        headers = ("Title", "Description")

        file = QFile(':/default.txt')
        file.open(QIODevice.ReadOnly)
        model = TreeModel(headers, file.readAll())
        file.close()

        self.view.setModel(model)
        for column in range(model.columnCount()):
            self.view.resizeColumnToContents(column)

        self.exitAction.triggered.connect(QApplication.instance().quit)

        self.view.selectionModel().selectionChanged.connect(self.updateActions)

        self.actionsMenu.aboutToShow.connect(self.updateActions)
        self.insertRowAction.triggered.connect(self.insertRow)
        self.insertColumnAction.triggered.connect(self.insertColumn)
        self.removeRowAction.triggered.connect(self.removeRow)
        self.removeColumnAction.triggered.connect(self.removeColumn)
        self.insertChildAction.triggered.connect(self.insertChild)

        self.updateActions()
    def __exportStyles(self, lexers):
        """
        Private method to export the styles of the given lexers.
        
        @param lexers list of lexer objects for which to export the styles
        """
        fn, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
            self, self.tr("Export Highlighting Styles"), "",
            self.tr("Highlighting styles file (*.e4h)"), "",
            E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))

        if not fn:
            return

        ext = QFileInfo(fn).suffix()
        if not ext:
            ex = selectedFilter.split("(*")[1].split(")")[0]
            if ex:
                fn += ex

        f = QFile(fn)
        if f.open(QIODevice.WriteOnly):
            from E5XML.HighlightingStylesWriter import HighlightingStylesWriter
            HighlightingStylesWriter(f, lexers).writeXML()
            f.close()
        else:
            E5MessageBox.critical(
                self, self.tr("Export Highlighting Styles"),
                self.tr(
                    """<p>The highlighting styles could not be exported"""
                    """ to file <b>{0}</b>.</p><p>Reason: {1}</p>""").format(
                        fn, f.errorString()))
Esempio n. 12
0
 def loadFile(self, filename):
     file = QFile()
     file.setFileName("./js/" + filename)
     file.open(QIODevice.ReadOnly)
     code = file.readAll()
     file.close()
     return "".join(str(line) for line in code)
Esempio n. 13
0
def main(args):
    def split_and_strip(s, splitter):
        return [s.strip() for s in line.split(splitter)]

    app = QApplication(args)
    model = QStandardItemModel()
    file = QFile(QFileInfo(__file__).absolutePath() + '/grades.txt')
    if file.open(QFile.ReadOnly):
        line = file.readLine(200).decode('utf-8')
        header = split_and_strip(line, ',')
        model.setHorizontalHeaderLabels(header)
        row = 0
        while file.canReadLine():
            line = file.readLine(200).decode('utf-8')
            if not line.startswith('#') and ',' in line:
                fields = split_and_strip(line, ',')
                for col, field in enumerate(fields):
                    newItem = QStandardItem(field)
                    model.setItem(row, col, newItem)
                row += 1
    file.close()
    tableView = FreezeTableWidget(model)
    tableView.setWindowTitle("Frozen Column Example")
    tableView.resize(560, 680)
    tableView.show()
    return app.exec_()
Esempio n. 14
0
    def loadFile(self, filename=None):
        self.logger.info('loading ACL file %s' % filename)
        if filename is not None:
            f = QFile(filename)

            if not f.open(QIODevice.ReadOnly | QIODevice.Text):
                self.logger.error('error opening ACL file %s for read' %
                                  filename)
                return False

            bytes = f.readAll()

            if bytes.isEmpty():
                self.logger.error('unabled to read from ACL file %s' %
                                  filename)
                f.close()
                return False

            f.close()

            info = QFileInfo(filename)
            modified = int(info.lastModified().toMSecsSinceEpoch() / 1000)

            return self.parseJSON(doc=str(bytes),
                                  save=False,
                                  date=modified,
                                  status='loaded_from_file')

        return False
Esempio n. 15
0
def copy_embedded_file(src_name, dst_name, macros={}):
    """ Copy an embedded source file to a destination file.  src_name is the
    name of the source file.  dst_name is the name of the destination file.
    macros is an optional dictionary of key/value string macros and instances
    of each key are replaced by the corresponding value.  A UserException is
    raised if there was an error.
    """

    contents = read_embedded_file(src_name)

    for key, value in macros.items():
        contents.replace(bytes(key, encoding='ascii'),
                bytes(value, encoding='ascii'))

    dst_file = QFile(dst_name)

    if not dst_file.open(QIODevice.WriteOnly|QIODevice.Text):
        raise UserException(
                "Unable to create file {0}.".format(dst_file.fileName()),
                dst_file.errorString())

    if dst_file.write(contents) < 0:
        raise UserException(
                "Unable to write to file {0}.".format(dst_file.fileName()),
                dst_file.errorString())

    dst_file.close()
Esempio n. 16
0
def exportShortcuts(fn):
    """
    Module function to export the keyboard shortcuts for the defined QActions.
    
    @param fn filename of the export file (string)
    """
    # let the plugin manager create on demand plugin objects
    pm = e5App().getObject("PluginManager")
    pm.initOnDemandPlugins()
    
    f = QFile(fn)
    if f.open(QIODevice.WriteOnly):
        from E5XML.ShortcutsWriter import ShortcutsWriter
        ShortcutsWriter(f).writeXML()
        f.close()
    else:
        E5MessageBox.critical(
            None,
            QCoreApplication.translate(
                "Shortcuts", "Export Keyboard Shortcuts"),
            QCoreApplication.translate(
                "Shortcuts",
                "<p>The keyboard shortcuts could not be written to file"
                " <b>{0}</b>.</p>")
            .format(fn))
Esempio n. 17
0
	def updateStyleSheet(self):
		self.ss = None
		if globalSettings.styleSheet:
			sheetfile = QFile(globalSettings.styleSheet)
			sheetfile.open(QIODevice.ReadOnly)
			self.ss = QTextStream(sheetfile).readAll()
			sheetfile.close()
Esempio n. 18
0
 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())
Esempio n. 19
0
 def readStyleSheet(self, fileName):
     css = None
     file = QFile(fileName)
     if file.open(QIODevice.ReadOnly):
         css = file.readAll()
         file.close()
     return css
Esempio n. 20
0
 def load(self):
     exception = None
     fh = None
     try:
         if not self.filename:
             raise IOError("no filename specified for loading")
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(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 = stream.readQString()
             owner = stream.readQString()
             country = stream.readQString()
             description = stream.readQString()
             teu = stream.readInt32()
             ship = Ship(name, owner, country, teu, description)
             self.ships[id(ship)] = ship
             self.owners.add(owner)
             self.countries.add(country)
         self.dirty = False
     except IOError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
Esempio n. 21
0
    def __importCertificate(self):
        """
        Private method to read a certificate.
        
        @return certificates read (list of QSslCertificate)
        """
        fname = E5FileDialog.getOpenFileName(
            self,
            self.tr("Import Certificate"),
            "",
            self.tr("Certificate Files (*.pem *.crt *.der *.cer *.ca);;" "All Files (*)"),
        )

        if fname:
            f = QFile(fname)
            if not f.open(QIODevice.ReadOnly):
                E5MessageBox.critical(
                    self,
                    self.tr("Export Certificate"),
                    self.tr(
                        """<p>The certificate could not be read from file""" """ <b>{0}</b></p><p>Error: {1}</p>"""
                    ).format(fname, f.errorString()),
                )
                return []

            crt = f.readAll()
            f.close()
            cert = QSslCertificate.fromData(crt, QSsl.Pem)
            if not cert:
                cert = QSslCertificate.fromData(crt, QSsl.Der)

            return cert

        return []
Esempio n. 22
0
 def save(self):
     if not self.filename:
         path = "."
         fname, filetype = QFileDialog.getSaveFileName(
             self, "Page Designer - Save As", path,
             "Page Designer Files (*.pgd)")
         if not fname:
             return
         self.filename = fname
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         self.scene.clearSelection()
         stream = QDataStream(fh)
         stream.setVersion(QDataStream.Qt_5_7)
         stream.writeInt32(MagicNumber)
         stream.writeInt16(FileVersion)
         for item in self.scene.items():
             self.writeItemToStream(stream, item)
     except IOError as e:
         QMessageBox.warning(
             self, "Page Designer -- Save Error",
             "Failed to save {0}: {1}".format(self.filename, e))
     finally:
         if fh is not None:
             fh.close()
     global Dirty
     Dirty = False
Esempio n. 23
0
 def read(self, fileName):
     uncompressed = QByteArray()
     # Read data
     f = QFile(fileName)
     if (f.open(QIODevice.ReadOnly)) :
         compressed = f.readAll()
         f.close()
         uncompressed, length = decompress(compressed, 48 * 48)
     
     # Check the data
     if (uncompressed.count() != 48 * 48) :
         self.mError = self.tr("This is not a valid Droidcraft map file!")
         return None
     
     uncompressed = uncompressed.data()
     # Build 48 x 48 map
     # Create a Map -> Create a Tileset -> Add Tileset to map
     # -> Create a TileLayer -> Fill layer -> Add TileLayer to Map
     map = Map(Map.Orientation.Orthogonal, 48, 48, 32, 32)
     mapTileset = Tileset.create("tileset", 32, 32)
     mapTileset.loadFromImage(QImage(":/tileset.png"), "tileset.png")
     map.addTileset(mapTileset)
     # Fill layer
     mapLayer =  TileLayer("map", 0, 0, 48, 48)
     # Load
     for i in range(0, 48 * 48):
         tileFile = int(uncompressed[i])&0xff
         y = int(i / 48)
         x = i - (48 * y)
         tile = mapTileset.tileAt(tileFile)
         mapLayer.setCell(x, y, Cell(tile))
     
     map.addLayer(mapLayer)
     return map
Esempio n. 24
0
 def open_grammar_file(self):
     # 打开文法文件
     filename, _s = QFileDialog.getOpenFileName(
         self, "Open File", '', "All Files (*);;"
         "C++ Files (*.cpp *.h *.py);;"
         "Txt files (*.txt);;"
         "Python files (*.py);;"
         "HTML-Files (*.htm *.html)")
     if filename:  # 文件名有效时才进行打开
         self.filename = filename
         try:
             # 读取文件内容并设置显示到文法的显示窗口
             file = QFile(filename)
             if file.open(QFile.ReadOnly | QFile.Text):
                 text = file.readAll()
                 text = str(text, encoding='utf-8')
                 # 设置内容显示
                 self.grammar.setPlainText(text)
                 file.close()
                 return True
         except Exception as e:
             print(e)
             QMessageBox.information(self, 'ERROR',
                                     'Error, please open file again.')
     return False
Esempio n. 25
0
def importShortcuts(fn):
    """
    Module function to import the keyboard shortcuts for the defined E5Actions.
    
    @param fn filename of the import file (string)
    """
    # let the plugin manager create on demand plugin objects
    pm = e5App().getObject("PluginManager")
    pm.initOnDemandPlugins()
    
    f = QFile(fn)
    if f.open(QIODevice.ReadOnly):
        from E5XML.ShortcutsReader import ShortcutsReader
        reader = ShortcutsReader(f)
        reader.readXML()
        f.close()
        if not reader.hasError():
            shortcuts = reader.getShortcuts()
            setActions(shortcuts)
            saveShortcuts()
            syncPreferences()
    else:
        E5MessageBox.critical(
            None,
            QCoreApplication.translate(
                "Shortcuts", "Import Keyboard Shortcuts"),
            QCoreApplication.translate(
                "Shortcuts",
                "<p>The keyboard shortcuts could not be read from file"
                " <b>{0}</b>.</p>")
            .format(fn))
        return
Esempio n. 26
0
    def updateAutoComplete(self):
        """ updates the Completer's reference text based on the kingdom """

        value_Kingdom = self.settings.get('value_Kingdom', 'Plantae')
        if value_Kingdom == 'Plantae':
            nameCol = 'complete_name'
        if value_Kingdom == 'Fungi':
            nameCol = 'normalized_name'
        stream = QFile(f':/rc_/{value_Kingdom}_Reference.csv')
        if stream.open(QFile.ReadOnly):
            df = StringIO(str(stream.readAll(), 'utf-8'))
            stream.close()
        # completer.setCompletionMode(QCompleter.InlineCompletion)
#		completer.maxVisibleItems=10
#		completer.setCaseSensitivity(Qt.CaseInsensitive)
# make the completer selection also erase the text edit
#       completer.activated.connect(self.cleartext,type=Qt.QueuedConnection)

        wordList = pd.read_csv(df, encoding='utf-8', dtype='str')
        wordList = wordList[nameCol].str.capitalize().tolist()
        self.wordList = sorted(wordList)

        completer = QCompleter(self.wordList, self.lineEdit_sciName)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.lineEdit_sciName.setCompleter(completer)

        completerAssociated = QCompleter(
            self.wordList,
            self.associatedTaxaWindow.lineEdit_newAssociatedTaxa)
        completerAssociated.setCaseSensitivity(Qt.CaseInsensitive)
        self.associatedTaxaWindow.associatedMainWin.lineEdit_newAssociatedTaxa.setCompleter(
            completerAssociated)
Esempio n. 27
0
    def saveFile(self):
        fileName, _ = QFileDialog.getSaveFileName(self, "Save file as", '',
                                                  '*.cht')

        if fileName:
            f = QFile(fileName)

            if f.open(QFile.WriteOnly | QFile.Text):
                for row in range(self.model.rowCount(QModelIndex())):
                    pieces = []

                    pieces.append(
                        self.model.data(
                            self.model.index(row, 0, QModelIndex()),
                            Qt.DisplayRole))
                    pieces.append('%g' % self.model.data(
                        self.model.index(row, 1, QModelIndex()),
                        Qt.DisplayRole))
                    pieces.append(
                        self.model.data(
                            self.model.index(row, 0, QModelIndex()),
                            Qt.DecorationRole).name())

                    f.write(b','.join([p.encode('utf-8') for p in pieces]))
                    f.write(b'\n')

            f.close()
            self.statusBar().showMessage("Saved %s" % fileName, 2000)
Esempio n. 28
0
    def show_web_view(self):

        pageSourcePart1 = r"""<html><head>
            <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
            </head><body>
            <p><mathjax>"""
        if self.selectedText != "":
            self.textEdit.setText(self.selectedText)
            self.selectedText = ""
        pageSourcePart2 = ""
        pageSourcePart3 = """</mathjax></p>
                            </body></html>"""


        # Создаём временный файл и записываем в него формулы
        # далее этот файл открывается в webView, чтобы наглядно был виден mathJax

        formulas = self.textEdit.toPlainText().splitlines()
        for i,line in enumerate(formulas):
            formulas[i] = "<p>" + line + "</p> "
            pageSourcePart2 = pageSourcePart2 + formulas[i] + "\n"


        tempFile = QFile('mathjax.html')
        tempFile.open(QFile.WriteOnly)
        stream = QTextStream(tempFile)
        stream << (pageSourcePart1 + pageSourcePart2 + pageSourcePart3)
        tempFile.close()
        fileUrl = QtCore.QUrl.fromLocalFile(QFileInfo(tempFile).canonicalFilePath())
        self.webView.setUrl(fileUrl)
Esempio n. 29
0
    def saveFile(self):
        fileName, _ = QFileDialog.getSaveFileName(self, "Save file as", '',
                '*.cht')

        if fileName:
            f = QFile(fileName)

            if f.open(QFile.WriteOnly | QFile.Text):
                for row in range(self.model.rowCount(QModelIndex())):
                    pieces = []

                    pieces.append(
                            self.model.data(
                                    self.model.index(row, 0, QModelIndex()),
                                    Qt.DisplayRole))
                    pieces.append(
                            '%g' % self.model.data(
                                    self.model.index(row, 1, QModelIndex()),
                                    Qt.DisplayRole))
                    pieces.append(
                            self.model.data(
                                    self.model.index(row, 0, QModelIndex()),
                                    Qt.DecorationRole).name())

                    f.write(b','.join([p.encode('utf-8') for p in pieces]))
                    f.write(b'\n')

            f.close()
            self.statusBar().showMessage("Saved %s" % fileName, 2000)
Esempio n. 30
0
    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
Esempio n. 31
0
    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
Esempio n. 32
0
def load(path):
    file = QFile(path)
    try:
        file.open(QIODevice.ReadOnly)
        return file.readAll()
    finally:
        file.close()
 def __importCertificate(self):
     """
     Private method to read a certificate.
     
     @return certificates read (list of QSslCertificate)
     """
     fname = E5FileDialog.getOpenFileName(
         self,
         self.tr("Import Certificate"),
         "",
         self.tr("Certificate Files (*.pem *.crt *.der *.cer *.ca);;"
                 "All Files (*)"))
     
     if fname:
         f = QFile(fname)
         if not f.open(QIODevice.ReadOnly):
             E5MessageBox.critical(
                 self,
                 self.tr("Export Certificate"),
                 self.tr(
                     """<p>The certificate could not be read from file"""
                     """ <b>{0}</b></p><p>Error: {1}</p>""")
                 .format(fname, f.errorString()))
             return []
         
         crt = f.readAll()
         f.close()
         cert = QSslCertificate.fromData(crt, QSsl.Pem)
         if not cert:
             cert = QSslCertificate.fromData(crt, QSsl.Der)
         
         return cert
     
     return []
Esempio n. 34
0
 def readTaxonomicSettings(self):
     """ Fetches the most up-to-date taxonomy relevant settings"""
     # TODO check if this is redundant, shouldn't the settings window "Save and exit" button establish these changes?
     # meaning, whenever this was called the function could just go straight to the settings module and use it?
     # additionally, this may be reloading the local alignments excessively
     # The function is called in pandastablemodel (at least)
     #which service to utalize to make alignments
     self.TaxAlignSource = self.settings.get('value_TaxAlignSource')
     # how to handle name reccomendations
     self.NameChangePolicy = self.settings.get('value_NameChangePolicy')
     # how to handle authority reccomendations
     self.AuthChangePolicy = self.settings.get('value_AuthChangePolicy')
     # tnrs score threshold
     self.value_TNRS_Threshold = self.settings.get('value_TNRS_Threshold')
     # which kingdom we're interested in
     current_value_Kingdom = self.settings.get('value_Kingdom')
     try:  # see if it's necessary to reload the local_Reference
         if self.value_Kingdom != current_value_Kingdom:
             raise AttributeError  # force exception and boolean into same outcome
     except AttributeError:  # load the local reference
         self.value_Kingdom = current_value_Kingdom
         if '(local)' in self.TaxAlignSource:
             from io import StringIO
             stream = QFile(f':/rc_/{self.value_Kingdom}_Reference.csv')
             if stream.open(QFile.ReadOnly):
                 df = StringIO(str(stream.readAll(), 'utf-8'))
                 stream.close()
             self.local_Reference = pd.read_csv(df,
                                                encoding='utf-8',
                                                dtype='str')
Esempio n. 35
0
    def load_datastream(self, fname):
        error = None
        fh = None

        try:
            fh = QFile(fname)
            if not fh.open(QIODevice.ReadOnly):
                raise IOError(str(fh.errorString()))

            stream = QDataStream(fh)
            while not stream.atEnd():
                self.label = stream.readQString()
                self.diameter = stream.readInt32()
                self.top_elev = stream.readDouble()
                self.design_load = stream.readDouble()
        except EnvironmentError as e:
            error = "Failed to load:{0}".format(e)

        finally:
            if fh is not None:
                fh.close()
            if error is not None:
                print(error)
            self.__dirty = False
            print("load data from{0}".format(QFileInfo(fname).fileName()))


# 缺少计算参数的类
Esempio n. 36
0
def copy_embedded_file(src_name, dst_name, macros={}):
    """ Copy an embedded text file to a destination file.  src_name is the name
    of the source file.  dst_name is the name of the destination file.  macros
    is an optional dictionary of key/value string macros and instances of each
    key are replaced by the corresponding value.  A UserException is raised if
    there was an error.
    """

    contents = read_embedded_file(src_name)

    for key, value in macros.items():
        contents.replace(bytes(key, encoding='ascii'),
                         bytes(value, encoding='ascii'))

    dst_file = QFile(dst_name)

    if not dst_file.open(QIODevice.WriteOnly | QIODevice.Text):
        raise UserException(
            "Unable to create file {0}.".format(dst_file.fileName()),
            dst_file.errorString())

    if dst_file.write(contents) < 0:
        raise UserException(
            "Unable to write to file {0}.".format(dst_file.fileName()),
            dst_file.errorString())

    dst_file.close()
Esempio n. 37
0
 def save(self):
     exception = None
     fh = None
     try:
         if not self.filename:
             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_5_7)
         for ship in self.ships:
             stream.writeQString(ship.name)
             stream.writeQString(ship.owner)
             stream.writeQString(ship.country)
             stream.writeQString(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
Esempio n. 38
0
def exportShortcuts(fn, helpViewer=None):
    """
    Module function to export the keyboard shortcuts for the defined QActions.
    
    @param fn filename of the export file (string)
    @param helpViewer reference to the help window object
    """
    # let the plugin manager create on demand plugin objects
    pm = e5App().getObject("PluginManager")
    pm.initOnDemandPlugins()

    f = QFile(fn)
    if f.open(QIODevice.WriteOnly):
        from E5XML.ShortcutsWriter import ShortcutsWriter
        ShortcutsWriter(f).writeXML(helpViewer=helpViewer)
        f.close()
    else:
        E5MessageBox.critical(
            None,
            QCoreApplication.translate("Shortcuts",
                                       "Export Keyboard Shortcuts"),
            QCoreApplication.translate(
                "Shortcuts",
                "<p>The keyboard shortcuts could not be written to file"
                " <b>{0}</b>.</p>").format(fn))
Esempio n. 39
0
 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
Esempio n. 40
0
def importShortcuts(fn, helpViewer=None):
    """
    Module function to import the keyboard shortcuts for the defined E5Actions.
    
    @param fn filename of the import file (string)
    @param helpViewer reference to the help window object
    """
    # let the plugin manager create on demand plugin objects
    pm = e5App().getObject("PluginManager")
    pm.initOnDemandPlugins()

    f = QFile(fn)
    if f.open(QIODevice.ReadOnly):
        from E5XML.ShortcutsReader import ShortcutsReader
        reader = ShortcutsReader(f)
        reader.readXML()
        f.close()
        if not reader.hasError():
            shortcuts = reader.getShortcuts()
            setActions(shortcuts, helpViewer=helpViewer)
            saveShortcuts()
            syncPreferences()
    else:
        E5MessageBox.critical(
            None,
            QCoreApplication.translate("Shortcuts",
                                       "Import Keyboard Shortcuts"),
            QCoreApplication.translate(
                "Shortcuts",
                "<p>The keyboard shortcuts could not be read from file"
                " <b>{0}</b>.</p>").format(fn))
        return
Esempio n. 41
0
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel("Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")
Esempio n. 42
0
 def save(self):
     if self.filename.startswith("Unnamed"):
         filename, _ = 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(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
Esempio n. 43
0
    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()
Esempio n. 44
0
 def readTemplates(self, filename=None):
     """
     Public method to read in the templates file (.e4c).
     
     @param filename name of a templates file to read (string)
     """
     if filename is None:
         filename = os.path.join(
             Utilities.getConfigDir(), "eric6templates.e4c")
         if not os.path.exists(filename):
             return
     
     f = QFile(filename)
     if f.open(QIODevice.ReadOnly):
         from E5XML.TemplatesReader import TemplatesReader
         reader = TemplatesReader(f, viewer=self)
         reader.readXML()
         f.close()
     else:
         E5MessageBox.critical(
             self,
             self.tr("Read templates"),
             self.tr(
                 "<p>The templates file <b>{0}</b> could not be read.</p>")
             .format(filename))
Esempio n. 45
0
    def readXmlDocument(self):
        xml_file = QFile(':/xml/examples.xml')
        xml_file.open(QFile.ReadOnly | QFile.Text)
        contents = xml_file.readAll().data()
        xml_file.close()

        self.contentsDoc = parseString(contents)
Esempio n. 46
0
    def __init__(self, url):
        super(MainWindow, self).__init__()

        self.progress = 0

        fd = QFile(":/jquery.min.js")

        if fd.open(QIODevice.ReadOnly | QFile.Text):
            self.jQuery = QTextStream(fd).readAll()
            fd.close()
        else:
            self.jQuery = ''

        QNetworkProxyFactory.setUseSystemConfiguration(True)

        self.view = QWebView(self)
        self.view.load(url)
        self.view.loadFinished.connect(self.adjustLocation)
        self.view.titleChanged.connect(self.adjustTitle)
        self.view.loadProgress.connect(self.setProgress)
        self.view.loadFinished.connect(self.finishLoading)

        self.locationEdit = QLineEdit(self)
        self.locationEdit.setSizePolicy(
            QSizePolicy.Expanding,
            self.locationEdit.sizePolicy().verticalPolicy())
        self.locationEdit.returnPressed.connect(self.changeLocation)

        toolBar = self.addToolBar("Navigation")
        toolBar.addAction(self.view.pageAction(QWebPage.Back))
        toolBar.addAction(self.view.pageAction(QWebPage.Forward))
        toolBar.addAction(self.view.pageAction(QWebPage.Reload))
        toolBar.addAction(self.view.pageAction(QWebPage.Stop))
        toolBar.addWidget(self.locationEdit)

        viewMenu = self.menuBar().addMenu("&View")
        viewSourceAction = QAction("Page Source", self)
        viewSourceAction.triggered.connect(self.viewSource)
        viewMenu.addAction(viewSourceAction)

        effectMenu = self.menuBar().addMenu("&Effect")
        effectMenu.addAction("Highlight all links", self.highlightAllLinks)

        self.rotateAction = QAction(self.style().standardIcon(
            QStyle.SP_FileDialogDetailedView),
                                    "Turn images upside down",
                                    self,
                                    checkable=True,
                                    toggled=self.rotateImages)
        effectMenu.addAction(self.rotateAction)

        toolsMenu = self.menuBar().addMenu("&Tools")
        toolsMenu.addAction("Remove GIF images", self.removeGifImages)
        toolsMenu.addAction("Remove all inline frames",
                            self.removeInlineFrames)
        toolsMenu.addAction("Remove all object elements",
                            self.removeObjectElements)
        toolsMenu.addAction("Remove all embedded elements",
                            self.removeEmbeddedElements)
        self.setCentralWidget(self.view)
Esempio n. 47
0
    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
Esempio n. 48
0
 def load_style_sheet(self, sheetName, iconsDir):
     """load qss file"""
     print('Using qss file: %s'%sheetName)
     qss = QFile(sheetName)
     qss.open(QFile.ReadOnly)
     styleSheet = str(qss.readAll(), encoding='utf8').replace(':PathPrefix', iconsDir)
     QApplication.instance().setStyleSheet(styleSheet)
     qss.close()
Esempio n. 49
0
    def readXmlDocument(self):
        root = QFileInfo(__file__).absolutePath()
        xml_file = QFile(root + '/examples.xml')
        xml_file.open(QFile.ReadOnly | QFile.Text)
        contents = xml_file.readAll().data()
        xml_file.close()

        self.contentsDoc = parseString(contents)
Esempio n. 50
0
	def updateStyleSheet(self):
		if globalSettings.styleSheet:
			sheetfile = QFile(globalSettings.styleSheet)
			sheetfile.open(QIODevice.ReadOnly)
			self.ss = QTextStream(sheetfile).readAll()
			sheetfile.close()
		else:
			self.ss = ''
Esempio n. 51
0
 def test_write_error_real(self):
     """Test a real write error with /dev/full on supported systems."""
     qf = QFile('/dev/full')
     qf.open(QIODevice.WriteOnly | QIODevice.Unbuffered)
     dev = qtutils.PyQIODevice(qf)
     with pytest.raises(OSError, match='No space left on device'):
         dev.write(b'foo')
     qf.close()
Esempio n. 52
0
    def __init__(self, parent):
        super(QKOSAbout, self).__init__(parent)
        gridlayout = QGridLayout(self)
        titlefont = QFont()
        titlefont.setPointSize(24)
        policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        label = QLabel("About QKeysOnScreen", self)
        label.setFont(titlefont)
        label.setSizePolicy(policy)
        gridlayout.addWidget(label, 0, 0)
        labelcopyright = QLabel("\u00a9 2015 Fredrick Brennan <*****@*****.**>")
        labelcopyright.setSizePolicy(policy)
        gridlayout.addWidget(labelcopyright, 1, 0)
        labeldesc = (
            "<p>QKeysOnScreen is a simple application intended for "
            + "presentations, video tutorials, and any other case where"
            + " you'd want to display the current state of the keyboard"
            + ' on the screen. For more information see our <a href="'
            + 'https://github.com/ctrlcctrlv/QKeysOnScreen">Github</a>'
            + " project."
        )
        qlabeldesc = QLabel(labeldesc)
        qlabeldesc.setWordWrap(True)
        gridlayout.addWidget(qlabeldesc, 2, 0)

        from PyQt5.QtCore import QT_VERSION_STR
        from PyQt5.Qt import PYQT_VERSION_STR
        import platform

        pyversion = ".".join([str(o) for o in sys.version_info])
        uname_result = platform.uname()
        uname = "{} {}".format(uname_result.system, uname_result.release)
        labelversions = (
            "<strong>Versions:</strong><br>Qt: {0}<br>PyQt: {1}" + "<br>Python: {2}<br>OS: {3}<br>QKeysOnScreen: 0.0.1"
        ).format(QT_VERSION_STR, PYQT_VERSION_STR, platform.python_version(), uname, platform.machine())
        qlabelversions = QLabel(labelversions)
        qlabelversions.setStyleSheet("border: 1px solid green")
        gridlayout.addWidget(qlabelversions, 0, 1)

        self.kb = get_keyboard_path()
        self.mouse = get_mouse_path()
        self.infoqlabel = QLabel(
            "<strong>Devices:</strong><br>" + "Our mouse is {0}<br/>Our keyboard is {1}".format(self.mouse, self.kb),
            self,
        )
        self.infoqlabel.setStyleSheet("border: 1px solid green")
        gridlayout.addWidget(self.infoqlabel, 2, 1)

        qte = QTextEdit(self)
        qte.setReadOnly(True)
        qfile = QFile(":/LICENSE")
        qfile.open(QIODevice.ReadOnly)
        qte.setPlainText(bytes(qfile.readAll()).decode("utf-8"))
        qfile.close()

        gridlayout.addWidget(qte, 3, 0, 1, 2)

        self.setLayout(gridlayout)
Esempio n. 53
0
    def __load(self):
        """
        Private method to load the saved history entries from disk.
        """
        historyFile = QFile(self.getFileName())
        if not historyFile.exists():
            return
        if not historyFile.open(QIODevice.ReadOnly):
            E5MessageBox.warning(
                None,
                self.tr("Loading History"),
                self.tr("""<p>Unable to open history file <b>{0}</b>.<br/>""" """Reason: {1}</p>""").format(
                    historyFile.fileName, historyFile.errorString()
                ),
            )
            return

        history = []

        # double check, that the history file is sorted as it is read
        needToSort = False
        lastInsertedItem = HistoryEntry()
        data = QByteArray(historyFile.readAll())
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.setVersion(QDataStream.Qt_4_6)
        while not stream.atEnd():
            ver = stream.readUInt32()
            if ver != HISTORY_VERSION:
                continue
            itm = HistoryEntry()
            itm.url = Utilities.readStringFromStream(stream)
            stream >> itm.dateTime
            itm.title = Utilities.readStringFromStream(stream)

            if not itm.dateTime.isValid():
                continue

            if itm == lastInsertedItem:
                if not lastInsertedItem.title and len(history) > 0:
                    history[0].title = itm.title
                continue

            if not needToSort and history and lastInsertedItem < itm:
                needToSort = True

            history.insert(0, itm)
            lastInsertedItem = itm
        historyFile.close()

        if needToSort:
            history.sort()

        self.setHistory(history, True)

        # if the history had to be sorted, rewrite the history sorted
        if needToSort:
            self.__lastSavedUrl = ""
            self.__saveTimer.changeOccurred()
Esempio n. 54
0
 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
Esempio n. 55
0
    def __init__(self, url):
        super(MainWindow, self).__init__()

        self.progress = 0

        fd = QFile(":/jquery.min.js")

        if fd.open(QIODevice.ReadOnly | QFile.Text):
            self.jQuery = QTextStream(fd).readAll()
            fd.close()
        else:
            self.jQuery = ''

        QNetworkProxyFactory.setUseSystemConfiguration(True)

        self.view = QWebView(self)
        self.view.load(url)
        self.view.loadFinished.connect(self.adjustLocation)
        self.view.titleChanged.connect(self.adjustTitle)
        self.view.loadProgress.connect(self.setProgress)
        self.view.loadFinished.connect(self.finishLoading)

        self.locationEdit = QLineEdit(self)
        self.locationEdit.setSizePolicy(QSizePolicy.Expanding,
                self.locationEdit.sizePolicy().verticalPolicy())
        self.locationEdit.returnPressed.connect(self.changeLocation)

        toolBar = self.addToolBar("Navigation")
        toolBar.addAction(self.view.pageAction(QWebPage.Back))
        toolBar.addAction(self.view.pageAction(QWebPage.Forward))
        toolBar.addAction(self.view.pageAction(QWebPage.Reload))
        toolBar.addAction(self.view.pageAction(QWebPage.Stop))
        toolBar.addWidget(self.locationEdit)

        viewMenu = self.menuBar().addMenu("&View")
        viewSourceAction = QAction("Page Source", self)
        viewSourceAction.triggered.connect(self.viewSource)
        viewMenu.addAction(viewSourceAction)

        effectMenu = self.menuBar().addMenu("&Effect")
        effectMenu.addAction("Highlight all links", self.highlightAllLinks)

        self.rotateAction = QAction(
                self.style().standardIcon(QStyle.SP_FileDialogDetailedView),
                "Turn images upside down", self, checkable=True,
                toggled=self.rotateImages)
        effectMenu.addAction(self.rotateAction)

        toolsMenu = self.menuBar().addMenu("&Tools")
        toolsMenu.addAction("Remove GIF images", self.removeGifImages)
        toolsMenu.addAction("Remove all inline frames",
                self.removeInlineFrames)
        toolsMenu.addAction("Remove all object elements",
                self.removeObjectElements)
        toolsMenu.addAction("Remove all embedded elements",
                self.removeEmbeddedElements)
        self.setCentralWidget(self.view)
Esempio n. 56
0
def ReadTextFile(filePath):

    file = QFile(filePath)
    file.open(QFile.ReadOnly | QFile.Text)
    textStream = QTextStream(file)
    data = textStream.readAll()
    file.close()

    return data
Esempio n. 57
0
def setStyle(widget, aliasPath, objName=None):
    file_qss = QFile(aliasPath)
    file_qss.open(QFile.ReadOnly)
    ba = file_qss.readAll()
    s = bytes(ba.data()).decode()
    if objName:
        widget.setObjectName(objName)
    widget.setStyleSheet(s)
    file_qss.close()
Esempio n. 58
0
 def test_write_error_real(self):
     """Test a real write error with /dev/full on supported systems."""
     qf = QFile("/dev/full")
     qf.open(QIODevice.WriteOnly | QIODevice.Unbuffered)
     dev = qtutils.PyQIODevice(qf)
     with pytest.raises(OSError) as excinfo:
         dev.write(b"foo")
     qf.close()
     assert str(excinfo.value) == "No space left on device"
Esempio n. 59
0
def read_js(js_path):
    js = None
    stream = QFile(js_path)
    if stream.open(QFile.ReadOnly):
        js = QByteArray((stream.readAll()))
        stream.close()
    else:
        print(stream.errorString())

    return js