Пример #1
0
    def __receiveJson(self):
        """
        Private method to receive the data from the client.
        """
        while self.qsock and self.qsock.canReadLine():
            line = bytes(self.qsock.readLine()).decode()
            
##            print(line)          ##debug
            
            try:
                commandDict = json.loads(line.strip())
            except (TypeError, ValueError) as err:
                E5MessageBox.critical(
                    None,
                    self.tr("Single Application Protocol Error"),
                    self.tr("""<p>The response received from the single"""
                            """ application client could not be decoded."""
                            """ Please report this issue with the received"""
                            """ data to the eric bugs email address.</p>"""
                            """<p>Error: {0}</p>"""
                            """<p>Data:<br/>{1}</p>""").format(
                        str(err), Utilities.html_encode(line.strip())),
                    E5MessageBox.StandardButtons(
                        E5MessageBox.Ok))
                return
            
            command = commandDict["command"]
            arguments = commandDict["arguments"]
            
            self.handleCommand(command, arguments)
Пример #2
0
    def closeEvent(self, evt):
        """
        Protected method handling the close event.
        
        @param evt close event (QCloseEvent)
        """
        if self.__modified:
            res = E5MessageBox.question(
                self, self.tr("eric6 Snapshot"),
                self.tr("""The application contains an unsaved snapshot."""),
                E5MessageBox.StandardButtons(E5MessageBox.Abort
                                             | E5MessageBox.Discard
                                             | E5MessageBox.Save))
            if res == E5MessageBox.Abort:
                evt.ignore()
                return
            elif res == E5MessageBox.Save:
                self.on_saveButton_clicked()

        Preferences.Prefs.settings.setValue("Snapshot/Delay",
                                            self.delaySpin.value())
        Preferences.Prefs.settings.setValue(
            "Snapshot/Mode",
            self.modeCombo.itemData(self.modeCombo.currentIndex()))
        Preferences.Prefs.settings.setValue("Snapshot/Filename",
                                            self.__filename)
        Preferences.Prefs.settings.sync()
 def closeEvent(self, e):
     """
     Protected slot implementing a close event handler.
     
     @param e close event (QCloseEvent)
     """
     if self.__hgClient.isExecuting():
         self.__hgClient.cancel()
     
     if self.__dirtyList:
         res = E5MessageBox.question(
             self,
             self.tr("Unsaved Changes"),
             self.tr("""The guards list has been changed."""
                     """ Shall the changes be applied?"""),
             E5MessageBox.StandardButtons(
                 E5MessageBox.Apply |
                 E5MessageBox.Discard),
             E5MessageBox.Apply)
         if res == E5MessageBox.Apply:
             self.__applyGuards()
         else:
             self.__dirtyList = False
     
     e.accept()
Пример #4
0
    def __showDfuEnableInstructions(self, flash=True):
        """
        Private method to show some instructions to enable the DFU mode.
        
        @param flash flag indicating to show a warning message for flashing
        @type bool
        @return flag indicating OK to continue or abort
        @rtype bool
        """
        msg = self.tr("<h3>Enable DFU Mode</h3>"
                      "<p>1. Disconnect everything from your board</p>"
                      "<p>2. Disconnect your board</p>"
                      "<p>3. Connect the DFU/BOOT0 pin with a 3.3V pin</p>"
                      "<p>4. Re-connect your board</p>"
                      "<hr />")

        if flash:
            msg += self.tr(
                "<p><b>Warning:</b> Make sure that all other DFU capable"
                " devices except your PyBoard are disconnected."
                "<hr />")

        msg += self.tr("<p>Press <b>OK</b> to continue...</p>")
        res = E5MessageBox.information(
            self.microPython, self.tr("Enable DFU mode"), msg,
            E5MessageBox.StandardButtons(E5MessageBox.Abort | E5MessageBox.Ok))

        return res == E5MessageBox.Ok
