Esempio n. 1
0
    def _initPreviewToTextSync(self):
        """Initialize the system per items 1, 2, and 4 above."""
        # When a web page finishes loading, reinsert our JavaScript.
        page = self._dock._widget.webEngineView.page()

        # Insert our scripts into every loaded page.
        qwebchannel_js = QFile(':/qtwebchannel/qwebchannel.js')
        if not qwebchannel_js.open(QIODevice.ReadOnly):
            raise SystemExit('Failed to load qwebchannel.js with error: %s' %
                             qwebchannel_js.errorString())
        qwebchannel_js = bytes(qwebchannel_js.readAll()).decode('utf-8')

        # Set up the QWebChannel. See http://doc.qt.io/qt-5/qtwebchannel-javascript.html.
        # Run the script containing QWebChannel.js first.
        beforeScript = QWebEngineScript()
        beforeScript.setSourceCode(qwebchannel_js + self._jsPreviewSync +
                                   self._qtJsInit)
        beforeScript.setName('qwebchannel.js, previewSync')
        # Run this JavaScript separated from any JavaScript present in the loaded web page. This provides better security (rogue pages can't access the QWebChannel) and better isolation (handlers, etc. won't conflict, I hope).
        beforeScript.setWorldId(QWebEngineScript.ApplicationWorld)
        beforeScript.setInjectionPoint(QWebEngineScript.DocumentCreation)
        # Per `setWebChannel <http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel>`_, only one channel is allowed per page. So, don't run this on sub-frames, since it will attempt the creation of more channels for each subframe.
        beforeScript.setRunsOnSubFrames(False)
        page.scripts().insert(beforeScript)

        # Set up the web channel. See https://riverbankcomputing.com/pipermail/pyqt/2015-August/036346.html
        # and http://stackoverflow.com/questions/28565254/how-to-use-qt-webengine-and-qwebchannel.
        # For debug, ``set QTWEBENGINE_REMOTE_DEBUGGING=port`` then browse to
        # http://127.0.0.1:port, where port=60000 works for me. See https://riverbankcomputing.com/pipermail/pyqt/2015-August/036346.html.
        self.channel = QWebChannel(page)
        self.channel.registerObject("previewSync", self)
        # Expose the ``qt.webChannelTransport`` object in the world where these scripts live.
        page.setWebChannel(self.channel, QWebEngineScript.ApplicationWorld)
Esempio n. 2
0
    def loadStamps(self):
        prefs = preferences.Preferences.instance()
        stampsDirectory = prefs.stampsDirectory()
        stampsDir = QDir(stampsDirectory)
        iterator = QDirIterator(stampsDirectory,
                              ["*.stamp"],
                              QDir.Files | QDir.Readable)
        while (iterator.hasNext()):
            stampFileName = iterator.next()
            stampFile = QFile(stampFileName)
            if (not stampFile.open(QIODevice.ReadOnly)):
                continue
            data = stampFile.readAll()
            document = QJsonDocument.fromBinaryData(data)
            if (document.isNull()):
                # document not valid binary data, maybe it's an JSON text file
                error = QJsonParseError()
                document = QJsonDocument.fromJson(data, error)
                if (error.error != QJsonParseError.NoError):
                    qDebug("Failed to parse stamp file:" + error.errorString())
                    continue

            stamp = TileStamp.fromJson(document.object(), stampsDir)
            if (stamp.isEmpty()):
                continue
            stamp.setFileName(iterator.fileInfo().fileName())
            self.mTileStampModel.addStamp(stamp)
            index = stamp.quickStampIndex()
            if (index >= 0 and index < self.mQuickStamps.size()):
                self.mQuickStamps[index] = stamp
