コード例 #1
0
ファイル: TRPreviewer.py プロジェクト: pycom/EricShort
 def add(self, fileName, setTranslation=True):
     """
     Public method to add a translation to the list.
     
     If the translation file (*.qm) has not been loaded yet, it will
     be loaded automatically.
     
     @param fileName name of the translation file to be added (string)
     @param setTranslation flag indicating, if this should be set as
         the active translation (boolean)
     """
     if not self.__haveFileName(fileName):
         ntr = Translation()
         ntr.fileName = fileName
         ntr.name = self.__uniqueName(fileName)
         if ntr.name is None:
             E5MessageBox.warning(
                 self.parent(),
                 self.tr("Set Translator"),
                 self.tr(
                     """<p>The translation filename <b>{0}</b>"""
                     """ is invalid.</p>""").format(fileName))
             return
         
         ntr.translator = self.loadTransFile(fileName)
         if ntr.translator is None:
             return
         
         self.selector.addItem(ntr.name)
         self.translations.append(ntr)
     
     if setTranslation:
         tr = self.__findFileName(fileName)
         self.set(tr.name)
コード例 #2
0
ファイル: SnapWidget.py プロジェクト: renerocksai/EricShort
    def __saveImage(self, fileName):
        """
        Private method to save the snapshot.
        
        @param fileName name of the file to save to (string)
        @return flag indicating success (boolean)
        """
        if QFileInfo(fileName).exists():
            res = E5MessageBox.yesNo(
                self,
                self.tr("Save Snapshot"),
                self.tr("<p>The file <b>{0}</b> already exists."
                        " Overwrite it?</p>").format(fileName),
                icon=E5MessageBox.Warning)
            if not res:
                return False

        file = QFile(fileName)
        if not file.open(QFile.WriteOnly):
            E5MessageBox.warning(
                self, self.tr("Save Snapshot"),
                self.tr("Cannot write file '{0}:\n{1}.").format(
                    fileName, file.errorString()))
            return False

        ok = self.__snapshot.save(file)
        file.close()

        if not ok:
            E5MessageBox.warning(
                self, self.tr("Save Snapshot"),
                self.tr("Cannot write file '{0}:\n{1}.").format(
                    fileName, file.errorString()))

        return ok
コード例 #3
0
ファイル: WatchPointViewer.py プロジェクト: pycom/EricShort
 def __findDuplicates(self, cond, special, showMessage=False,
                      index=QModelIndex()):
     """
     Private method to check, if an entry already exists.
     
     @param cond condition to check (string)
     @param special special condition to check (string)
     @param showMessage flag indicating a message should be shown,
         if a duplicate entry is found (boolean)
     @param index index that should not be considered duplicate
         (QModelIndex)
     @return flag indicating a duplicate entry (boolean)
     """
     idx = self.__model.getWatchPointIndex(cond, special)
     duplicate = idx.isValid() and \
         idx.internalPointer() != index.internalPointer()
     if showMessage and duplicate:
         if not special:
             msg = self.tr("""<p>A watch expression '<b>{0}</b>'"""
                           """ already exists.</p>""")\
                 .format(Utilities.html_encode(cond))
         else:
             msg = self.tr(
                 """<p>A watch expression '<b>{0}</b>'"""
                 """ for the variable <b>{1}</b> already exists.</p>""")\
                 .format(special, Utilities.html_encode(cond))
         E5MessageBox.warning(
             self,
             self.tr("Watch expression already exists"),
             msg)
     
     return duplicate
コード例 #4
0
 def save(self):
     """
     Public method to save the bookmarks.
     """
     if not self.__loaded:
         return
     
     from .XbelWriter import XbelWriter
     writer = XbelWriter()
     bookmarkFile = self.getFileName()
     
     # save root folder titles in English (i.e. not localized)
     self.__menu.title = BOOKMARKMENU
     self.__toolbar.title = BOOKMARKBAR
     if not writer.write(bookmarkFile, self.__bookmarkRootNode):
         E5MessageBox.warning(
             None,
             self.tr("Saving Bookmarks"),
             self.tr("""Error saving bookmarks to <b>{0}</b>.""")
             .format(bookmarkFile))
     
     # restore localized titles
     self.__menu.title = self.tr(BOOKMARKMENU)
     self.__toolbar.title = self.tr(BOOKMARKBAR)
     
     self.bookmarksSaved.emit()
コード例 #5
0
    def __populateList(self):
        """
        Private method to populate the list of available plugins.
        """
        self.dictionariesList.clear()
        self.downloadProgress.setValue(0)

        url = self.dictionariesUrlEdit.text()

        if self.__isOnline():
            self.__refreshButton.setEnabled(False)
            self.__installButton.setEnabled(False)
            self.__uninstallButton.setEnabled(False)
            self.__cancelButton.setEnabled(True)

            self.statusLabel.setText(url)

            self.__downloadCancelled = False

            request = QNetworkRequest(QUrl(url))
            request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                 QNetworkRequest.AlwaysNetwork)
            reply = WebBrowserWindow.networkManager().get(request)
            reply.finished.connect(lambda: self.__listFileDownloaded(reply))
            reply.downloadProgress.connect(self.__downloadProgress)
            self.__replies.append(reply)
        else:
            E5MessageBox.warning(
                self, self.tr("Error populating list of dictionaries"),
                self.tr("""<p>Could not download the dictionaries list"""
                        """ from {0}.</p><p>Error: {1}</p>""").format(
                            url, self.tr("Computer is offline.")))
コード例 #6
0
    def __downloadDictionary(self):
        """
        Private slot to download a dictionary.
        """
        if self.__isOnline():
            if self.__dictionariesToDownload:
                url = self.__dictionariesToDownload.pop(0)
                self.statusLabel.setText(url)

                self.__downloadCancelled = False

                request = QNetworkRequest(QUrl(url))
                request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                     QNetworkRequest.AlwaysNetwork)
                reply = WebBrowserWindow.networkManager().get(request)
                reply.finished.connect(lambda: self.__installDictionary(reply))
                reply.downloadProgress.connect(self.__downloadProgress)
                self.__replies.append(reply)
            else:
                self.__installationFinished()
        else:
            E5MessageBox.warning(
                self, self.tr("Error downloading dictionary file"),
                self.tr(
                    """<p>Could not download the requested dictionary file"""
                    """ from {0}.</p><p>Error: {1}</p>""").format(
                        url, self.tr("Computer is offline.")))

            self.__installationFinished()
コード例 #7
0
    def start(self, pfn, fn=None):
        """
        Public slot to start the calculation of the profile data.
        
        @param pfn basename of the profiling file (string)
        @param fn file to display the profiling data for (string)
        """
        self.basename = os.path.splitext(pfn)[0]

        fname = "{0}.profile".format(self.basename)
        if not os.path.exists(fname):
            E5MessageBox.warning(
                self, self.tr("Profile Results"),
                self.tr("""<p>There is no profiling data"""
                        """ available for <b>{0}</b>.</p>""").format(pfn))
            self.close()
            return
        try:
            f = open(fname, 'rb')
            self.stats = pickle.load(f)
            f.close()
        except (EnvironmentError, pickle.PickleError, EOFError):
            E5MessageBox.critical(
                self, self.tr("Loading Profiling Data"),
                self.tr("""<p>The profiling data could not be"""
                        """ read from file <b>{0}</b>.</p>""").format(fname))
            self.close()
            return

        self.file = fn
        self.__populateLists()
        self.__finish()
コード例 #8
0
ファイル: PluginUpdate.py プロジェクト: zhoumaomao11/Pymakr
    def __versionCheckResult(self, versions):
        """
        Private method to show the result of the version check action.

        @param versions contents of the downloaded versions file (list of
            strings)
        """
        url = ""
        ui = self.__ui
        try:
            # check release version
            if calc_int_version(versions[0]) > calc_int_version(Version):
                res = E5MessageBox.yesNo(
                    ui,
                    ui.tr("Update available"),
                    ui.tr("""Pymakr version <b>{0}</b> is now"""
                          """ available at <b>{1}</b>. Would you like"""
                          """ to get it?""").format(versions[0], versions[1]),
                    yesDefault=True)
                url = res and versions[1] or ''
            else:
                if ui.manualUpdatesCheck:
                    E5MessageBox.information(
                        ui, ui.tr("Pymakr is up to date"),
                        ui.tr("""You are using the latest version of"""
                              """ Pymakr"""))
        except IndexError:
            E5MessageBox.warning(ui, ui.tr("Error during updates check"),
                                 ui.tr("""Could not perform updates check."""))

        if url:
            QDesktopServices.openUrl(QUrl(url))
