Exemplo n.º 1
1
    def go_to_definition(self):
        self.dirty = True
        self.results = []
        locations = self.get_locations()
        if self._isVariable:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if (x.type == FILTERS['attribs']) and (x.name == self._search)]
        else:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if ((x.type == FILTERS['functions']) or
                    (x.type == FILTERS['classes'])) and
                   (x.name.startswith(self._search))]
        for data in preResults:
            file_object = QFile(data[1])
            if not file_object.open(QFile.ReadOnly):
                return

            stream = QTextStream(file_object)
            line_index = 0
            line = stream.readLine()
            while not self._cancel and not stream.atEnd():
                if line_index == data[2]:
                    data[3] = line
                    self.results.append(data)
                    break
                #take the next line!
                line = stream.readLine()
                line_index += 1
Exemplo n.º 2
0
    def _on_browser_open(self):
        if self._imagecontainer is None:
            QMessageBox.warning(self, 'Data structure not loaded',
                                'The input directory structure file was not loaded.\n'
                                'Click "Scan input directory" in section "General" to proceed.')
        elif self._browser is None:
            try:
                browser = Browser(self._settings, self._imagecontainer, None)
                browser.show()
                browser.raise_()
                browser.setFocus()
                app = AppPreferences()

                f = QFile(":cecog_style")
                f.open(QFile.ReadOnly|QFile.Text)
                ts = QTextStream(f).readAll()

                browser.setStyleSheet(ts)
                self._browser = browser
            except Exception as e:
                traceback.print_exc()
                QMessageBox.critical(self, "Error", str(e))
        else:
            self._browser.show()
            self._browser.raise_()
Exemplo n.º 3
0
    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles
Exemplo n.º 4
0
    def openFile(self, path=None):
        if not path:
            path, _ = QFileDialog.getOpenFileName(self, "Open SVG File",
                    self.currentPath, "SVG files (*.svg *.svgz *.svg.gz)")

        if path:
            svg_file = QFile(path)
            if not svg_file.exists():
                QMessageBox.critical(self, "Open SVG File",
                        "Could not open file '%s'." % path)

                self.outlineAction.setEnabled(False)
                self.backgroundAction.setEnabled(False)
                return

            self.view.openFile(svg_file)

            if not path.startswith(':/'):
                self.currentPath = path
                self.setWindowTitle("%s - SVGViewer" % self.currentPath)

            self.outlineAction.setEnabled(True)
            self.backgroundAction.setEnabled(True)

            self.resize(self.view.sizeHint() + QSize(80, 80 + self.menuBar().height()))
Exemplo n.º 5
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
Exemplo n.º 6
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))
Exemplo n.º 7
0
 def removeSubscription(self, subscription, emitSignal=True):
     """
     Public method to remove an AdBlock subscription.
     
     @param subscription AdBlock subscription to be removed
         (AdBlockSubscription)
     @param emitSignal flag indicating to send a signal (boolean)
     """
     if subscription is None:
         return
     
     if subscription.url().toString().startswith(
         (self.__defaultSubscriptionUrlString,
          self.__customSubscriptionUrlString)):
         return
     
     try:
         self.__subscriptions.remove(subscription)
         rulesFileName = subscription.rulesFileName()
         QFile.remove(rulesFileName)
         requiresSubscriptions = self.getRequiresSubscriptions(subscription)
         for requiresSubscription in requiresSubscriptions:
             self.removeSubscription(requiresSubscription, False)
         if emitSignal:
             self.rulesChanged.emit()
     except ValueError:
         pass
Exemplo 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)
Exemplo n.º 9
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
Exemplo n.º 10
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()
Exemplo n.º 11
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
Exemplo n.º 12
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))
Exemplo n.º 13
0
    def __init__(self, parent=None):
        super(DragWidget, self).__init__(parent)

        dictionaryFile = QFile(':/dictionary/words.txt')
        dictionaryFile.open(QIODevice.ReadOnly)

        x = 5
        y = 5

        for word in QTextStream(dictionaryFile).readAll().split():
            wordLabel = DragLabel(word, self)
            wordLabel.move(x, y)
            wordLabel.show()
            x += wordLabel.width() + 2
            if x >= 195:
                x = 5
                y += wordLabel.height() + 2

        newPalette = self.palette()
        newPalette.setColor(QPalette.Window, Qt.white)
        self.setPalette(newPalette)

        self.setAcceptDrops(True)
        self.setMinimumSize(400, max(200, y))
        self.setWindowTitle("Draggable Text")
Exemplo n.º 14
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)
Exemplo n.º 15
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
Exemplo n.º 16
0
 def removeScript(self, script):
     """
     Public method to remove a script.
     
     @param script script to be removed (GreaseMonkeyScript)
     @return flag indicating success (boolean)
     """
     if not script:
         return False
     
     from .GreaseMonkeyScript import GreaseMonkeyScript
     if script.startAt() == GreaseMonkeyScript.DocumentStart:
         try:
             self.__startScripts.remove(script)
         except ValueError:
             pass
     else:
         try:
             self.__endScripts.remove(script)
         except ValueError:
             pass
     
     fullName = script.fullName()
     if fullName in self.__disabledScripts:
         self.__disabledScripts.remove(fullName)
     QFile.remove(script.fileName())
     
     self.scriptsChanged.emit()
     return True
Exemplo n.º 17
0
 def read(self, fileNameOrDevice):
     """
     Public method to read a login data file.
     
     @param fileNameOrDevice name of the file to read (string)
         or reference to the device to read (QIODevice)
     @return tuple containing the logins, forms and never URLs
     """
     self.__logins = {}
     self.__loginForms = {}
     self.__never = []
     
     if isinstance(fileNameOrDevice, QIODevice):
         self.setDevice(fileNameOrDevice)
     else:
         f = QFile(fileNameOrDevice)
         if not f.exists():
             return self.__logins, self.__loginForms, self.__never
         f.open(QFile.ReadOnly)
         self.setDevice(f)
     
     while not self.atEnd():
         self.readNext()
         if self.isStartElement():
             version = self.attributes().value("version")
             if self.name() == "Password" and \
                (not version or version == "1.0"):
                 self.__readPasswords()
             else:
                 self.raiseError(QCoreApplication.translate(
                     "PasswordReader",
                     "The file is not a Passwords version 1.0 file."))
     
     return self.__logins, self.__loginForms, self.__never
Exemplo n.º 18
0
 def read(self, fileNameOrDevice):
     """
     Public method to read a user agent file.
     
     @param fileNameOrDevice name of the file to read (string)
         or reference to the device to read (QIODevice)
     @return dictionary with user agent data (host as key, agent string as
         value)
     """
     self.__agents = {}
     
     if isinstance(fileNameOrDevice, QIODevice):
         self.setDevice(fileNameOrDevice)
     else:
         f = QFile(fileNameOrDevice)
         if not f.exists():
             return self.__agents
         f.open(QFile.ReadOnly)
         self.setDevice(f)
     
     while not self.atEnd():
         self.readNext()
         if self.isStartElement():
             version = self.attributes().value("version")
             if self.name() == "UserAgents" and \
                (not version or version == "1.0"):
                 self.__readUserAgents()
             else:
                 self.raiseError(QCoreApplication.translate(
                     "UserAgentReader",
                     "The file is not a UserAgents version 1.0 file."))
     
     return self.__agents
Exemplo n.º 19
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
Exemplo n.º 20
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")
Exemplo n.º 21
0
    def readObjectTypes(self, fileName):
        self.mError = ''
        objectTypes = QVector()
        file = QFile(fileName)
        if (not file.open(QIODevice.ReadOnly | QIODevice.Text)):
            self.mError = QCoreApplication.translate(
                        "ObjectTypes", "Could not open file.")
            return objectTypes

        reader = QXmlStreamReader(file)
        if (not reader.readNextStartElement() or reader.name() != "objecttypes"):
            self.mError = QCoreApplication.translate(
                        "ObjectTypes", "File doesn't contain object types.")
            return objectTypes

        while (reader.readNextStartElement()):
            if (reader.name() == "objecttype"):
                atts = reader.attributes()
                name = QString(atts.value("name"))
                color = QColor(atts.value("color"))
                objectTypes.append(ObjectType(name, color))

            reader.skipCurrentElement()

        if (reader.hasError()):
            self.mError = QCoreApplication.translate("ObjectTypes", "%s\n\nLine %d, column %d"%(reader.errorString(), reader.lineNumber(), reader.columnNumber()))
            return objectTypes

        return objectTypes
Exemplo n.º 22
0
 def __finished(self):
     """
     Private slot to handle the download finished.
     """
     self.__finishedDownloading = True
     if not self.__startedSaving:
         return
     
     noError = self.__reply.error() == QNetworkReply.NoError
     
     self.progressBar.setVisible(False)
     if not self.__isFtpDownload:
         self.stopButton.setEnabled(False)
         self.stopButton.setVisible(False)
         self.pauseButton.setEnabled(False)
         self.pauseButton.setVisible(False)
     self.openButton.setEnabled(noError)
     self.openButton.setVisible(noError)
     self.__output.close()
     if QFile.exists(self.__fileName):
         QFile.remove(self.__fileName)
     self.__output.rename(self.__fileName)
     self.__updateInfoLabel()
     self.__state = DownloadItem.DownloadSuccessful
     self.statusChanged.emit()
     self.downloadFinished.emit()
     
     if self.__autoOpen:
         self.__open()
Exemplo n.º 23
0
 def removeEngine(self, name):
     """
     Public method to remove an engine.
     
     @param name name of the engine (string)
     """
     if len(self.__engines) <= 1:
         return
     
     if name not in self.__engines:
         return
     
     engine = self.__engines[name]
     for keyword in [k for k in self.__keywords
                     if self.__keywords[k] == engine]:
         del self.__keywords[keyword]
     del self.__engines[name]
     
     file_ = QDir(self.enginesDirectory()).filePath(
         self.generateEngineFileName(name))
     QFile.remove(file_)
     
     if name == self.__current:
         self.setCurrentEngineName(list(self.__engines.keys())[0])
     
     self.changed.emit()