Пример #5
0
    def closeEvent(self, e):
        """
        Protected slot implementing a close event handler.
        
        @param e close event (QCloseEvent)
        """
        if self.__hgClient:
            if self.__hgClient.isExecuting():
                self.__hgClient.cancel()
        else:
            if self.process is not None and \
               self.process.state() != QProcess.NotRunning:
                self.process.terminate()
                QTimer.singleShot(2000, self.process.kill)
                self.process.waitForFinished(3000)

        if self.__dirtyList:
            res = E5MessageBox.question(
                self, self.tr("Unsaved Changes"),
                self.tr("""The guards list has been changed."""
                        """ Shall the changes be applied?"""),
                E5MessageBox.StandardButtons(E5MessageBox.Apply
                                             | E5MessageBox.Discard),
                E5MessageBox.Apply)
            if res == E5MessageBox.Apply:
                self.__applyGuards()
            else:
                self.__dirtyList = False

        e.accept()
Пример #6
0
    def __addPackage(self, pkgDir):
        """
        Private method to add a package to the list.
        
        @param pkgDir name of the package directory (string)
        """
        if pkgDir:
            if "\\" in pkgDir or "/" in pkgDir:
                # It is a directory. Check for an __init__.py file.
                if os.path.isabs(pkgDir):
                    prefix = ""
                else:
                    prefix = self.packageRootEdit.text()
                initName = os.path.join(prefix,
                                        Utilities.toNativeSeparators(pkgDir),
                                        "__init__.py")
                if not os.path.exists(initName):
                    res = E5MessageBox.information(
                        self, self.tr("Add Package"),
                        self.tr("""<p>The directory <b>{0}</b> is not"""
                                """ a Python package.</p>""").format(pkgDir),
                        E5MessageBox.StandardButtons(E5MessageBox.Ignore
                                                     | E5MessageBox.Ok))
                    if res == E5MessageBox.Ok:
                        return

            pkg = pkgDir.replace(
                Utilities.toNativeSeparators(self.packageRootEdit.text()), "")
            if pkg.startswith(("\\", "/")):
                pkg = pkg[1:]
            if pkg:
                QListWidgetItem(
                    pkg.replace("\\", ".").replace("/", "."),
                    self.packagesList)
                self.packageEdit.clear()
 def on_patchSelector_activated(self, patch):
     """
     Private slot to get the list of guards defined for the given patch
     name.
     
     @param patch selected patch name (empty for current patch)
     """
     if self.__dirtyList:
         res = E5MessageBox.question(
             self,
             self.tr("Unsaved Changes"),
             self.tr("""The guards list has been changed."""
                     """ Shall the changes be applied?"""),
             E5MessageBox.StandardButtons(
                 E5MessageBox.Apply |
                 E5MessageBox.Discard),
             E5MessageBox.Apply)
         if res == E5MessageBox.Apply:
             self.__applyGuards()
         else:
             self.__dirtyList = False
     
     self.guardsList.clear()
     self.patchNameLabel.setText("")
     
     self.guardCombo.clear()
     guardsList = self.extension.getGuardsList(self.__repodir)
     self.guardCombo.addItems(guardsList)
     self.guardCombo.setEditText("")
     
     args = self.vcs.initCommand("qguard")
     if patch:
         args.append(patch)
     
     output = self.__hgClient.runcommand(args)[0]
     
     if output:
         patchName, guards = output.split(":", 1)
         self.patchNameLabel.setText(patchName)
         guardsList = guards.strip().split()
         for guard in guardsList:
             if guard.startswith("+"):
                 icon = UI.PixmapCache.getIcon("plus.png")
                 guard = guard[1:]
                 sign = "+"
             elif guard.startswith("-"):
                 icon = UI.PixmapCache.getIcon("minus.png")
                 guard = guard[1:]
                 sign = "-"
             else:
                 continue
             itm = QListWidgetItem(icon, guard, self.guardsList)
             itm.setData(Qt.UserRole, sign)
     
     self.on_guardsList_itemSelectionChanged()
Пример #8
0
 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()