Esempio n. 3
0
 def read_quaternary(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. 4
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. 5
0
def vizCompressed(fileName):
    #fileName = 'D:/Data/10_23_shunfengmix/rgb_image_58'

    filenamesplit = os.path.splitext(filename)
    print("file name:", filenamesplit)
    file = QFile(filenamesplit[0] + '.compressed')
    file.open(QFile.ReadOnly)
    if file.isOpen():
        data = file.readAll()
        labels = qUncompress(data)
    img = cv2.imread(filenamesplit[0] + '.jpg')

    for r in range(img.shape[0]):
        for c in range(img.shape[1]):
            index = r * img.shape[1] + c
            if (labels[index] == '1'):  #tape
                img[r, c] = [0, 0, 255]
            elif (labels[index] == '2'):  #boundry
                img[r, c] = [0, 165, 255]
            elif (labels[index] != '0'):  #exception
                img[r, c] = [255, 255, 0]

    cv2.imshow('image', img)
    cv2.waitKey(0)
    cv2.imwrite(filenamesplit[0] + '_rf.jpg', img)
Esempio n. 6
0
    def __insertFlashCookie(self, path):
        """
        Private method to insert a Flash cookie into the cache.
        
        @param path Flash cookies path
        @type str
        """
        solFile = QFile(path)
        if not solFile.open(QFile.ReadOnly):
            return

        dataStr = ""
        data = bytes(solFile.readAll())
        if data:
            try:
                reader = FlashCookieReader()
                reader.setBytes(data)
                reader.parse()
                dataStr = reader.toString()
            except FlashCookieReaderError as err:
                dataStr = err.msg

        solFileInfo = QFileInfo(solFile)

        cookie = FlashCookie()
        cookie.contents = dataStr
        cookie.name = solFileInfo.fileName()
        cookie.path = solFileInfo.canonicalPath()
        cookie.size = int(solFile.size())
        cookie.lastModified = solFileInfo.lastModified()
        cookie.origin = self.__extractOriginFrom(path)

        self.__flashCookies.append(cookie)
Esempio n. 7
0
    def openFile(self, path=None):
        if not path:
            path, _ = QFileDialog.getOpenFileName(self, "Open File", '',
                                                  "C++ Files (*.cpp *.h)")
        if path:
            inFile = QFile(path)
            if inFile.open(QFile.ReadOnly | QFile.Text):
                text = inFile.readAll()

                try:
                    # Python v3.
                    text = str(text, encoding='ascii')
                except TypeError:
                    # Python v2.
                    text = str(text)

                self.editor.setFilename(self.current_file)
                self.editor.setPlainText(text)

                try:
                    amount = self.experiment.getScrollDisplacement(
                        self.current_file)
                    self.editor.verticalScrollBar().setValue(amount * (-1))
                except KeyError as e:
                    pass
Esempio n. 8
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. 9
0
    def load(self, what):
        # open file and load project
        if what != "":
            xml = QFile(what.toLocalFile())
        else:
            xml = QFile("save/temp")
        if xml.open(QFile.ReadOnly):
            self.project.deserialize(fromstring(xml.readAll()))
        if(what == ""):
            os.remove("./save/temp")
        self.view_manager._main.rootObject().setProperty(
            "workspaceHeight", int(self.project.workspace_height))
        self.view_manager._main.rootObject().setProperty(
            "workspaceWidth", int(self.project.workspace_width))

        # create views
        for id in self.project.nodes:
            self.nodeViews[id] = self.view_manager.create_node(
                self.project.nodes[id])
            # node_ids should be biggest of loaded ids
            if self.NODE_IDS <= id:
                self.NODE_IDS = id + 1
        # create edges
        for id in self.project.edges:
            self.edgeViews[id] = self.view_manager.create_edge(
                self.project.edges[id],
                self.project.nodes[self.project.edges[id].node1],
                self.project.nodes[self.project.edges[id].node2])
            # egde_ids should be biggest of loaded ids
            if self.EDGE_IDS <= id:
                self.EDGE_IDS = id + 1
Esempio n. 10
0
    def openFile(self):
        filename, _ = QFileDialog.getOpenFileName(self, 'Open File',
                os.getenv('HOME'))

        if not filename:
            return

        fh = ''

        if QFile.exists(filename):
            fh = QFile(filename)

        if not fh.open(QFile.ReadOnly):
            QtGui.qApp.quit()

        data = fh.readAll()
        codec = QTextCodec.codecForUtfText(data)
        unistr = codec.toUnicode(data)

        tmp = ('Nopepad: %s' % filename)
        self.setWindowTitle(tmp)

        basename = QFileInfo(fh).baseName()
        self.statusBar().showMessage('File \'%s\' loaded' % basename)

        self.textEdit.setText(unistr)
Esempio n. 11
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. 12
0
    def on_openButton_clicked(self):
        dialog = QFileDialog(self)
        if PATH.IS_SCREEN:
            DIR = PATH.SCREENDIR
        else:
            DIR = PATH.PANELDIR
        dialog.setDirectory(DIR)
        fileName, _ = dialog.getOpenFileName()
        if fileName:
            file = QFile(fileName)
            file.open(QFile.ReadOnly)
            styleSheet = file.readAll()
            try:
                # Python v2.
                styleSheet = unicode(styleSheet, encoding='utf8')
            except NameError:
                # Python v3.
                styleSheet = str(styleSheet, encoding='utf8')

            self.styleTextView.setPlainText(styleSheet)
            model = self.styleSheetCombo.model()
            item = QtGui.QStandardItem(os.path.basename(fileName))
            item.setData( fileName, role = QtCore.Qt.UserRole + 1)
            model.appendRow(item)
            self.styleSheetCombo.setCurrentIndex(self.styleSheetCombo.count()-1)
Esempio n. 13
0
 def set_StyleSheet(self, sheetName):
     if sheetName:
         file = QFile('stylesheet/%s.qss' % sheetName.lower())
         file.open(QFile.ReadOnly)
         styleSheet = file.readAll()
         styleSheet = str(styleSheet, encoding='utf8') # Python v3.
         self.setStyleSheet(styleSheet)
Esempio n. 14
0
    def openFile(self, path=None):
        if self.maybeSave():
            if not path:
                path, _ = QFileDialog.getOpenFileName(
                    self, "Open File",
                    QDir.homePath() + "/Documents/",
                    "Text Files (*.txt *.csv *.py);;All Files (*.*)")

            if path:
                inFile = QFile(path)
                if inFile.open(QFile.ReadWrite | QFile.Text):
                    text = inFile.readAll()

                    try:
                        # Python v3.
                        text = str(text, encoding='utf8')
                    except TypeError:
                        # Python v2.
                        text = str(text)
                    self.editor.setPlainText(text)
                    self.filename = path
                    self.setModified(False)
                    self.fname = QFileInfo(path).fileName()
                    self.setWindowTitle(self.fname + "[*]")
                    self.document = self.editor.document()
                    self.setCurrentFile(self.filename)
    def load_css(self, path, name):
        path = QFile(path)
        if not path.open(QFile.ReadOnly | QtCore.QFile.Text):
            return
        css = path.readAll().data().decode("utf-8")
        SCRIPT = """
        (function() {
        try {
        css = document.createElement('style');
        css.type = 'text/css';
        css.id = "%s";
        document.head.appendChild(css);
        css.innerText = `%s`;
        } catch(e) {}
        })()
        """ % (name, css)

        script = QWebEngineScript()
        self.web_page.runJavaScript(SCRIPT, QWebEngineScript.ApplicationWorld)
        script.setName(name)
        script.setSourceCode(SCRIPT)
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setRunsOnSubFrames(True)
        script.setWorldId(QWebEngineScript.ApplicationWorld)
        self.web_page.scripts().insert(script)
Esempio n. 16
0
def load(path):
    file = QFile(path)
    try:
        file.open(QIODevice.ReadOnly)
        return file.readAll()
    finally:
        file.close()
Esempio n. 17
0
 def __insertFlashCookie(self, path):
     """
     Private method to insert a Flash cookie into the cache.
     
     @param path Flash cookies path
     @type str
     """
     solFile = QFile(path)
     if not solFile.open(QFile.ReadOnly):
         return
     
     dataStr = ""
     data = bytes(solFile.readAll())
     if data:
         try:
             reader = FlashCookieReader()
             reader.setBytes(data)
             reader.parse()
             dataStr = reader.toString()
         except FlashCookieReaderError as err:
             dataStr = err.msg
     
     solFileInfo = QFileInfo(solFile)
     
     cookie = FlashCookie()
     cookie.contents = dataStr
     cookie.name = solFileInfo.fileName()
     cookie.path = solFileInfo.canonicalPath()
     cookie.size = int(solFile.size())
     cookie.lastModified = solFileInfo.lastModified()
     cookie.origin = self.__extractOriginFrom(path)
     
     self.__flashCookies.append(cookie)
Esempio n. 18
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. 19
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
 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. 21
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. 22
0
 def readStyleSheet(self, fileName):
     css = None
     file = QFile(fileName)
     if file.open(QIODevice.ReadOnly):
         css = file.readAll()
         file.close()
     return css
Esempio n. 23
0
 def __init__(self):
     # 应用
     self.__app = QApplication(sys.argv)
     # 主窗口
     self.__mainWindow = QMainWindow()
     # 样式表
     file = QFile('style.qss')
     file.open(QFile.ReadOnly)
     styleSheet = file.readAll()
     styleSheet = str(styleSheet, encoding='utf8')
     self.__mainWindow.setStyleSheet(styleSheet)
     # 主窗口大小
     self.__mainWindow.setGeometry(300, 300, 940, 610)
     # 主窗口标题
     self.__mainWindow.setWindowTitle('Title')
     # 主窗口icon
     self.__mainWindow.setWindowIcon(QIcon('../favicon.ico'))
     # 菜单栏
     menubar = self.__mainWindow.menuBar()
     menubar.addMenu('menu')
     menubar.addMenu('menu2')
     # 状态栏
     self.__mainWindow.statusBar().showMessage('这里是状态栏...')
     # 信号
     self.__signal = MySignal()
     self.__signal.show_single_page.connect(my_print)
     # signal.signal.connect(my_print)
     pass
Esempio n. 24
0
def client_script():
    """ Reads qtwebchannel.js from disk and creates QWebEngineScript to inject to QT window.
        This allows for JavaScript code to call python methods marked by pyqtSlot in registered objects.

    Args:
        None.

    Returns:
        None.

    Raises:
    """
    qwebchannel_js = QFile(':/qtwebchannel/qwebchannel.js')
    if not qwebchannel_js.open(QIODevice.ReadOnly):
        raise SystemExit(
            'Failed to load qwebchannel.js with error: %s' %
            qwebchannel_js.errorString())
    qwebchannel_js = bytes(qwebchannel_js.readAll()).decode('utf-8')
    script = QWebEngineScript()
    script.setSourceCode(qwebchannel_js)
    script.setName('qWebChannelJS')
    script.setWorldId(QWebEngineScript.MainWorld)
    script.setInjectionPoint(QWebEngineScript.DocumentReady)
    script.setRunsOnSubFrames(True)
    return script
Esempio n. 25
0
    def _initPreviewToTextSync(self):
        """Initialize the system per items 1, 2, and 4 above."""
        # When a web page finishes loading, reinsert our JavaScript.
        page = self._dock._widget.webEngineView.page()

        # Insert our scripts into every loaded page.
        qwebchannel_js = QFile(':/qtwebchannel/qwebchannel.js')
        if not qwebchannel_js.open(QIODevice.ReadOnly):
            raise SystemExit(
                'Failed to load qwebchannel.js with error: %s' %
                qwebchannel_js.errorString())
        qwebchannel_js = bytes(qwebchannel_js.readAll()).decode('utf-8')

        # Set up the QWebChannel. See http://doc.qt.io/qt-5/qtwebchannel-javascript.html.
        # Run the script containing QWebChannel.js first.
        beforeScript = QWebEngineScript()
        beforeScript.setSourceCode(qwebchannel_js + self._jsPreviewSync + self._qtJsInit)
        beforeScript.setName('qwebchannel.js, previewSync')
        # Run this JavaScript separated from any JavaScript present in the loaded web page. This provides better security (rogue pages can't access the QWebChannel) and better isolation (handlers, etc. won't conflict, I hope).
        beforeScript.setWorldId(QWebEngineScript.ApplicationWorld)
        beforeScript.setInjectionPoint(QWebEngineScript.DocumentCreation)
        # Per `setWebChannel <http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel>`_, only one channel is allowed per page. So, don't run this on sub-frames, since it will attempt the creation of more channels for each subframe.
        beforeScript.setRunsOnSubFrames(False)
        page.scripts().insert(beforeScript)

        # Set up the web channel. See https://riverbankcomputing.com/pipermail/pyqt/2015-August/036346.html
        # and http://stackoverflow.com/questions/28565254/how-to-use-qt-webengine-and-qwebchannel.
        # For debug, ``set QTWEBENGINE_REMOTE_DEBUGGING=port`` then browse to
        # http://127.0.0.1:port, where port=60000 works for me. See https://riverbankcomputing.com/pipermail/pyqt/2015-August/036346.html.
        self.channel = QWebChannel(page)
        self.channel.registerObject("previewSync", self)
        # Expose the ``qt.webChannelTransport`` object in the world where these scripts live.
        page.setWebChannel(self.channel, QWebEngineScript.ApplicationWorld)
Esempio n. 26
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. 27
0
 def load(self, what):
     try:
         # open file and load project
         if what != "":
             xml = QFile(what.toLocalFile())
         else:
             xml = QFile("temp")
         if xml.open(QFile.ReadOnly):
             self.project.deserialize(fromstring(xml.readAll()))
         if(what == ""):
             os.remove("./temp")
         # create views
         for id in self.project.nodes:
             self.nodeViews[id] = self.view_manager.create_node(
                 self.project.nodes[id])
             # node_ids should be biggest of loaded ids
             if self.NODE_IDS <= id:
                 self.NODE_IDS = id + 1
         # create edges
         for id in self.project.edges:
             self.edgeViews[id] = self.view_manager.create_edge(
                 self.project.edges[id],
                 self.project.nodes[self.project.edges[id].node1],
                 self.project.nodes[self.project.edges[id].node2])
             # egde_ids should be biggest of loaded ids
             if self.EDGE_IDS <= id:
                 self.EDGE_IDS = id + 1
         print("Loaded nodes: " + str(self.project.nodes))
         print("Loaded NodeViews: " + str(self.nodeViews))
         print("Loaded edges: " + str(self.project.edges))
         print("Loaded EdgeViews: " + str(self.edgeViews))
     except:
         print("Nepodarilo sa nacitat subor")
Esempio n. 28
0
    def __init__(self, parent=None):
        super(QRibbonToolBar, self).__init__(parent)
        self.parent = parent
        self.setWindowTitle('工具栏')

        # if not isinstance(self.parent, RibbonMainWindow):
        #     raise TypeError("__init__(self, parent=None) 'parent' requires 'FramelessWindow' type.")
        # with open(os.path.join(os.path.dirname(__file__), 'qss/QRibbonWidget.qss')) as fp:
        # with open(':/QRibbonWidget.qss') as fp:
        #     self.setStyleSheet(fp.read())
        f = QFile(':/QRibbonWidget.qss')
        f.open(QFile.ReadOnly)
        self.setStyleSheet(str(f.readAll(), 'utf-8'))
        f.close()

        self.ribbon_widget = QRibbonWidget(self)
        self.addWidget(self.ribbon_widget)
        self.setAllowedAreas(Qt.NoToolBarArea)
        self.setMovable(False)
        self.setFloatable(False)

        self.setMouseTracking(True)

        # self.add_widget = self.ribbon_widget.title_bar.add_widget
        self.add_menu = self.ribbon_widget.menu_bar.add_menu
        self.add_group = self.ribbon_widget.menu_bar.add_group
Esempio n. 29
0
 def read(self, fileName):
     file = QFile(fileName)
     if (not file.open(QIODevice.ReadOnly | QIODevice.Text)) :
         self.mError = self.tr("Could not open file for reading.")
         return None
     
     contents = file.readAll()
     contents = contents.data().decode()
     if (self.mSubFormat == JsonMapFormat.SubFormat.JavaScript and len(contents) > 0 and contents[0] != '{') :
         # Scan past JSONP prefix; look for an open curly at the start of the line
         i = contents.index("\n{")
         if (i > 0) :
             contents = contents[i:]
             contents = contents.strip() # potential trailing whitespace
             if (contents.endswith(';')):
                 contents = contents[:-1]
             if (contents.endswith(')')):
                 contents = contents[:-1]
     
     try:
         variant = json.loads(contents)
     except:
         self.mError = self.tr("Error parsing file.")
         return None
     
     converter = VariantToMapConverter()
     map = converter.toMap(variant, QFileInfo(fileName).dir())
     if (not map):
         self.mError = converter.errorString()
     return map
Esempio n. 30
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. 31
0
def _createWebengineScript(path: Url,
                           name: str,
                           injectionPoint=None,
                           isStylesheet: bool = False) -> QWebEngineScript:

    if injectionPoint is None:
        injectionPoint = QWebEngineScript.DocumentCreation

    script = QWebEngineScript()
    script_file = QFile(path)

    if script_file.open(QFile.ReadOnly):
        script_string = str(script_file.readAll(), 'utf-8')
        script.setInjectionPoint(injectionPoint)
        script.setName(name)
        script.setRunsOnSubFrames(True)
        script.setWorldId(QWebEngineScript.MainWorld)
        if isStylesheet:
            source = ("(function(){"
                      ""
                      "const css = document.createElement('style');\n"
                      "css.type = 'text/css';\n"
                      "css.innerText = `" + script_string.strip() + "`\n"
                      "document.head.appendChild(css);\n"
                      "})()")
            script.setSourceCode(source)
        else:
            script.setSourceCode(script_string)

    return script
    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. 33
0
    def openJSONData(self, filePath):
        self.msgBox = QMessageBox()
        self.fly = QApplication.desktop().screen().rect().center(
        ) - self.msgBox.rect().center()
        fileInfo = QFileInfo(filePath)
        fileName = fileInfo.fileName()
        openFile = QFile(filePath)

        openFile.open(QIODevice.ReadOnly | QIODevice.Text)
        if openFile.error() != openFile.NoError:
            self.msgBox.information(
                QDialog().move(self.fly), "{}".format(fileName),
                self.translate("openV2rayJSONFile",
                               "Unable to open the file {}:  {}.").format(
                                   fileName, openFile.errorString()))
            openFile = None
            return

        JSONData = str(openFile.readAll(), "utf-8")
        try:
            JSONData = json.loads(JSONData)
        except ValueError as e:
            self.msgBox.information(
                QDialog().move(self.fly),
                self.translate("openV2rayJSONFile", "Parse JSON Data Error"),
                self.translate("openV2rayJSONFile",
                               "Unable to parse {}:  error:{}.").format(
                                   fileName, e))
            openFile = None
            JSONData = None
            return
        else:
            return JSONData
        openFile.close()
Esempio n. 34
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. 35
0
    def loadStyleSheet(self, sheetName):
        if sheetName == 'None':
            self.styleTextView.setPlainText('')
            styleSheet = ''
            self.styleTextView.setPlainText(styleSheet)
            return
        if sheetName == 'As Loaded':
            styleSheet = self.origStyleSheet
        else:
            if PATH.IS_SCREEN:
                DIR = PATH.SCREENDIR
                BNAME = PATH.BASENAME
            else:
                DIR =PATH.PANELDIR
                BNAME = PATH.BASENAME
            qssname = os.path.join(DIR, BNAME, sheetName)
            file = QFile(qssname)
            file.open(QFile.ReadOnly)
            styleSheet = file.readAll()
            try:
                # Python v2.
                styleSheet = unicode(styleSheet, encoding='utf8')
            except NameError:
                # Python v3.
                styleSheet = str(styleSheet, encoding='utf8')

        self.styleTextView.setPlainText(styleSheet)
Esempio n. 36
0
 def loadStyleSheet(self, sheetName):
     file_name = sheetName + '.css'
     file = QFile('../css/{}'.format(file_name))
     file.open(QFile.ReadOnly)
     styleSheet = file.readAll()
     styleSheet = str(styleSheet, encoding='utf8')
     QtWidgets.QApplication.instance().setStyleSheet(styleSheet)
Esempio n. 37
0
    def loadStamps(self):
        prefs = preferences.Preferences.instance()
        stampsDirectory = prefs.stampsDirectory()
        stampsDir = QDir(stampsDirectory)
        iterator = QDirIterator(stampsDirectory, ["*.stamp"],
                                QDir.Files | QDir.Readable)
        while (iterator.hasNext()):
            stampFileName = iterator.next()
            stampFile = QFile(stampFileName)
            if (not stampFile.open(QIODevice.ReadOnly)):
                continue
            data = stampFile.readAll()
            document = QJsonDocument.fromBinaryData(data)
            if (document.isNull()):
                # document not valid binary data, maybe it's an JSON text file
                error = QJsonParseError()
                document = QJsonDocument.fromJson(data, error)
                if (error.error != QJsonParseError.NoError):
                    qDebug("Failed to parse stamp file:" + error.errorString())
                    continue

            stamp = TileStamp.fromJson(document.object(), stampsDir)
            if (stamp.isEmpty()):
                continue
            stamp.setFileName(iterator.fileInfo().fileName())
            self.mTileStampModel.addStamp(stamp)
            index = stamp.quickStampIndex()
            if (index >= 0 and index < self.mQuickStamps.size()):
                self.mQuickStamps[index] = stamp
Esempio n. 38
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. 39
0
    def create_dock_windows(self):

        self.dock_view_list = ViewList()
        self.dock_view_list.select_item_index.connect(self.select_item_change)
        # self.view_dock_widget.setWidget(self.view_list)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_view_list)

        self.dock_slice_info = InfoWidget()
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_slice_info)
        self.dock_slice_info.setMinimumWidth(self.width * 0.5)
        self.dock_slice_info.setMinimumHeight(self.height * 0.4)

        self.dock_slice_tif = TifWidget()
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_slice_tif)
        self.dock_slice_tif.setMinimumWidth(self.width * 0.5)
        self.dock_slice_tif.setFixedHeight(self.height * 0.5)

        self.dock_debug_info = DebugInfo()
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_debug_info)
        self.dock_debug_info.setMinimumWidth(self.width * 0.5)
        self.dock_debug_info.setFixedHeight(self.height * 0.4)

        self.dock_debug_info.set_text_browser('')
        version_file = QFile("Version.txt")
        version_file.open(QIODevice.ReadOnly)
        ver_info = str(version_file.readAll(), encoding='utf-8')
        version_file.close()
        self.dock_debug_info.set_head_info(ver_info)