コード例 #9
0
ファイル: EditorAPIsPage.py プロジェクト: testmana2/test
 def on_addInstalledApiFileButton_clicked(self):
     """
     Private slot to add an API file from the list of installed API files
     for the selected lexer language.
     """
     installedAPIFiles = self.__currentAPI.installedAPIFiles()
     if installedAPIFiles:
         installedAPIFilesPath = QFileInfo(installedAPIFiles[0]).path()
         installedAPIFilesShort = []
         for installedAPIFile in installedAPIFiles:
             installedAPIFilesShort.append(
                 QFileInfo(installedAPIFile).fileName())
         file, ok = QInputDialog.getItem(
             self,
             self.tr("Add from installed APIs"),
             self.tr("Select from the list of installed API files"),
             installedAPIFilesShort,
             0, False)
         if ok:
             self.apiList.addItem(Utilities.toNativeSeparators(
                 QFileInfo(QDir(installedAPIFilesPath), file)
                 .absoluteFilePath()))
     else:
         E5MessageBox.warning(
             self,
             self.tr("Add from installed APIs"),
             self.tr("""There are no APIs installed yet."""
                     """ Selection is not available."""))
         self.addInstalledApiFileButton.setEnabled(False)
     self.prepareApiButton.setEnabled(self.apiList.count() > 0)
コード例 #10
0
    def __showPackageDetails(self, packageName, packageVersion):
        """
        Private method to populate the package details dialog.
        
        @param packageName name of the package to show details for
        @type str
        @param packageVersion version of the package
        @type str
        """
        QApplication.setOverrideCursor(Qt.WaitCursor)
        QApplication.processEvents(QEventLoop.ExcludeUserInputEvents)

        packageData = self.__pip.getPackageDetails(packageName, packageVersion)

        QApplication.restoreOverrideCursor()
        if packageData:
            from .PipPackageDetailsDialog import PipPackageDetailsDialog

            self.showDetailsButton.setEnabled(True)

            if self.__packageDetailsDialog is not None:
                self.__packageDetailsDialog.close()

            self.__packageDetailsDialog = (PipPackageDetailsDialog(
                packageData, self))
            self.__packageDetailsDialog.show()
        else:
            E5MessageBox.warning(
                self, self.tr("Search PyPI"),
                self.tr("""<p>No package details info for <b>{0}</b>"""
                        """ available.</p>""").format(packageName))
コード例 #11
0
ファイル: TRPreviewer.py プロジェクト: renerocksai/EricShort
    def set(self, name):
        """
        Public slot to set a translator by name.
        
        @param name name (language) of the translator to set (string)
        """
        nTranslator = None

        if name != noTranslationName:
            trans = self.__findName(name)
            if trans is None:
                E5MessageBox.warning(
                    self.parent(), self.tr("Set Translator"),
                    self.tr(
                        """<p>The translator <b>{0}</b> is not known.</p>""").
                    format(name))
                return

            nTranslator = trans.translator

        if nTranslator == self.currentTranslator:
            return

        if self.currentTranslator is not None:
            QApplication.removeTranslator(self.currentTranslator)
        if nTranslator is not None:
            QApplication.installTranslator(nTranslator)
        self.currentTranslator = nTranslator

        self.selector.blockSignals(True)
        self.selector.setCurrentIndex(self.selector.findText(name))
        self.selector.blockSignals(False)

        self.translationChanged.emit()
コード例 #12
0
    def on_deleteButton_clicked(self):
        """
        Private slot to delete the selected documentation sets.
        """
        yes = E5MessageBox.yesNo(
            self, self.tr("Delete Documentation Sets"),
            self.tr("""Shall the selected documentation sets really be"""
                    """ deleted?"""))
        if yes:
            for itm in self.documentationList.selectedItems():
                if itm.parent is None:
                    # it is a category item, skip it
                    continue

                category = itm.parent()
                fileName = itm.data(0, Qt.UserRole)
                try:
                    os.remove(fileName)
                except OSError as err:
                    E5MessageBox.warning(
                        self, self.tr("Delete Documentation Sets"),
                        self.tr("""<p>The documentation set <b>{0}</b> could"""
                                """ not be deleted.</p><p>Reason: {1}</p>""").
                        format(fileName, str(err)))
                    continue

                category.removeChild(itm)
                del itm

                if category.childCount() == 0:
                    self.__deleteCategory(category)
コード例 #13
0
ファイル: EditorAPIsPage.py プロジェクト: zhoumaomao11/Pymakr
 def on_addInstalledApiFileButton_clicked(self):
     """
     Private slot to add an API file from the list of installed API files
     for the selected lexer language.
     """
     installedAPIFiles = self.__currentAPI.installedAPIFiles()
     if installedAPIFiles:
         installedAPIFilesPath = QFileInfo(installedAPIFiles[0]).path()
         installedAPIFilesShort = []
         for installedAPIFile in installedAPIFiles:
             installedAPIFilesShort.append(
                 QFileInfo(installedAPIFile).fileName())
         file, ok = QInputDialog.getItem(
             self, self.tr("Add from installed APIs"),
             self.tr("Select from the list of installed API files"),
             installedAPIFilesShort, 0, False)
         if ok:
             self.apiList.addItem(
                 Utilities.toNativeSeparators(
                     QFileInfo(QDir(installedAPIFilesPath),
                               file).absoluteFilePath()))
     else:
         E5MessageBox.warning(
             self, self.tr("Add from installed APIs"),
             self.tr("""There are no APIs installed yet."""
                     """ Selection is not available."""))
         self.addInstalledApiFileButton.setEnabled(False)
     self.prepareApiButton.setEnabled(self.apiList.count() > 0)
コード例 #14
0
ファイル: UIPreviewer.py プロジェクト: renerocksai/EricShort
    def __loadFile(self, fn):
        """
        Private slot to load a ui file.
        
        @param fn name of the ui file to be laoded (string)
        """
        if self.mainWidget:
            self.mainWidget.close()
            self.previewSV.takeWidget()
            del self.mainWidget
            self.mainWidget = None

        # load the file
        try:
            self.mainWidget = uic.loadUi(fn)
        except Exception:
            pass

        if self.mainWidget:
            self.currentFile = fn
            self.__updateChildren(self.styleCombo.currentText())
            if isinstance(self.mainWidget, QDialog) or \
               isinstance(self.mainWidget, QMainWindow):
                self.mainWidget.show()
                self.mainWidget.installEventFilter(self)
            else:
                self.previewSV.setWidget(self.mainWidget)
                self.mainWidget.show()
        else:
            E5MessageBox.warning(
                self, self.tr("Load UI File"),
                self.tr("""<p>The file <b>{0}</b> could not be loaded.</p>""").
                format(fn))
        self.__updateActions()
コード例 #15
0
    def getWorkspace(self, silent=False):
        """
        Public method to get the workspace directory.
        
        @param silent flag indicating silent operations
        @type bool
        @return workspace directory used for saving files
        @rtype str
        """
        # Attempts to find the path on the filesystem that represents the
        # plugged in PyBoard board.
        deviceDirectory = Utilities.findVolume(self.DeviceVolumeName)

        if deviceDirectory:
            return deviceDirectory
        else:
            # return the default workspace and give the user a warning (unless
            # silent mode is selected)
            if not silent:
                E5MessageBox.warning(
                    self.microPython, self.tr("Workspace Directory"),
                    self.tr("Python files for PyBoard devices are stored"
                            " on the device. Therefore, to edit these files"
                            " you need to have the device plugged in. Until"
                            " you plug in a device, the standard directory"
                            " will be used."))

            return super(PyBoardDevice, self).getWorkspace()