Пример #9
0
    def printBrowserPdf(self, browser=None):
        """
        Public slot called to print the displayed page to PDF.
        
        @param browser reference to the browser to be printed (HelpBrowser)
        """
        if browser is None:
            browser = self.currentBrowser()

        name = WebBrowserTools.getFileNameFromUrl(browser.url())
        if name:
            name = name.rsplit('.', 1)[0]
            name += '.pdf'
        if hasattr(browser.page(), "printToPdf"):
            from .Tools.PrintToPdfDialog import PrintToPdfDialog
            if not name:
                name = "printout.pdf"
            dlg = PrintToPdfDialog(name, self)
            if dlg.exec_() == QDialog.Accepted:
                filePath, pageLayout = dlg.getData()
                if filePath:
                    if os.path.exists(filePath):
                        res = E5MessageBox.warning(
                            self, self.tr("Print to PDF"),
                            self.tr("""<p>The file <b>{0}</b> exists"""
                                    """ already. Shall it be"""
                                    """ overwritten?</p>""").format(filePath),
                            E5MessageBox.StandardButtons(E5MessageBox.No
                                                         | E5MessageBox.Yes),
                            E5MessageBox.No)
                        if res == E5MessageBox.No:
                            return
                    browser.page().printToPdf(
                        lambda pdf: self.__pdfGeneratedForSave(filePath, pdf),
                        pageLayout)
        elif Globals.isLinuxPlatform():
            printer = QPrinter(mode=QPrinter.HighResolution)
            if Preferences.getPrinter("ColorMode"):
                printer.setColorMode(QPrinter.Color)
            else:
                printer.setColorMode(QPrinter.GrayScale)
            printerName = Preferences.getPrinter("PrinterName")
            if printerName:
                printer.setPrinterName(printerName)
            printer.setOutputFormat(QPrinter.PdfFormat)
            if name:
                printer.setOutputFileName(name)
            printer.setResolution(Preferences.getPrinter("Resolution"))

            printDialog = QPrintDialog(printer, self)
            if printDialog.exec_() == QDialog.Accepted:
                browser.render(printer)
Пример #10
0
    def download(self, downloadItem):
        """
        Public method to download a file.
        
        @param downloadItem reference to the download object containing the
        download data.
        @type QWebEngineDownloadItem
        """
        url = downloadItem.url()
        if url.isEmpty():
            return

        self.__closeDownloadTab(url)

        # Safe Browsing
        from WebBrowser.SafeBrowsing.SafeBrowsingManager import (
            SafeBrowsingManager)
        if SafeBrowsingManager.isEnabled():
            threatLists = (
                WebBrowserWindow.safeBrowsingManager().lookupUrl(url)[0])
            if threatLists:
                threatMessages = (WebBrowserWindow.safeBrowsingManager().
                                  getThreatMessages(threatLists))
                res = E5MessageBox.warning(
                    WebBrowserWindow.getWindow(),
                    self.tr("Suspicuous URL detected"),
                    self.tr("<p>The URL <b>{0}</b> was found in the Safe"
                            " Browsing database.</p>{1}").format(
                                url.toString(), "".join(threatMessages)),
                    E5MessageBox.StandardButtons(E5MessageBox.Abort
                                                 | E5MessageBox.Ignore),
                    E5MessageBox.Abort)
                if res == E5MessageBox.Abort:
                    downloadItem.cancel()
                    return

        window = WebBrowserWindow.getWindow()
        if window:
            pageUrl = window.currentBrowser().url()
        else:
            pageUrl = QUrl()
        from .DownloadItem import DownloadItem
        itm = DownloadItem(downloadItem=downloadItem,
                           pageUrl=pageUrl,
                           parent=self)
        self.__addItem(itm)

        if Preferences.getWebBrowser("DownloadManagerAutoOpen"):
            self.show()
        else:
            self.__startUpdateTimer()
Пример #11
0
 def __flashCircuitPython(self):
     """
     Private slot to flash a CircuitPython firmware to the device.
     """
     ok = E5MessageBox.information(
         self.microPython, self.tr("Flash CircuitPython Firmware"),
         self.tr("Please reset the device to bootloader mode and confirm"
                 " when ready."),
         E5MessageBox.StandardButtons(E5MessageBox.Abort | E5MessageBox.Ok))
     if ok:
         from .CircuitPythonFirmwareSelectionDialog import (
             CircuitPythonFirmwareSelectionDialog)
         dlg = CircuitPythonFirmwareSelectionDialog()
         if dlg.exec_() == QDialog.Accepted:
             cpyPath, devicePath = dlg.getData()
             shutil.copy2(cpyPath, devicePath)