Esempio n. 40
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. 41
0
 def loadStylesheet(self, filename):
     print("Loading STYLE: {0}".format(filename))
     file = QFile(filename)
     file.open(QFile.ReadOnly | QFile.Text)
     stylesheet = file.readAll()
     QApplication.instance().setStyleSheet(str(stylesheet,
                                               encoding='utf-8'))
Esempio n. 42
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. 43
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. 44
0
    def instanceSelected(self, index):
        index += 2 * self.schemaSelection.currentIndex()
        instanceFile = QFile(':/instance_%d.xml' % index)
        instanceFile.open(QFile.ReadOnly)
        instanceData = instanceFile.readAll()
        self.instanceEdit.setPlainText(encode_utf8(instanceData))

        self.validate()
Esempio n. 45
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. 46
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. 47
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. 48
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. 49
0
 def clickAction_styleLoad(self):
     fname, filter = QFileDialog.getOpenFileName(self, "QT스타일시트파일 불러오기", '.', "Qt-StyleSheet(*.qss)")
     if fname:
         file = QFile(fname)
         file.open(QFile.ReadOnly)
         styleSheet = file.readAll()
         styleSheet = str(styleSheet, encoding='utf8') # Python v3.
         self.setStyleSheet(styleSheet)
         print ("test")