コード例 #16
0
    def __populateFromTroveLists(self):
        """
        Private method to populate lists from the Trove list file.
        """
        filename = os.path.join(os.path.dirname(__file__), "data",
                                "trove_classifiers.txt")
        try:
            f = open(filename, "r")
            lines = f.readlines()
            f.close()
        except (IOError, OSError) as err:
            E5MessageBox.warning(
                self, self.tr("Reading Trove Classifiers"),
                self.tr(
                    """<p>The Trove Classifiers file <b>{0}</b>"""
                    """ could not be read.</p><p>Reason: {1}</p>""").format(
                        filename, str(err)))
            return

        self.__classifiersDict = {}
        for line in lines:
            line = line.strip()
            if line.startswith("License "):
                self.licenseClassifierComboBox.addItem(
                    "/".join(line.split(" :: ")[1:]), line)
            elif line.startswith("Development Status "):
                self.developmentStatusComboBox.addItem(
                    line.split(" :: ")[1], line)
            else:
                self.__addClassifierEntry(line)
        self.__classifiersDict = {}
コード例 #17
0
 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.__isOnline():
         self.__updateButton.setEnabled(False)
         self.__downloadButton.setEnabled(False)
         self.__downloadInstallButton.setEnabled(False)
         self.__closeButton.setEnabled(False)
         self.__downloadCancelButton.setEnabled(True)
         
         self.statusLabel.setText(url)
         
         request = QNetworkRequest(QUrl(url))
         request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                              QNetworkRequest.AlwaysNetwork)
         reply = self.__networkManager.get(request)
         reply.finished.connect(
             lambda: self.__downloadFileDone(reply, filename, doneMethod))
         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.")))
コード例 #18
0
ファイル: TRPreviewer.py プロジェクト: renerocksai/EricShort
    def add(self, fileName, setTranslation=True):
        """
        Public method to add a translation to the list.
        
        If the translation file (*.qm) has not been loaded yet, it will
        be loaded automatically.
        
        @param fileName name of the translation file to be added (string)
        @param setTranslation flag indicating, if this should be set as
            the active translation (boolean)
        """
        if not self.__haveFileName(fileName):
            ntr = Translation()
            ntr.fileName = fileName
            ntr.name = self.__uniqueName(fileName)
            if ntr.name is None:
                E5MessageBox.warning(
                    self.parent(), self.tr("Set Translator"),
                    self.tr("""<p>The translation filename <b>{0}</b>"""
                            """ is invalid.</p>""").format(fileName))
                return

            ntr.translator = self.loadTransFile(fileName)
            if ntr.translator is None:
                return

            self.selector.addItem(ntr.name)
            self.translations.append(ntr)

        if setTranslation:
            tr = self.__findFileName(fileName)
            self.set(tr.name)
コード例 #19
0
ファイル: SnapWidget.py プロジェクト: pycom/EricShort
 def __saveImage(self, fileName):
     """
     Private method to save the snapshot.
     
     @param fileName name of the file to save to (string)
     @return flag indicating success (boolean)
     """
     if QFileInfo(fileName).exists():
         res = E5MessageBox.yesNo(
             self,
             self.tr("Save Snapshot"),
             self.tr("<p>The file <b>{0}</b> already exists."
                     " Overwrite it?</p>").format(fileName),
             icon=E5MessageBox.Warning)
         if not res:
             return False
     
     file = QFile(fileName)
     if not file.open(QFile.WriteOnly):
         E5MessageBox.warning(
             self, self.tr("Save Snapshot"),
             self.tr("Cannot write file '{0}:\n{1}.")
             .format(fileName, file.errorString()))
         return False
     
     ok = self.__snapshot.save(file)
     file.close()
     
     if not ok:
         E5MessageBox.warning(
             self, self.tr("Save Snapshot"),
             self.tr("Cannot write file '{0}:\n{1}.")
             .format(fileName, file.errorString()))
     
     return ok
コード例 #20
0
ファイル: TRPreviewer.py プロジェクト: pycom/EricShort
 def set(self, name):
     """
     Public slot to set a translator by name.
     
     @param name name (language) of the translator to set (string)
     """
     nTranslator = None
     
     if name != noTranslationName:
         trans = self.__findName(name)
         if trans is None:
             E5MessageBox.warning(
                 self.parent(),
                 self.tr("Set Translator"),
                 self.tr(
                     """<p>The translator <b>{0}</b> is not known.</p>""")
                 .format(name))
             return
             
         nTranslator = trans.translator
     
     if nTranslator == self.currentTranslator:
         return
     
     if self.currentTranslator is not None:
         QApplication.removeTranslator(self.currentTranslator)
     if nTranslator is not None:
         QApplication.installTranslator(nTranslator)
     self.currentTranslator = nTranslator
     
     self.selector.blockSignals(True)
     self.selector.setCurrentIndex(self.selector.findText(name))
     self.selector.blockSignals(False)
     
     self.translationChanged.emit()
コード例 #21
0
    def on_addButton_clicked(self):
        """
        Private slot to add documents to the help database.
        """
        fileNames = E5FileDialog.getOpenFileNames(
            self, self.tr("Add Documentation"), "",
            self.tr("Qt Compressed Help Files (*.qch)"))
        if not fileNames:
            return

        for fileName in fileNames:
            ns = QHelpEngineCore.namespaceName(fileName)
            if not ns:
                E5MessageBox.warning(
                    self, self.tr("Add Documentation"),
                    self.tr("""The file <b>{0}</b> is not a valid"""
                            """ Qt Help File.""").format(fileName))
                continue

            if len(self.documentsList.findItems(ns, Qt.MatchFixedString)):
                E5MessageBox.warning(
                    self, self.tr("Add Documentation"),
                    self.tr(
                        """The namespace <b>{0}</b> is already registered.""").
                    format(ns))
                continue

            self.__engine.registerDocumentation(fileName)
            self.documentsList.addItem(ns)
            self.__registeredDocs.append(ns)
            if ns in self.__unregisteredDocs:
                self.__unregisteredDocs.remove(ns)
コード例 #22
0
ファイル: TRPreviewer.py プロジェクト: pycom/EricShort
 def buildWidget(self):
     """
     Public slot to load a UI file.
     """
     if self.__widget:
         self.__widget.close()
         self.__layout.removeWidget(self.__widget)
         del self.__widget
         self.__widget = None
     
     try:
         self.__widget = uic.loadUi(self.__uiFileName)
     except Exception:
         pass
     
     if not self.__widget:
         E5MessageBox.warning(
             self,
             self.tr("Load UI File"),
             self.tr(
                 """<p>The file <b>{0}</b> could not be loaded.</p>""")
             .format(self.__uiFileName))
         self.__valid = False
         return
     
     self.__widget.setParent(self)
     self.__layout.addWidget(self.__widget)
     self.__widget.show()
     self.__valid = True
     self.adjustSize()
     
     self.__timer.stop()
コード例 #23
0
 def __applyGuards(self):
     """
     Private slot to apply the defined guards to the current patch.
     """
     if self.__dirtyList:
         guardsList = []
         for row in range(self.guardsList.count()):
             itm = self.guardsList.item(row)
             guard = itm.data(Qt.UserRole) + itm.text()
             guardsList.append(guard)
         
         args = self.vcs.initCommand("qguard")
         args.append(self.patchNameLabel.text())
         if guardsList:
             args.append("--")
             args.extend(guardsList)
         else:
             args.append("--none")
         
         error = self.__hgClient.runcommand(args)[1]
         
         if error:
             E5MessageBox.warning(
                 self,
                 self.tr("Apply Guard Definitions"),
                 self.tr("""<p>The defined guards could not be"""
                         """ applied.</p><p>Reason: {0}</p>""")
                 .format(error))
         else:
             self.__dirtyList = False
             self.on_patchSelector_activated(
                 self.patchNameLabel.text())