Exemplo n.º 24
0
    def downloadFile(self):
        self.url = QUrl(self.urlLineEdit.text())
        fileInfo = QFileInfo(self.url.path())
        fileName = fileInfo.fileName()

        if not fileName:
            fileName = 'index.html'

        if QFile.exists(fileName):
            ret = QMessageBox.question(self, "HTTP",
                    "There already exists a file called %s in the current "
                    "directory. Overwrite?" % fileName,
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

            if ret == QMessageBox.No:
                return

            QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(self, "HTTP",
                    "Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        self.progressDialog.setWindowTitle("HTTP")
        self.progressDialog.setLabelText("Downloading %s." % fileName)
        self.downloadButton.setEnabled(False)

        self.httpRequestAborted = False
        self.startRequest(self.url)
Exemplo n.º 25
0
    def _copy_lib_file(cls, file_name, dir_name, dst_file_name=None):
        """ Copy a library file to a directory and return the full pathname of
        the copy.
        """

        # Note that we use the Qt file operations to support the possibility
        # that pyqtdeploy itself has been deployed as a single executable.

        if dst_file_name is None:
            dst_file_name = file_name
            s_file_name = cls._get_lib_file_name(file_name)
        else:
            s_file_name = file_name

        d_file_name = dir_name + '/' +  dst_file_name

        # Make sure the destination doesn't exist.
        QFile.remove(d_file_name)

        if not QFile.copy(s_file_name, d_file_name):
            raise UserException("Unable to copy file {0}".format(file_name))

        # The file will be read-only if it was embedded.
        QFile.setPermissions(d_file_name,
                QFileDevice.ReadOwner|QFileDevice.WriteOwner)

        return d_file_name
Exemplo n.º 26
0
    def loadDescription(self, startPara, nrPara):
        readme = QFile(self.readmePath)
        if not readme.open(QFile.ReadOnly):
            Colors.debug("- MenuContentItem.loadDescription: Could not load:", self.readmePath)
            return ""

        in_str = QTextStream(readme)
        # Skip a certain number of paragraphs.
        while startPara:
            if not in_str.readLine():
                startPara -= 1

        # Read in the number of wanted paragraphs.
        result = ""
        line = in_str.readLine()
        while True:
            result += line + " "
            line = in_str.readLine()
            if not line:
                nrPara -= 1
                line = "<br><br>" + in_str.readLine()

            if nrPara == 0 or in_str.atEnd():
                break

        return Colors.contentColor + result
Exemplo n.º 27
0
    def makeState(self, parentState, animationFileName):
        topLevel = QState(parentState)

        animation = Animation()

        file = QFile(animationFileName)
        if file.open(QIODevice.ReadOnly):
            animation.load(file)

        frameCount = animation.totalFrames()
        previousState = None
        for i in range(frameCount):
            animation.setCurrentFrame(i)

            frameState = QState(topLevel)
            nodeCount = animation.nodeCount()
            for j in range(nodeCount):
                frameState.assignProperty(self.m_stickMan.node(j), "pos", animation.nodePos(j))

            frameState.setObjectName("frame %d" % i)

            if previousState is None:
                topLevel.setInitialState(frameState)
            else:
                previousState.addTransition(previousState.propertiesAssigned, frameState)

            previousState = frameState

        previousState.addTransition(previousState.propertiesAssigned, topLevel.initialState())

        return topLevel
Exemplo n.º 28
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)
Exemplo n.º 29
0
    def readThemeIndex(self, themeName):

        dirList = []
        parents = []
        themeIndex = QFile()

        # Read theme index files
        for i in range(len(self.iconDirs)):
            themeIndex.setFileName(path.join(unicode(self.iconDirs[i]), 
                unicode(themeName), "index.theme"))
            if themeIndex.exists():
                indexReader = QSettings(themeIndex.fileName(), 
                        QSettings.IniFormat)
                for key in indexReader.allKeys():
                    if str(key).endswith("/Size"):
                        size = str(indexReader.value(key))
                        
                        dirList.append((size, 
                            unicode(key[:-5])))
                
                parents = indexReader.value('Icon Theme/Inherits')
                dump=parents
                parents = list()
                parents.append(dump)
                break
            
        return QIconTheme(dirList, parents)
Exemplo n.º 30
0
    def writeObjectTypes(self, fileName, objectTypes):
        self.mError = ''
        file = QFile(fileName)
        if (not file.open(QIODevice.WriteOnly | QIODevice.Text)):
            self.mError = QCoreApplication.translate(
                        "ObjectTypes", "Could not open file for writing.")
            return False

        writer = QXmlStreamWriter(file)
        writer.setAutoFormatting(True)
        writer.setAutoFormattingIndent(1)
        writer.writeStartDocument()
        writer.writeStartElement("objecttypes")
        for objectType in objectTypes:
            writer.writeStartElement("objecttype")
            writer.writeAttribute("name", objectType.name)
            writer.writeAttribute("color", objectType.color.name())
            writer.writeEndElement()

        writer.writeEndElement()
        writer.writeEndDocument()
        if (file.error() != QFile.NoError):
            self.mError = file.errorString()
            return False

        return True
Exemplo n.º 31
0
 def save(self):
     """
     Public slot to save the history entries to disk.
     """
     historyFile = QFile(self.getFileName())
     if not historyFile.exists():
         self.__lastSavedUrl = ""
     
     saveAll = self.__lastSavedUrl == ""
     first = len(self.__history) - 1
     if not saveAll:
         # find the first one to save
         for index in range(len(self.__history)):
             if self.__history[index].url == self.__lastSavedUrl:
                 first = index - 1
                 break
     if first == len(self.__history) - 1:
         saveAll = True
     
     if saveAll:
         # use a temporary file when saving everything
         f = QTemporaryFile()
         f.setAutoRemove(False)
         opened = f.open()
     else:
         f = historyFile
         opened = f.open(QIODevice.Append)
     
     if not opened:
         E5MessageBox.warning(
             None,
             self.tr("Saving History"),
             self.tr(
                 """<p>Unable to open history file <b>{0}</b>.<br/>"""
                 """Reason: {1}</p>""")
             .format(f.fileName(), f.errorString()))
         return
     
     for index in range(first, -1, -1):
         data = QByteArray()
         stream = QDataStream(data, QIODevice.WriteOnly)
         stream.setVersion(QDataStream.Qt_4_6)
         itm = self.__history[index]
         stream.writeUInt32(HISTORY_VERSION)
         stream.writeString(itm.url.encode())
         stream << itm.dateTime
         stream.writeString(itm.title.encode('utf-8'))
         f.write(data)
     
     f.close()
     if saveAll:
         if historyFile.exists() and not historyFile.remove():
             E5MessageBox.warning(
                 None,
                 self.tr("Saving History"),
                 self.tr(
                     """<p>Error removing old history file <b>{0}</b>."""
                     """<br/>Reason: {1}</p>""")
                 .format(historyFile.fileName(),
                         historyFile.errorString()))
         if not f.copy(historyFile.fileName()):
             E5MessageBox.warning(
                 None,
                 self.tr("Saving History"),
                 self.tr(
                     """<p>Error moving new history file over old one """
                     """(<b>{0}</b>).<br/>Reason: {1}</p>""")
                 .format(historyFile.fileName(), f.errorString()))
     self.historySaved.emit()
     try:
         self.__lastSavedUrl = self.__history[0].url
     except IndexError:
         self.__lastSavedUrl = ""
Exemplo n.º 32
0
def main():
    # Parse the command line.  Note that this mimics the original C++ (warts
    # and all) in order to preserve backwards compatibility.
    global verbose
    global compressLevel
    global compressThreshold
    global resourceRoot

    outFilename = ''
    helpRequested = False
    listFiles = False
    files = []

    errorMsg = None
    argc = len(sys.argv)
    i = 1

    while i < argc:
        arg = sys.argv[i]
        i += 1

        if arg[0] == '-':
            opt = arg[1:]

            if opt == "o":
                if i >= argc:
                    errorMsg = "Missing output name"
                    break

                outFilename = sys.argv[i]
                i += 1

            elif opt == "root":
                if i >= argc:
                    errorMsg = "Missing root path"
                    break

                resourceRoot = QDir.cleanPath(sys.argv[i])
                i += 1

                if resourceRoot == '' or resourceRoot[0] != '/':
                    errorMsg = "Root must start with a /"
                    break

            elif opt == "compress":
                if i >= argc:
                    errorMsg = "Missing compression level"
                    break

                compressLevel = int(sys.argv[i])
                i += 1

            elif opt == "threshold":
                if i >= argc:
                    errorMsg = "Missing compression threshold"
                    break

                compressThreshold = int(sys.argv[i])
                i += 1

            elif opt == "verbose":
                verbose = True

            elif opt == "list":
                listFiles = True

            elif opt == "version":
                sys.stderr.write("pyrcc5 v%s\n" % PYQT_VERSION_STR)
                sys.exit(1)

            elif opt == "help" or opt == "h":
                helpRequested = True

            elif opt == "no-compress":
                compressLevel = -2

            else:
                errorMsg = "Unknown option: '%s'" % arg
                break
        else:
            if not QFile.exists(arg):
                sys.stderr.write("%s: File does not exist '%s'\n" %
                                 (sys.argv[0], arg))
                sys.exit(1)

            files.append(arg)

    # Handle any errors or a request for help.
    if len(files) == 0 or errorMsg is not None or helpRequested:
        showHelp(errorMsg)
        sys.exit(1)

    if not processResourceFile(files, outFilename, listFiles):
        sys.exit(1)
Exemplo n.º 33
0
    def initUI2(self):
        global flag_content_image
        flag_content_image = 0
        global flag_style_image
        flag_style_image = 0
        global flag_finish_generate
        flag_finish_generate = 0

        file = QFile(':css/StyleSheet.css')
        file.open(QFile.ReadOnly)
        stream = QTextStream(file)
        text = stream.readAll()
        self.setStyleSheet(text)
        self.setWindowTitle(self.title)
        self.setWindowIcon(QIcon(":css/Icons/logo.png"))
        self.setGeometry(0, 0, self.width, self.height - 60)

        # Creating main container-frame, parent it to QWindow
        self.main_frame = QtWidgets.QFrame(self)
        self.main_frame.setObjectName("MainFrame")
        self.main_frame.setFixedWidth(self.width)
        self.main_frame.setFixedHeight(self.height)
        # the first sub window
        self.main_layout = QtWidgets.QVBoxLayout(self.main_frame)

        # home and help buttons
        # the Icons sub frame
        self.iconsub_frame = QtWidgets.QFrame(self.main_frame)
        self.iconsub_frame.setFixedHeight(80)
        self.main_layout.addWidget(self.iconsub_frame)
        self.iconsub_layout = QtWidgets.QHBoxLayout(self.iconsub_frame)
        self.iconsub_layout.setAlignment(Qt.AlignLeft)

        # help button
        help_btn = QtWidgets.QPushButton("", self)
        help_btn.setObjectName("TransparentButtons")
        help_btn.setStyleSheet("QPushButton {background: url(:css/Icons/help.png) no-repeat transparent;}")
        help_btn.setToolTip('Show help pdf.')
        help_btn.setFixedWidth(68)
        help_btn.setFixedHeight(68)
        help_btn.clicked.connect(main_window_gui.show_help_pdf)
        self.iconsub_layout.addWidget(help_btn)

        # home button
        home_btn = QtWidgets.QPushButton("", self)
        home_btn.setObjectName("TransparentButtons")
        home_btn.setStyleSheet("QPushButton {background: url(:css/Icons/home.png) no-repeat transparent;} ")
        home_btn.setFixedWidth(68)
        home_btn.setFixedHeight(68)
        home_btn.setToolTip('Return home screen.')
        home_btn.clicked.connect(self.show_home)
        self.iconsub_layout.addWidget(home_btn)

        self.buttonsSub_Frame = QtWidgets.QFrame(self.main_frame)
        self.buttonsSub_Frame.setFixedWidth(self.width)
        self.buttonsSub_Frame.setFixedHeight(100)
        self.main_layout.addWidget(self.buttonsSub_Frame)
        self.buttonsSub_Layout = QtWidgets.QHBoxLayout(self.buttonsSub_Frame)
        self.buttonsSub_Layout.setAlignment(Qt.AlignCenter|Qt.AlignTop)

        QtCore.QMetaObject.connectSlotsByName(main)

        # upload content button
        contentBtn = QtWidgets.QPushButton("Upload content image", self)
        contentBtn.setObjectName("MainGuiButtons")
        contentBtn.setToolTip('Upload content image.')
        contentBtn.clicked.connect(self.setContentImage)
        self.buttonsSub_Layout.addWidget(contentBtn)

        # upload style
        StyleBtn = QtWidgets.QPushButton("Upload style image", self)
        StyleBtn.setObjectName("MainGuiButtons")
        StyleBtn.setToolTip('Upload style image.')
        StyleBtn.clicked.connect(self.setStyleImage)
        self.buttonsSub_Layout.addWidget(StyleBtn)

        #framer for the uploaded content and style images
        self.photosframe = QtWidgets.QFrame(self.main_frame)
        self.photosframe.setFixedWidth(self.width)
        self.main_layout.addWidget(self.photosframe)
        self.photosSub_Layout = QtWidgets.QHBoxLayout(self.photosframe)
        self.photosSub_Layout.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        #lable for  the content image
        self.contentLabel = QtWidgets.QLabel('', self)
        pixmap = QPixmap(":css/Icons/imageNeedUpload.png")
        pixmap = pixmap.scaled(256, 256)
        self.contentLabel.setPixmap(pixmap)
        self.photosSub_Layout.addWidget(self.contentLabel)
        self.contentLabel.setAlignment(Qt.AlignCenter)

        #lable for the style image
        self.styleLabel = QtWidgets.QLabel('', self)
        self.styleLabel.setPixmap(pixmap)
        self.photosSub_Layout.addWidget(self.styleLabel)
        self.styleLabel.setAlignment(Qt.AlignCenter)

        self.details_Frame = QtWidgets.QFrame(self.main_frame)
        self.details_Frame.setFixedWidth(self.width)
        self.details_Frame.setFixedHeight(60)
        self.main_layout.addWidget(self.details_Frame)
        self.details_Layout = QtWidgets.QHBoxLayout(self.details_Frame)
        self.details_Layout.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        iterText = QtWidgets.QLabel('Image quality:')
        self.details_Layout.addWidget(iterText)
        self.iterationbox = QtWidgets.QComboBox(self.main_frame)
        self.iterationbox.addItem("Low")
        self.iterationbox.addItem("Medium")
        self.iterationbox.addItem("High")
        self.details_Layout.addWidget(self.iterationbox)

        resText = QtWidgets.QLabel('    Image resolution:')
        self.details_Layout.addWidget(resText)
        self.resolutionbox = QtWidgets.QComboBox(self.main_frame)
        self.resolutionbox.addItem("Small- 256 px")
        self.resolutionbox.addItem("Medium- 512 px")
        self.resolutionbox.addItem("Large- 1024 px")
        self.details_Layout.addWidget(self.resolutionbox)

        modelText = QtWidgets.QLabel('  Choose model:')
        self.details_Layout.addWidget(modelText)
        self.modelBox = QtWidgets.QComboBox(self.main_frame)
        self.modelBox.addItem("Vgg16")
        self.modelBox.addItem("Vgg19")
        #self.modelBox.addItem("ResNet")
        self.details_Layout.addWidget(self.modelBox)

        self.generateBtnSub_Frame = QtWidgets.QFrame(self.main_frame)
        self.generateBtnSub_Frame.setFixedWidth(self.width)
        self.main_layout.addWidget(self.generateBtnSub_Frame)
        self.generateBtnSub_Layout = QtWidgets.QHBoxLayout(self.generateBtnSub_Frame)
        self.generateBtnSub_Layout.setAlignment(Qt.AlignCenter)

        self.generateBtn = QtWidgets.QPushButton("Generate", self)
        self.generateBtn.setToolTip('Generate image.')
        self.generateBtn.setObjectName("MainGuiButtons")
        self.generateBtn.clicked.connect(self.start_thread)
        self.generateBtnSub_Layout.addWidget(self.generateBtn)
        self.generateBtn.setEnabled(True)

        # show the window on full screen
        self.showMaximized()
Exemplo n.º 34
0
    def initUI3(self):
        global flag_content_image
        flag_content_image = 0
        global flag_style_image
        flag_style_image = 0
        global flag_finish_generate
        flag_finish_generate = 0

        file = QFile(':css/StyleSheet.css')
        file.open(QFile.ReadOnly)
        stream = QTextStream(file)
        text = stream.readAll()
        self.setStyleSheet(text)
        self.setWindowTitle(self.title)
        self.setWindowIcon(QIcon(":css/Icons/logo.png"))
        self.setGeometry(0, 0, self.width, self.height - 60)

        # Creating main container-frame, parent it to QWindow
        self.main_frame = QtWidgets.QFrame(self)
        self.main_frame.setObjectName("MainFrame")
        self.main_frame.setFixedWidth(self.width)
        self.main_frame.setFixedHeight(self.height)
        # the first sub window
        self.main_layout = QtWidgets.QVBoxLayout(self.main_frame)
        # home and help buttons
        # the Icons sub frame
        self.iconsub_frame = QtWidgets.QFrame(self.main_frame)
        self.iconsub_frame.setFixedHeight(80)
        self.main_layout.addWidget(self.iconsub_frame)
        self.iconsub_layout = QtWidgets.QHBoxLayout(self.iconsub_frame)
        self.iconsub_layout.setAlignment(Qt.AlignLeft)

        # help button
        help_btn = QtWidgets.QPushButton("", self)
        help_btn.setObjectName("TransparentButtons")
        help_btn.setStyleSheet("QPushButton {background: url(:css/Icons/help.png) no-repeat transparent;}")
        help_btn.setToolTip('Show help pdf.')
        help_btn.setFixedWidth(68)
        help_btn.setFixedHeight(68)
        help_btn.clicked.connect(main_window_gui.show_help_pdf)
        self.iconsub_layout.addWidget(help_btn)

        # home button
        home_btn = QtWidgets.QPushButton("", self)
        home_btn.setObjectName("TransparentButtons")
        home_btn.setStyleSheet("QPushButton {background: url(:css/Icons/home.png) no-repeat transparent;} ")
        home_btn.setFixedWidth(68)
        home_btn.setFixedHeight(68)
        home_btn.setToolTip('Return home screen.')
        home_btn.clicked.connect(self.show_home)
        self.iconsub_layout.addWidget(home_btn)

        self.buttonsSub_Frame = QtWidgets.QFrame(self.main_frame)
        self.buttonsSub_Frame.setFixedWidth(self.width)
        self.buttonsSub_Frame.setFixedHeight(100)
        self.main_layout.addWidget(self.buttonsSub_Frame)
        self.buttonsSub_Layout = QtWidgets.QHBoxLayout(self.buttonsSub_Frame)
        self.buttonsSub_Layout.setAlignment(Qt.AlignCenter|Qt.AlignTop)

        QtCore.QMetaObject.connectSlotsByName(main)

        # upload content button
        contentBtn = QtWidgets.QPushButton("Upload content image", self)
        contentBtn.setObjectName("MainGuiButtons")
        contentBtn.setToolTip('Upload content image.')
        contentBtn.clicked.connect(TransferImageGui.setContentImage)
        self.buttonsSub_Layout.addWidget(contentBtn)


        #framer for the uploaded content and style images
        self.photosframe = QtWidgets.QFrame(self.main_frame)
        self.photosframe.setFixedWidth(self.width)
        self.main_layout.addWidget(self.photosframe)
        self.photosSub_Layout = QtWidgets.QHBoxLayout(self.photosframe)
        self.photosSub_Layout.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        #lable for  the content image
        self.contentLabel = QtWidgets.QLabel('', self)
        pixmap = QPixmap(":css/Icons/imageNeedUpload.png")
        pixmap = pixmap.scaled(256, 256)
        self.contentLabel.setPixmap(pixmap)
        self.photosSub_Layout.addWidget(self.contentLabel)
        self.contentLabel.setAlignment(Qt.AlignCenter)

        self.buttonsStyle_Frame = QtWidgets.QFrame(self.main_frame)
        self.buttonsStyle_Frame.setFixedWidth(self.width)
        self.buttonsStyle_Frame.setFixedHeight(100)
        self.main_layout.addWidget(self.buttonsStyle_Frame)
        self.buttonsStyle_Layout = QtWidgets.QHBoxLayout(self.buttonsStyle_Frame)
        self.buttonsStyle_Layout.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        # upload style
        StyleBtn = QtWidgets.QPushButton("Upload style image", self)
        StyleBtn.setObjectName("MainGuiButtons")
        StyleBtn.setToolTip('Upload style image.')
        #StyleBtn.clicked.connect(self.setStyleImage)
        self.buttonsStyle_Layout.addWidget(StyleBtn)

        self.photosStyleframe = QtWidgets.QFrame(self.main_frame)
        self.photosStyleframe.setFixedWidth(self.width)
        self.main_layout.addWidget(self.photosStyleframe)
        self.photos_Layout = QtWidgets.QHBoxLayout(self.photosStyleframe)
        self.photos_Layout.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        self.number = 1
        self.button = QPushButton()
        self.button.setFixedSize(256,256)
        self.button.setIcon(QIcon(QPixmap("images/style/road.jpg")))
        self.button.setIconSize(QtCore.QSize(500, 256))
        self.button.clicked.connect(self.styleChoosed())
        self.photos_Layout.addWidget(self.button)

        self.number = 2
        self.button = QPushButton()
        self.button.setFixedSize(256,256)
        self.button.setIcon(QIcon(QPixmap("images/style/candy.jpg")))
        self.button.setIconSize(QtCore.QSize(500, 256))
        self.button.clicked.connect(self.styleChoosed())
        self.photos_Layout.addWidget(self.button)

        self.number = 3
        self.button = QPushButton()
        self.button.setFixedSize(256,256)
        self.button.setIcon(QIcon(QPixmap("images/style/starry-night.jpg")))
        self.button.setIconSize(QtCore.QSize(450, 300))
        self.button.clicked.connect(self.styleChoosed())
        self.photos_Layout.addWidget(self.button)
Exemplo n.º 35
0
def loadStylesheet(filename):
    file = QFile(filename)
    file.open(QFile.ReadOnly | QFile.Text)
    stylesheet = file.readAll()
    QApplication.instance().setStyleSheet(str(stylesheet, encoding='utf-8'))
Exemplo n.º 36
0
            # frame
            cv2.putText(frame, label, (startX, startY - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
            cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

        # show the output frame
        cv2.imshow("Frame", frame)
        key = cv2.waitKey(1) & 0xFF

        # if the `q` key was pressed, break from the loop
        if key == ord("q"):
            break

    # do a bit of cleanup
    cv2.destroyAllWindows()
    vs.stop()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    file = QFile(":/dark.qss")
    file.open(QFile.ReadOnly | QFile.Text)
    stream = QTextStream(file)
    app.setStyleSheet(stream.readAll())
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
Exemplo n.º 37
0
    def initUI(self):
        file = QFile(':css/StyleSheet.css')
        file.open(QFile.ReadOnly)
        stream = QTextStream(file)
        text = stream.readAll()
        self.setStyleSheet(text)
        self.setObjectName("Windowimg")
        self.setWindowTitle(self.title)
        self.setWindowIcon(QIcon(':Pictures/logo.png'))
        self.setGeometry(0, 0, self.width, self.height-60)
        #Creating main container-frame, parent it to QWindow
        self.main_frame = QtWidgets.QFrame(self)
        self.main_frame.setObjectName("MainFrame")
        self.main_frame.setFixedSize(self.width, self.height)


        #the first sub window
        main_layout = QtWidgets.QVBoxLayout(self.main_frame)
        self.firstsub_Frame = QtWidgets.QFrame(self.main_frame)

        main_layout.addWidget(self.firstsub_Frame)
        self.firstsub_Layout = QtWidgets.QFormLayout(self.firstsub_Frame)
        self.firstsub_Frame.setFixedHeight(self.height/5.2)

        # Return to main window button
        returnBtn = QtWidgets.QPushButton("")
        returnBtn.setStyleSheet("QPushButton {background: url(:Pictures/backimg.png) no-repeat transparent;} ")
        returnBtn.setFixedWidth(110)
        returnBtn.setFixedHeight(110)
        returnBtn.clicked.connect(self.closeThisWindow)

        # help button
        helpBtn = QtWidgets.QPushButton("")
        helpBtn.setStyleSheet("QPushButton {background: url(:Pictures/help.png) no-repeat transparent;} ")
        helpBtn.setFixedWidth(110)
        helpBtn.setFixedHeight(110)
        helpBtn.clicked.connect(self.showHelp)
        buttonsform = QtWidgets.QFormLayout(self)

        buttonsform.addRow(returnBtn, helpBtn)
        #Setting up the form fields
        #form title init
        formTitleLbl = QtWidgets.QLabel('Lie Detector')
        formTitleLbl.setAlignment(Qt.AlignCenter)
        formTitleLbl.setContentsMargins(0,0,50,50)
        formTitleLbl.setObjectName("LableHeader")
        self.firstsub_Layout.addRow(formTitleLbl)

        #init the browse file fields - lable , textfield, file browse button , start/stop record buttons
        fileBrowseHBoxLayout = QtWidgets.QGridLayout()
        self.fileBrowserTxt=QtWidgets.QTextEdit("", self)
        self.fileBrowserTxt.setReadOnly(True)
        self.fileBrowserLbl=QtWidgets.QLabel('Pick Wav File', self)
        self.fileBrowserTxt.setFixedWidth(500)
        self.fileBrowserTxt.setFixedHeight(25)
        self.fileBrowserLbl.setFixedWidth(150)
        self.fileBrowserLbl.setFixedHeight(25)
        self.fileBrowserBtn = QtWidgets.QPushButton("", self)
        self.fileBrowserBtn.setMaximumHeight(100)
        self.fileBrowserBtn.setMaximumWidth(100)
        self.fileBrowserBtn.setFixedHeight(27)
        self.fileBrowserBtn.setFixedWidth(27)
        self.fileBrowserBtn.setStyleSheet("QPushButton {background: url(:Pictures/filebrowse.png) no-repeat transparent;} ")
        self.fileBrowserBtn.clicked.connect(lambda: self.openFile(self.firstsub_Layout))
        fileBrowseHBoxLayout.addWidget(self.fileBrowserLbl,1,0)
        fileBrowseHBoxLayout.addWidget(self.fileBrowserTxt,1,1)
        fileBrowseHBoxLayout.addWidget(self.fileBrowserBtn,1,2)
        fileBrowseHBoxLayout.setAlignment(Qt.AlignCenter)
        self.firstsub_Layout.addRow(fileBrowseHBoxLayout)
        recordHBoxLayout = QtWidgets.QGridLayout()
        self.startRecordBtn = QtWidgets.QPushButton("", self)
        self.startRecordBtn.setFixedHeight(25)
        self.startRecordBtn.setFixedWidth(25)
        self.startRecordBtn.setStyleSheet("QPushButton {background: url(:Pictures/microphone1.png) no-repeat transparent;} ")
        self.recordingLbl = QtWidgets.QLabel('Recording', self)
        self.recordingLbl.setContentsMargins(self.height/2,self.width/2,50,50)
        self.recordingLbl.setVisible(False)
        self.recordingLbl.setFixedWidth(100)
        self.recordingLbl.setFixedHeight(40)
        self.loadingLbl = QtWidgets.QLabel('', self)
        self.loadingLbl.setFixedWidth(200)
        self.loadingLbl.setFixedHeight(25)
        self.stopRecordBtn = QtWidgets.QPushButton("", self)
        self.stopRecordBtn.setStyleSheet("QPushButton {background: url(:Pictures/microphone2.png) no-repeat transparent;} ")
        self.stopRecordBtn.setVisible(False)
        self.stopRecordBtn.setFixedWidth(25)
        self.stopRecordBtn.setFixedHeight(25)
        fileBrowseHBoxLayout.addWidget(self.startRecordBtn, 1, 4)
        fileBrowseHBoxLayout.addWidget(self.stopRecordBtn, 1, 4)
        recordHBoxLayout.setAlignment(Qt.AlignCenter)
        self.firstsub_Layout.addRow(recordHBoxLayout)

        # The second sub window - loading gif window
        self.secondsub_Frame = QtWidgets.QFrame(self.main_frame)
        main_layout.addWidget(self.secondsub_Frame)
        self.secondsub_Layout = QtWidgets.QFormLayout(self.secondsub_Frame)
        self.secondsub_Frame.setFixedWidth(self.width)
        self.secondsub_Frame.setFixedHeight(self.height/8)
        self.secondsub_Layout.addRow(self.recordingLbl,self.loadingLbl)
        self.secondsub_Frame.setContentsMargins(self.width/2-self.recordingLbl.width(),0,0,0)
        # Settings Layout
        self.settings_Frame = QtWidgets.QFrame(self.main_frame)
        main_layout.addWidget(self.settings_Frame)
        self.settings_Layout = QtWidgets.QFormLayout(self.settings_Frame)
        self.settings_Frame.setFixedWidth(self.width)
        self.settings_Frame.setFixedHeight(self.height/8)
        self.settings_Frame.setContentsMargins(self.width, 0, 0, 0)
        self.settings_Layout.setFormAlignment(Qt.AlignCenter)
        self.settings_Frame.setVisible(False)
        # the third sub window
        self.thirdsub_Frame = QtWidgets.QFrame(self.main_frame)
        main_layout.addWidget(self.thirdsub_Frame)
        self.thirdsub_Layout = QtWidgets.QGridLayout(self.thirdsub_Frame)
        self.thirdsub_Frame.setFixedWidth(self.width-25)
        self.thirdsub_Frame.setFixedHeight(self.height/2.2)
        logo = QtWidgets.QLabel('', self)
        pixmap = QPixmap(':Pictures/logo.png')
        logo.setPixmap(pixmap)
        self.thirdsub_Layout.addWidget(logo)

        logo.setAlignment(Qt.AlignCenter|Qt.AlignTop)

        # assign functions to buttons
        self.startRecordBtn.clicked.connect(lambda: self.startRecord())
        self.stopRecordBtn.clicked.connect(lambda: self.stopRecord())

        # building the Coefficients number comboBox
        self.buildCoefComboBox()

        # building the Model comboBox
        self.buildModelComboBox()

        #Predict button
        self.processGraphsBtn = QtWidgets.QPushButton("Predict", self)
        self.processGraphsBtn.setObjectName("Buttons")
        self.processGraphsBtn.setFixedWidth(131)
        self.processGraphsBtn.setFixedHeight(30)
        self.processGraphsBtn.clicked.connect(lambda: self.dataProcessingmfcc())
        self.settings_Layout.addRow(self.processGraphsBtn)

        # Predict button
        self.mfccGraphsBtn = QtWidgets.QPushButton("MFCC", self)
        self.mfccGraphsBtn.setObjectName("Buttons")
        self.mfccGraphsBtn.setFixedWidth(131)
        self.mfccGraphsBtn.setFixedHeight(30)
        self.mfccGraphsBtn.clicked.connect(lambda: self.showMfcc())
        self.settings_Layout.addRow(self.mfccGraphsBtn,self.processGraphsBtn)

        #show the window
        self.show()
Exemplo n.º 38
0
                        parents.append(
                            parents[-1].child(parents[-1].childCount() - 1))
                        indentations.append(position)

                else:
                    while position < indentations[-1] and len(parents) > 0:
                        parents.pop()
                        indentations.pop()

                # Append a new item to the current parent's list of children.
                parents[-1].appendChild(TreeItem(columnData, parents[-1]))

            number += 1


if __name__ == '__main__':
    import sys

    app = QGuiApplication(sys.argv)
    view = QQuickView()

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

    root_context = view.rootContext().setContextProperty('model', model)
    view.setSource(QUrl.fromLocalFile('simpletreemodel.qml'))
    view.show()
    sys.exit(app.exec_())
Exemplo n.º 39
0
def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	readStdIn = False
	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Exemplo n.º 40
0
    def accept(self):
        className = self.field('className')
        baseClass = self.field('baseClass')
        macroName = self.field('macroName')
        baseInclude = self.field('baseInclude')

        outputDir = self.field('outputDir')
        header = self.field('header')
        implementation = self.field('implementation')

        block = ''

        if self.field('comment'):
            block += '/*\n'
            block += '    ' + header + '\n'
            block += '*/\n'
            block += '\n'

        if self.field('protect'):
            block += '#ifndef ' + macroName + '\n'
            block += '#define ' + macroName + '\n'
            block += '\n'

        if self.field('includeBase'):
            block += '#include ' + baseInclude + '\n'
            block += '\n'

        block += 'class ' + className
        if baseClass:
            block += ' : public ' + baseClass

        block += '\n'
        block += '{\n'

        if self.field('qobjectMacro'):
            block += '    Q_OBJECT\n'
            block += '\n'

        block += 'public:\n'

        if self.field('qobjectCtor'):
            block += '    ' + className + '(QObject *parent = 0);\n'
        elif self.field('qwidgetCtor'):
            block += '    ' + className + '(QWidget *parent = 0);\n'
        elif self.field('defaultCtor'):
            block += '    ' + className + '();\n'

            if self.field('copyCtor'):
                block += '    ' + className + '(const ' + className + ' &other);\n'
                block += '\n'
                block += '    ' + className + ' &operator=' + '(const ' + className + ' &other);\n'

        block += '};\n'

        if self.field('protect'):
            block += '\n'
            block += '#endif\n'

        headerFile = QFile(outputDir + '/' + header)

        if not headerFile.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(None, "Class Wizard",
                    "Cannot write file %s:\n%s" % (headerFile.fileName(), headerFile.errorString()))
            return

        headerFile.write(block)

        block = ''

        if self.field('comment'):
            block += '/*\n'
            block += '    ' + implementation + '\n'
            block += '*/\n'
            block += '\n'

        block += '#include "' + header + '"\n'
        block += '\n'

        if self.field('qobjectCtor'):
            block += className + '::' + className + '(QObject *parent)\n'
            block += '    : ' + baseClass + '(parent)\n'
            block += '{\n'
            block += '}\n'
        elif self.field('qwidgetCtor'):
            block += className + '::' + className + '(QWidget *parent)\n'
            block += '    : ' + baseClass + '(parent)\n'
            block += '{\n'
            block += '}\n'
        elif self.field('defaultCtor'):
            block += className + '::' + className + '()\n'
            block += '{\n'
            block += '    // missing code\n'
            block += '}\n'

            if self.field('copyCtor'):
                block += '\n'
                block += className + '::' + className + '(const ' + className + ' &other)\n'
                block += '{\n'
                block += '    *this = other;\n'
                block += '}\n'
                block += '\n'
                block += className + ' &' + className + '::operator=(const ' + className + ' &other)\n'
                block += '{\n'

                if baseClass:
                    block += '    ' + baseClass + '::operator=(other);\n'

                block += '    // missing code\n'
                block += '    return *this;\n'
                block += '}\n'

        implementationFile = QFile(outputDir + '/' + implementation)

        if not implementationFile.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(None, "Class Wizard",
                    "Cannot write file %s:\n%s" % (implementationFile.fileName(), implementationFile.errorString()))
            return

        implementationFile.write(block)

        super(ClassWizard, self).accept()
Exemplo n.º 41
0
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import (QFile, QTextStream)
from PyQt5.QtWidgets import QApplication

import breeze_resources
from ui import (Ui, SecondUi)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    # set stylesheet
    file = QFile(":/light.qss")
    file.open(QFile.ReadOnly | QFile.Text)
    stream = QTextStream(file)
    app.setStyleSheet(stream.readAll())
    # Set up UI windows
    window = Ui()
    secWindow = SecondUi()
    window.showUpdate.connect(secWindow.showResult)
    sys.exit(app.exec_())
Exemplo n.º 42
0
class HttpWindow(QDialog):
    def __init__(self, parent=None):
        super(HttpWindow, self).__init__(parent)

        self.url = QUrl()
        self.qnam = QNetworkAccessManager()
        self.reply = None
        self.outFile = None
        self.httpGetId = 0
        self.httpRequestAborted = False

        self.urlLineEdit = QLineEdit("https://www.qt.io")

        urlLabel = QLabel("&URL:")
        urlLabel.setBuddy(self.urlLineEdit)
        self.statusLabel = QLabel(
            "Please enter the URL of a file you want to download."
        )
        self.statusLabel.setWordWrap(True)

        self.downloadButton = QPushButton("Download")
        self.downloadButton.setDefault(True)
        self.quitButton = QPushButton("Quit")
        self.quitButton.setAutoDefault(False)

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.downloadButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        self.progressDialog = QProgressDialog(self)

        self.urlLineEdit.textChanged.connect(self.enableDownloadButton)
        self.qnam.authenticationRequired.connect(self.slotAuthenticationRequired)
        self.qnam.sslErrors.connect(self.sslErrors)
        self.progressDialog.canceled.connect(self.cancelDownload)
        self.downloadButton.clicked.connect(self.downloadFile)
        self.quitButton.clicked.connect(self.close)

        topLayout = QHBoxLayout()
        topLayout.addWidget(urlLabel)
        topLayout.addWidget(self.urlLineEdit)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(topLayout)
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("HTTP")
        self.urlLineEdit.setFocus()

    def startRequest(self, url):
        self.reply = self.qnam.get(QNetworkRequest(url))
        self.reply.finished.connect(self.httpFinished)
        self.reply.readyRead.connect(self.httpReadyRead)
        self.reply.downloadProgress.connect(self.updateDataReadProgress)

    def downloadFile(self):
        self.url = QUrl(self.urlLineEdit.text())
        fileInfo = QFileInfo(self.url.path())
        fileName = fileInfo.fileName()

        if not fileName:
            fileName = "index.html"

        if QFile.exists(fileName):
            ret = QMessageBox.question(
                self,
                "HTTP",
                "There already exists a file called %s in the current "
                "directory. Overwrite?" % fileName,
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No,
            )

            if ret == QMessageBox.No:
                return

            QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(
                self,
                "HTTP",
                "Unable to save the file %s: %s."
                % (fileName, self.outFile.errorString()),
            )
            self.outFile = None
            return

        self.progressDialog.setWindowTitle("HTTP")
        self.progressDialog.setLabelText("Downloading %s." % fileName)
        self.downloadButton.setEnabled(False)

        self.httpRequestAborted = False
        self.startRequest(self.url)

    def cancelDownload(self):
        self.statusLabel.setText("Download canceled.")
        self.httpRequestAborted = True
        if self.reply is not None:
            self.reply.abort()
        self.downloadButton.setEnabled(True)

    def httpFinished(self):
        if self.httpRequestAborted:
            if self.outFile is not None:
                self.outFile.close()
                self.outFile.remove()
                self.outFile = None

            self.reply.deleteLater()
            self.reply = None
            self.progressDialog.hide()
            return

        self.progressDialog.hide()
        self.outFile.flush()
        self.outFile.close()

        redirectionTarget = self.reply.attribute(
            QNetworkRequest.RedirectionTargetAttribute
        )

        if self.reply.error():
            self.outFile.remove()
            QMessageBox.information(
                self, "HTTP", "Download failed: %s." % self.reply.errorString()
            )
            self.downloadButton.setEnabled(True)
        elif redirectionTarget is not None:
            newUrl = self.url.resolved(redirectionTarget)

            ret = QMessageBox.question(
                self,
                "HTTP",
                "Redirect to %s?" % newUrl.toString(),
                QMessageBox.Yes | QMessageBox.No,
            )

            if ret == QMessageBox.Yes:
                self.url = newUrl
                self.reply.deleteLater()
                self.reply = None
                self.outFile.open(QIODevice.WriteOnly)
                self.outFile.resize(0)
                self.startRequest(self.url)
                return
        else:
            fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName()
            self.statusLabel.setText(
                "Downloaded %s to %s." % (fileName, QDir.currentPath())
            )

            self.downloadButton.setEnabled(True)

        self.reply.deleteLater()
        self.reply = None
        self.outFile = None

    def httpReadyRead(self):
        if self.outFile is not None:
            self.outFile.write(self.reply.readAll())

    def updateDataReadProgress(self, bytesRead, totalBytes):
        if self.httpRequestAborted:
            return

        self.progressDialog.setMaximum(totalBytes)
        self.progressDialog.setValue(bytesRead)

    def enableDownloadButton(self):
        self.downloadButton.setEnabled(self.urlLineEdit.text() != "")

    def slotAuthenticationRequired(self, authenticator):
        import os
        from PyQt5 import uic

        ui = os.path.join(os.path.dirname(__file__), "authenticationdialog.ui")
        dlg = uic.loadUi(ui)
        dlg.adjustSize()
        dlg.siteDescription.setText(
            "%s at %s" % (authenticator.realm(), self.url.host())
        )

        dlg.userEdit.setText(self.url.userName())
        dlg.passwordEdit.setText(self.url.password())

        if dlg.exec_() == QDialog.Accepted:
            authenticator.setUser(dlg.userEdit.text())
            authenticator.setPassword(dlg.passwordEdit.text())

    def sslErrors(self, reply, errors):
        errorString = ", ".join([str(error.errorString()) for error in errors])

        ret = QMessageBox.warning(
            self,
            "HTTP Example",
            "One or more SSL errors has occurred: %s" % errorString,
            QMessageBox.Ignore | QMessageBox.Abort,
        )

        if ret == QMessageBox.Ignore:
            self.reply.ignoreSslErrors()
def main():
    # Initialise.

    defaultContext = "@default"
    fetchedTor = MetaTranslator()
    codecForTr = ''
    codecForSource = ''
    tsFileNames = []
    uiFileNames = []

    verbose = False
    noObsolete = False
    metSomething = False
    numFiles = 0
    standardSyntax = True
    metTsFlag = False
    tr_func = None
    translate_func = None

    # Parse the command line.

    for arg in sys.argv[1:]:
        if arg == "-ts":
            standardSyntax = False

    argc = len(sys.argv)
    i = 1

    while i < argc:
        arg = sys.argv[i]
        i += 1

        if arg == "-help":
            printUsage()
            sys.exit(0)

        if arg == "-version":
            sys.stderr.write("pylupdate5 v%s\n" % PYQT_VERSION_STR)
            sys.exit(0)

        if arg == "-noobsolete":
            noObsolete = True
            continue

        if arg == "-verbose":
            verbose = True
            continue

        if arg == "-ts":
            metTsFlag = True
            continue

        if arg == "-tr-function":
            if i >= argc:
                sys.stderr.write(
                        "pylupdate5 error: missing -tr-function name\n")
                sys.exit(2)

            tr_func = sys.argv[i]
            i += 1
            continue

        if arg == "-translate-function":
            if i >= argc:
                sys.stderr.write(
                        "pylupdate5 error: missing -translate-function name\n")
                sys.exit(2)

            translate_func = sys.argv[i]
            i += 1
            continue

        numFiles += 1

        fullText = ""

        if not metTsFlag:
            f = QFile(arg)

            if not f.open(QIODevice.ReadOnly):
                sys.stderr.write(
                        "pylupdate5 error: Cannot open file '%s'\n" % arg)
                sys.exit(1)

            t = QTextStream(f)
            fullText = t.readAll()
            f.close()

        if standardSyntax:
            oldDir = QDir.currentPath()
            QDir.setCurrent(QFileInfo(arg).path())

            fetchedTor = MetaTranslator()
            codecForTr = ''
            codecForSource = ''
            tsFileNames = []
            uiFileNames = []

            for key, value in proFileTagMap(fullText).items():
                for t in value.split(' '):
                    if key == "SOURCES":
                        fetchtr_py(QDir.current().absoluteFilePath(t),
                                fetchedTor, defaultContext, True,
                                codecForSource, tr_func, translate_func)
                        metSomething = True

                    elif key == "TRANSLATIONS":
                        tsFileNames.append(QDir.current().absoluteFilePath(t))
                        metSomething = True

                    elif key in ("CODEC", "DEFAULTCODEC", "CODECFORTR"):
                        codecForTr = t
                        fetchedTor.setCodec(codecForTr)

                    elif key == "CODECFORSRC":
                        codecForSource = t

                    elif key == "FORMS":
                        fetchtr_ui(QDir.current().absoluteFilePath(t),
                                fetchedTor, defaultContext, True)

            updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete,
                    verbose)

            if not metSomething:
                sys.stderr.write(
                        "pylupdate5 warning: File '%s' does not look like a "
                        "project file\n" % arg)
            elif len(tsFileNames) == 0:
                sys.stderr.write(
                        "pylupdate5 warning: Met no 'TRANSLATIONS' entry in "
                        "project file '%s'\n" % arg)

            QDir.setCurrent(oldDir)
        else:
            if metTsFlag:
                if arg.lower().endswith(".ts"):
                    fi = QFileInfo(arg)

                    if not fi.exists() or fi.isWritable():
                        tsFileNames.append(arg)
                    else:
                        sys.stderr.write(
                                "pylupdate5 warning: For some reason, I "
                                "cannot save '%s'\n" % arg)
                else:
                    sys.stderr.write(
                            "pylupdate5 error: File '%s' lacks .ts extension\n" % arg)
            else:
                fi = QFileInfo(arg)

                if fi.suffix() in ("py", "pyw"):
                    fetchtr_py(fi.absoluteFilePath(), fetchedTor,
                            defaultContext, True, codecForSource, tr_func,
                            translate_func)
                else:
                    fetchtr_ui(fi.absoluteFilePath(), fetchedTor,
                            defaultContext, True)

    if not standardSyntax:
        updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose)

    if numFiles == 0:
        printUsage()
        sys.exit(1)
Exemplo n.º 44
0
def main():
	multiprocessing.set_start_method('spawn')

	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	try:
		# See https://github.com/retext-project/retext/issues/399
		# and https://launchpad.net/bugs/941826
		ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
	except OSError:
		pass

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)

	parser = QCommandLineParser()
	parser.addHelpOption()
	parser.addVersionOption()
	previewOption = QCommandLineOption('preview',
		QApplication.translate('main', 'Open the files in preview mode'))
	newWindowOption = QCommandLineOption('new-window',
		QApplication.translate('main', 'Create a new window even if there is an existing one'))
	parser.addOption(previewOption)
	parser.addOption(newWindowOption)
	parser.addPositionalArgument('files',
		QApplication.translate('main', 'List of files to open'),
		'[files...]')

	parser.process(app)
	filesToOpen = parser.positionalArguments()

	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()

	openInExistingWindow = (globalSettings.openFilesInExistingWindow
		and not parser.isSet(newWindowOption))
	connection = QDBusConnection.sessionBus()
	if connection.isConnected() and openInExistingWindow:
		connection.registerObject('/', window, QDBusConnection.ExportAllSlots)
		serviceName = 'me.mitya57.ReText'
		if not connection.registerService(serviceName) and filesToOpen:
			print('Opening the file(s) in the existing window of ReText.')
			iface = QDBusInterface(serviceName, '/', '', connection)
			for fileName in filesToOpen:
				iface.call('openFileWrapper', fileName)
			qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection)
			qWidgetIface.call('raise')
			sys.exit(0)

	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, filesToOpen))
	readStdIn = False

	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if parser.isSet(previewOption):
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Exemplo n.º 45
0
 def __loadRules(self):
     """
     Private method to load the rules of the subscription.
     """
     fileName = self.rulesFileName()
     f = QFile(fileName)
     if f.exists():
         if not f.open(QIODevice.ReadOnly):
             E5MessageBox.warning(
                 None,
                 self.tr("Load subscription rules"),
                 self.tr(
                     """Unable to open AdBlock file '{0}' for reading.""")
                 .format(fileName))
         else:
             textStream = QTextStream(f)
             header = textStream.readLine(1024)
             if not header.startswith("[Adblock"):
                 E5MessageBox.warning(
                     None,
                     self.tr("Load subscription rules"),
                     self.tr("""AdBlock file '{0}' does not start"""
                             """ with [Adblock.""")
                     .format(fileName))
                 f.close()
                 f.remove()
                 self.__lastUpdate = QDateTime()
             else:
                 from .AdBlockRule import AdBlockRule
                 
                 self.__updatePeriod = 0
                 self.__remoteModified = QDateTime()
                 self.__rules = []
                 self.__rules.append(AdBlockRule(header, self))
                 while not textStream.atEnd():
                     line = textStream.readLine()
                     self.__rules.append(AdBlockRule(line, self))
                     expires = self.__expiresRe.search(line)
                     if expires:
                         period, kind = expires.groups()
                         if kind:
                             # hours
                             self.__updatePeriod = int(period)
                         else:
                             # days
                             self.__updatePeriod = int(period) * 24
                     remoteModified = self.__remoteModifiedRe.search(line)
                     if remoteModified:
                         day, month, year, time, hour, minute = (
                             remoteModified.groups()
                         )
                         self.__remoteModified.setDate(
                             QDate(int(year),
                                   self.__monthNameToNumber[month],
                                   int(day))
                         )
                         if time:
                             self.__remoteModified.setTime(
                                 QTime(int(hour), int(minute)))
                         else:
                             # no time given, set it to 23:59
                             self.__remoteModified.setTime(QTime(23, 59))
                 self.changed.emit()
     elif not fileName.endswith("_custom"):
         self.__lastUpdate = QDateTime()
     
     self.checkForUpdate()