Esempio n. 50
0
 def __createSpeedDialPage(self):
     """
     Private method to create the Speeddial page.
     
     @return prepared speeddial page (QByteArray)
     """
     if self._speedDialPage is None:
         htmlFile = QFile(":/html/speeddialPage.html")
         htmlFile.open(QFile.ReadOnly)
         html = bytes(htmlFile.readAll()).decode()
         
         html = (
             html.replace("@FAVICON@", "qrc:icons/ericWeb16.png")
             .replace("@IMG_PLUS@", "qrc:icons/plus.png")
             .replace("@IMG_CLOSE@", "qrc:icons/close.png")
             .replace("@IMG_EDIT@", "qrc:icons/edit.png")
             .replace("@IMG_RELOAD@", "qrc:icons/reload.png")
             .replace("@IMG_SETTINGS@", "qrc:icons/setting.png")
             .replace("@LOADING-IMG@", "qrc:icons/loading.gif")
             .replace("@BOX-BORDER@", "qrc:icons/box-border-small.png")
             
             .replace("@JQUERY@", "qrc:javascript/jquery.js")
             .replace("@JQUERY-UI@", "qrc:javascript/jquery-ui.js")
             
             .replace("@SITE-TITLE@", self.tr("Speed Dial"))
             .replace("@URL@", self.tr("URL"))
             .replace("@TITLE@", self.tr("Title"))
             .replace("@APPLY@", self.tr("Apply"))
             .replace("@CLOSE@", self.tr("Close"))
             .replace("@NEW-PAGE@", self.tr("New Page"))
             .replace("@TITLE-EDIT@", self.tr("Edit"))
             .replace("@TITLE-REMOVE@", self.tr("Remove"))
             .replace("@TITLE-RELOAD@", self.tr("Reload"))
             .replace("@TITLE-WARN@",
                      self.tr("Are you sure to remove this speed dial?"))
             .replace("@TITLE-FETCHTITLE@",
                      self.tr("Load title from page"))
             .replace("@SETTINGS-TITLE@",
                      self.tr("Speed Dial Settings"))
             .replace("@ADD-TITLE@", self.tr("Add New Page"))
             .replace("@TXT_NRROWS@",
                      self.tr("Maximum pages in a row:"))
             .replace("@TXT_SDSIZE@", self.tr("Change size of pages:"))
         )
         
         self._speedDialPage = Utilities.html_uencode(html)
     
     import Helpviewer.HelpWindow
     html = QByteArray(self._speedDialPage.encode("utf-8"))
     dial = Helpviewer.HelpWindow.HelpWindow.speedDial()
     
     html.replace("@INITIAL-SCRIPT@", dial.initialScript().encode("utf-8"))
     html.replace("@ROW-PAGES@", str(dial.pagesInRow()).encode("utf-8"))
     html.replace("@SD-SIZE@", str(dial.sdSize()).encode("utf-8"))
     
     return html