Пример #12
0
    def __pdfGeneratedForSave(self, filePath, pdfData):
        """
        Private slot to save the generated PDF data to a file.
        
        @param filePath path to save the PDF to
        @type str
        @param pdfData generated PDF document
        @type QByteArray
        """
        if pdfData.size() == 0:
            return

        pdfFile = QFile(filePath)
        if pdfFile.open(QFile.WriteOnly):
            pdfFile.write(pdfData)
            pdfFile.close()
        if pdfFile.error() != QFileDevice.NoError:
            E5MessageBox.critical(
                self, self.tr("Print to PDF"),
                self.tr("""<p>The PDF could not be written to file <b>{0}"""
                        """</b>.</p><p><b>Error:</b> {1}</p>""").format(
                            filePath, pdfFile.errorString()),
                E5MessageBox.StandardButtons(E5MessageBox.Ok))
    def on_bTest_clicked(self):
        """
        Private method to test the selected options.
        """
        if self.rAbout.isChecked():
            E5MessageBox.about(None, self.eCaption.text(),
                               self.eMessage.toPlainText())
        elif self.rAboutQt.isChecked():
            E5MessageBox.aboutQt(None, self.eCaption.text())
        elif self.rInformation.isChecked() or \
            self.rQuestion.isChecked() or \
            self.rWarning.isChecked() or \
                self.rCritical.isChecked():
            buttons = E5MessageBox.NoButton
            if self.abortCheck.isChecked():
                buttons |= E5MessageBox.Abort
            if self.applyCheck.isChecked():
                buttons |= E5MessageBox.Apply
            if self.cancelCheck.isChecked():
                buttons |= E5MessageBox.Cancel
            if self.closeCheck.isChecked():
                buttons |= E5MessageBox.Close
            if self.discardCheck.isChecked():
                buttons |= E5MessageBox.Discard
            if self.helpCheck.isChecked():
                buttons |= E5MessageBox.Help
            if self.ignoreCheck.isChecked():
                buttons |= E5MessageBox.Ignore
            if self.noCheck.isChecked():
                buttons |= E5MessageBox.No
            if self.notoallCheck.isChecked():
                buttons |= E5MessageBox.NoToAll
            if self.okCheck.isChecked():
                buttons |= E5MessageBox.Ok
            if self.openCheck.isChecked():
                buttons |= E5MessageBox.Open
            if self.resetCheck.isChecked():
                buttons |= E5MessageBox.Reset
            if self.restoreCheck.isChecked():
                buttons |= E5MessageBox.RestoreDefaults
            if self.retryCheck.isChecked():
                buttons |= E5MessageBox.Retry
            if self.saveCheck.isChecked():
                buttons |= E5MessageBox.Save
            if self.saveallCheck.isChecked():
                buttons |= E5MessageBox.SaveAll
            if self.yesCheck.isChecked():
                buttons |= E5MessageBox.Yes
            if self.yestoallCheck.isChecked():
                buttons |= E5MessageBox.YesToAll
            if buttons == E5MessageBox.NoButton:
                buttons = E5MessageBox.Ok

            defaultButton = self.buttonsCodeListBinary[
                self.defaultCombo.currentIndex()]

            if self.rInformation.isChecked():
                E5MessageBox.information(self, self.eCaption.text(),
                                         self.eMessage.toPlainText(),
                                         E5MessageBox.StandardButtons(buttons),
                                         defaultButton)
            elif self.rQuestion.isChecked():
                E5MessageBox.question(self, self.eCaption.text(),
                                      self.eMessage.toPlainText(),
                                      E5MessageBox.StandardButtons(buttons),
                                      defaultButton)
            elif self.rWarning.isChecked():
                E5MessageBox.warning(self, self.eCaption.text(),
                                     self.eMessage.toPlainText(),
                                     E5MessageBox.StandardButtons(buttons),
                                     defaultButton)
            elif self.rCritical.isChecked():
                E5MessageBox.critical(self, self.eCaption.text(),
                                      self.eMessage.toPlainText(),
                                      E5MessageBox.StandardButtons(buttons),
                                      defaultButton)
        elif self.rYesNo.isChecked() or \
                self.rRetryAbort.isChecked():
            if self.iconInformation.isChecked():
                icon = E5MessageBox.Information
            elif self.iconQuestion.isChecked():
                icon = E5MessageBox.Question
            elif self.iconWarning.isChecked():
                icon = E5MessageBox.Warning
            elif self.iconCritical.isChecked():
                icon = E5MessageBox.Critical

            if self.rYesNo.isChecked():
                E5MessageBox.yesNo(self,
                                   self.eCaption.text(),
                                   self.eMessage.toPlainText(),
                                   icon=icon,
                                   yesDefault=self.yesDefaultCheck.isChecked())
            elif self.rRetryAbort.isChecked():
                E5MessageBox.retryAbort(self,
                                        self.eCaption.text(),
                                        self.eMessage.toPlainText(),
                                        icon=icon)
        elif self.rOkToClearData.isChecked():
            E5MessageBox.okToClearData(self, self.eCaption.text(),
                                       self.eMessage.toPlainText(),
                                       lambda: True)