Exemplo n.º 46
0
 def __rulesDownloaded(self, reply):
     """
     Private slot to deal with the downloaded rules.
     
     @param reply reference to the network reply
     @type QNetworkReply
     """
     response = reply.readAll()
     reply.close()
     self.__downloading = None
     
     if reply.error() != QNetworkReply.NoError:
         if not self.__defaultSubscription:
             # don't show error if we try to load the default
             E5MessageBox.warning(
                 None,
                 self.tr("Downloading subscription rules"),
                 self.tr(
                     """<p>Subscription rules could not be"""
                     """ downloaded.</p><p>Error: {0}</p>""")
                 .format(reply.errorString()))
         else:
             # reset after first download attempt
             self.__defaultSubscription = False
         return
     
     if response.isEmpty():
         E5MessageBox.warning(
             None,
             self.tr("Downloading subscription rules"),
             self.tr("""Got empty subscription rules."""))
         return
     
     fileName = self.rulesFileName()
     QFile.remove(fileName)
     f = QFile(fileName)
     if not f.open(QIODevice.ReadWrite):
         E5MessageBox.warning(
             None,
             self.tr("Downloading subscription rules"),
             self.tr(
                 """Unable to open AdBlock file '{0}' for writing.""")
             .file(fileName))
         return
     
     from WebBrowser.WebBrowserWindow import WebBrowserWindow
     if (
         WebBrowserWindow.adBlockManager().useLimitedEasyList() and
         self.url().toString().startswith(
             WebBrowserWindow.adBlockManager().getDefaultSubscriptionUrl())
     ):
         limited = True
         # ignore Third-party advertisers rules for performance
         # whitelist rules at the end will be used
         index = response.indexOf(
             "!---------------------------"
             "Third-party advertisers"
             "---------------------------!")
         part1 = response.left(index)
         index = response.indexOf(
             "!-----------------------"
             "Whitelists to fix broken sites"
             "------------------------!")
         part2 = response.mid(index)
         f.write(part1)
         f.write(part2)
     else:
         limited = False
         f.write(response)
     f.close()
     self.__lastUpdate = QDateTime.currentDateTime()
     if limited or self.__validateCheckSum(fileName):
         self.__loadRules()
     else:
         QFile.remove(fileName)
     self.__downloading = None
     reply.deleteLater()
 def do_snap(self,gfile):
     img = Snapshot.snapshot(width = 200, height = 200).scaled(200,200,Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     outdata = ""
     outdata = outdata + self.overseek()
     outdata = outdata + "; bigtree thumbnail end\r\n\r\n"
     fh = QFile(gfile)
     fh.open(QIODevice.ReadOnly)
     stream = QTextStream(fh)
     stream.setCodec(CODEC)
     # lino = 0
     fg = stream.readAll() + "\r\n"
     fh.close()
     bigtree3dfile = os.path.splitext(gfile)[0]+"[Bigtree].gcode"
     fh = QFile(bigtree3dfile)
     fh.open(QIODevice.WriteOnly)
     stream = QTextStream(fh)
     stream.setCodec(CODEC)
     stream << outdata
     stream << fg
     fh.close()
     os.remove(gfile)
Exemplo n.º 48
0
 def createIcon(self):
     pathExe = sys.executable
     pathIcon = QStandardPaths.writableLocation(
         QStandardPaths.DesktopLocation) + "/" + "Memo.lnk"
     if not os.path.exists(pathIcon):
         QFile.link(pathExe, pathIcon)
Exemplo n.º 49
0
 def _load_objects(self):
     load_objects_js = QFile('src/js/load_objects.js')
     if load_objects_js.open(QIODevice.ReadOnly):
         content = load_objects_js.readAll()
         load_objects_js.close()
         self.page().runJavaScript(content.data().decode())
Exemplo n.º 50
0
    def _init_from_parameters(
        self,
        uis,
        serial_number,
        name,
        bus=None,
        tabs=None,
        rx_interval=0,
        edit_actions=None,
        nv_configuration=None,
        can_configuration=None,
        hierarchy=None,
    ):
        if tabs is None:
            tabs = Tabs.defaults()

        if can_configuration is None:
            can_configuration = "original"

        can_configuration = can_configurations[can_configuration]

        self.nvs = None
        self.widget_nvs = None

        self.bus_online = False
        self.bus_tx = False

        self.bus = BusProxy(bus=bus)

        self.nv_looping_set = None
        self.nv_tab_looping_set = None

        self.rx_interval = rx_interval
        self.serial_number = serial_number
        self.name = "{name} :{id}".format(name=name, id=self.node_id)
        self.nickname = ""
        self.auto_read_nv_widget_min_max = True

        self.nv_views = None

        device_ui = "device.ui"
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(device_ui).isAbsolute():
            ui_file = os.path.join(
                QFileInfo.absolutePath(QFileInfo(__file__)), device_ui
            )
        else:
            ui_file = device_ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio)
        self.loaded_uis = {}

        self.traverse(uis)

        # TODO: yuck, actually tidy the code
        self.dash_uis = uis

        notifiees = []

        if Elements.dash in self.elements:
            self.uis = self.dash_uis

            matrix = load_matrix(self.can_path)
            # TODO: this is icky
            if Elements.tx not in self.elements:
                self.neo_frames = epyqlib.canneo.Neo(
                    matrix=matrix, bus=self.bus, rx_interval=self.rx_interval
                )

                notifiees.append(self.neo_frames)

        if Elements.rx in self.elements:
            # TODO: the repetition here is not so pretty
            matrix_rx = load_matrix(self.can_path)
            neo_rx = epyqlib.canneo.Neo(
                matrix=matrix_rx,
                frame_class=epyqlib.txrx.MessageNode,
                signal_class=epyqlib.txrx.SignalNode,
                node_id_adjust=self.node_id_adjust,
                strip_summary=False,
            )

            rx = epyqlib.txrx.TxRx(tx=False, neo=neo_rx)
            notifiees.append(rx)
            rx_model = epyqlib.txrx.TxRxModel(rx)

            # TODO: put this all in the model...
            rx.changed.connect(rx_model.changed)
            rx.begin_insert_rows.connect(rx_model.begin_insert_rows)
            rx.end_insert_rows.connect(rx_model.end_insert_rows)

        if Elements.tx in self.elements:
            matrix_tx = load_matrix(self.can_path)
            message_node_tx_partial = functools.partial(
                epyqlib.txrx.MessageNode, tx=True
            )
            signal_node_tx_partial = functools.partial(epyqlib.txrx.SignalNode, tx=True)
            neo_tx = epyqlib.canneo.Neo(
                matrix=matrix_tx,
                frame_class=message_node_tx_partial,
                signal_class=signal_node_tx_partial,
                node_id_adjust=self.node_id_adjust,
            )
            notifiees.extend(f for f in neo_tx.frames if f.mux_name is None)

            self.neo_frames = neo_tx

            tx = epyqlib.txrx.TxRx(tx=True, neo=neo_tx, bus=self.bus)
            tx_model = epyqlib.txrx.TxRxModel(tx)
            tx.changed.connect(tx_model.changed)

        # TODO: something with sets instead?
        if Elements.rx in self.elements or Elements.tx in self.elements:
            txrx_views = self.ui.findChildren(epyqlib.txrxview.TxRxView)
            if len(txrx_views) > 0:
                # TODO: actually find them and actually support multiple
                pairs = (
                    (self.ui.rx, rx_model),
                    (self.ui.tx, tx_model),
                )
                column = epyqlib.txrx.Columns.indexes.name
                for view, model in pairs:
                    if model.root.tx:
                        proxy = epyqlib.utils.qt.PySortFilterProxyModel(
                            filter_column=column,
                        )
                        proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
                        proxy.setSourceModel(model)
                        view.setModel(proxy)
                        view.set_sorting_enabled(True)
                        view.sort_by_column(column=column, order=Qt.AscendingOrder)
                    else:
                        view.setModel(model)

        self.widget_nvs = None
        if Elements.nv in self.elements:
            matrix_nv = load_matrix(self.can_path)
            self.frames_nv = epyqlib.canneo.Neo(
                matrix=matrix_nv,
                frame_class=epyqlib.nv.Frame,
                signal_class=epyqlib.nv.Nv,
                node_id_adjust=self.node_id_adjust,
                strip_summary=False,
            )

            self.nv_looping_set = epyqlib.twisted.loopingset.Set()
            self.nv_tab_looping_set = epyqlib.twisted.loopingset.Set()

            access_level_path = self.raw_dict["access_level_path"]
            if access_level_path is not None:
                access_level_path = access_level_path.split(";")

            access_password_path = self.raw_dict["access_password_path"]
            if access_password_path is not None:
                access_password_path = access_password_path.split(";")

            def none_or_uuid(uuid_string):
                if uuid_string is None:
                    return None

                return uuid.UUID(uuid_string)

            parameter_uuids = self.raw_dict.get("parameter_uuids", {})
            serial_number_uuid = none_or_uuid(
                parameter_uuids.get("serial_number"),
            )

            # TODO: CAMPid 0794311304143707516085683164039671793972
            if self.raw_dict["nv_meta_enum"] == "Meta":
                self.metas = epyqlib.nv.meta_limits_first
            else:
                self.metas = (epyqlib.nv.MetaEnum.value,)

            self.nvs = epyqlib.nv.Nvs(
                neo=self.frames_nv,
                bus=self.bus,
                configuration=nv_configuration,
                hierarchy=hierarchy,
                metas=self.metas,
                access_level_path=access_level_path,
                access_password_path=access_password_path,
                serial_number_uuid=serial_number_uuid,
            )

            default_metas = [
                meta
                for meta in (
                    epyqlib.nv.MetaEnum.user_default,
                    epyqlib.nv.MetaEnum.factory_default,
                )
                if meta not in self.metas
            ]

            if len(default_metas) > 0 and "parameter_defaults" in self.raw_dict:
                parameter_defaults_path = os.path.join(
                    os.path.dirname(self.config_path),
                    self.raw_dict["parameter_defaults"],
                )
                with open(parameter_defaults_path) as f:
                    self.nvs.defaults_from_dict(
                        d=json.load(f, parse_float=decimal.Decimal),
                        default_metas=default_metas,
                    )

            for nv in self.nvs.all_nv():
                if isinstance(nv, epyqlib.nv.Nv):
                    if epyqlib.nv.MetaEnum.minimum not in self.metas:
                        if nv.min is not None:
                            nv.set_meta(
                                data=nv.min,
                                meta=epyqlib.nv.MetaEnum.minimum,
                            )

                    if epyqlib.nv.MetaEnum.maximum not in self.metas:
                        if nv.max is not None:
                            nv.set_meta(
                                data=nv.max,
                                meta=epyqlib.nv.MetaEnum.maximum,
                            )

            self.widget_frames_nv = epyqlib.canneo.Neo(
                matrix=matrix_nv,
                frame_class=epyqlib.nv.Frame,
                signal_class=epyqlib.nv.Nv,
                node_id_adjust=self.node_id_adjust,
            )
            self.widget_nvs = epyqlib.nv.Nvs(
                neo=self.widget_frames_nv,
                bus=self.bus,
                stop_cyclic=self.nv_looping_set.stop,
                start_cyclic=self.nv_looping_set.start,
                configuration=nv_configuration,
                serial_number_uuid=serial_number_uuid,
            )
            notifiees.append(self.widget_nvs)

            self.nv_views = self.ui.findChildren(epyqlib.nvview.NvView)
            if len(self.nv_views) > 0:
                nv_model = epyqlib.nv.NvModel(self.nvs)
                self.nvs.changed.connect(nv_model.changed)

                self.first_nv_view = self.nv_views[0]

                column = epyqlib.nv.Columns.indexes.name
                for view in self.nv_views:
                    view.set_device(self)
                    view.set_can_contents(
                        can_contents=self.can_contents,
                        suffix=pathlib.Path(self.can_path).suffix,
                    )
                    if self.nvs.access_level_node is not None:
                        view.set_access_level_signal_path(
                            path=self.nvs.access_level_node.signal_path(),
                        )

                    sort_proxy = epyqlib.utils.qt.PySortFilterProxyModel(
                        filter_column=column,
                    )
                    sort_proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
                    sort_proxy.setSourceModel(nv_model)

                    diff_proxy = epyqlib.utils.qt.DiffProxyModel(
                        columns=epyqlib.nv.diffable_columns,
                        reference_column=(epyqlib.nv.Columns.indexes.user_default),
                        diff_highlights={
                            QtCore.Qt.ItemDataRole.BackgroundRole: epyqlib.nv.diff_highlight,
                        },
                        reference_highlights={
                            QtCore.Qt.ItemDataRole.BackgroundRole: epyqlib.nv.reference_highlight,
                        },
                    )
                    diff_proxy.setSourceModel(sort_proxy)

                    view.setModel(diff_proxy)
                    view.configure_sort_proxy(sort_proxy)
                    view.configure_diff_proxy(diff_proxy)

                    view.set_metas(self.metas)
                    view.set_sorting_enabled(True)
                    view.sort_by_column(column=column, order=Qt.AscendingOrder)

                    nv_range_check_overridable = self.raw_dict.get(
                        "nv_range_check_overridable",
                        False,
                    )

                    view.ui.enforce_range_limits_check_box.setVisible(
                        nv_range_check_overridable,
                    )

        if Elements.variables in self.elements:
            variable_model = epyqlib.variableselectionmodel.VariableModel(
                nvs=self.nvs,
                nv_model=nv_model,
                bus=self.bus,
                tx_id=self.neo_frames.frame_by_name("CCP").id,
                rx_id=self.neo_frames.frame_by_name("CCPResponse").id,
            )

            column = epyqlib.variableselectionmodel.Columns.indexes.name
            proxy = epyqlib.utils.qt.PySortFilterProxyModel(
                filter_column=column,
            )
            proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
            proxy.setSourceModel(variable_model)
            self.ui.variable_selection.set_model(proxy)
            self.ui.variable_selection.set_sorting_enabled(True)
            self.ui.variable_selection.sort_by_column(
                column=column, order=Qt.AscendingOrder
            )
            self.ui.variable_selection.set_signal_paths(
                reset_signal_path=can_configuration.data_logger_reset_signal_path,
                recording_signal_path=can_configuration.data_logger_recording_signal_path,
                configuration_is_valid_signal_path=can_configuration.data_logger_configuration_is_valid_signal_path,
            )

        if Elements.fault_log in self.elements:
            fault_log = epyqlib.faultlogmodel.create_blank()

            nv_message_names = self.raw_dict["fault_log"]["nv_message_names"]
            process_message_names = self.raw_dict["fault_log"]["process_message_names"]

            fault_log.connect(
                process_frames=self.neo_frames,
                process_message_names=process_message_names,
                nv_frames=self.widget_nvs,
                nv_message_names=nv_message_names,
            )
            self.ui.fault_log_view.set_model(fault_log.model)

        if Tabs.dashes in tabs:
            for i, (name, dash) in enumerate(self.dash_uis.items()):
                self.ui.tabs.insertTab(i, dash, name)
        if Tabs.txrx not in tabs:
            self.ui.tabs.removeTab(self.ui.tabs.indexOf(self.ui.txrx))
        if Tabs.variables not in tabs:
            self.ui.tabs.removeTab(self.ui.tabs.indexOf(self.ui.variables))
        if Tabs.nv not in tabs:
            self.ui.tabs.removeTab(self.ui.tabs.indexOf(self.ui.nv))
        else:
            self.ui.tabs.currentChanged.connect(self.tab_changed)
        if Tabs.scripting not in tabs:
            self.ui.tabs.removeTab(self.ui.tabs.indexOf(self.ui.scripting))
        if Tabs.fault_log not in tabs:
            self.ui.tabs.removeTab(self.ui.tabs.indexOf(self.ui.faultlog))
        if Tabs.files not in tabs:
            self.ui.tabs.removeTab(self.ui.tabs.indexOf(self.ui.files))

        self.ui.tabs.setCurrentIndex(0)

        self.widget_nv_frames = collections.defaultdict(list)

        def flatten(dict_node):
            flat = set()
            for key, value in dict_node.items():
                if isinstance(value, dict):
                    flat |= flatten(value)
                else:
                    flat.add(value)

            return flat

        flat = flatten(self.dash_uis)
        flat = [v for v in flat if isinstance(v, QWidget)]

        default_widget_value = math.nan

        self.dash_connected_signals = set()
        self.dash_missing_signals = set()
        self.dash_missing_defaults = set()
        self.nv_looping_reads = {}
        if Tabs.variables in tabs:
            flat.append(self.ui.variable_selection)
        if Tabs.nv in tabs:
            flat.append(self.ui.nv)
        for dash in flat:
            # TODO: CAMPid 99457281212789437474299
            children = dash.findChildren(QObject)
            widgets = [c for c in children if isinstance(c, AbstractWidget)]

            dash.connected_frames = set()
            frames = dash.connected_frames

            for widget in widgets:
                # TODO: CAMPid 07340793413419714301373147
                widget.set_range(min=0, max=100)
                try:
                    widget.set_value(default_widget_value)
                except ValueError:
                    widget.set_value(0)

                frame = widget.property("frame")
                if frame is not None:
                    signal = widget.property("signal")
                    signal_path = (frame, signal)
                else:
                    signal_path = tuple(e for e in widget._signal_path if len(e) > 0)

                try:
                    signal = self.neo_frames.signal_by_path(*signal_path)
                except epyqlib.canneo.NotFoundError:
                    if not widget.ignore:
                        widget_path = []
                        p = widget
                        while p is not dash:
                            widget_path.insert(0, p.objectName())
                            p = p.parent()

                        self.dash_missing_signals.add(
                            "{}:/{} - {}".format(
                                (
                                    dash.file_name
                                    if hasattr(dash, "file_name")
                                    else "<builtin>"
                                ),
                                "/".join(widget_path),
                                ":".join(signal_path)
                                if len(signal_path) > 0
                                else "<none specified>",
                            )
                        )
                else:
                    # TODO: CAMPid 079320743340327834208
                    if signal.frame.id == self.nvs.set_frames[0].id:
                        nv_signal = self.widget_nvs.neo.signal_by_path(*signal_path)

                        self.widget_nv_frames[nv_signal.frame].append(
                            nv_signal,
                        )

                        if nv_signal.multiplex not in self.nv_looping_reads:

                            def read(
                                nv_signal=nv_signal,
                                read=self.nvs.protocol.read,
                            ):
                                d = read(
                                    nv_signal=nv_signal,
                                    meta=epyqlib.nv.MetaEnum.value,
                                )

                                d.addErrback(ignore_timeout)

                                return d

                            self.nv_looping_reads[nv_signal.multiplex] = read

                        if dash is self.ui.nv:
                            self.nv_tab_looping_set.add_request(
                                key=widget,
                                request=epyqlib.twisted.loopingset.Request(
                                    f=self.nv_looping_reads[nv_signal.multiplex],
                                    period=1,
                                ),
                            )
                        else:
                            self.nv_looping_set.add_request(
                                key=widget,
                                request=epyqlib.twisted.loopingset.Request(
                                    f=self.nv_looping_reads[nv_signal.multiplex],
                                    period=1,
                                ),
                            )

                        if hasattr(widget, "tx") and widget.tx:
                            signal = self.widget_nvs.neo.signal_by_path(
                                self.nvs.set_frames[0].name, *signal_path[1:]
                            )
                        else:
                            signal = self.widget_nvs.neo.signal_by_path(
                                self.nvs.status_frames[0].name, *signal_path[1:]
                            )

                    frame = signal.frame
                    frames.add(frame)
                    self.dash_connected_signals.add(signal)
                    widget.set_signal(signal)

                    if hasattr(widget, "tx") and widget.tx:
                        self.first_nv_view.ui.enforce_range_limits_check_box.stateChanged.connect(
                            widget.set_check_range,
                        )
                        widget.set_check_range(
                            self.first_nv_view.ui.enforce_range_limits_check_box.checkState(),
                        )

                if edit_actions is not None:
                    # TODO: CAMPid 97453289314763416967675427
                    if widget.property("editable"):
                        for action in edit_actions:
                            if action[1](widget):
                                action[0](dash=dash, widget=widget, signal=widget.edit)
                                break

        monitor_matrix = load_matrix(self.can_path)
        monitor_frames = epyqlib.canneo.Neo(
            matrix=monitor_matrix,
            node_id_adjust=self.node_id_adjust,
        )
        monitor_frame = monitor_frames.frame_by_name(
            can_configuration.monitor_frame,
        )

        self.ui.overlay_stack.layout().setStackingMode(
            QStackedLayout.StackingMode.StackAll,
        )
        self.ui.overlays.setAttribute(Qt.WA_TransparentForMouseEvents)

        self.connection_monitor = FrameTimeout(frame=monitor_frame)
        self.connection_monitor.lost.connect(self.connection_status_changed)
        self.connection_monitor.found.connect(self.connection_status_changed)
        self.connection_monitor.found.connect(self.read_nv_widget_min_max)
        self.connection_monitor.start()

        notifiees.append(self.connection_monitor)

        self.bus_status_changed(online=False, transmit=False)

        all_signals = set()
        for frame in self.neo_frames.frames:
            for signal in frame.signals:
                if signal.name != "__padding__":
                    all_signals.add(signal)

        frame_signals = []
        for signal in all_signals - self.dash_connected_signals:
            frame_signals.append("{} : {}".format(signal.frame.name, signal.name))

        if Elements.nv in self.elements:
            nv_frame_signals = []
            for frame in list(self.nvs.set_frames.values()) + list(
                self.nvs.status_frames.values()
            ):
                for signal in frame.signals:
                    nv_frame_signals.append(
                        "{} : {}".format(signal.frame.name, signal.name)
                    )

            frame_signals = list(set(frame_signals) - set(nv_frame_signals))

        if len(frame_signals) > 0:
            logger.warning("\n === Signals not referenced by a widget")
            for frame_signal in sorted(frame_signals):
                logger.warning(frame_signal)

        if len(self.dash_missing_signals) > 0:
            logger.error("\n === Signals referenced by a widget but not defined")
            undefined_signals = sorted(self.dash_missing_signals)
            logger.error("\n".join(undefined_signals))

            message = (
                "The following signals are referenced by the .ui "
                "files but were not found in the loaded CAN "
                "database.  The widgets will show `{}`.".format(default_widget_value)
            )

            message = textwrap.dedent(
                """\
            {message}

            {signals}
            """
            ).format(message=message, signals="\n\n".join(undefined_signals))

            epyqlib.utils.qt.dialog(
                parent=None,
                message=message,
                icon=QMessageBox.Information,
            )

        if Elements.scripting in self.elements:
            scripting_model = epyqlib.scripting.Model(
                get_devices=lambda: {None: self, self.nickname: self},
            )
            self.ui.scripting_view.set_model(scripting_model)

        self.device_interface = DeviceInterface(device=self)

        if Tabs.files in tabs:
            self.ui.files_view.set_device_interface(self.device_interface)

        self.notifiees = notifiees
        for notifiee in notifiees:
            self.bus.notifier.add(notifiee)

        self.extension.post()