Esempio n. 51
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
Esempio n. 52
0
    def read_file(self, path):
        """Read in a file
        """
        file = QFile(path)
        fileinfo = QFileInfo(file)

        file.open(QIODevice.ReadOnly)
        data = file.readAll()
        codec = QTextCodec.codecForName("UTF-8")

        self.contents = codec.toUnicode(data).rstrip("\n")

        self.filename = fileinfo.fileName()
Esempio n. 53
0
    def open(self):
        fileName, _ = QFileDialog.getOpenFileName(self)
        if fileName:
            inFile = QFile(fileName)
            if not inFile.open(QFile.ReadOnly):
                QMessageBox.warning(self, "Codecs",
                        "Cannot read file %s:\n%s" % (fileName, inFile.errorString()))
                return

            data = inFile.readAll()

            self.previewForm.setEncodedData(data)
            if self.previewForm.exec_():
                self.textEdit.setPlainText(self.previewForm.decodedString())
Esempio n. 54
0
def read_embedded_file(src_name):
    """ Return the contents of an embedded source file as a QByteArray.
    src_name is the name of the source file.  A UserException is raised if
    there was an error.
    """

    src_file = QFile(src_name)

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

    contents = src_file.readAll()
    src_file.close()

    return contents
Esempio n. 55
0
    def loadStyleSheet(self, sheetName):
        file = QFile(':/qss/%s.qss' % sheetName.lower())
        file.open(QFile.ReadOnly)

        styleSheet = file.readAll()
        try:
            # Python v2.
            styleSheet = unicode(styleSheet, encoding='utf8')
        except NameError:
            # Python v3.
            styleSheet = str(styleSheet, encoding='utf8')

        self.ui.styleTextEdit.setPlainText(styleSheet)
        QApplication.instance().setStyleSheet(styleSheet)
        self.ui.applyButton.setEnabled(False)
Esempio n. 56
0
            def on_load():
                file = QFile(filename)
                fileinfo = QFileInfo(file)

                file.open(QFile.ReadOnly)
                data = file.readAll()
                codec = QTextCodec.codecForUtfText(data)
                unistr = codec.toUnicode(data)

                self.page().mainFrame().findFirstElement("#editor").setInnerXml(unistr)
                self.page().mainFrame().evaluateJavaScript("init()")

                suffix = fileinfo.suffix()
                self.page().mainFrame().evaluateJavaScript("editor.getSession().setMode('%s');" % (
                    self.SUFIX_2_MODE[suffix] if suffix in self.SUFIX_2_MODE else self.SUFIX_2_MODE[None]
                ))
Esempio n. 57
0
 def __createHomePage(self):
     """
     Private method to create the Home page.
     
     @return prepared home page (QByteArray)
     """
     if self._homePage is None:
         htmlFile = QFile(":/html/startPage.html")
         htmlFile.open(QFile.ReadOnly)
         html = htmlFile.readAll()
         
         html.replace("@IMAGE@", b"qrc:icons/ericWeb32.png")
         html.replace("@FAVICON@", b"qrc:icons/ericWeb16.png")
         
         self._homePage = html
     
     return QByteArray(self._homePage)