コード例 #24
0
    def __findDuplicates(self,
                         cond,
                         special,
                         showMessage=False,
                         index=QModelIndex()):
        """
        Private method to check, if an entry already exists.
        
        @param cond condition to check (string)
        @param special special condition to check (string)
        @param showMessage flag indicating a message should be shown,
            if a duplicate entry is found (boolean)
        @param index index that should not be considered duplicate
            (QModelIndex)
        @return flag indicating a duplicate entry (boolean)
        """
        idx = self.__model.getWatchPointIndex(cond, special)
        duplicate = idx.isValid() and \
            idx.internalPointer() != index.internalPointer()
        if showMessage and duplicate:
            if not special:
                msg = self.tr("""<p>A watch expression '<b>{0}</b>'"""
                              """ already exists.</p>""")\
                    .format(Utilities.html_encode(cond))
            else:
                msg = self.tr(
                    """<p>A watch expression '<b>{0}</b>'"""
                    """ for the variable <b>{1}</b> already exists.</p>""")\
                    .format(special, Utilities.html_encode(cond))
            E5MessageBox.warning(self,
                                 self.tr("Watch expression already exists"),
                                 msg)

        return duplicate
コード例 #25
0
    def on_caImportButton_clicked(self):
        """
        Private slot to import server certificates.
        """
        certs = self.__importCertificate()
        if certs:
            caCerts = self.__getSystemCaCertificates()
            for cert in certs:
                if cert in caCerts:
                    if qVersion() >= "5.0.0":
                        commonStr = ", ".join(cert.subjectInfo(QSslCertificate.CommonName))
                    else:
                        commonStr = cert.subjectInfo(QSslCertificate.CommonName)
                    E5MessageBox.warning(
                        self,
                        self.tr("Import Certificate"),
                        self.tr("""<p>The certificate <b>{0}</b> already exists.""" """ Skipping.</p>""").format(
                            Utilities.decodeString(commonStr)
                        ),
                    )
                else:
                    caCerts.append(cert)

            pems = QByteArray()
            for cert in caCerts:
                pems.append(cert.toPem() + "\n")
            Preferences.Prefs.settings.setValue("Help/SystemCertificates", pems)

            self.caCertificatesTree.clear()
            self.__populateCaCertificatesTree()

            self.__updateDefaultConfiguration()
コード例 #26
0
 def __showMimeType(self):
     """
     Private slot to show the mime type of the selected entry.
     """
     itmList = self.getSelectedItems()
     if itmList:
         mimetype = Utilities.MimeTypes.mimeType(itmList[0].fileName())
         if mimetype is None:
             E5MessageBox.warning(
                 self, self.tr("Show Mime-Type"),
                 self.tr("""The mime type of the file could not be"""
                         """ determined."""))
         elif mimetype.split("/")[0] == "text":
             E5MessageBox.information(
                 self, self.tr("Show Mime-Type"),
                 self.tr("""The file has the mime type <b>{0}</b>.""").
                 format(mimetype))
         else:
             textMimeTypesList = Preferences.getUI("TextMimeTypes")
             if mimetype in textMimeTypesList:
                 E5MessageBox.information(
                     self, self.tr("Show Mime-Type"),
                     self.tr("""The file has the mime type <b>{0}</b>.""").
                     format(mimetype))
             else:
                 ok = E5MessageBox.yesNo(
                     self, self.tr("Show Mime-Type"),
                     self.tr("""The file has the mime type <b>{0}</b>."""
                             """<br/> Shall it be added to the list of"""
                             """ text mime types?""").format(mimetype))
                 if ok:
                     textMimeTypesList.append(mimetype)
                     Preferences.setUI("TextMimeTypes", textMimeTypesList)
コード例 #27
0
ファイル: TRPreviewer.py プロジェクト: renerocksai/EricShort
    def buildWidget(self):
        """
        Public slot to load a UI file.
        """
        if self.__widget:
            self.__widget.close()
            self.__layout.removeWidget(self.__widget)
            del self.__widget
            self.__widget = None

        try:
            self.__widget = uic.loadUi(self.__uiFileName)
        except Exception:
            pass

        if not self.__widget:
            E5MessageBox.warning(
                self, self.tr("Load UI File"),
                self.tr("""<p>The file <b>{0}</b> could not be loaded.</p>""").
                format(self.__uiFileName))
            self.__valid = False
            return

        self.__widget.setParent(self)
        self.__layout.addWidget(self.__widget)
        self.__widget.show()
        self.__valid = True
        self.adjustSize()

        self.__timer.stop()
コード例 #28
0
 def on_caImportButton_clicked(self):
     """
     Private slot to import server certificates.
     """
     certs = self.__importCertificate()
     if certs:
         caCerts = self.__getSystemCaCertificates()
         for cert in certs:
             if cert in caCerts:
                 if qVersion() >= "5.0.0":
                     commonStr = ", ".join(
                         cert.subjectInfo(QSslCertificate.CommonName))
                 else:
                     commonStr = cert.subjectInfo(
                         QSslCertificate.CommonName)
                 E5MessageBox.warning(
                     self,
                     self.tr("Import Certificate"),
                     self.tr(
                         """<p>The certificate <b>{0}</b> already exists."""
                         """ Skipping.</p>""")
                     .format(Utilities.decodeString(commonStr)))
             else:
                 caCerts.append(cert)
         
         pems = QByteArray()
         for cert in caCerts:
             pems.append(cert.toPem() + '\n')
         Preferences.Prefs.settings.setValue(
             "Help/SystemCertificates", pems)
         
         self.caCertificatesTree.clear()
         self.__populateCaCertificatesTree()
         
         self.__updateDefaultConfiguration()
コード例 #29
0
ファイル: BookmarksManager.py プロジェクト: testmana2/test
 def save(self):
     """
     Public method to save the bookmarks.
     """
     if not self.__loaded:
         return
     
     from .XbelWriter import XbelWriter
     writer = XbelWriter()
     bookmarkFile = self.getFileName()
     
     # save root folder titles in English (i.e. not localized)
     self.__menu.title = BOOKMARKMENU
     self.__toolbar.title = BOOKMARKBAR
     if not writer.write(bookmarkFile, self.__bookmarkRootNode):
         E5MessageBox.warning(
             None,
             self.tr("Saving Bookmarks"),
             self.tr("""Error saving bookmarks to <b>{0}</b>.""")
             .format(bookmarkFile))
     
     # restore localized titles
     self.__menu.title = self.tr(BOOKMARKMENU)
     self.__toolbar.title = self.tr(BOOKMARKBAR)
     
     self.bookmarksSaved.emit()
コード例 #30
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)))
                    self.__populateCache()
                    self.changed.emit()
        elif not fileName.endswith("_custom"):
            self.__lastUpdate = QDateTime()

        self.checkForUpdate()
コード例 #31
0
    def __registerDocumentations(self, fileNames):
        """
        Private method to register a given list of documentations.
        
        @param fileNames list of documentation files to be registered
        @type list of str
        """
        for fileName in fileNames:
            ns = QHelpEngineCore.namespaceName(fileName)
            if not ns:
                E5MessageBox.warning(
                    self, self.tr("Add Documentation"),
                    self.tr("""The file <b>{0}</b> is not a valid"""
                            """ Qt Help File.""").format(fileName))
                continue

            if len(self.documentsList.findItems(ns, Qt.MatchFixedString)):
                E5MessageBox.warning(
                    self, self.tr("Add Documentation"),
                    self.tr(
                        """The namespace <b>{0}</b> is already registered.""").
                    format(ns))
                continue

            self.__engine.registerDocumentation(fileName)
            self.documentsList.addItem(ns)
            self.__registeredDocs.append(ns)
            if ns in self.__unregisteredDocs:
                self.__unregisteredDocs.remove(ns)

        self.__initFiltersTab()
コード例 #32
0
 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.__obsoleteItem = None
     
     self.__newItems = 0
     self.__updateLocalItems = 0
     self.__updateRemoteItems = 0
     
     self.downloadProgress.setValue(0)
     
     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)
     
     self.newLabel.setText(self.tr("New: <b>{0}</b>")
                           .format(self.__newItems))
     self.updateLocalLabel.setText(self.tr("Local Updates: <b>{0}</b>")
                                   .format(self.__updateLocalItems))
     self.updateRemoteLabel.setText(self.tr("Remote Updates: <b>{0}</b>")
                                    .format(self.__updateRemoteItems))