Exemplo n.º 51
0
class TcpS(QDialog, Ui_TcpServer):
    """
    Class documentation goes here.
    """

    sendFileName = pyqtSignal(str)

    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(TcpS, self).__init__(parent)
        self.setupUi(self)
        self.payloadSize = 64 * 1024
        self.totalBytes = 0
        self.bytesWritten = 0
        self.bytesToWrite = 0
        self.theFileName = ""
        self.fileName = ""
        self.localFile = QFile()
        self.outBlock = QByteArray()
        self.time = QTime()
        self.initServer()

    def initServer(self):
        """
        网络设置初始化
        """
        self.tcpPort = 7788
        self.tcpServer = QTcpServer(self)
        self.clientConnection = QTcpSocket(self)
        self.tcpServer.newConnection.connect(self.sendMessage)
        self.serverStatuslabel.setText("请选择要传送的文件")
        self.progressBar.reset()
        self.serverOpenBtn.setEnabled(True)
        self.serverSendBtn.setEnabled(False)
        self.tcpServer.close()

    def refused(self):
        """
        对端拒绝接收文件
        """
        self.tcpServer.close()
        self.serverStatuslabel.setText("对方拒绝接收")

    def closeEvent(self, event):
        """
        关闭事件
        """
        self.on_serverCloseBtn_clicked()

    def sendMessage(self):
        """
        发送文件
        """
        self.serverSendBtn.setEnabled(False)
        self.clientConnection = self.tcpServer.nextPendingConnection()
        self.clientConnection.bytesWritten.connect(self.updateClientProgress)
        self.serverStatuslabel.setText("开始传送文件 {} !".format(self.theFileName))

        self.localFile = QFile(self.fileName)
        if not (self.localFile.open(QFile.ReadOnly)):
            errorMsg = "无法读取文件 {}:\n {}".format(self.fileName,
                                                self.localFile.errorString())
            QMessageBox.warning(self, "应用程序", errorMsg)
            return

        self.serverCloseBtn.setText("取消")

        self.totalBytes = self.localFile.size()  #单位:字节
        sendOut = QDataStream(self.outBlock, QIODevice.WriteOnly)
        sendOut.setVersion(QDataStream.Qt_5_4)
        self.time.start()
        currentFile = self.fileName.split("/")[-1]
        sendOut.writeInt64(0)
        sendOut.writeInt64(0)
        sendOut.writeQString(currentFile)
        self.totalBytes += self.outBlock.size()
        sendOut.device().seek(0)
        sendOut.writeInt64(self.totalBytes)
        sendOut.writeInt64(self.outBlock.size() - 2)
        self.bytesToWrite = self.totalBytes - self.clientConnection.write(
            self.outBlock)
        self.outBlock.resize(0)

    def updateClientProgress(self, numBytes):
        """
        发送进度显示
        """
        qApp.processEvents()
        self.bytesWritten += numBytes
        if self.bytesWritten > 0:
            self.block = self.localFile.read(
                min(self.bytesToWrite, self.payloadSize))
            self.bytesToWrite -= self.clientConnection.write(self.block)
        else:
            self.localFile.close()

        byteSent = self.bytesWritten / (1024 * 1024)
        useTime = self.time.elapsed() / 1000
        speed = self.bytesWritten / useTime / (1024 * 1024)
        total = self.totalBytes / (1024 * 1024)
        left = (total - byteSent) / speed

        if byteSent < 0.01:
            byteSent = self.bytesWritten / 1024
            speed = self.bytesWritten / useTime / 1024
            total = self.totalBytes / 1024
            if left > 0:
                sendInfo = "已发送 {0:.2f}KB({1:.2f}KB/s)\n共{2:.2f}KB 已用时:{3:.1f}秒\n 估计剩余时间:{4:.1f}秒".format(
                    byteSent, speed, total, useTime, left)
            else:
                sendInfo = "已发送 {0:.2f}KB({1:.2f}KB/s)\n共{2:.2f}KB 用时:{3:.1f}秒\n".format(
                    byteSent, speed, total, useTime)
        else:
            if left > 0:
                sendInfo = "已发送 {0:.2f}MB({1:.2f}MB/s)\n共{2:.2f}MB 已用时:{3:.1f}秒\n 估计剩余时间:{4:.1f}秒".format(
                    byteSent, speed, total, useTime, left)
            else:
                sendInfo = "已发送 {0:.2f}MB({1:.2f}MB/s)\n共{2:.2f}MB 用时:{3:.1f}秒\n".format(
                    byteSent, speed, total, useTime)

        self.progressBar.setMaximum(total)
        self.progressBar.setValue(byteSent)

        if self.bytesWritten == self.totalBytes:
            self.serverCloseBtn.setText("关闭")

        self.serverStatuslabel.setText(sendInfo)

    @pyqtSlot()
    def on_serverOpenBtn_clicked(self):
        """
        打开文件
        """
        self.fileName = QFileDialog.getOpenFileName(self, '打开文件', './')[0]
        if self.fileName:
            self.theFileName = self.fileName.split("/")[-1]
            self.serverStatuslabel.setText("要传送的文件为:{}".format(
                self.theFileName))
            self.serverSendBtn.setEnabled(True)
            self.serverOpenBtn.setEnabled(False)

    @pyqtSlot()
    def on_serverSendBtn_clicked(self):
        """
        发送文件
        """
        if not (self.tcpServer.listen(QHostAddress.Any, self.tcpPort)):
            errorMsg = self.tcpServer.errorString()
            QMessageBox.warning(self, "错误", "发送失败:\n {}".format(errorMsg))
            self.TcpServer.close()
            return

        self.serverStatuslabel.setText("等待对方接收... ...")
        self.serverSendBtn.setEnabled(False)
        self.sendFileName.emit(self.theFileName)

    @pyqtSlot()
    def on_serverCloseBtn_clicked(self):
        """
        取消或者关闭
        """
        if self.tcpServer.isListening():
            self.tcpServer.close()
            if self.localFile.isOpen():
                self.localFile.close()
            self.clientConnection.abort()

        if self.serverCloseBtn.text() == "取消":
            self.serverCloseBtn.setText("关闭")
        else:
            self.close()
            self.serverOpenBtn.setEnabled(True)
            self.serverSendBtn.setEnabled(False)
            self.progressBar.reset()
            self.totalBytes = 0
            self.bytesWritten = 0
            self.bytesToWrite = 0
            self.serverStatuslabel.setText("请选择要传送的文件")