Пример #14
0
    def acceptNavigationRequest(self, url, type_, isMainFrame):
        """
        Public method to determine, if a request may be accepted.
        
        @param url URL to navigate to
        @type QUrl
        @param type_ type of the navigation request
        @type QWebEnginePage.NavigationType
        @param isMainFrame flag indicating, that the request originated from
            the main frame
        @type bool
        @return flag indicating acceptance
        @rtype bool
        """
        scheme = url.scheme()
        if scheme == "mailto":
            QDesktopServices.openUrl(url)
            return False

        # AdBlock
        if url.scheme() == "abp":
            if WebBrowserWindow.adBlockManager().addSubscriptionFromUrl(url):
                return False

        # GreaseMonkey
        if PYQT_WEBENGINE_VERSION >= 0x50e00:  # PyQtWebEngine >= 5.14.0
            navigationType = type_ in [
                QWebEnginePage.NavigationTypeLinkClicked,
                QWebEnginePage.NavigationTypeRedirect
            ]
        else:
            navigationType = type_ == QWebEnginePage.NavigationTypeLinkClicked
        if navigationType and url.toString().endswith(".user.js"):
            WebBrowserWindow.greaseMonkeyManager().downloadScript(url)
            return False

        if url.scheme() == "eric":
            if url.path() == "AddSearchProvider":
                query = QUrlQuery(url)
                self.view().mainWindow().openSearchManager().addEngine(
                    QUrl(query.queryItemValue("url")))
                return False
            elif url.path() == "PrintPage":
                self.printPageRequested.emit()
                return False

        # Safe Browsing
        self.__badSite = False
        from WebBrowser.SafeBrowsing.SafeBrowsingManager import (
            SafeBrowsingManager)
        if (SafeBrowsingManager.isEnabled() and url.scheme()
                not in SafeBrowsingManager.getIgnoreSchemes()):
            threatLists = (
                WebBrowserWindow.safeBrowsingManager().lookupUrl(url)[0])
            if threatLists:
                threatMessages = (WebBrowserWindow.safeBrowsingManager().
                                  getThreatMessages(threatLists))
                res = E5MessageBox.warning(
                    WebBrowserWindow.getWindow(),
                    self.tr("Suspicuous URL detected"),
                    self.tr("<p>The URL <b>{0}</b> was found in the Safe"
                            " Browsing database.</p>{1}").format(
                                url.toString(), "".join(threatMessages)),
                    E5MessageBox.StandardButtons(E5MessageBox.Abort
                                                 | E5MessageBox.Ignore),
                    E5MessageBox.Abort)
                if res == E5MessageBox.Abort:
                    self.safeBrowsingAbort.emit()
                    return False

                self.__badSite = True
                threatType = (
                    WebBrowserWindow.safeBrowsingManager().getThreatType(
                        threatLists[0]))
                self.safeBrowsingBad.emit(threatType, "".join(threatMessages))

        result = QWebEnginePage.acceptNavigationRequest(
            self, url, type_, isMainFrame)

        if result:
            if isMainFrame:
                isWeb = url.scheme() in ("http", "https", "ftp", "ftps",
                                         "file")
                globalJsEnabled = WebBrowserWindow.webSettings().testAttribute(
                    QWebEngineSettings.JavascriptEnabled)
                if isWeb:
                    enable = globalJsEnabled
                else:
                    enable = True
                self.settings().setAttribute(
                    QWebEngineSettings.JavascriptEnabled, enable)

                self.__channelUrl = url
                self.__setupChannelTimer.start()
            self.navigationRequestAccepted.emit(url, type_, isMainFrame)

        return result