コード例 #33
0
    def __processSearchResult(self, data):
        """
        Private method to process the search result data from PyPI.
        
        @param data result data with hits in the first element
        @type tuple
        """
        if data:
            packages = self.__transformHits(data[0])
            if packages:
                self.searchInfoLabel.setText(
                    self.tr("%n package(s) found.", "", len(packages)))
                wrapper = textwrap.TextWrapper(width=80)
                count = 0
                total = 0
                for package in packages:
                    itm = QTreeWidgetItem(self.searchResultList, [
                        package['name'].strip(), "{0:4d}".format(
                            package['score']), "\n".join([
                                wrapper.fill(line) for line in
                                package['summary'].strip().splitlines()
                            ])
                    ])
                    itm.setData(0, self.SearchVersionRole, package['version'])
                    count += 1
                    total += 1
                    if count == 100:
                        count = 0
                        QApplication.processEvents()
            else:
                QApplication.restoreOverrideCursor()
                E5MessageBox.warning(
                    self, self.tr("Search PyPI"),
                    self.tr("""<p>The package search did not return"""
                            """ anything.</p>"""))
                self.searchInfoLabel.setText(
                    self.tr("""<p>The package search did not return"""
                            """ anything.</p>"""))
        else:
            QApplication.restoreOverrideCursor()
            E5MessageBox.warning(
                self, self.tr("Search PyPI"),
                self.tr("""<p>The package search did not return anything."""
                        """</p>"""))
            self.searchInfoLabel.setText(
                self.tr("""<p>The package search did not return anything."""
                        """</p>"""))

        header = self.searchResultList.header()
        self.searchResultList.sortItems(1, Qt.DescendingOrder)
        header.setStretchLastSection(False)
        header.resizeSections(QHeaderView.ResizeToContents)
        headerSize = 0
        for col in range(header.count()):
            headerSize += header.sectionSize(col)
        if headerSize < header.width():
            header.setStretchLastSection(True)

        self.__finishSearch()
コード例 #34
0
ファイル: queues.py プロジェクト: skeptycal/eric6-20.3
    def hgQueueDeletePurgeActivateQueue(self, name, operation):
        """
        Public method to delete the reference to a queue and optionally
        remove the patch directory or set the active queue.
        
        @param name file/directory name (string)
        @param operation operation to be performed (Queues.QUEUE_DELETE,
            Queues.QUEUE_PURGE, Queues.QUEUE_ACTIVATE)
        @exception ValueError raised to indicate an invalid operation
        """
        # find the root of the repo
        repodir = self.vcs.splitPath(name)[0]
        while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
            repodir = os.path.dirname(repodir)
            if os.path.splitdrive(repodir)[1] == os.sep:
                return

        if operation == Queues.QUEUE_PURGE:
            title = self.tr("Purge Queue")
        elif operation == Queues.QUEUE_DELETE:
            title = self.tr("Delete Queue")
        elif operation == Queues.QUEUE_ACTIVATE:
            title = self.tr("Activate Queue")
        else:
            raise ValueError("illegal value for operation")

        from .HgQueuesQueueManagementDialog import (
            HgQueuesQueueManagementDialog)
        dlg = HgQueuesQueueManagementDialog(
            HgQueuesQueueManagementDialog.QUEUE_INPUT, title, True, repodir,
            self.vcs)
        if dlg.exec_() == QDialog.Accepted:
            queueName = dlg.getData()
            if queueName:
                args = self.vcs.initCommand("qqueue")
                if operation == Queues.QUEUE_PURGE:
                    args.append("--purge")
                elif operation == Queues.QUEUE_DELETE:
                    args.append("--delete")
                args.append(queueName)

                client = self.vcs.getClient()
                error = client.runcommand(args)[1]

                if error:
                    if operation == Queues.QUEUE_PURGE:
                        errMsg = self.tr("Error while purging the queue.")
                    elif operation == Queues.QUEUE_DELETE:
                        errMsg = self.tr("Error while deleting the queue.")
                    elif operation == Queues.QUEUE_ACTIVATE:
                        errMsg = self.tr(
                            "Error while setting the active queue.")
                    E5MessageBox.warning(
                        None, title,
                        """<p>{0}</p><p>{1}</p>""".format(errMsg, error))
                else:
                    if (self.queuesListQueuesDialog is not None
                            and self.queuesListQueuesDialog.isVisible()):
                        self.queuesListQueuesDialog.refresh()
コード例 #35
0
    def __saveScriptToDevice(self, scriptName=""):
        """
        Private method to save the current script onto the connected
        device.
        
        @param scriptName name of the file on the device
        @type str
        """
        aw = e5App().getObject("ViewManager").activeWindow()
        if not aw:
            return

        if scriptName:
            title = self.tr("Save Script as '{0}'").format(scriptName)
        else:
            title = self.tr("Save Script")

        if not (aw.isPyFile() or aw.isMicroPythonFile()):
            yes = E5MessageBox.yesNo(
                self.microPython, title,
                self.tr("""The current editor does not contain a Python"""
                        """ script. Write it anyway?"""))
            if not yes:
                return

        script = aw.text().strip()
        if not script:
            E5MessageBox.warning(self.microPython, title,
                                 self.tr("""The script is empty. Aborting."""))
            return

        if not scriptName:
            scriptName = os.path.basename(aw.getFileName())
            scriptName, ok = QInputDialog.getText(
                self.microPython, title,
                self.tr("Enter a file name on the device:"), QLineEdit.Normal,
                scriptName)
            if not ok or not bool(scriptName):
                return

            title = self.tr("Save Script as '{0}'").format(scriptName)

        commands = [
            "fd = open('{0}', 'wb')".format(scriptName),
            "f = fd.write",
        ]
        for line in script.splitlines():
            commands.append("f(" + repr(line + "\n") + ")")
        commands.append("fd.close()")
        out, err = self.microPython.commandsInterface().execute(commands)
        if err:
            E5MessageBox.critical(
                self.microPython, title,
                self.tr("""<p>The script could not be saved to the"""
                        """ device.</p><p>Reason: {0}</p>""").format(
                            err.decode("utf-8")))

        # reset the device
        self.__resetDevice()
コード例 #36
0
 def __load(self):
     """
     Private method to load the saved history entries from disk.
     """
     historyFile = QFile(self.getFileName())
     if not historyFile.exists():
         return
     if not historyFile.open(QIODevice.ReadOnly):
         E5MessageBox.warning(
             None,
             self.tr("Loading History"),
             self.tr(
                 """<p>Unable to open history file <b>{0}</b>.<br/>"""
                 """Reason: {1}</p>""")
             .format(historyFile.fileName, historyFile.errorString()))
         return
     
     history = []
     
     # double check, that the history file is sorted as it is read
     needToSort = False
     lastInsertedItem = HistoryEntry()
     data = QByteArray(historyFile.readAll())
     stream = QDataStream(data, QIODevice.ReadOnly)
     stream.setVersion(QDataStream.Qt_4_6)
     while not stream.atEnd():
         ver = stream.readUInt32()
         if ver != HISTORY_VERSION:
             continue
         itm = HistoryEntry()
         itm.url = Utilities.readStringFromStream(stream)
         stream >> itm.dateTime
         itm.title = Utilities.readStringFromStream(stream)
         
         if not itm.dateTime.isValid():
             continue
         
         if itm == lastInsertedItem:
             if not lastInsertedItem.title and len(history) > 0:
                 history[0].title = itm.title
             continue
         
         if not needToSort and history and lastInsertedItem < itm:
             needToSort = True
         
         history.insert(0, itm)
         lastInsertedItem = itm
     historyFile.close()
     
     if needToSort:
         history.sort()
     
     self.setHistory(history, True)
     
     # if the history had to be sorted, rewrite the history sorted
     if needToSort:
         self.__lastSavedUrl = ""
         self.__saveTimer.changeOccurred()