Exemplo n.º 52
0
 def loadInitialFile(self):
     settings = QSettings()
     fname = str(settings.value("LastFile"))
     if fname and QFile.exists(fname):
         self.loadFile(fname)
Exemplo n.º 53
0
        self.saveFile(False)

    def closeEvent(self, e):
        if self.ensureSaved():
            e.accept()
        else:
            e.ignore()


if __name__ == '__main__':

    import sys

    translator = QTranslator()
    translator.load('translate/es_MX.qm')

    stylesFile = QFile('stylesheets/MetroLite.qss')
    stylesFile.open(QFile.ReadOnly | QFile.Text)
    styleSheet = stylesFile.readAll()
    styleSheet = str(styleSheet, encoding='utf-8')

    app = QApplication(sys.argv)
    app.installTranslator(translator)
    app.setStyleSheet(styleSheet)

    window = MainWindow()
    window.resize(1024, 768)
    window.show()

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    sys.exit(app.exec_())
Exemplo n.º 54
0
    def start_main_window(conn):
        db.DBBase._DB_CONN = conn
        #if args.test:
        #	import threading, time
        #	ser_list = []
        #	for x in range(5000):
        #		s = gallerydb.gallery()
        #		s.profile = app_constants.NO_IMAGE_PATH
        #		s.title = 'Test {}'.format(x)
        #		s.artist = 'Author {}'.format(x)
        #		s.path = app_constants.static_dir
        #		s.type = 'Test'
        #		s.language = 'English'
        #		s.info = 'I am number {}'.format(x)
        #		ser_list.append(s)

        #	done = False
        #	thread_list = []
        #	i = 0
        #	while not done:
        #		try:
        #			if threading.active_count() > 5000:
            #				thread_list = []
        #				done = True
        #			else:
        #				thread_list.append(
        #					threading.Thread(target=gallerydb.galleryDB.add_gallery,
        #					  args=(ser_list[i],)))
        #				thread_list[i].start()
        #				i += 1
        #				print(i)
        #				print('Threads running: {}'.format(threading.activeCount()))
        #		except IndexError:
        #			done = True

        WINDOW = app.AppWindow(args.exceptions)

        # styling
        d_style = app_constants.default_stylesheet_path
        u_style =  app_constants.user_stylesheet_path

        if len(u_style) is not 0:
            try:
                style_file = QFile(u_style)
                log_i('Select userstyle: OK')
            except:
                style_file = QFile(d_style)
                log_i('Select defaultstyle: OK')
        else:
            style_file = QFile(d_style)
            log_i('Select defaultstyle: OK')

        style_file.open(QFile.ReadOnly)
        style = str(style_file.readAll(), 'utf-8')
        application.setStyleSheet(style)
        try:
            os.mkdir(app_constants.temp_dir)
        except FileExistsError:
            try:
                for root, dirs, files in scandir.walk('temp', topdown=False):
                    for name in files:
                        os.remove(os.path.join(root, name))
                    for name in dirs:
                        os.rmdir(os.path.join(root, name))
            except:
                log.exception("Empty temp: FAIL")
        log_d('Create temp: OK')

        if test:
            return application, WINDOW

        return application.exec_()
