def showCertificateChain(self, certificateChain): """ Public method to show the SSL certificates of a certificate chain. @param certificateChain list od SSL certificates (list of QSslCertificate) """ self.chainLabel.show() self.chainComboBox.show() self.chainComboBox.clear() self.__chain = certificateChain[:] for cert in self.__chain: if qVersion() >= "5.0.0": name = ", ".join(cert.subjectInfo(QSslCertificate.CommonName)) else: name = cert.subjectInfo(QSslCertificate.CommonName) if not name: if qVersion() >= "5.0.0": name = ", ".join( cert.subjectInfo(QSslCertificate.Organization)) else: name = cert.subjectInfo(QSslCertificate.Organization) if not name: name = cert.serialNumber() self.chainComboBox.addItem(name) self.on_chainComboBox_activated(0)
def version(): """Return a string with various version informations.""" lines = ["qutebrowser v{}".format(qutebrowser.__version__)] gitver = _git_str() if gitver is not None: lines.append("Git commit: {}".format(gitver)) if qVersion() != QT_VERSION_STR: qt_version = 'Qt: {} (compiled {})'.format(qVersion(), QT_VERSION_STR) else: qt_version = 'Qt: {}'.format(qVersion()) lines += [ '', '{}: {}'.format(platform.python_implementation(), platform.python_version()), qt_version, 'PyQt: {}'.format(PYQT_VERSION_STR), '', ] lines += _module_versions() lines += ['pdf.js: {}'.format(_pdfjs_version())] if qWebKitVersion is None: lines.append('Webkit: no') else: lines.append('Webkit: {}'.format(qWebKitVersion())) lines += [ 'SSL: {}'.format(QSslSocket.sslLibraryVersionString()), '', ] qapp = QApplication.instance() if qapp: style = qapp.style() lines.append('Style: {}'.format(style.metaObject().className())) importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__)) lines += [ 'Platform: {}, {}'.format(platform.platform(), platform.architecture()[0]), 'Frozen: {}'.format(hasattr(sys, 'frozen')), "Imported from {}".format(importpath), ] lines += _os_info() lines += [ '', 'Paths:', ] for name, path in _path_info().items(): lines += ['{}: {}'.format(name, path)] return '\n'.join(lines)
def __loadFinished(self, ok): """ Private slot to set some data after the page was loaded. @param ok flag indicating a successful load (boolean) """ try: if self.__browser.url().scheme() in ["eric", "about"]: self.__bookmarkButton.setVisible(False) else: self.__checkBookmark() self.__bookmarkButton.setVisible(True) if ok: self.__rssButton.setVisible(self.__browser.checkRSS()) if ok and \ self.__browser.url().scheme() == "https" and \ QSslCertificate is not None: sslInfo = self.__browser.page().getSslCertificate() if sslInfo is not None: if qVersion() >= "5.0.0": org = Utilities.decodeString(", ".join( sslInfo.subjectInfo(QSslCertificate.Organization))) else: org = Utilities.decodeString( sslInfo.subjectInfo(QSslCertificate.Organization)) if org == "": if qVersion() >= "5.0.0": cn = Utilities.decodeString(", ".join( sslInfo.subjectInfo( QSslCertificate.CommonName))) else: cn = Utilities.decodeString( sslInfo.subjectInfo( QSslCertificate.CommonName)) if cn != "": org = cn.split(".", 1)[1] if org == "": org = self.tr("Unknown") self.__sslLabel.setText(" {0} ".format(org)) self.__sslLabel.setVisible(True) if qVersion() >= "5.0.0": valid = not sslInfo.isBlacklisted() else: valid = sslInfo.isValid() if valid: config = self.__browser.page().getSslConfiguration() if config is None or config.sessionCipher().isNull(): valid = False self.__sslLabel.setValidity(valid) return self.__sslLabel.setVisible(False) except RuntimeError: pass
def check_qt_version(args): """Check if the Qt version is recent enough.""" from PyQt5.QtCore import qVersion from qutebrowser.utils import qtutils if qtutils.version_check('5.2.0', operator.lt): text = ("Fatal error: Qt and PyQt >= 5.2.0 are required, but {} is " "installed.".format(qVersion())) _die(text) elif args.backend == 'webengine' and qtutils.version_check('5.6.0', operator.lt): text = ("Fatal error: Qt and PyQt >= 5.6.0 are required for " "QtWebEngine support, but {} is installed.".format(qVersion())) _die(text)
def getDomainReport(self, domain): """ Public method to retrieve a report for a domain. @param domain domain name @type str """ self.__lastDomain = domain queryItems = [ ("apikey", Preferences.getHelp("VirusTotalServiceKey")), ("domain", domain), ] url = QUrl(self.GetDomainReportUrl) if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery query = QUrlQuery() query.setQueryItems(queryItems) url.setQuery(query) else: url.setQueryItems(queryItems) request = QNetworkRequest(url) import Helpviewer.HelpWindow nam = Helpviewer.HelpWindow.HelpWindow.networkAccessManager() reply = nam.get(request) reply.finished.connect(self.__getDomainReportFinished) self.__replies.append(reply)
def getIpAddressReport(self, ipAddress): """ Public method to retrieve a report for an IP address. @param ipAddress valid IPv4 address in dotted quad notation @type str """ self.__lastIP = ipAddress queryItems = [ ("apikey", Preferences.getHelp("VirusTotalServiceKey")), ("ip", ipAddress), ] url = QUrl(self.GetIpAddressReportUrl) if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery query = QUrlQuery() query.setQueryItems(queryItems) url.setQuery(query) else: url.setQueryItems(queryItems) request = QNetworkRequest(url) import Helpviewer.HelpWindow nam = Helpviewer.HelpWindow.HelpWindow.networkAccessManager() reply = nam.get(request) reply.finished.connect(self.__getIpAddressReportFinished) self.__replies.append(reply)
def generateVersionInfo(linesep = '\n'): """ Module function to generate a string with various version infos. @param linesep string to be used to separate lines (string) @return string with version infos (string) """ try: import sipconfig sip_version_str = sipconfig.Configuration().sip_version_str except ImportError: sip_version_str = "sip version not available" info = "Version Numbers:%s Python %s%s" % \ (linesep, sys.version.split()[0], linesep) if KdeQt.isKDEAvailable(): info += " KDE %s%s PyKDE %s%s" % \ (str(KdeQt.kdeVersionString()), linesep, str(KdeQt.pyKdeVersionString()), linesep) info += " Qt %s%s PyQt4 %s%s" % \ (str(qVersion()), linesep, str(PYQT_VERSION_STR), linesep) info += " sip %s%s QScintilla %s%s" % \ (str(sip_version_str), linesep, str(QSCINTILLA_VERSION_STR), linesep) info += " %s %s%s" % \ (Program, Version, linesep * 2) info += "Platform: %s%s%s%s" % \ (sys.platform, linesep, sys.version, linesep) return info
def suggestionsUrl(self, searchTerm): """ Public method to get a URL ready for suggestions. @param searchTerm term to search for (string) @return URL (QUrl) """ if not self._suggestionsUrlTemplate: return QUrl() ret = QUrl.fromEncoded(QByteArray(self.parseTemplate( searchTerm, self._suggestionsUrlTemplate).encode("utf-8"))) if self.__searchMethod != "post": if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery urlQuery = QUrlQuery(ret) for parameter in self._suggestionsParameters: urlQuery.addQueryItem( parameter[0], self.parseTemplate(searchTerm, parameter[1])) ret.setQuery(urlQuery) else: for parameter in self._suggestionsParameters: ret.addQueryItem( parameter[0], self.parseTemplate(searchTerm, parameter[1])) return ret
def __init__(self, lexers): """ Constructor @param lexers reference to the lexers dictionary """ super(EditorHighlightersPage, self).__init__() self.setupUi(self) self.setObjectName("EditorHighlightersPage") self.editorLexerList.headerItem().setText(self.editorLexerList.columnCount(), "") header = self.editorLexerList.header() if qVersion() >= "5.0.0": header.setSectionResizeMode(QHeaderView.ResizeToContents) else: header.setResizeMode(QHeaderView.ResizeToContents) header.setSortIndicator(0, Qt.AscendingOrder) try: self.extsep = os.extsep except AttributeError: self.extsep = "." self.extras = ["-----------", self.tr("Alternative")] languages = [""] + sorted(lexers.keys()) + self.extras self.editorLexerCombo.addItems(languages) pygmentsLexers = [""] + sorted([l[0] for l in get_all_lexers()]) self.pygmentsLexerCombo.addItems(pygmentsLexers) # set initial values lexerAssocs = Preferences.getEditorLexerAssocs() for ext in lexerAssocs: QTreeWidgetItem(self.editorLexerList, [ext, lexerAssocs[ext]]) self.editorLexerList.sortByColumn(0, Qt.AscendingOrder)
def toSecondLevelDomain(url): """ Module function to get a second level domain from the given URL. @param url URL to extract domain from (QUrl) @return name of second level domain (string) """ if qVersion() >= "4.8.0": topLevelDomain = url.topLevelDomain() urlHost = url.host() if not topLevelDomain or not urlHost: return "" domain = urlHost[:len(urlHost) - len(topLevelDomain)] if domain.count(".") == 0: return urlHost while domain.count(".") != 0: domain = domain[domain.find(".") + 1:] return domain + topLevelDomain else: domain = url.host() if domain.count(".") == 0: return "" while domain.count(".") != 1: domain = domain[domain.find(".") + 1:] return domain
def paintEvent(self, evt): """ Protected method handling a paint event. @param evt reference to the paint event (QPaintEvent) """ super(E5LineEdit, self).paintEvent(evt) if qVersion() < "4.7.0": if not self.text() and \ self.__inactiveText and \ not self.hasFocus(): panel = QStyleOptionFrame() self.initStyleOption(panel) textRect = self.style().subElementRect( QStyle.SE_LineEditContents, panel, self) textRect.adjust(2, 0, 0, 0) left = self.textMargin(self.LeftSide) right = self.textMargin(self.RightSide) textRect.adjust(left, 0, -right, 0) painter = QPainter(self) painter.setPen(self.palette().brush( QPalette.Disabled, QPalette.Text).color()) painter.drawText( textRect, Qt.AlignLeft | Qt.AlignVCenter, self.__inactiveText)
def __sourceChanged(self, url): """ Private slot to handle the sourceChanged signal of the contents pane. @param url the url that was clicked (QUrl) """ self.contents.setSource(QUrl('')) filename = url.path() if Utilities.isWindowsPlatform(): if filename.startswith("/"): filename = filename[1:] if qVersion() >= "5.0.0": ver = url.query() else: ver = bytes(url.encodedQuery()).decode() v1 = ver.split('_')[0] v2 = ver.split('_')[1] if v1 == "" or v2 == "": return self.contents.scrollToAnchor(ver) if self.sbsCheckBox.isEnabled() and self.sbsCheckBox.isChecked(): self.vcs.svnSbsDiff(filename, revisions=(v1, v2)) else: if self.diff is None: from .SvnDiffDialog import SvnDiffDialog self.diff = SvnDiffDialog(self.vcs) self.diff.show() self.diff.start(filename, [v1, v2])
def url(self): """ Public method to generate the URL for this subscription. @return AdBlock URL for the subscription (QUrl) """ url = QUrl() url.setScheme("abp") url.setPath("subscribe") queryItems = [] queryItems.append(("location", bytes(self.__location).decode())) queryItems.append(("title", self.__title)) if self.__requiresLocation and self.__requiresTitle: queryItems.append(("requiresLocation", self.__requiresLocation)) queryItems.append(("requiresTitle", self.__requiresTitle)) if not self.__enabled: queryItems.append(("enabled", "false")) if self.__lastUpdate.isValid(): queryItems.append(("lastUpdate", self.__lastUpdate.toString(Qt.ISODate))) if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery query = QUrlQuery() query.setQueryItems(queryItems) url.setQuery(query) else: url.setQueryItems(queryItems) return url
def __print(self, printer): """ Private slot to the actual printing. @param printer reference to the printer object (QPrinter) """ p = QPainter(printer) marginX = (printer.pageRect().x() - printer.paperRect().x()) // 2 marginY = (printer.pageRect().y() - printer.paperRect().y()) // 2 # double the margin on bottom of page if printer.orientation() == QPrinter.Portrait: width = printer.width() - marginX * 2 height = printer.height() - marginY * 3 else: marginX *= 2 width = printer.width() - marginX * 2 height = printer.height() - marginY * 2 if qVersion() >= "5.0.0": img = self.mainWidget.grab().toImage() else: img = QPixmap.grabWidget(self.mainWidget).toImage() self.__updateChildren(self.lastStyle) p.drawImage(marginX, marginY, img.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)) p.end()
def version(): """Return a string with various version informations.""" lines = ["qutebrowser v{}".format(qutebrowser.__version__)] gitver = _git_str() if gitver is not None: lines.append("Git commit: {}".format(gitver)) lines += [ '', '{}: {}'.format(platform.python_implementation(), platform.python_version()), 'Qt: {}, runtime: {}'.format(QT_VERSION_STR, qVersion()), 'PyQt: {}'.format(PYQT_VERSION_STR), ] lines += _module_versions() if QSslSocket is not None and QSslSocket.supportsSsl(): ssl_version = QSslSocket.sslLibraryVersionString() else: ssl_version = 'unavailable' lines += [ 'Webkit: {}'.format(qWebKitVersion()), 'Harfbuzz: {}'.format(os.environ.get('QT_HARFBUZZ', 'system')), 'SSL: {}'.format(ssl_version), '', 'Frozen: {}'.format(hasattr(sys, 'frozen')), 'Platform: {}, {}'.format(platform.platform(), platform.architecture()[0]), ] lines += _os_info() return '\n'.join(lines)
def eventFilter(self, obj, evt): """ Public method to handle some events for the tabbar. @param obj reference to the object (QObject) @param evt reference to the event object (QEvent) @return flag indicating, if the event was handled (boolean) """ if obj == self.__tabBar: if evt.type() == QEvent.MouseButtonPress: pos = evt.pos() for i in range(self.__tabBar.count()): if self.__tabBar.tabRect(i).contains(pos): break if i == self.__tabBar.currentIndex(): if self.isMinimized(): self.expand() else: self.shrink() return True elif self.isMinimized(): self.expand() elif evt.type() == QEvent.Wheel: if qVersion() >= "5.0.0": delta = evt.angleDelta().y() else: delta = evt.delta() if delta > 0: self.prevTab() else: self.nextTab() return True return QWidget.eventFilter(self, obj, evt)
def check_qt_version(): """Check if the Qt version is recent enough.""" from PyQt5.QtCore import (qVersion, QT_VERSION, PYQT_VERSION, PYQT_VERSION_STR) from pkg_resources import parse_version from qutebrowser.utils import log if (QT_VERSION < 0x050701 or PYQT_VERSION < 0x050700 or parse_version(qVersion()) < parse_version('5.7.1')): text = ("Fatal error: Qt >= 5.7.1 and PyQt >= 5.7 are required, " "but Qt {} / PyQt {} is installed.".format(qt_version(), PYQT_VERSION_STR)) _die(text) if qVersion().startswith('5.8.'): log.init.warning("Running qutebrowser with Qt 5.8 is untested and " "unsupported!")
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'EncodedPolylineExporter_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = EncodedPolylineExporterDialog(iface) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Encoded Polyline Exporter') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'EncodedPolylineExporter') self.toolbar.setObjectName(u'EncodedPolylineExporter')
def version_check(version: str, exact: bool = False, compiled: bool = True) -> bool: """Check if the Qt runtime version is the version supplied or newer. Args: version: The version to check against. exact: if given, check with == instead of >= compiled: Set to False to not check the compiled version. """ # Catch code using the old API for this assert exact not in [operator.gt, operator.lt, operator.ge, operator.le, operator.eq], exact if compiled and exact: raise ValueError("Can't use compiled=True with exact=True!") parsed = pkg_resources.parse_version(version) op = operator.eq if exact else operator.ge result = op(pkg_resources.parse_version(qVersion()), parsed) if compiled and result: # qVersion() ==/>= parsed, now check if QT_VERSION_STR ==/>= parsed. result = op(pkg_resources.parse_version(QT_VERSION_STR), parsed) if compiled and result: # FInally, check PYQT_VERSION_STR as well. result = op(pkg_resources.parse_version(PYQT_VERSION_STR), parsed) return result
def __createServerCertificateEntry(self, server, cert): """ Private method to create a server certificate entry. @param server server name of the certificate (string) @param cert certificate to insert (QSslCertificate) """ # step 1: extract the info to be shown if qVersion() >= "5.0.0": organisation = Utilities.decodeString(", ".join(cert.subjectInfo(QSslCertificate.Organization))) commonName = Utilities.decodeString(", ".join(cert.subjectInfo(QSslCertificate.CommonName))) else: organisation = Utilities.decodeString(cert.subjectInfo(QSslCertificate.Organization)) commonName = Utilities.decodeString(cert.subjectInfo(QSslCertificate.CommonName)) if organisation is None or organisation == "": organisation = self.tr("(Unknown)") if commonName is None or commonName == "": commonName = self.tr("(Unknown common name)") expiryDate = cert.expiryDate().toString("yyyy-MM-dd") # step 2: create the entry items = self.serversCertificatesTree.findItems(organisation, Qt.MatchFixedString | Qt.MatchCaseSensitive) if len(items) == 0: parent = QTreeWidgetItem(self.serversCertificatesTree, [organisation]) else: parent = items[0] itm = QTreeWidgetItem(parent, [commonName, server, expiryDate]) itm.setData(0, self.CertRole, cert.toPem())
def get_fatal_crash_dialog(debug, data): """Get a fatal crash dialog based on a crash log. If the crash is a segfault in qt_mainloop and we're on an old Qt version this is a simple error dialog which lets the user know they should upgrade if possible. If it's anything else, it's a normal FatalCrashDialog with the possibility to report the crash. Args: debug: Whether the debug flag (--debug) was given. data: The crash log data. """ errtype, frame = parse_fatal_stacktrace(data) if (qtutils.version_check('5.4') or errtype != 'Segmentation fault' or frame != 'qt_mainloop'): return FatalCrashDialog(debug, data) else: title = "qutebrowser was restarted after a fatal crash!" text = ("<b>qutebrowser was restarted after a fatal crash!</b><br/>" "Unfortunately, this crash occurred in Qt (the library " "qutebrowser uses), and your version ({}) is outdated - " "Qt 5.4 or later is recommended. Unfortuntately Debian and " "Ubuntu don't ship a newer version (yet?)...".format( qVersion())) return QMessageBox(QMessageBox.Critical, title, text, QMessageBox.Ok)
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()
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'flowTrace_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Flow Trace') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None
def _qt_version(): """Get the running Qt version. Needs to be in a function so we can do a local import easily (to not import from QtCore too early) but can patch this out easily for tests. """ from PyQt5.QtCore import qVersion return pkg_resources.parse_version(qVersion())
def check_qt_version(): """Check if the Qt version is recent enough.""" from PyQt5.QtCore import qVersion from qutebrowser.utils import qtutils if qtutils.version_check('5.2.0', operator.lt): text = ("Fatal error: Qt and PyQt >= 5.2.0 are required, but {} is " "installed.".format(qVersion())) _die(text)
def qapp_args(): """Make QtWebEngine unit tests run on Qt 5.7.1. See https://github.com/qutebrowser/qutebrowser/issues/3163 """ if qVersion() == '5.7.1': return [sys.argv[0], '--disable-seccomp-filter-sandbox'] return []
def version_check(version, op=operator.ge): """Check if the Qt runtime version is the version supplied or newer. Args: version: The version to check against. op: The operator to use for the check. """ return op(Version(qVersion()), Version(version))
def version(): """Return a string with various version informations.""" lines = ["qutebrowser v{}".format(qutebrowser.__version__)] gitver = _git_str() if gitver is not None: lines.append("Git commit: {}".format(gitver)) if qVersion() != QT_VERSION_STR: qt_version = "Qt: {} (compiled {})".format(qVersion(), QT_VERSION_STR) else: qt_version = "Qt: {}".format(qVersion()) lines += [ "", "{}: {}".format(platform.python_implementation(), platform.python_version()), qt_version, "PyQt: {}".format(PYQT_VERSION_STR), "", ] lines += _module_versions() lines += ["pdf.js: {}".format(_pdfjs_version())] if qWebKitVersion is None: lines.append("Webkit: no") else: lines.append("Webkit: {}".format(qWebKitVersion())) lines += ["SSL: {}".format(QSslSocket.sslLibraryVersionString()), ""] qapp = QApplication.instance() if qapp: style = qapp.style() lines.append("Style: {}".format(style.metaObject().className())) importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__)) lines += [ "Platform: {}, {}".format(platform.platform(), platform.architecture()[0]), "Frozen: {}".format(hasattr(sys, "frozen")), "Imported from {}".format(importpath), ] lines += _os_info() return "\n".join(lines)
def __parseUrl(self, url): """ Private method to parse the AdBlock URL for the subscription. @param url AdBlock URL for the subscription (QUrl) """ if url.scheme() != "abp": return if url.path() != "subscribe": return if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery urlQuery = QUrlQuery(url) self.__title = urlQuery.queryItemValue("title") self.__enabled = urlQuery.queryItemValue("enabled") != "false" self.__location = QByteArray(urlQuery.queryItemValue("location")) # Check for required subscription self.__requiresLocation = urlQuery.queryItemValue( "requiresLocation") self.__requiresTitle = urlQuery.queryItemValue("requiresTitle") if self.__requiresLocation and self.__requiresTitle: import Helpviewer.HelpWindow Helpviewer.HelpWindow.HelpWindow.adBlockManager()\ .loadRequiredSubscription(self.__requiresLocation, self.__requiresTitle) lastUpdateString = urlQuery.queryItemValue("lastUpdate") self.__lastUpdate = QDateTime.fromString(lastUpdateString, Qt.ISODate) else: self.__title = \ QUrl.fromPercentEncoding(url.encodedQueryItemValue("title")) self.__enabled = QUrl.fromPercentEncoding( url.encodedQueryItemValue("enabled")) != "false" self.__location = QByteArray(QUrl.fromPercentEncoding( url.encodedQueryItemValue("location"))) # Check for required subscription self.__requiresLocation = QUrl.fromPercentEncoding( url.encodedQueryItemValue("requiresLocation")) self.__requiresTitle = QUrl.fromPercentEncoding( url.encodedQueryItemValue("requiresTitle")) if self.__requiresLocation and self.__requiresTitle: import Helpviewer.HelpWindow Helpviewer.HelpWindow.HelpWindow.adBlockManager()\ .loadRequiredSubscription(self.__requiresLocation, self.__requiresTitle) lastUpdateByteArray = url.encodedQueryItemValue("lastUpdate") lastUpdateString = QUrl.fromPercentEncoding(lastUpdateByteArray) self.__lastUpdate = QDateTime.fromString(lastUpdateString, Qt.ISODate) self.__loadRules()
def inactiveText(self): """ Public method to get the inactive text. @return inactive text (string) """ if qVersion() < "4.7.0": return self.__inactiveText else: return self.placeholderText()
def __init__(self, iface): '''Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface ''' # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'OfflineMapMatching_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = OfflineMapMatchingDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Offline-MapMatching') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'OfflineMapMatching') self.toolbar.setObjectName(u'OfflineMapMatching') #add help-document to the GUI dir = os.path.dirname(__file__) file = os.path.abspath(os.path.join(dir, 'help_docs', 'help.html')) if os.path.exists(file): with open(file) as helpf: help = helpf.read() self.dlg.textBrowser_help.insertHtml(help) self.dlg.textBrowser_help.moveCursor(QTextCursor.Start) #declare additional instance vars self.map_matcher = MapMatcher() self.provider = OfflineMapMatchingProvider() #connect slots and signals self.dlg.comboBox_trajectory.currentIndexChanged.connect(self.startPopulateFieldsComboBox) self.dlg.pushButton_start.clicked.connect(self.startMapMatching)
def _default_args(self): backend = 'webengine' if self.request.config.webengine else 'webkit' args = [ '--debug', '--no-err-windows', '--temp-basedir', '--json-logging', '--loglevel', 'vdebug', '--backend', backend, '--debug-flag', 'no-sql-history', '--debug-flag', 'werror' ] if qVersion() == '5.7.1': # https://github.com/qutebrowser/qutebrowser/issues/3163 args += ['--qt-flag', 'disable-seccomp-filter-sandbox'] args.append('about:blank') return args
def _base_args(config): """Get the arguments to pass with every invocation.""" args = ['--debug', '--json-logging', '--no-err-windows'] if config.webengine: args += ['--backend', 'webengine'] else: args += ['--backend', 'webkit'] if qVersion() == '5.7.1': # https://github.com/qutebrowser/qutebrowser/issues/3163 args += ['--qt-flag', 'disable-seccomp-filter-sandbox'] args.append('about:blank') return args
def __init__(self, iface): super(gtoPlugin, self).__init__() self.setObjectName(plugin_objectName) self.plugin_name = plugin_name self.plugin_dir = os.path.dirname(__file__) self.plugin_actions = [] self.first_start = True # qgis interface self.iface = iface self.iface.mainWindow().showMinimized() # app info self.info = gtoInfo(self) # debug ? path = os.path.join(self.plugin_dir, 'log') self.debug = os.path.exists(path) if self.debug: self.info.do_backup() # new session start_time = str(datetime.datetime.now()).split(".")[0] self.info.log("GTO version {0} loaded (UTC): ".format(self.get_version()), start_time) self.info.log(plugin_name, "debug:", self.debug) # DockWidget self.dockwidget = QDockWidget() self.dockwidget.setWindowTitle(plugin_name) self.dockwidget.setObjectName('GTODockWidget') self.dockwidget.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget) self.app = gtoMain(self) # correct settings in statusbar:S try: wids = iface.mainWindow().statusBar().findChildren(QWidget) for wid in wids: if wid.objectName() == 'mOntheFlyProjectionStatusButton' or wid.objectName() == 'mMessageLogViewerButton': if not wid.isHidden(): wid.setMaximumHeight(16777215) wid.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) except: pass # initialize locale locale = QgsApplication.locale() locale_path = os.path.join( self.plugin_dir, 'i18n', 'plugin_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '3.0.0': QCoreApplication.installTranslator(self.translator) # run self.run()
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.deleteChartImagesDirectory() # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'ActiveBubo_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = ActiveBuboDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Active Bubo') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'ActiveBubo') self.toolbar.setObjectName(u'ActiveBubo') #///////////////////////// self.dlg.lineEdit.clear() self.dlg.lineEdit_2.clear() self.dlg.lineEdit_2.setPlainText( "tag_ident in ('1750', '1751', '1753', '1754', '3899', '4045', '5158', '4846', '4848') AND speed > 1.5" ) self.dlg.openShapefile_button.clicked.connect(self.open_shapefile) self.dlg.exportAsReport_button.clicked.connect(self.exportAsReport) self.dlg.process_button.clicked.connect(self.process) self.dlg.addExpression_button.clicked.connect(self.addExpression) self.dlg.previousPicture_button.clicked.connect(self.previousPicture) self.dlg.nextPicture_button.clicked.connect(self.nextPicture) self.dlg.btn_equals.clicked.connect(self.equalsButtonHandler) self.dlg.btn_lessThan.clicked.connect(self.lessThanButtonHandler) self.dlg.btn_greaterThan.clicked.connect(self.greaterThanButtonHandler) self.dlg.btn_in.clicked.connect(self.inButtonHandler) self.dlg.btn_like.clicked.connect(self.likeButtonHandler) self.dlg.btn_and.clicked.connect(self.andButtonHandler) self.dlg.btn_or.clicked.connect(self.orButtonHandler) self.dlg.btn_not.clicked.connect(self.notButtonHandler) self.dlg.btnParenthesisOpen.clicked.connect( self.oParenthesisButtonHandler) self.dlg.btnParenthesisClose.clicked.connect( self.cParenthesisButtonHandler)
def fix_harfbuzz(args): """Fix harfbuzz issues. This switches to the most stable harfbuzz font rendering engine available on the platform instead of using the system wide one. This fixes crashes on various sites. - On Qt 5.2 (and probably earlier) the new engine probably has more crashes and is also experimental. e.g. https://bugreports.qt.io/browse/QTBUG-36099 - On Qt 5.3.0 there's a bug that affects a lot of websites: https://bugreports.qt.io/browse/QTBUG-39278 So the new engine will be more stable. - On Qt 5.3.1 this bug is fixed and the old engine will be the more stable one again. IMPORTANT: This needs to be done before QWidgets is imported in any way! WORKAROUND (remove this when we bump the requirements to 5.3.1) Args: args: The argparse namespace. """ from qutebrowser.utils import log from PyQt5.QtCore import qVersion if 'PyQt5.QtWidgets' in sys.modules: msg = "Harfbuzz fix attempted but QtWidgets is already imported!" if getattr(sys, 'frozen', False): log.init.debug(msg) else: log.init.warning(msg) if sys.platform.startswith('linux') and args.harfbuzz == 'auto': if qVersion() == '5.3.0': log.init.debug("Using new harfbuzz engine (auto)") os.environ['QT_HARFBUZZ'] = 'new' else: log.init.debug("Using old harfbuzz engine (auto)") os.environ['QT_HARFBUZZ'] = 'old' elif args.harfbuzz in ['old', 'new']: # forced harfbuzz variant # FIXME looking at the Qt code, 'new' isn't a valid value, but leaving # it empty and using new yields different behavior... # (probably irrelevant when workaround gets removed) log.init.debug("Using {} harfbuzz engine (forced)".format( args.harfbuzz)) os.environ['QT_HARFBUZZ'] = args.harfbuzz else: log.init.debug("Using system harfbuzz engine")
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'AnimateOsm_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Animate OSM') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'AnimateOsm') self.toolbar.setObjectName(u'AnimateOsm') #print "** INITIALIZING AnimateOsm" self.pluginIsActive = False self.dockwidget = None self.dev = True self.do_log = False self.polygon_layer = None self.data_dir = os.path.join(self.plugin_dir, 'data') self.output_dir = os.path.join(self.plugin_dir, 'output') #self.log(self.data_dir) #self.log(self.output_dir) self.open_file_dialog = QFileDialog() self.open_file_dialog.setDirectory(self.data_dir) self.choose_dir_dialog = QFileDialog() self.choose_dir_dialog.setDirectory(self.output_dir)
def initProcessing(self): """Init Processing provider for QGIS >= 3.8.""" self.provider = TaxrefApiProvider() QgsApplication.processingRegistry().addProvider(self.provider) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(os.path.dirname(__file__), 'i18n', '{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def _gmain(): """ GUI Entry Point """ setup_logging(logging.DEBUG) logger.info("Starting psvpack-qt") logger.info("PyQt %s / libqt5 %s / Qt5 Runtime %s", PYQT_VERSION_STR, QT_VERSION_STR, qVersion()) qtApp = QApplication(sys.argv) app = App() sys.exit(qtApp.exec_())
def version_check(version, op=operator.ge, strict=False): """Check if the Qt runtime version is the version supplied or newer. Args: version: The version to check against. op: The operator to use for the check. strict: If given, also check the compiled Qt version. """ parsed = pkg_resources.parse_version(version) result = op(pkg_resources.parse_version(qVersion()), parsed) if result and strict: result = op(pkg_resources.parse_version(QT_VERSION_STR), parsed) return result
def save(self): """ Public slot to save the Qt configuration. """ if qVersion() < "5.0.0": Preferences.setQt("Qt4TranslationsDir", self.qt4TransPicker.text()) else: Preferences.setQt("Qt5TranslationsDir", self.qt4TransPicker.text()) Preferences.setQt("QtToolsPrefix4", self.qt4PrefixEdit.text()) Preferences.setQt("QtToolsPostfix4", self.qt4PostfixEdit.text()) Preferences.setQt("PyuicIndent", self.pyuicIndentSpinBox.value()) Preferences.setQt("PyuicFromImports", self.pyuicImportsCheckBox.isChecked())
def qt_version(qversion=None, qt_version_str=None): """Get a Qt version string based on the runtime/compiled versions.""" if qversion is None: from PyQt5.QtCore import qVersion qversion = qVersion() if qt_version_str is None: from PyQt5.QtCore import QT_VERSION_STR qt_version_str = QT_VERSION_STR if qversion != qt_version_str: return '{} (compiled {})'.format(qversion, qt_version_str) else: return qversion
def qute_warning(url): """Handler for qute://warning.""" path = url.path() if path == '/old-qt': src = jinja.render('warning-old-qt.html', title='Old Qt warning', qt_version=qVersion()) elif path == '/webkit': src = jinja.render('warning-webkit.html', title='QtWebKit backend warning') else: raise NotFoundError("Invalid warning page {}".format(path)) return 'text/html', src
def check_qt_version(): """Check if the Qt version is recent enough.""" from PyQt5.QtCore import (qVersion, QT_VERSION, PYQT_VERSION, PYQT_VERSION_STR) from pkg_resources import parse_version parsed_qversion = parse_version(qVersion()) if (QT_VERSION < 0x050C00 or PYQT_VERSION < 0x050C00 or parsed_qversion < parse_version('5.12.0')): text = ("Fatal error: Qt >= 5.12.0 and PyQt >= 5.12.0 are required, " "but Qt {} / PyQt {} is installed.".format( qt_version(), PYQT_VERSION_STR)) _die(text)
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'GraticularBlockCuttingTool_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = GraticularBlockCuttingToolDialogBase() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&GraticularBlockCuttingTool') self.toolbar = self.iface.addToolBar(u'GraticularBlockCuttingTool') self.toolbar.setObjectName(u'GraticularBlockCuttingTool') # self.dlg.setWindowTitle(Title) # self.dlg.comboScale.addItem("5M") self.dlg.comboScale.addItem("6M") self.dlg.comboScale.addItem("1M") self.dlg.comboScale.addItem("10S") self.dlg.comboScale.addItem("6S") # self.dlg.btn_EditUserSettings.clicked.connect(self.EditUserSettings) self.dlg.btn_SaveUserSettings.clicked.connect(self.SaveUserSettings) self.dlg.btn_CutPolygons.clicked.connect(self.CutPolygons) self.dlg.btn_ClearMessage.clicked.connect(self.ClearMessage) self.dlg.btn_CheckArea.clicked.connect(self.CheckArea) self.dlg.btn_PopulateFieldAttributes.clicked.connect( self.PopulateFieldAttributes) self.dlg.btn_Test.clicked.connect(self.download)
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'CloneGeometry_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.colorValues = [ "#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#000000", "#800000", "#008000", "#000080", "#808000", "#800080", "#008080", "#808080", "#C00000", "#00C000", "#0000C0", "#C0C000", "#C000C0", "#00C0C0", "#C0C0C0", "#400000", "#004000", "#000040", "#404000", "#400040", "#004040", "#404040", "#200000", "#002000", "#000020", "#202000", "#200020", "#002020", "#202020", "#600000", "#006000", "#000060", "#606000", "#600060", "#006060", "#606060", "#A00000", "#00A000", "#0000A0", "#A0A000", "#A000A0", "#00A0A0", "#A0A0A0", "#E00000", "#00E000", "#0000E0", "#E0E000", "#E000E0", "#00E0E0", "#E0E0E0" ] self.colorIndex = 0 self.mColor = QColor(0, 85, 255, 255) #default color border self.dlg = CloneGeometryDialog() # self.dlg.maskColor.clicked.connect(self.color_picker) self.dlg.checkBox_mask.clicked.connect(self.colorState) self.buttonOk = self.dlg.button_box.button(QDialogButtonBox.Ok) self.dlg.radioToMemory.clicked.connect(self.checktolayer) self.dlg.radioToLayer.clicked.connect(self.checktolayer) self.dlg.comboBox.currentIndexChanged.connect(self.checktolayer) self.buttonOk.clicked.connect(self.cloneGeometry) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Clone geometry') # about button self.ui_about = AbtDialog() self.dlg.pushButton_about.setIcon( QIcon(':/plugins/CloneGeometry/about.png')) self.dlg.pushButton_about.clicked.connect(self.show_about)
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'SocialActivity_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Load config.ini file config = configparser.ConfigParser() config.read(os.path.join(self.plugin_dir, 'config.ini')) self.twitter_consumer_key = config['twitter']['twitter_consumer_key'] self.twitter_consumer_secret = config['twitter'][ 'twitter_consumer_secret'] self.twitter_access_key = config['twitter']['twitter_access_key'] self.twitter_access_secret = config['twitter']['twitter_access_secret'] # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Social Activity') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.firstStart_DialogBase = None self.start_latitude = None self.start_longitude = None #self.max_range = 300 self.firstStart_DialogSettings = None # a reference to our map canvas self.canvas = self.iface.mapCanvas() # this QGIS tool emits as QgsPoint after each click on the map canvas self.pointTool = QgsMapToolEmitPoint(self.canvas) self.pointTool.canvasClicked.connect(self.display_point)
def __init__(self, iface): """Constructor. """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) self.plugin_version = self.get_plugin_version() # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'SentinelHub_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.translate(u'&SentinelHub') self.toolbar = self.iface.addToolBar(u'SentinelHub') self.toolbar.setObjectName(u'SentinelHub') self.pluginIsActive = False self.dockwidget = None self.base_url = None self.data_source = None # Set value self.instance_id = QSettings().value(Settings.instance_id_location) if self.instance_id is None: self.instance_id = '' self.download_folder = QSettings().value(Settings.download_folder_location) if self.download_folder is None: self.download_folder = '' self.qgis_layers = [] self.capabilities = Capabilities('') self.active_time = 'time0' self.cloud_cover = {} self.download_current_window = True self.custom_bbox_params = {} for name in ['latMin', 'latMax', 'lngMin', 'lngMax']: self.custom_bbox_params[name] = ''
def getCode(self, indLevel, indString): """ Public method to get the source code. @param indLevel indentation level (int) @param indString string used for indentation (space or tab) (string) @return generated code (string) """ # calculate the indentation string istring = indLevel * indString estring = os.linesep + indLevel * indString # now generate the code reVar = self.variableLineEdit.text() if not reVar: reVar = "regexp" regexp = self.regexpLineEdit.text() code = '{0} = QRegExp(r"""{1}"""){2}'.format( reVar, regexp.replace('"', '\\"'), os.linesep) if not self.caseSensitiveCheckBox.isChecked(): code += '{0}{1}.setCaseSensitivity(Qt.CaseInsensitive){2}'.format( istring, reVar, os.linesep) if self.minimalCheckBox.isChecked(): code += '{0}{1}.setMinimal(True){2}'.format( istring, reVar, os.linesep) syntax = self.syntaxCombo.itemData(self.syntaxCombo.currentIndex()) needPatternSyntax = True if qVersion() < "5.0.0" and syntax == QRegExp.RegExp or \ qVersion() >= "5.0.0" and syntax == QRegExp.RegExp2: # default value selected needPatternSyntax = False if needPatternSyntax: code += '{0}{1}.setPatternSyntax({2}){3}'.format( istring, reVar, self.__getPatternSyntaxCode(syntax), estring) return code
def __performGrab(self): """ Private method to perform a screen grab other than a selected region. """ self.__grabberWidget.releaseMouse() self.__grabberWidget.hide() self.__grabTimer.stop() if self.__mode == SnapWidget.ModeFullscreen: desktop = QApplication.desktop() if qVersion() >= "5.0.0": self.__snapshot = QApplication.screens()[0].grabWindow( desktop.winId(), desktop.x(), desktop.y(), desktop.width(), desktop.height()) else: self.__snapshot = QPixmap.grabWindow(desktop.winId(), desktop.x(), desktop.y(), desktop.width(), desktop.height()) elif self.__mode == SnapWidget.ModeScreen: desktop = QApplication.desktop() screenId = desktop.screenNumber(QCursor.pos()) geom = desktop.screenGeometry(screenId) x = geom.x() y = geom.y() if qVersion() >= "5.0.0": self.__snapshot = QApplication.screens()[0].grabWindow( desktop.winId(), x, y, geom.width(), geom.height()) else: self.__snapshot = QPixmap.grabWindow(desktop.winId(), x, y, geom.width(), geom.height()) else: self.__snapshot = QPixmap() self.__redisplay() self.__modified = True self.__updateCaption()
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface #Objeto de autenticacion self.autenticacion = Autenticacion() # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'ActualizacionCatastral_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.root = QgsProject.instance().layerTreeRoot() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&ActualizacionCatastral') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'ActualizacionCatastral') self.toolbar.setObjectName(u'ActualizacionCatastral') #print "** INITIALIZING ActualizacionCatastral" self.pluginIsActive = False self.dockwidget = ActualizacionCatastralDockWidget() # eventos botones self.dockwidget.botonActualizar.clicked.connect(self.actualizarCapa) self.dockwidget.botonCambiar.clicked.connect(self.guardarValor) # usoLogin - usada para acceso al Qgis mediante aplicacion de logueo # False QSettings().setValue("usoLogin", "False")
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'RunwaysClassifier_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialogs (after translation) and keep reference self.classifier_dlg = RunwaysClassifierDialog() self.selection_dlg = RunwaysNumberSelectionDialog() self.view_dlg = RunwaysViewDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Runways Classifier') self.layer_name = "" # name of airpport layer self.initialSize = None # initial size of the map canvas self.imgSize = None # hold the image size (600x600) self.myLayer = None # the layer of airport points self.pointsCount = 0 # counter of airports that their image saving self.scale = 67000 # zoom scale to the map self.imgPath = os.path.join(os.path.dirname(__file__),"imgs\qimg_") # base path of each image self.bool = True self.rd = None # short name for runways detector *(has to be changed) self.airportsData = [] # data about each airport after analyzing the image self.dataBuffer = None # buffer that contain tif, tfw, icao and airport name for each airport that is going to be sent to image processer self.records = None # records that grabbed from data base self.records_num = 0 # number of grabbed records self.i = None # self.runways_num = None # airports with number of runways that will be present at the view dialog (spin box number) self.airport_num = None # number of airports their images going to be saved (spin box number)
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'YKRTool_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Ilmastovaikutusten arviointityökalu') self.conn = None self.connParams = None self.tableNames = {} # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None self.mainDialog = uic.loadUi( os.path.join(self.plugin_dir, 'ykr_tool_main.ui')) self.settingsDialog = uic.loadUi( os.path.join(self.plugin_dir, 'ykr_tool_db_settings.ui')) self.infoDialog = uic.loadUi( os.path.join(self.plugin_dir, 'ykr_tool_info.ui')) self.targetYear = None self.ykrPopLayer = None self.ykrBuildingsLayer = None self.ykrJobsLayer = None self.futureAreasLayer = None self.futureNetworkLayer = None self.futureStopsLayer = None
def helpAbout(self): """ Display version info about this program. """ pyVersion = '.'.join([repr(num) for num in sys.version_info[:3]]) textLines = [ _('TreeLine version {0}').format(__version__), _('written by {0}').format(__author__), '', _('Library versions:'), ' Python: {0}'.format(pyVersion), ' Qt: {0}'.format(qVersion()), ' PyQt: {0}'.format(PYQT_VERSION_STR), ' OS: {0}'.format(platform.platform()) ] QMessageBox.about(QApplication.activeWindow(), 'TreeLine', '\n'.join(textLines))
def createRequest(self, op, request, outgoingData=None): """ Public method to create a request. @param op the operation to be performed (QNetworkAccessManager.Operation) @param request reference to the request object (QNetworkRequest) @param outgoingData reference to an IODevice containing data to be sent (QIODevice) @return reference to the created reply object (QNetworkReply) """ if op != QNetworkAccessManager.GetOperation: return None url = request.url() if url.path() != "subscribe": return None if qVersion() >= "5.0.0": from PyQt5.QtCore import QUrlQuery, QUrl title = QUrl.fromPercentEncoding( QByteArray(QUrlQuery(url).queryItemValue("title").encode())) else: from PyQt5.QtCore import QUrl title = QUrl.fromPercentEncoding( url.encodedQueryItemValue(b"title")) if not title: return None res = E5MessageBox.yesNo( None, self.tr("Subscribe?"), self.tr( """<p>Subscribe to this AdBlock subscription?</p>""" """<p>{0}</p>""").format(title)) if res: from .AdBlockSubscription import AdBlockSubscription import Helpviewer.HelpWindow dlg = Helpviewer.HelpWindow.HelpWindow.adBlockManager()\ .showDialog() subscription = AdBlockSubscription( url, False, Helpviewer.HelpWindow.HelpWindow.adBlockManager()) Helpviewer.HelpWindow.HelpWindow.adBlockManager()\ .addSubscription(subscription) dlg.addSubscription(subscription, False) dlg.setFocus() dlg.raise_() return EmptyNetworkReply(self.parent())
def __init__(self, iface): # Save the reference to the QGIS interface self.iface = iface #initialize plugin directory self.pluginDir = os.path.dirname(__file__) # initialize locale locale = QSettings().value("locale/userLocale")[0:2] localePath = os.path.join(self.pluginDir, 'i18n', 'opeNoise_{}.qm'.format(locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'pgmanager_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&PostgreSQL User Manager') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.databaseToolBar() # self.toolbar.setObjectName(u'pgmanager') # print "** INITIALIZING pgmanager" self.database = None self.pluginIsActive = False self.dockwidget = None self.changes = None self.currentObjectType = None self.currentSchemaName = None self.currentTableName = None self.loadedPrivileges = None self.currentWidgetItem = None self.schemas_tables = None self.roles = None self.disconnected = None
def wheelEvent(self, event): """ Protected slot handling mouse wheel events. @param event reference to the wheel event (QWheelEvent) """ if qVersion() >= "5.0.0": isVertical = event.angleDelta().x() == 0 else: isVertical = event.orientation() == Qt.Vertical if self._master and \ event.modifiers() == Qt.NoModifier and \ isVertical: QCoreApplication.sendEvent(self._master.verticalScrollBar(), event)
def _on_mode_entered(self, mode): if mode != usertypes.KeyMode.caret: return if self._tab.search.search_displayed: # We are currently in search mode. # convert the search to a blue selection so we can operate on it # https://bugreports.qt.io/browse/QTBUG-60673 self._tab.search.clear() self._tab.run_js_async( javascript.assemble('caret', 'setPlatform', sys.platform, qVersion())) self._js_call('setInitialCursor', self._selection_cb)
def __init__(self, mode="bug", parent=None): """ Constructor @param mode mode of this dialog (string, "bug" or "feature") @param parent parent widget of this dialog (QWidget) """ super(EmailDialog, self).__init__(parent) self.setupUi(self) self.setWindowFlags(Qt.Window) self.__mode = mode if self.__mode == "feature": self.setWindowTitle(self.tr("Send feature request")) self.msgLabel.setText(self.tr( "Enter your &feature request below." " Version information is added automatically.")) self.__toAddress = FeatureAddress else: # default is bug self.msgLabel.setText(self.tr( "Enter your &bug description below." " Version information is added automatically.")) self.__toAddress = BugAddress self.sendButton = self.buttonBox.addButton( self.tr("Send"), QDialogButtonBox.ActionRole) self.sendButton.setEnabled(False) self.sendButton.setDefault(True) height = self.height() self.mainSplitter.setSizes([int(0.7 * height), int(0.3 * height)]) self.attachments.headerItem().setText( self.attachments.columnCount(), "") if qVersion() >= "5.0.0": self.attachments.header().setSectionResizeMode( QHeaderView.Interactive) else: self.attachments.header().setResizeMode(QHeaderView.Interactive) sig = Preferences.getUser("Signature") if sig: self.message.setPlainText(sig) cursor = self.message.textCursor() cursor.setPosition(0) self.message.setTextCursor(cursor) self.message.ensureCursorVisible() self.__deleteFiles = []