コード例 #37
0
ファイル: HistoryManager.py プロジェクト: testmana2/test
    def __load(self):
        """
        Private method to load the saved history entries from disk.
        """
        historyFile = QFile(self.getFileName())
        if not historyFile.exists():
            return
        if not historyFile.open(QIODevice.ReadOnly):
            E5MessageBox.warning(
                None,
                self.tr("Loading History"),
                self.tr("""<p>Unable to open history file <b>{0}</b>.<br/>""" """Reason: {1}</p>""").format(
                    historyFile.fileName, historyFile.errorString()
                ),
            )
            return

        history = []

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

            if not itm.dateTime.isValid():
                continue

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

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

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

        if needToSort:
            history.sort()

        self.setHistory(history, True)

        # if the history had to be sorted, rewrite the history sorted
        if needToSort:
            self.__lastSavedUrl = ""
            self.__saveTimer.changeOccurred()
コード例 #38
0
 def __doSearch(self):
     """
     Private method to search for packages.
     """
     self.searchResultList.clear()
     pattern = self.searchEdit.text()
     if pattern:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         QApplication.processEvents()
         
         if CondaInterface.condaVersion() >= (4, 4, 0):
             prefix = ""
         else:
             prefix = self.environmentsComboBox.itemData(
                 self.environmentsComboBox.currentIndex())
         ok, result = self.__conda.searchPackages(
             pattern,
             fullNameOnly=self.fullNameButton.isChecked(),
             packageSpec=self.packageSpecButton.isChecked(),
             platform=self.platformComboBox.currentText(),
             prefix=prefix,
         )
         
         if result:
             if ok:
                 self.searchResultList.setUpdatesEnabled(False)
                 for package in result:
                     itm = QTreeWidgetItem(self.searchResultList, [package])
                     itm.setExpanded(False)
                     for detail in result[package]:
                         version = detail["version"]
                         build = detail["build"]
                         if "subdir" in detail:
                             platform = detail["subdir"]
                         elif "platform" in detail:
                             platform = detail["platform"]
                         else:
                             platform = ""
                         citm = QTreeWidgetItem(
                             itm, ["", version, build, platform])
                         citm.setData(0, self.PackageDetailedDataRole,
                                      detail)
             
                 self.searchResultList.sortItems(0, Qt.AscendingOrder)
                 self.searchResultList.resizeColumnToContents(0)
                 self.searchResultList.setUpdatesEnabled(True)
             else:
                 QApplication.restoreOverrideCursor()
                 try:
                     message = result["message"]
                 except KeyError:
                     message = result["error"]
                 E5MessageBox.warning(
                     self,
                     self.tr("Conda Search Package Error"),
                     message)
         QApplication.restoreOverrideCursor()
コード例 #39
0
    def addEngineFromForm(self, res, view):
        """
        Public method to add a new search engine from a form.
        
        @param res result of the JavaScript run on by
            WebBrowserView.__addSearchEngine()
        @type dict or None
        @param view reference to the web browser view
        @type WebBrowserView
        """
        if not res:
            return

        method = res["method"]
        actionUrl = QUrl(res["action"])
        inputName = res["inputName"]

        if method != "get":
            E5MessageBox.warning(
                self, self.tr("Method not supported"),
                self.tr("""{0} method is not supported.""").format(
                    method.upper()))
            return

        if actionUrl.isRelative():
            actionUrl = view.url().resolved(actionUrl)

        searchUrlQuery = QUrlQuery(actionUrl)
        searchUrlQuery.addQueryItem(inputName, "{searchTerms}")

        inputFields = res["inputs"]
        for inputField in inputFields:
            name = inputField[0]
            value = inputField[1]

            if not name or name == inputName or not value:
                continue

            searchUrlQuery.addQueryItem(name, value)

        engineName, ok = QInputDialog.getText(
            view, self.tr("Engine name"),
            self.tr("Enter a name for the engine"), QLineEdit.Normal)
        if not ok:
            return

        actionUrl.setQuery(searchUrlQuery)

        from .OpenSearchEngine import OpenSearchEngine
        engine = OpenSearchEngine()
        engine.setName(engineName)
        engine.setDescription(engineName)
        engine.setSearchUrlTemplate(
            actionUrl.toDisplayString(QUrl.FullyDecoded))
        engine.setImage(view.icon().pixmap(16, 16).toImage())

        self.__addEngineByEngine(engine)
コード例 #40
0
ファイル: PluginManager.py プロジェクト: Darriall/eric
 def __downloadRepositoryFileDone(self):
     """
     Private method called after the repository file was downloaded.
     """
     reply = self.sender()
     if reply in self.__replies:
         self.__replies.remove(reply)
     if reply.error() != QNetworkReply.NoError:
         E5MessageBox.warning(
             None,
             self.tr("Error downloading file"),
             self.tr(
                 """<p>Could not download the requested file"""
                 """ from {0}.</p><p>Error: {1}</p>"""
             ).format(Preferences.getUI("PluginRepositoryUrl6"),
                      reply.errorString())
         )
         return
     
     ioDevice = QFile(self.pluginRepositoryFile + ".tmp")
     ioDevice.open(QIODevice.WriteOnly)
     ioDevice.write(reply.readAll())
     ioDevice.close()
     if QFile.exists(self.pluginRepositoryFile):
         QFile.remove(self.pluginRepositoryFile)
     ioDevice.rename(self.pluginRepositoryFile)
     
     if os.path.exists(self.pluginRepositoryFile):
         f = QFile(self.pluginRepositoryFile)
         if f.open(QIODevice.ReadOnly):
             # save current URL
             url = Preferences.getUI("PluginRepositoryUrl6")
             
             # read the repository file
             from E5XML.PluginRepositoryReader import PluginRepositoryReader
             reader = PluginRepositoryReader(f, self.checkPluginEntry)
             reader.readXML()
             if url != Preferences.getUI("PluginRepositoryUrl6"):
                 # redo if it is a redirect
                 self.checkPluginUpdatesAvailable()
                 return
             
             if self.__updateAvailable:
                 res = E5MessageBox.information(
                     None,
                     self.tr("New plugin versions available"),
                     self.tr("<p>There are new plug-ins or plug-in"
                             " updates available. Use the plug-in"
                             " repository dialog to get them.</p>"),
                     E5MessageBox.StandardButtons(
                         E5MessageBox.Ignore |
                         E5MessageBox.Open),
                     E5MessageBox.Open)
                 if res == E5MessageBox.Open:
                     self.__ui.showPluginsAvailable()
コード例 #41
0
 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)
コード例 #42
0
 def __applyGuards(self):
     """
     Private slot to apply the defined guards to the current patch.
     """
     if self.__dirtyList:
         guardsList = []
         for row in range(self.guardsList.count()):
             itm = self.guardsList.item(row)
             guard = itm.data(Qt.UserRole) + itm.text()
             guardsList.append(guard)
         
         args = self.vcs.initCommand("qguard")
         args.append(self.patchNameLabel.text())
         if guardsList:
             args.append("--")
             args.extend(guardsList)
         else:
             args.append("--none")
         
         error = ""
         if self.__hgClient:
             error = self.__hgClient.runcommand(args)[1]
         else:
             process = QProcess()
             process.setWorkingDirectory(self.__repodir)
             process.start('hg', args)
             procStarted = process.waitForStarted(5000)
             if procStarted:
                 finished = process.waitForFinished(30000)
                 if finished:
                     if process.exitCode() != 0:
                         error = str(process.readAllStandardError(),
                                     self.vcs.getEncoding(), 'replace')
                 else:
                     E5MessageBox.warning(
                         self,
                         self.tr("Apply Guard Definitions"),
                         self.tr(
                             """The Mercurial process did not finish"""
                             """ in time."""))
         
         if error:
             E5MessageBox.warning(
                 self,
                 self.tr("Apply Guard Definitions"),
                 self.tr("""<p>The defined guards could not be"""
                         """ applied.</p><p>Reason: {0}</p>""")
                 .format(error))
         else:
                         self.__dirtyList = False
                         self.on_patchSelector_activated(
                             self.patchNameLabel.text())
コード例 #43
0
ファイル: SqlBrowser.py プロジェクト: pycom/EricShort
 def __uiStartUp(self):
     """
     Private slot to do some actions after the UI has started and the main
     loop is up.
     """
     for warning in self.__warnings:
         E5MessageBox.warning(
             self,
             self.tr("SQL Browser startup problem"),
             warning)
     
     if len(QSqlDatabase.connectionNames()) == 0:
         self.__browser.addConnectionByDialog()