Exemplo n.º 55
0
    def initUI(self):
        file = QFile(':css/StyleSheet.css')
        file.open(QFile.ReadOnly)
        stream = QTextStream(file)
        text = stream.readAll()
        self.setStyleSheet(text)
        self.setWindowTitle(self.title)
        self.setWindowIcon(QIcon(":css/Icons/logo.png"))
        self.setGeometry(0, 0, self.width, self.height-60)

        #Creating main frame,it is a container for the all framers. parent it to QWindow
        self.main_frame = QtWidgets.QFrame(self)
        self.main_frame.setObjectName("MainFrame")
        self.main_frame.setFixedWidth(self.width)
        self.main_frame.setFixedHeight(self.height)
        self.main_layout = QtWidgets.QVBoxLayout(self.main_frame)

        # the Icons sub frame
        self.iconsub_frame = QtWidgets.QFrame(self.main_frame)
        self.iconsub_frame.setFixedHeight(80)
        self.main_layout.addWidget(self.iconsub_frame)
        self.iconsub_layout = QtWidgets.QHBoxLayout(self.iconsub_frame)
        self.iconsub_layout.setAlignment(Qt.AlignLeft)

        # help button
        help_btn = QtWidgets.QPushButton("", self)
        help_btn.setObjectName("TransparentButtons")
        help_btn.setStyleSheet("QPushButton {background: url(:css/Icons/help.png) no-repeat transparent;}")
        help_btn.setToolTip('Show help pdf.')
        help_btn.setFixedWidth(68)
        help_btn.setFixedHeight(68)
        help_btn.clicked.connect(self.show_help_pdf)
        self.iconsub_layout.addWidget(help_btn)

        # the Icon sub frame
        self.logo_sub_frame = QtWidgets.QFrame(self.main_frame)
        self.logo_sub_frame.setFixedWidth(self.width)
        self.main_layout.addWidget(self.logo_sub_frame)
        self.logosub_layout = QtWidgets.QHBoxLayout(self.logo_sub_frame)
        self.logosub_layout.setAlignment(Qt.AlignCenter)

        # Setting up the logo
        logo = QtWidgets.QLabel('', self)
        pixmap = QPixmap(":css/Icons/logo.png")
        pixmap = pixmap.scaled(260, 260)
        logo.setPixmap(pixmap)
        self.logosub_layout.addWidget(logo)
        logo.setAlignment(Qt.AlignCenter)

        # The Button sub frame
        self.button_sub_frame = QtWidgets.QFrame(self.main_frame)
        self.main_layout.addWidget(self.button_sub_frame)
        self.button_sub_layout = QtWidgets.QHBoxLayout(self.button_sub_frame)
        self.button_sub_frame.setFixedWidth(self.width)
        self.button_sub_layout.setAlignment(Qt.AlignTop | Qt.AlignCenter)

        # start to create style button
        StartCreateNewBtn = QtWidgets.QPushButton("Style your image", self)
        StartCreateNewBtn.setObjectName("MainGuiButtons")
        StartCreateNewBtn.setToolTip('Start image style process.')
        StartCreateNewBtn.clicked.connect(self.openTransferImageGui)
        self.button_sub_layout.addWidget(StartCreateNewBtn)

        StartCreateNewBtn = QtWidgets.QPushButton("Style from gallery", self)
        StartCreateNewBtn.setObjectName("MainGuiButtons")
        StartCreateNewBtn.setToolTip('Open style gallery.')
        StartCreateNewBtn.clicked.connect(self.openGalleryGui)
        self.button_sub_layout.addWidget(StartCreateNewBtn)

        # credit text label on main layout
        creditsLbl = QtWidgets.QLabel('Created By Koral Zakai & May Steinfeld, '
                                      'Supervisor: Zeev Vladimir Volkovich, '
                                      '03/06/2019')
        creditsLbl.setAlignment(Qt.AlignCenter)
        self.main_layout.addWidget(creditsLbl)

        # show the window on full screen
        self.showMaximized()