コード例 #44
0
 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)
コード例 #45
0
ファイル: IconEditorGrid.py プロジェクト: testmana2/test
 def editPaste(self, pasting=False):
     """
     Public slot to paste an image from the clipboard.
     
     @param pasting flag indicating part two of the paste operation
         (boolean)
     """
     img, ok = self.__clipboardImage()
     if ok:
         if img.width() > self.__image.width() or \
                 img.height() > self.__image.height():
             res = E5MessageBox.yesNo(
                 self,
                 self.tr("Paste"),
                 self.tr(
                     """<p>The clipboard image is larger than the"""
                     """ current image.<br/>Paste as new image?</p>"""))
             if res:
                 self.editPasteAsNew()
             return
         elif not pasting:
             self.__isPasting = True
             self.__clipboardSize = img.size()
         else:
             cmd = IconEditCommand(self, self.tr("Paste Clipboard"),
                                   self.__image)
             self.__markImage.fill(self.NoMarkColor.rgba())
             painter = QPainter(self.__image)
             painter.setPen(self.penColor())
             painter.setCompositionMode(self.__compositingMode)
             painter.drawImage(
                 self.__pasteRect.x(), self.__pasteRect.y(), img, 0, 0,
                 self.__pasteRect.width() + 1,
                 self.__pasteRect.height() + 1)
             
             self.__undoStack.push(cmd)
             cmd.setAfterImage(self.__image)
             
             self.__updateImageRect(
                 self.__pasteRect.topLeft(),
                 self.__pasteRect.bottomRight() + QPoint(1, 1))
     else:
         E5MessageBox.warning(
             self,
             self.tr("Pasting Image"),
             self.tr("""Invalid image data in clipboard."""))
コード例 #46
0
ファイル: TRPreviewer.py プロジェクト: pycom/EricShort
 def loadTransFile(self, transFileName):
     """
     Public slot to load a translation file.
     
     @param transFileName file name of the translation file (string)
     @return reference to the new translator object (QTranslator)
     """
     tr = QTranslator()
     if tr.load(transFileName):
         return tr
     
     E5MessageBox.warning(
         self.parent(),
         self.tr("Load Translator"),
         self.tr("""<p>The translation file <b>{0}</b> could"""
                 """ not be loaded.</p>""").format(transFileName))
     return None