Exemplo n.º 56
0
 def getStyleSheet(self, path):
     f = QFile(path)
     f.open(QFile.ReadOnly | QFile.Text)
     stylesheet = QTextStream(f).readAll()
     f.close()
     return stylesheet
Exemplo n.º 57
0
 def to_js(self, job, _, path):
     js_path = os.path.join(THIS_DIR, "js", path)
     if os.path.isfile(js_path):
         f = QFile(js_path, self)
         job.reply(b"application/javascript", f)
Exemplo n.º 58
0
from PyQt5.QtCore import (QFile, QTextStream)
from PyQt5.QtWidgets import (QApplication)

# stylesheet
import breeze_resources

from Components.App.App import App

if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)

    # set stylesheet
    file = QFile("./styles/dark.qss")
    file.open(QFile.ReadOnly | QFile.Text)
    stream = QTextStream(file)
    app.setStyleSheet(stream.readAll())

    calc = App()
    calc.show()
    sys.exit(app.exec_())

    del calc
Exemplo n.º 59
0
def removeTemporaryFiles(filelist):
    for file in filelist:
        QFile.remove(file)
Exemplo n.º 60
0
class PluginRepositoryWidget(QWidget, Ui_PluginRepositoryDialog):
    """
    Class implementing a dialog showing the available plugins.
    
    @signal closeAndInstall() emitted when the Close & Install button is
        pressed
    """
    closeAndInstall = pyqtSignal()
    
    DescrRole = Qt.UserRole
    UrlRole = Qt.UserRole + 1
    FilenameRole = Qt.UserRole + 2
    AuthorRole = Qt.UserRole + 3

    PluginStatusUpToDate = 0
    PluginStatusNew = 1
    PluginStatusLocalUpdate = 2
    PluginStatusRemoteUpdate = 3
    
    def __init__(self, parent=None, external=False):
        """
        Constructor
        
        @param parent parent of this dialog (QWidget)
        @param external flag indicating an instatiation as a main
            window (boolean)
        """
        super(PluginRepositoryWidget, self).__init__(parent)
        self.setupUi(self)
        
        self.__updateButton = self.buttonBox.addButton(
            self.tr("Update"), QDialogButtonBox.ActionRole)
        self.__downloadButton = self.buttonBox.addButton(
            self.tr("Download"), QDialogButtonBox.ActionRole)
        self.__downloadButton.setEnabled(False)
        self.__downloadInstallButton = self.buttonBox.addButton(
            self.tr("Download && Install"),
            QDialogButtonBox.ActionRole)
        self.__downloadInstallButton.setEnabled(False)
        self.__downloadCancelButton = self.buttonBox.addButton(
            self.tr("Cancel"), QDialogButtonBox.ActionRole)
        self.__installButton = \
            self.buttonBox.addButton(self.tr("Close && Install"),
                                     QDialogButtonBox.ActionRole)
        self.__downloadCancelButton.setEnabled(False)
        self.__installButton.setEnabled(False)
        
        self.repositoryUrlEdit.setText(
            Preferences.getUI("PluginRepositoryUrl6"))
        
        self.repositoryList.headerItem().setText(
            self.repositoryList.columnCount(), "")
        self.repositoryList.header().setSortIndicator(0, Qt.AscendingOrder)
        
        self.__pluginContextMenu = QMenu(self)
        self.__hideAct = self.__pluginContextMenu.addAction(
            self.tr("Hide"), self.__hidePlugin)
        self.__hideSelectedAct = self.__pluginContextMenu.addAction(
            self.tr("Hide Selected"), self.__hideSelectedPlugins)
        self.__pluginContextMenu.addSeparator()
        self.__showAllAct = self.__pluginContextMenu.addAction(
            self.tr("Show All"), self.__showAllPlugins)
        self.__pluginContextMenu.addSeparator()
        self.__pluginContextMenu.addAction(
            self.tr("Cleanup Downloads"), self.__cleanupDownloads)
        
        self.pluginRepositoryFile = \
            os.path.join(Utilities.getConfigDir(), "PluginRepository")
        
        self.__external = external
        
        # attributes for the network objects
        self.__networkManager = QNetworkAccessManager(self)
        self.__networkManager.proxyAuthenticationRequired.connect(
            proxyAuthenticationRequired)
        if SSL_AVAILABLE:
            self.__sslErrorHandler = E5SslErrorHandler(self)
            self.__networkManager.sslErrors.connect(self.__sslErrors)
        self.__replies = []
        
        self.__networkConfigurationManager = QNetworkConfigurationManager(self)
        self.__onlineStateChanged(
            self.__networkConfigurationManager.isOnline())
        
        self.__networkConfigurationManager.onlineStateChanged.connect(
            self.__onlineStateChanged)
        
        self.__doneMethod = None
        self.__inDownload = False
        self.__pluginsToDownload = []
        self.__pluginsDownloaded = []
        self.__isDownloadInstall = False
        self.__allDownloadedOk = False
        
        self.__hiddenPlugins = Preferences.getPluginManager("HiddenPlugins")
        
        self.__populateList()
    
    @pyqtSlot(bool)
    def __onlineStateChanged(self, online):
        """
        Private slot handling online state changes.
        
        @param online flag indicating the online status
        @type bool
        """
        self.__updateButton.setEnabled(online)
        self.on_repositoryList_itemSelectionChanged()
        if online:
            msg = self.tr("Network Status: online")
        else:
            msg = self.tr("Network Status: offline")
        self.statusLabel.setText(msg)
    
    @pyqtSlot(QAbstractButton)
    def on_buttonBox_clicked(self, button):
        """
        Private slot to handle the click of a button of the button box.
        
        @param button reference to the button pressed (QAbstractButton)
        """
        if button == self.__updateButton:
            self.__updateList()
        elif button == self.__downloadButton:
            self.__isDownloadInstall = False
            self.__downloadPlugins()
        elif button == self.__downloadInstallButton:
            self.__isDownloadInstall = True
            self.__allDownloadedOk = True
            self.__downloadPlugins()
        elif button == self.__downloadCancelButton:
            self.__downloadCancel()
        elif button == self.__installButton:
            self.__closeAndInstall()
    
    def __formatDescription(self, lines):
        """
        Private method to format the description.
        
        @param lines lines of the description (list of strings)
        @return formatted description (string)
        """
        # remove empty line at start and end
        newlines = lines[:]
        if len(newlines) and newlines[0] == '':
            del newlines[0]
        if len(newlines) and newlines[-1] == '':
            del newlines[-1]
        
        # replace empty lines by newline character
        index = 0
        while index < len(newlines):
            if newlines[index] == '':
                newlines[index] = '\n'
            index += 1
        
        # join lines by a blank
        return ' '.join(newlines)
    
    @pyqtSlot(QPoint)
    def on_repositoryList_customContextMenuRequested(self, pos):
        """
        Private slot to show the context menu.
        
        @param pos position to show the menu (QPoint)
        """
        self.__hideAct.setEnabled(
            self.repositoryList.currentItem() is not None and
            len(self.__selectedItems()) == 1)
        self.__hideSelectedAct.setEnabled(
            len(self.__selectedItems()) > 1)
        self.__showAllAct.setEnabled(bool(self.__hasHiddenPlugins()))
        self.__pluginContextMenu.popup(self.repositoryList.mapToGlobal(pos))
    
    @pyqtSlot(QTreeWidgetItem, QTreeWidgetItem)
    def on_repositoryList_currentItemChanged(self, current, previous):
        """
        Private slot to handle the change of the current item.
        
        @param current reference to the new current item (QTreeWidgetItem)
        @param previous reference to the old current item (QTreeWidgetItem)
        """
        if self.__repositoryMissing or current is None:
            return
        
        self.urlEdit.setText(
            current.data(0, PluginRepositoryWidget.UrlRole) or "")
        self.descriptionEdit.setPlainText(
            current.data(0, PluginRepositoryWidget.DescrRole) and
            self.__formatDescription(
                current.data(0, PluginRepositoryWidget.DescrRole)) or "")
        self.authorEdit.setText(
            current.data(0, PluginRepositoryWidget.AuthorRole) or "")
    
    def __selectedItems(self):
        """
        Private method to get all selected items without the toplevel ones.
        
        @return list of selected items (list)
        """
        ql = self.repositoryList.selectedItems()
        for index in range(self.repositoryList.topLevelItemCount()):
            ti = self.repositoryList.topLevelItem(index)
            if ti in ql:
                ql.remove(ti)
        return ql
    
    @pyqtSlot()
    def on_repositoryList_itemSelectionChanged(self):
        """
        Private slot to handle a change of the selection.
        """
        self.__downloadButton.setEnabled(
            len(self.__selectedItems()) and
            self.__networkConfigurationManager.isOnline())
        self.__downloadInstallButton.setEnabled(
            len(self.__selectedItems()) and
            self.__networkConfigurationManager.isOnline())
        self.__installButton.setEnabled(len(self.__selectedItems()))
    
    def __updateList(self):
        """
        Private slot to download a new list and display the contents.
        """
        url = self.repositoryUrlEdit.text()
        self.__downloadFile(url,
                            self.pluginRepositoryFile,
                            self.__downloadRepositoryFileDone)
    
    def __downloadRepositoryFileDone(self, status, filename):
        """
        Private method called after the repository file was downloaded.
        
        @param status flaging indicating a successful download (boolean)
        @param filename full path of the downloaded file (string)
        """
        self.__populateList()
    
    def __downloadPluginDone(self, status, filename):
        """
        Private method called, when the download of a plugin is finished.
        
        @param status flag indicating a successful download (boolean)
        @param filename full path of the downloaded file (string)
        """
        if status:
            self.__pluginsDownloaded.append(filename)
        if self.__isDownloadInstall:
            self.__allDownloadedOk &= status
        
        del self.__pluginsToDownload[0]
        if len(self.__pluginsToDownload):
            self.__downloadPlugin()
        else:
            self.__downloadPluginsDone()
    
    def __downloadPlugin(self):
        """
        Private method to download the next plugin.
        """
        self.__downloadFile(self.__pluginsToDownload[0][0],
                            self.__pluginsToDownload[0][1],
                            self.__downloadPluginDone)
    
    def __downloadPlugins(self):
        """
        Private slot to download the selected plugins.
        """
        self.__pluginsDownloaded = []
        self.__pluginsToDownload = []
        self.__downloadButton.setEnabled(False)
        self.__downloadInstallButton.setEnabled(False)
        self.__installButton.setEnabled(False)
        for itm in self.repositoryList.selectedItems():
            if itm not in [self.__stableItem, self.__unstableItem,
                           self.__unknownItem]:
                url = itm.data(0, PluginRepositoryWidget.UrlRole)
                filename = os.path.join(
                    Preferences.getPluginManager("DownloadPath"),
                    itm.data(0, PluginRepositoryWidget.FilenameRole))
                self.__pluginsToDownload.append((url, filename))
        self.__downloadPlugin()
    
    def __downloadPluginsDone(self):
        """
        Private method called, when the download of the plugins is finished.
        """
        self.__downloadButton.setEnabled(len(self.__selectedItems()))
        self.__downloadInstallButton.setEnabled(len(self.__selectedItems()))
        self.__installButton.setEnabled(True)
        self.__doneMethod = None
        if not self.__external:
            ui = e5App().getObject("UserInterface")
        else:
            ui = None
        if ui and ui.notificationsEnabled():
            ui.showNotification(
                UI.PixmapCache.getPixmap("plugin48.png"),
                self.tr("Download Plugin Files"),
                self.tr("""The requested plugins were downloaded."""))
        
        if self.__isDownloadInstall:
            self.closeAndInstall.emit()
        else:
            if ui is None or not ui.notificationsEnabled():
                E5MessageBox.information(
                    self,
                    self.tr("Download Plugin Files"),
                    self.tr("""The requested plugins were downloaded."""))
            self.downloadProgress.setValue(0)
            
            # repopulate the list to update the refresh icons
            self.__populateList()
    
    def __resortRepositoryList(self):
        """
        Private method to resort the tree.
        """
        self.repositoryList.sortItems(
            self.repositoryList.sortColumn(),
            self.repositoryList.header().sortIndicatorOrder())
    
    def __populateList(self):
        """
        Private method to populate the list of available plugins.
        """
        self.repositoryList.clear()
        self.__stableItem = None
        self.__unstableItem = None
        self.__unknownItem = None
        
        self.downloadProgress.setValue(0)
        self.__doneMethod = None
        
        if os.path.exists(self.pluginRepositoryFile):
            self.__repositoryMissing = False
            f = QFile(self.pluginRepositoryFile)
            if f.open(QIODevice.ReadOnly):
                from E5XML.PluginRepositoryReader import PluginRepositoryReader
                reader = PluginRepositoryReader(f, self.addEntry)
                reader.readXML()
                self.repositoryList.resizeColumnToContents(0)
                self.repositoryList.resizeColumnToContents(1)
                self.repositoryList.resizeColumnToContents(2)
                self.__resortRepositoryList()
                url = Preferences.getUI("PluginRepositoryUrl6")
                if url != self.repositoryUrlEdit.text():
                    self.repositoryUrlEdit.setText(url)
                    E5MessageBox.warning(
                        self,
                        self.tr("Plugins Repository URL Changed"),
                        self.tr(
                            """The URL of the Plugins Repository has"""
                            """ changed. Select the "Update" button to get"""
                            """ the new repository file."""))
            else:
                E5MessageBox.critical(
                    self,
                    self.tr("Read plugins repository file"),
                    self.tr("<p>The plugins repository file <b>{0}</b> "
                            "could not be read. Select Update</p>")
                    .format(self.pluginRepositoryFile))
        else:
            self.__repositoryMissing = True
            QTreeWidgetItem(
                self.repositoryList,
                ["", self.tr(
                    "No plugin repository file available.\nSelect Update.")
                 ])
            self.repositoryList.resizeColumnToContents(1)
    
    def __downloadFile(self, url, filename, doneMethod=None):
        """
        Private slot to download the given file.
        
        @param url URL for the download (string)
        @param filename local name of the file (string)
        @param doneMethod method to be called when done
        """
        if self.__networkConfigurationManager.isOnline():
            self.__updateButton.setEnabled(False)
            self.__downloadButton.setEnabled(False)
            self.__downloadInstallButton.setEnabled(False)
            self.__downloadCancelButton.setEnabled(True)
            
            self.statusLabel.setText(url)
            
            self.__doneMethod = doneMethod
            self.__downloadURL = url
            self.__downloadFileName = filename
            self.__downloadIODevice = QFile(self.__downloadFileName + ".tmp")
            self.__downloadCancelled = False
            
            request = QNetworkRequest(QUrl(url))
            request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                 QNetworkRequest.AlwaysNetwork)
            reply = self.__networkManager.get(request)
            reply.finished.connect(self.__downloadFileDone)
            reply.downloadProgress.connect(self.__downloadProgress)
            self.__replies.append(reply)
        else:
            E5MessageBox.warning(
                self,
                self.tr("Error downloading file"),
                self.tr(
                    """<p>Could not download the requested file"""
                    """ from {0}.</p><p>Error: {1}</p>"""
                ).format(url, self.tr("Computer is offline.")))
    
    def __downloadFileDone(self):
        """
        Private method called, after the file has been downloaded
        from the internet.
        """
        self.__updateButton.setEnabled(True)
        self.__downloadCancelButton.setEnabled(False)
        self.__onlineStateChanged(
            self.__networkConfigurationManager.isOnline())
        
        ok = True
        reply = self.sender()
        if reply in self.__replies:
            self.__replies.remove(reply)
        if reply.error() != QNetworkReply.NoError:
            ok = False
            if not self.__downloadCancelled:
                E5MessageBox.warning(
                    self,
                    self.tr("Error downloading file"),
                    self.tr(
                        """<p>Could not download the requested file"""
                        """ from {0}.</p><p>Error: {1}</p>"""
                    ).format(self.__downloadURL, reply.errorString())
                )
            self.downloadProgress.setValue(0)
            self.__downloadURL = None
            self.__downloadIODevice.remove()
            self.__downloadIODevice = None
            if self.repositoryList.topLevelItemCount():
                if self.repositoryList.currentItem() is None:
                    self.repositoryList.setCurrentItem(
                        self.repositoryList.topLevelItem(0))
                else:
                    self.__downloadButton.setEnabled(
                        len(self.__selectedItems()))
                    self.__downloadInstallButton.setEnabled(
                        len(self.__selectedItems()))
            reply.deleteLater()
            return
        
        self.__downloadIODevice.open(QIODevice.WriteOnly)
        self.__downloadIODevice.write(reply.readAll())
        self.__downloadIODevice.close()
        if QFile.exists(self.__downloadFileName):
            QFile.remove(self.__downloadFileName)
        self.__downloadIODevice.rename(self.__downloadFileName)
        self.__downloadIODevice = None
        self.__downloadURL = None
        reply.deleteLater()
        
        if self.__doneMethod is not None:
            self.__doneMethod(ok, self.__downloadFileName)
    
    def __downloadCancel(self):
        """
        Private slot to cancel the current download.
        """
        if self.__replies:
            reply = self.__replies[0]
            self.__downloadCancelled = True
            self.__pluginsToDownload = []
            reply.abort()
    
    def __downloadProgress(self, done, total):
        """
        Private slot to show the download progress.
        
        @param done number of bytes downloaded so far (integer)
        @param total total bytes to be downloaded (integer)
        """
        if total:
            self.downloadProgress.setMaximum(total)
            self.downloadProgress.setValue(done)
    
    def addEntry(self, name, short, description, url, author, version,
                 filename, status):
        """
        Public method to add an entry to the list.
        
        @param name data for the name field (string)
        @param short data for the short field (string)
        @param description data for the description field (list of strings)
        @param url data for the url field (string)
        @param author data for the author field (string)
        @param version data for the version field (string)
        @param filename data for the filename field (string)
        @param status status of the plugin (string [stable, unstable, unknown])
        """
        pluginName = filename.rsplit("-", 1)[0]
        if pluginName in self.__hiddenPlugins:
            return
        
        if status == "stable":
            if self.__stableItem is None:
                self.__stableItem = \
                    QTreeWidgetItem(self.repositoryList,
                                    [self.tr("Stable")])
                self.__stableItem.setExpanded(True)
            parent = self.__stableItem
        elif status == "unstable":
            if self.__unstableItem is None:
                self.__unstableItem = \
                    QTreeWidgetItem(self.repositoryList,
                                    [self.tr("Unstable")])
                self.__unstableItem.setExpanded(True)
            parent = self.__unstableItem
        else:
            if self.__unknownItem is None:
                self.__unknownItem = \
                    QTreeWidgetItem(self.repositoryList,
                                    [self.tr("Unknown")])
                self.__unknownItem.setExpanded(True)
            parent = self.__unknownItem
        itm = QTreeWidgetItem(parent, [name, version, short])
        
        itm.setData(0, PluginRepositoryWidget.UrlRole, url)
        itm.setData(0, PluginRepositoryWidget.FilenameRole, filename)
        itm.setData(0, PluginRepositoryWidget.AuthorRole, author)
        itm.setData(0, PluginRepositoryWidget.DescrRole, description)
        
        updateStatus = self.__updateStatus(filename, version)
        if updateStatus == PluginRepositoryWidget.PluginStatusUpToDate:
            itm.setIcon(1, UI.PixmapCache.getIcon("empty.png"))
            itm.setToolTip(1, self.tr("up-to-date"))
        elif updateStatus == PluginRepositoryWidget.PluginStatusNew:
            itm.setIcon(1, UI.PixmapCache.getIcon("download.png"))
            itm.setToolTip(1, self.tr("new download available"))
        elif updateStatus == PluginRepositoryWidget.PluginStatusLocalUpdate:
            itm.setIcon(1, UI.PixmapCache.getIcon("updateLocal.png"))
            itm.setToolTip(1, self.tr("update installable"))
        elif updateStatus == PluginRepositoryWidget.PluginStatusRemoteUpdate:
            itm.setIcon(1, UI.PixmapCache.getIcon("updateRemote.png"))
            itm.setToolTip(1, self.tr("updated download available"))
    
    def __updateStatus(self, filename, version):
        """
        Private method to check, if the given archive update status.
        
        @param filename data for the filename field (string)
        @param version data for the version field (string)
        @return plug-in update status (integer, one of PluginStatusNew,
            PluginStatusUpToDate, PluginStatusLocalUpdate,
            PluginStatusRemoteUpdate)
        """
        archive = os.path.join(Preferences.getPluginManager("DownloadPath"),
                               filename)
        
        # check, if it is an update (i.e. we already have archives
        # with the same pattern)
        archivesPattern = archive.rsplit('-', 1)[0] + "-*.zip"
        if len(glob.glob(archivesPattern)) == 0:
            return PluginRepositoryWidget.PluginStatusNew
        
        # check, if the archive exists
        if not os.path.exists(archive):
            return PluginRepositoryWidget.PluginStatusRemoteUpdate
        
        # check, if the archive is a valid zip file
        if not zipfile.is_zipfile(archive):
            return PluginRepositoryWidget.PluginStatusRemoteUpdate
        
        zip = zipfile.ZipFile(archive, "r")
        try:
            aversion = zip.read("VERSION").decode("utf-8")
        except KeyError:
            aversion = ""
        zip.close()
        
        if aversion == version:
            if not self.__external:
                # Check against installed/loaded plug-ins
                pluginManager = e5App().getObject("PluginManager")
                pluginName = filename.rsplit('-', 1)[0]
                pluginDetails = pluginManager.getPluginDetails(pluginName)
                if pluginDetails is None or pluginDetails["version"] < version:
                    return PluginRepositoryWidget.PluginStatusLocalUpdate
            
            return PluginRepositoryWidget.PluginStatusUpToDate
        else:
            return PluginRepositoryWidget.PluginStatusRemoteUpdate
    
    def __sslErrors(self, reply, errors):
        """
        Private slot to handle SSL errors.
        
        @param reply reference to the reply object (QNetworkReply)
        @param errors list of SSL errors (list of QSslError)
        """
        ignored = self.__sslErrorHandler.sslErrorsReply(reply, errors)[0]
        if ignored == E5SslErrorHandler.NotIgnored:
            self.__downloadCancelled = True
    
    def getDownloadedPlugins(self):
        """
        Public method to get the list of recently downloaded plugin files.
        
        @return list of plugin filenames (list of strings)
        """
        return self.__pluginsDownloaded
    
    @pyqtSlot(bool)
    def on_repositoryUrlEditButton_toggled(self, checked):
        """
        Private slot to set the read only status of the repository URL line
        edit.
        
        @param checked state of the push button (boolean)
        """
        self.repositoryUrlEdit.setReadOnly(not checked)
    
    def __closeAndInstall(self):
        """
        Private method to close the dialog and invoke the install dialog.
        """
        if not self.__pluginsDownloaded and self.__selectedItems():
            for itm in self.__selectedItems():
                filename = os.path.join(
                    Preferences.getPluginManager("DownloadPath"),
                    itm.data(0, PluginRepositoryWidget.FilenameRole))
                self.__pluginsDownloaded.append(filename)
        self.closeAndInstall.emit()
    
    def __hidePlugin(self):
        """
        Private slot to hide the current plug-in.
        """
        itm = self.__selectedItems()[0]
        pluginName = (itm.data(0, PluginRepositoryWidget.FilenameRole)
                      .rsplit("-", 1)[0])
        self.__updateHiddenPluginsList([pluginName])
    
    def __hideSelectedPlugins(self):
        """
        Private slot to hide all selected plug-ins.
        """
        hideList = []
        for itm in self.__selectedItems():
            pluginName = (itm.data(0, PluginRepositoryWidget.FilenameRole)
                          .rsplit("-", 1)[0])
            hideList.append(pluginName)
        self.__updateHiddenPluginsList(hideList)
    
    def __showAllPlugins(self):
        """
        Private slot to show all plug-ins.
        """
        self.__hiddenPlugins = []
        self.__updateHiddenPluginsList([])
    
    def __hasHiddenPlugins(self):
        """
        Private method to check, if there are any hidden plug-ins.
        
        @return flag indicating the presence of hidden plug-ins (boolean)
        """
        return bool(self.__hiddenPlugins)
    
    def __updateHiddenPluginsList(self, hideList):
        """
        Private method to store the list of hidden plug-ins to the settings.
        
        @param hideList list of plug-ins to add to the list of hidden ones
            (list of string)
        """
        if hideList:
            self.__hiddenPlugins.extend(
                [p for p in hideList if p not in self.__hiddenPlugins])
        Preferences.setPluginManager("HiddenPlugins", self.__hiddenPlugins)
        self.__populateList()
    
    def __cleanupDownloads(self):
        """
        Private slot to cleanup the plug-in downloads area.
        """
        downloadPath = Preferences.getPluginManager("DownloadPath")
        downloads = {}  # plug-in name as key, file name as value
        
        # step 1: extract plug-ins and downloaded files
        for pluginFile in os.listdir(downloadPath):
            if not os.path.isfile(os.path.join(downloadPath, pluginFile)):
                continue
            
            pluginName = pluginFile.rsplit("-", 1)[0]
            if pluginName not in downloads:
                downloads[pluginName] = []
            downloads[pluginName].append(pluginFile)
        
        # step 2: delete old entries
        for pluginName in downloads:
            downloads[pluginName].sort()
        
            if pluginName in self.__hiddenPlugins and \
                    not Preferences.getPluginManager("KeepHidden"):
                removeFiles = downloads[pluginName]
            else:
                removeFiles = downloads[pluginName][
                    :-Preferences.getPluginManager("KeepGenerations")]
            for removeFile in removeFiles:
                try:
                    os.remove(os.path.join(downloadPath, removeFile))
                except (IOError, OSError) as err:
                    E5MessageBox.critical(
                        self,
                        self.tr("Cleanup of Plugin Downloads"),
                        self.tr("""<p>The plugin download <b>{0}</b> could"""
                                """ not be deleted.</p><p>Reason: {1}</p>""")
                        .format(removeFile, str(err)))