コード例 #47
0
ファイル: PageScreenDialog.py プロジェクト: Darriall/eric
 def __savePageScreen(self):
     """
     Private slot to save the page screen.
     
     @return flag indicating success (boolean)
     """
     fileName = E5FileDialog.getSaveFileName(
         self,
         self.tr("Save Page Screen"),
         self.tr("screen.png"),
         self.tr("Portable Network Graphics File (*.png)"),
         E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
     if not fileName:
         return False
     
     if QFileInfo(fileName).exists():
         res = E5MessageBox.yesNo(
             self,
             self.tr("Save Page Screen"),
             self.tr("<p>The file <b>{0}</b> already exists."
                     " Overwrite it?</p>").format(fileName),
             icon=E5MessageBox.Warning)
         if not res:
             return False
     
     file = QFile(fileName)
     if not file.open(QFile.WriteOnly):
         E5MessageBox.warning(
             self,
             self.tr("Save Page Screen"),
             self.tr("Cannot write file '{0}:\n{1}.")
             .format(fileName, file.errorString()))
         return False
     
     res = self.__pagePixmap.save(file)
     file.close()
     
     if not res:
         E5MessageBox.warning(
             self,
             self.tr("Save Page Screen"),
             self.tr("Cannot write file '{0}:\n{1}.")
             .format(fileName, file.errorString()))
         return False
     
     return True
コード例 #48
0
ファイル: XMLStreamReaderBase.py プロジェクト: testmana2/test
 def showErrorMessage(self):
     """
     Public method to show an error message.
     """
     if self.hasError():
         msg = QCoreApplication.translate(
             "XMLStreamReaderBase",
             "<p>XML parse error in file <b>{0}</b>, line {1},"
             " column {2}</p><p>Error: {3}</p>").format(
             self.device().fileName(),
             self.lineNumber(), self.columnNumber(),
             self.errorString())
         E5MessageBox.warning(
             None,
             QCoreApplication.translate(
                 "XMLStreamReaderBase", "XML parse error"),
             msg)
コード例 #49
0
ファイル: SqlBrowserWidget.py プロジェクト: testmana2/eric
    def addConnectionByDialog(self):
        """
        Public slot to add a database connection via an input dialog.
        """
        from .SqlConnectionDialog import SqlConnectionDialog

        dlg = SqlConnectionDialog(self)
        if dlg.exec_() == QDialog.Accepted:
            driver, dbName, user, password, host, port = dlg.getData()
            err = self.addConnection(driver, dbName, user, password, host, port)

            if err.type() != QSqlError.NoError:
                E5MessageBox.warning(
                    self,
                    self.tr("Unable to open database"),
                    self.tr("""An error occurred while opening the connection."""),
                )
コード例 #50
0
ファイル: FeedsDialog.py プロジェクト: pycom/EricShort
 def __addFeed(self):
     """
     Private slot to add a RSS feed.
     """
     button = self.sender()
     urlString = button.feed[1]
     url = QUrl(urlString)
     if not url.host():
         if not urlString.startswith("/"):
             urlString = "/" + urlString
         urlString = self.__browser.url().host() + urlString
         tmpUrl = QUrl(urlString)
         if not tmpUrl.scheme():
             urlString = "http://" + urlString
         tmpUrl = QUrl(urlString)
         if not tmpUrl.scheme() or not tmpUrl.host():
             return
     if not url.isValid():
         return
     
     if button.feed[0]:
         title = button.feed[0]
     else:
         title = self.__browser.url().host()
     
     import Helpviewer.HelpWindow
     feedsManager = Helpviewer.HelpWindow.HelpWindow.feedsManager()
     if feedsManager.addFeed(urlString, title, self.__browser.icon()):
         if Helpviewer.HelpWindow.HelpWindow.notificationsEnabled():
             Helpviewer.HelpWindow.HelpWindow.showNotification(
                 UI.PixmapCache.getPixmap("rss48.png"),
                 self.tr("Add RSS Feed"),
                 self.tr("""The feed was added successfully."""))
         else:
             E5MessageBox.information(
                 self,
                 self.tr("Add RSS Feed"),
                 self.tr("""The feed was added successfully."""))
     else:
         E5MessageBox.warning(
             self,
             self.tr("Add RSS Feed"),
             self.tr("""The feed was already added before."""))
         
     self.close()
コード例 #51
0
 def on_serversImportButton_clicked(self):
     """
     Private slot to import server certificates.
     """
     certs = self.__importCertificate()
     if certs:
         server = "*"
         certificateDict = Preferences.toDict(
             Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
         if server in certificateDict:
             sCerts = QSslCertificate.fromData(certificateDict[server])
         else:
             sCerts = []
         
         pems = QByteArray()
         for cert in certs:
             if cert in sCerts:
                 if qVersion() >= "5.0.0":
                     commonStr = ", ".join(
                         cert.subjectInfo(QSslCertificate.CommonName))
                 else:
                     commonStr = cert.subjectInfo(
                         QSslCertificate.CommonName)
                 E5MessageBox.warning(
                     self,
                     self.tr("Import Certificate"),
                     self.tr(
                         """<p>The certificate <b>{0}</b> already exists."""
                         """ Skipping.</p>""")
                     .format(Utilities.decodeString(commonStr)))
             else:
                 pems.append(cert.toPem() + '\n')
         if server not in certificateDict:
             certificateDict[server] = QByteArray()
         certificateDict[server].append(pems)
         Preferences.Prefs.settings.setValue(
             "Ssl/CaCertificatesDict",
             certificateDict)
         
         self.serversCertificatesTree.clear()
         self.__populateServerCertificatesTree()
         
         self.__updateDefaultConfiguration()
コード例 #52
0
ファイル: PixmapDiagram.py プロジェクト: testmana2/test
 def __showPixmap(self, filename):
     """
     Private method to show a file.
     
     @param filename name of the file to be shown (string)
     @return flag indicating success (boolean)
     """
     image = QImage(filename)
     if image.isNull():
         E5MessageBox.warning(
             self,
             self.tr("Pixmap-Viewer"),
             self.tr(
                 """<p>The file <b>{0}</b> cannot be displayed."""
                 """ The format is not supported.</p>""").format(filename))
         return False
     
     self.pixmapLabel.setPixmap(QPixmap.fromImage(image))
     self.pixmapLabel.adjustSize()
     return True
コード例 #53
0
ファイル: __init__.py プロジェクト: paulmadore/Eric-IDE
def __getMasterPassword():
    """
    Private module function to get the password from the user.
    """
    global MasterPassword
    
    pw, ok = QInputDialog.getText(
        None,
        QCoreApplication.translate("Crypto", "Master Password"),
        QCoreApplication.translate("Crypto", "Enter the master password:"******"MasterPassword")
        try:
            if masterPassword:
                if verifyPassword(pw, masterPassword):
                    MasterPassword = pwEncode(pw)
                else:
                    E5MessageBox.warning(
                        None,
                        QCoreApplication.translate(
                            "Crypto", "Master Password"),
                        QCoreApplication.translate(
                            "Crypto",
                            """The given password is incorrect."""))
            else:
                E5MessageBox.critical(
                    None,
                    QCoreApplication.translate("Crypto", "Master Password"),
                    QCoreApplication.translate(
                        "Crypto",
                        """There is no master password registered."""))
        except ValueError as why:
            E5MessageBox.warning(
                None,
                QCoreApplication.translate("Crypto", "Master Password"),
                QCoreApplication.translate(
                    "Crypto",
                    """<p>The given password cannot be verified.</p>"""
                    """<p>Reason: {0}""".format(str(why))))
コード例 #54
0
ファイル: Browser.py プロジェクト: pycom/EricShort
 def __showMimeType(self):
     """
     Private slot to show the mime type of the selected entry.
     """
     itmList = self.getSelectedItems(
         [BrowserFileItem, BrowserClassItem,
          BrowserMethodItem, BrowserClassAttributeItem,
          BrowserImportItem])
     if itmList:
         mimetype = Utilities.MimeTypes.mimeType(itmList[0].fileName())
         if mimetype is None:
             E5MessageBox.warning(
                 self,
                 self.tr("Show Mime-Type"),
                 self.tr("""The mime type of the file could not be"""
                         """ determined."""))
         elif mimetype.split("/")[0] == "text":
             E5MessageBox.information(
                 self,
                 self.tr("Show Mime-Type"),
                 self.tr("""The file has the mime type <b>{0}</b>.""")
                 .format(mimetype))
         else:
             textMimeTypesList = Preferences.getUI("TextMimeTypes")
             if mimetype in textMimeTypesList:
                 E5MessageBox.information(
                     self,
                     self.tr("Show Mime-Type"),
                     self.tr("""The file has the mime type <b>{0}</b>.""")
                     .format(mimetype))
             else:
                 ok = E5MessageBox.yesNo(
                     self,
                     self.tr("Show Mime-Type"),
                     self.tr("""The file has the mime type <b>{0}</b>."""
                             """<br/> Shall it be added to the list of"""
                             """ text mime types?""").format(mimetype))
                 if ok:
                     textMimeTypesList.append(mimetype)
                     Preferences.setUI("TextMimeTypes", textMimeTypesList)
コード例 #55
0
ファイル: UserAgentManager.py プロジェクト: testmana2/test
 def __load(self):
     """
     Private method to load the saved user agent settings.
     """
     agentFile = self.getFileName()
     if not os.path.exists(agentFile):
         self.__loadNonXml(os.path.splitext(agentFile)[0])
     else:
         from .UserAgentReader import UserAgentReader
         reader = UserAgentReader()
         self.__agents = reader.read(agentFile)
         if reader.error() != QXmlStreamReader.NoError:
             E5MessageBox.warning(
                 None,
                 self.tr("Loading user agent data"),
                 self.tr("""Error when loading user agent data on"""
                         """ line {0}, column {1}:\n{2}""")
                 .format(reader.lineNumber(),
                         reader.columnNumber(),
                         reader.errorString()))
     
     self.__loaded = True
コード例 #56
0
 def on_addButton_clicked(self):
     """
     Private slot to add documents to the help database.
     """
     fileNames = E5FileDialog.getOpenFileNames(
         self,
         self.tr("Add Documentation"),
         "",
         self.tr("Qt Compressed Help Files (*.qch)"))
     if not fileNames:
         return
     
     for fileName in fileNames:
         ns = QHelpEngineCore.namespaceName(fileName)
         if not ns:
             E5MessageBox.warning(
                 self,
                 self.tr("Add Documentation"),
                 self.tr(
                     """The file <b>{0}</b> is not a valid"""
                     """ Qt Help File.""").format(fileName)
             )
             continue
         
         if len(self.documentsList.findItems(ns, Qt.MatchFixedString)):
             E5MessageBox.warning(
                 self,
                 self.tr("Add Documentation"),
                 self.tr(
                     """The namespace <b>{0}</b> is already registered.""")
                 .format(ns)
             )
             continue
         
         self.__engine.registerDocumentation(fileName)
         self.documentsList.addItem(ns)
         self.__registeredDocs.append(ns)
         if ns in self.__unregisteredDocs:
             self.__unregisteredDocs.remove(ns)
コード例 #57
0
ファイル: TRPreviewer.py プロジェクト: pycom/EricShort
 def loadWidget(self, uiFileName):
     """
     Public slot to load a UI file.
     
     @param uiFileName name of the UI file to load (string)
     """
     wview = self.__findWidget(uiFileName)
     if wview is None:
         name = os.path.basename(uiFileName)
         if not name:
             E5MessageBox.warning(
                 self,
                 self.tr("Load UI File"),
                 self.tr(
                     """<p>The file <b>{0}</b> could not be loaded.</p>""")
                 .format(uiFileName))
             return
         
         uname = name
         cnt = 1
         while self.findChild(WidgetView, uname) is not None:
             cnt += 1
             uname = "{0} <{1}>".format(name, cnt)
         name = uname
         
         wview = WidgetView(uiFileName, self, name)
         wview.buildWidget()
         if not wview.isValid():
             del wview
             return
         
         self.rebuildWidgets.connect(wview.buildWidget)  # __IGNORE_WARNING__
         wview.installEventFilter(self)  # __IGNORE_WARNING__
         
         win = self.addSubWindow(wview)  # __IGNORE_WARNING__
         self.widgets.append(win)
     
     wview.showNormal()  # __IGNORE_WARNING__
コード例 #58
0
ファイル: PasswordManager.py プロジェクト: testmana2/test
 def __load(self):
     """
     Private method to load the saved login credentials.
     """
     loginFile = self.getFileName()
     if not os.path.exists(loginFile):
         self.__loadNonXml(os.path.splitext(loginFile)[0])
     else:
         from .PasswordReader import PasswordReader
         reader = PasswordReader()
         self.__logins, self.__loginForms, self.__never = \
             reader.read(loginFile)
         if reader.error() != QXmlStreamReader.NoError:
             E5MessageBox.warning(
                 None,
                 self.tr("Loading login data"),
                 self.tr("""Error when loading login data on"""
                         """ line {0}, column {1}:\n{2}""")
                 .format(reader.lineNumber(),
                         reader.columnNumber(),
                         reader.errorString()))
     
     self.__loaded = True
コード例 #59
0
 def saveRules(self):
     """
     Public method to save the subscription rules.
     """
     fileName = self.rulesFileName()
     if not fileName:
         return
     
     f = QFile(fileName)
     if not f.open(QIODevice.ReadWrite | QIODevice.Truncate):
         E5MessageBox.warning(
             None,
             self.tr("Saving subscription rules"),
             self.tr(
                 """Unable to open adblock file '{0}' for writing.""")
             .format(fileName))
         return
     
     textStream = QTextStream(f)
     if not self.__rules or not self.__rules[0].isHeader():
         textStream << "[Adblock Plus 1.1.1]\n"
     for rule in self.__rules:
         textStream << rule.filter() << "\n"
コード例 #60
0
 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.")))