コード例 #1
0
 def _request_services(self):
     url_to_get = self.insert_token(DF_SERVICES_URL)
     self._services_network_fetcher.fetchContent(QUrl(url_to_get))
コード例 #2
0
 def showHelp(self, page='index.html'):
     helpFile = 'file:///{0}/help/{1}'.format(self.rivergisPath, page)
     QDesktopServices.openUrl(QUrl(helpFile))
コード例 #3
0
 def changeResult(self):
     item = self.tree.currentItem()
     if isinstance(item, TreeResultItem):
         url = QUrl(item.filename)
         self.webView.load(url)
コード例 #4
0
    def __init__(self, alg):
        super(AlgorithmDialogBase, self).__init__(iface.mainWindow())
        self.setupUi(self)

        self.feedback = AlgorithmDialogFeedback(self)
        self.feedback.progressChanged.connect(self.setPercentage)

        self.settings = QgsSettings()
        self.restoreGeometry(
            self.settings.value("/Processing/dialogBase", QByteArray()))

        self.executed = False
        self.mainWidget = None
        self.alg = alg

        # Rename OK button to Run
        self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnRun.setText(self.tr('Run'))

        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.setWindowTitle(self.alg.displayName())

        # desktop = QDesktopWidget()
        # if desktop.physicalDpiX() > 96:
        # self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96)

        algHelp = self.alg.shortHelp()
        if algHelp is None:
            self.textShortHelp.setVisible(False)
        else:
            self.textShortHelp.document().setDefaultStyleSheet(
                '''.summary { margin-left: 10px; margin-right: 10px; }
                                                    h2 { color: #555555; padding-bottom: 15px; }
                                                    a { text-decoration: none; color: #3498db; font-weight: bold; }
                                                    p { color: #666666; }
                                                    b { color: #333333; }
                                                    dl dd { margin-bottom: 5px; }'''
            )
            self.textShortHelp.setHtml(algHelp)

        self.textShortHelp.setOpenLinks(False)

        def linkClicked(url):
            webbrowser.open(url.toString())

        self.textShortHelp.anchorClicked.connect(linkClicked)

        isText, algHelp = self.alg.help()
        if algHelp is not None:
            algHelp = algHelp if isText else QUrl(algHelp)
            try:
                if isText:
                    self.txtHelp.setHtml(algHelp)
                else:
                    html = self.tr(
                        '<p>Downloading algorithm help... Please wait.</p>')
                    self.txtHelp.setHtml(html)
                    rq = QNetworkRequest(algHelp)
                    self.reply = QgsNetworkAccessManager.instance().get(rq)
                    self.reply.finished.connect(self.requestFinished)
            except Exception:
                self.tabWidget.removeTab(2)
        else:
            self.tabWidget.removeTab(2)

        self.showDebug = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_DEBUG_IN_DIALOG)
コード例 #5
0
    def setupUi(self):
        self.labels = {}
        self.widgets = {}
        self.checkBoxes = {}
        self.showAdvanced = False
        self.wrappers = {}
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel |
                                          QDialogButtonBox.Ok)
        tooltips = self._alg.getParameterDescriptions()
        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Expanding)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.verticalLayout.addWidget(self.bar)

        hLayout = QHBoxLayout()
        hLayout.setSpacing(5)
        hLayout.setMargin(0)
        descriptionLabel = QLabel(self.tr("Description"))
        self.descriptionBox = QLineEdit()
        self.descriptionBox.setText(self._alg.displayName())
        hLayout.addWidget(descriptionLabel)
        hLayout.addWidget(self.descriptionBox)
        self.verticalLayout.addLayout(hLayout)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.verticalLayout.addWidget(line)

        for param in self._alg.parameters:
            if param.isAdvanced:
                self.advancedButton = QPushButton()
                self.advancedButton.setText(self.tr('Show advanced parameters'))
                self.advancedButton.clicked.connect(
                    self.showAdvancedParametersClicked)
                advancedButtonHLayout = QHBoxLayout()
                advancedButtonHLayout.addWidget(self.advancedButton)
                advancedButtonHLayout.addStretch()
                self.verticalLayout.addLayout(advancedButtonHLayout)
                break
        for param in self._alg.parameters:
            if param.hidden:
                continue
            desc = param.description
            if isinstance(param, ParameterExtent):
                desc += self.tr('(xmin, xmax, ymin, ymax)')
            if isinstance(param, ParameterPoint):
                desc += self.tr('(x, y)')
            if param.optional:
                desc += self.tr(' [optional]')
            label = QLabel(desc)
            self.labels[param.name] = label

            wrapper = param.wrapper(self)
            self.wrappers[param.name] = wrapper

            widget = wrapper.widget
            if widget is not None:
                self.valueItems[param.name] = widget
                if param.name in list(tooltips.keys()):
                    tooltip = tooltips[param.name]
                else:
                    tooltip = param.description
                label.setToolTip(tooltip)
                widget.setToolTip(tooltip)
                if param.isAdvanced:
                    label.setVisible(self.showAdvanced)
                    widget.setVisible(self.showAdvanced)
                    self.widgets[param.name] = widget

                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(widget)

        for output in self._alg.outputs:
            if output.hidden:
                continue
            if isinstance(output, (OutputRaster, OutputVector, OutputTable,
                                   OutputHTML, OutputFile, OutputDirectory)):
                label = QLabel(output.description + '<' +
                               output.__class__.__name__ + '>')
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[output.name] = item

        label = QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QLabel(self.tr('Parent algorithms'))
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)
        self.verticalLayout.addStretch(1000)

        self.setPreviousValues()
        self.setWindowTitle(self._alg.displayName())
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)
        self.tabWidget = QTabWidget()
        self.tabWidget.setMinimumWidth(300)
        self.paramPanel = QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QgsScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)
        self.tabWidget.addTab(self.scrollArea, self.tr('Parameters'))

        self.txtHelp = QTextBrowser()

        html = None
        isText, algHelp = self._alg.help()
        if algHelp is not None:
            algHelp = algHelp if isText else QUrl(algHelp)
            try:
                if isText:
                    self.txtHelp.setHtml(algHelp)
                else:
                    html = self.tr('<p>Downloading algorithm help... Please wait.</p>')
                    self.txtHelp.setHtml(html)
                    self.tabWidget.addTab(self.txtHelp, 'Help')
                    self.reply = QgsNetworkAccessManager.instance().get(QNetworkRequest(algHelp))
                    self.reply.finished.connect(self.requestFinished)
            except:
                pass

        self.verticalLayout2.addWidget(self.tabWidget)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        QMetaObject.connectSlotsByName(self)

        for wrapper in list(self.wrappers.values()):
            wrapper.postInitialize(list(self.wrappers.values()))
コード例 #6
0
 def show_help():
     QDesktopServices.openUrl(QUrl(DOC_PLUGIN_URL))
コード例 #7
0
    def request(self,
                url,
                method="GET",
                body=None,
                headers=None,
                redirections=DEFAULT_MAX_REDIRECTS,
                connection_type=None,
                blocking=True):
        """
        Make a network request by calling QgsNetworkAccessManager.
        redirections argument is ignored and is here only for httplib2
        compatibility.
        """
        self.msg_log(u'http_call request: %s' % url)

        self.blocking_mode = blocking
        req = QNetworkRequest()
        # Avoid double quoting form QUrl
        url = urllib.parse.unquote(url)
        req.setUrl(QUrl(url))
        if headers is not None:
            # This fixes a wierd error with compressed content not being
            # correctly inflated.
            # If you set the header on the QNetworkRequest you are
            # basically telling QNetworkAccessManager "I know what
            # I'm doing, please don't do any content encoding processing".
            # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1
            try:
                del headers['Accept-Encoding']
            except KeyError:
                pass
            for k, v in list(headers.items()):
                self.msg_log("Setting header %s to %s" % (k, v))
                req.setRawHeader(k.encode(), v.encode())
        if self.authid:
            self.msg_log("Update request w/ authid: {0}".format(self.authid))
            self.auth_manager().updateNetworkRequest(req, self.authid)
        if self.reply is not None and self.reply.isRunning():
            self.reply.close()
        if method.lower() == 'delete':
            func = getattr(QgsNetworkAccessManager.instance(),
                           'deleteResource')
        else:
            func = getattr(QgsNetworkAccessManager.instance(), method.lower())
        # Calling the server ...
        # Let's log the whole call for debugging purposes:
        self.msg_log("Sending %s request to %s" %
                     (method.upper(), req.url().toString()))
        self.on_abort = False
        headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}
        for k, v in list(headers.items()):
            self.msg_log("%s: %s" % (k, v))
        if method.lower() in ['post', 'put']:
            if isinstance(body, io.IOBase):
                body = body.read()
            if isinstance(body, str):
                body = body.encode()
            self.reply = func(req, body)
        else:
            self.reply = func(req)
        if self.authid:
            self.msg_log("Update reply w/ authid: {0}".format(self.authid))
            self.auth_manager().updateNetworkReply(self.reply, self.authid)

        # necessary to trap local timout manage by QgsNetworkAccessManager
        # calling QgsNetworkAccessManager::abortRequest
        QgsNetworkAccessManager.instance().requestTimedOut.connect(
            self.requestTimedOut)

        self.reply.sslErrors.connect(self.sslErrors)
        self.reply.finished.connect(self.replyFinished)
        self.reply.downloadProgress.connect(self.downloadProgress)

        # block if blocking mode otherwise return immediatly
        # it's up to the caller to manage listeners in case of no blocking mode
        if not self.blocking_mode:
            return (None, None)

        # Call and block
        self.el = QEventLoop()
        self.reply.finished.connect(self.el.quit)

        # Catch all exceptions (and clean up requests)
        try:
            self.el.exec_(QEventLoop.ExcludeUserInputEvents)
        except Exception as e:
            raise e

        if self.reply:
            self.reply.finished.disconnect(self.el.quit)

        # emit exception in case of error
        if not self.http_call_result.ok:
            if self.http_call_result.exception and not self.exception_class:
                raise self.http_call_result.exception
            else:
                raise self.exception_class(self.http_call_result.reason)

        return (self.http_call_result, self.http_call_result.content)
コード例 #8
0
 def project_warehouse_view(self, project: Project):
     """Open this project in the warehouse if the warehouse meta entries exist
     """
     url = self.get_warehouse_url(project.warehouse_meta)
     if url is not None:
         QDesktopServices.openUrl(QUrl(url))
コード例 #9
0
 def layer_warehouse_view(self, data: QRaveMapLayer):
     """Open this project in the warehouse if the warehouse meta entries exist
     """
     url = self.get_warehouse_url(data.meta)
     if url is not None:
         QDesktopServices.openUrl(QUrl(url))
コード例 #10
0
 def showHelpPage(self):
     url = "showText?page=help"
     self.processAction(QUrl(url))
コード例 #11
0
def download_file(url,
                  filename,
                  on_progress=None,
                  on_finished=None,
                  on_error=None,
                  on_success=None):
    """
    Will download the file from url to a local filename.
    The method will only return once it's finished.

    While downloading it will repeatedly report progress by calling on_progress
    with two parameters bytes_received and bytes_total.

    If an error occurs, it raises a NetworkError exception.

    It will return the filename if everything was ok.
    """
    network_access_manager = QgsNetworkAccessManager.instance()

    req = QNetworkRequest(QUrl(url))
    req.setAttribute(QNetworkRequest.CacheSaveControlAttribute, False)
    req.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                     QNetworkRequest.AlwaysNetwork)
    req.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
    reply = network_access_manager.get(req)

    def on_download_progress(bytes_received, bytes_total):
        on_progress(bytes_received, bytes_total)

    def finished(filename, reply, on_error, on_success, on_finished):
        file = QFile(filename)
        file.open(QIODevice.WriteOnly)
        file.write(reply.readAll())
        file.close()
        if reply.error() and on_error:
            on_error(reply.error(), reply.errorString())
        elif not reply.error() and on_success:
            on_success()

        if on_finished:
            on_finished()
        reply.deleteLater()
        replies.remove(reply)

    if on_progress:
        reply.downloadProgress.connect(on_download_progress)

    on_reply_finished = partial(finished, filename, reply, on_error,
                                on_success, on_finished)

    reply.finished.connect(on_reply_finished)

    replies.append(reply)

    if not on_finished and not on_success:
        loop = QEventLoop()
        reply.finished.connect(loop.quit)
        loop.exec_()

        if reply.error():
            raise NetworkError(reply.error(), reply.errorString())
        else:
            return filename
コード例 #12
0
 def startPage(self):
     self.processAction(QUrl("showText?page=allTEL"))
コード例 #13
0
    def readConfigFileFromXML(self):
        """Read config file."""
        #TODO: STDOUT
        #self.dlg.textEdit.clear()
        #sys.stdout = Log(self.dlg.textEdit)
        #self.dlg.textEdit.clear()
        #self.dlg.textEdit.selectAll()
        #self.dlg.textEdit.setText('')
        self.flagClipTaskDone = 0

        QgsMessageLog.logMessage('Crop Rows - Plugin Path: ' +
                                 (os.path.dirname(os.path.abspath(__file__))))
        QgsMessageLog.logMessage('===========================================')
        QgsMessageLog.logMessage('Reading configuration file')

        xmlConfigFile = os.path.join(
            (os.path.dirname(os.path.abspath(__file__))), 'config.xml')

        QgsMessageLog.logMessage('Config file: ' + xmlConfigFile)

        source = open(xmlConfigFile, 'rb')
        tree = ET.parse(source)
        root = tree.getroot()
        root_tag = root.tag
        #print(root_tag)
        for cfg in root.findall('config'):
            pcpValue = cfg.find('processing_core_path').text
            opValue = cfg.find('osgeo_path').text
            tpValue = cfg.find('temporal_path').text
            clValue = cfg.find('clip_load').text
            lrValue = cfg.find('load_results').text
            crofValue = cfg.find('output_file').text
            aclipValue = cfg.find('alwaysclip').text
            self.dlg.inputProcessingApiURL.setText(str(pcpValue))
            QgsMessageLog.logMessage('Setting Processing Core Path: ' +
                                     str(pcpValue))
            self.dlg.webViewApiStatus.load(QUrl(pcpValue))
            self.dlg.inputGdalOsgeoPath.setText(str(opValue))
            QgsMessageLog.logMessage('Setting OSGEO Path: ' + str(opValue))
            self.dlg.inputSharedFolderPath.setText(str(tpValue))
            QgsMessageLog.logMessage('Setting Temporal Path: ' + str(tpValue))
            QgsMessageLog.logMessage('Setting output file: ' + str(crofValue))
            QgsMessageLog.logMessage('Option Load clipped: ' + str(clValue))
            QgsMessageLog.logMessage('Option Load results: ' + str(lrValue))
            QgsMessageLog.logMessage('Option Load alwaysclip: ' +
                                     str(aclipValue))
            QgsMessageLog.logMessage(
                '===========================================')
            #Checkboxes
            if str(clValue).lower() == 'true':
                self.dlg.checkLoadClipped.setCheckState(True)
            if str(lrValue).lower() == 'true':
                self.dlg.checkLoadCropRows.setCheckState(True)

            if str(aclipValue).lower() == 'true':
                self.flagNoCropRaster = False
            else:
                self.flagNoCropRaster = True

        self.dlg.radioButtonSeed1.setAutoExclusive(False)
        self.dlg.radioButtonSeed2.setAutoExclusive(False)
        self.dlg.radioButtonSeed3.setAutoExclusive(False)
        self.dlg.radioButtonSeed4.setAutoExclusive(False)
        self.dlg.radioButtonSeed1.setChecked(False)
        self.dlg.radioButtonSeed2.setChecked(False)
        self.dlg.radioButtonSeed3.setChecked(False)
        self.dlg.radioButtonSeed4.setChecked(False)
        self.dlg.radioButtonSeed1.setAutoExclusive(True)
        self.dlg.radioButtonSeed2.setAutoExclusive(True)
        self.dlg.radioButtonSeed3.setAutoExclusive(True)
        self.dlg.radioButtonSeed4.setAutoExclusive(True)
        self.dlg.labelOutputSeed.setText('')
        QgsMessageLog.logMessage('Seed status reloaded')

        source.close()
        del source
        flagApiServerIsRunning = self.url_ok(pcpValue + "/imlive")
        #check is api server is running
        QgsMessageLog.logMessage('API Server running: ' +
                                 str(flagApiServerIsRunning))

        if flagApiServerIsRunning == False:
            #hide api tab
            self.dlg.mainTabs.setTabEnabled(3, False)
        else:
            #show api tab
            self.dlg.mainTabs.setTabEnabled(3, True)
コード例 #14
0
def getVideoLocationInfo(videoPath, islocal=False, klv_folder=None):
    """ Get basic location info about the video """
    location = []
    try:
        if islocal:
            dataFile = os.path.join(klv_folder, "0.0.klv")
            f = open(dataFile, 'rb')
            stdout_data = f.read()
        else:
            p = _spawn(['-i', videoPath,
                        '-ss', '00:00:00',
                        '-to', '00:00:01',
                        '-map', 'data-re',
                        '-f', 'data', '-'])

            stdout_data, _ = p.communicate()

        if stdout_data == b'':
            return
        for packet in StreamParser(stdout_data):
            if isinstance(packet, UnknownElement):
                qgsu.showUserAndLogMessage(
                    "Error interpreting klv data, metadata cannot be read.", "the parser did not recognize KLV data", level=QGis.Warning)
                continue
            packet.MetadataList()
            frameCenterLat = packet.FrameCenterLatitude
            frameCenterLon = packet.FrameCenterLongitude
            loc = "-"

            if Reverse_geocoding_url != "":
                try:
                    url = QUrl(Reverse_geocoding_url.format(
                        str(frameCenterLat), str(frameCenterLon)))
                    request = QNetworkRequest(url)
                    reply = QgsNetworkAccessManager.instance().get(request)
                    loop = QEventLoop()
                    reply.finished.connect(loop.quit)
                    loop.exec_()
                    reply.finished.disconnect(loop.quit)
                    loop = None
                    result = reply.readAll()
                    data = json.loads(result.data())

                    if "village" in data["address"] and "state" in data["address"]:
                        loc = data["address"]["village"] + \
                            ", " + data["address"]["state"]
                    elif "town" in data["address"] and "state" in data["address"]:
                        loc = data["address"]["town"] + \
                            ", " + data["address"]["state"]
                    else:
                        loc = data["display_name"]

                except Exception:
                    qgsu.showUserAndLogMessage(
                        "", "getVideoLocationInfo: failed to get address from reverse geocoding service.", onlyLog=True)

            location = [frameCenterLat, frameCenterLon, loc]

            qgsu.showUserAndLogMessage("", "Got Location: lon: " + str(frameCenterLon) + 
                                       " lat: " + str(frameCenterLat) + " location: " + str(loc), onlyLog=True)

            break
        else:

            qgsu.showUserAndLogMessage(QCoreApplication.translate(
                "QgsFmvUtils", "This video doesn't have Metadata ! : "))

    except Exception as e:
        qgsu.showUserAndLogMessage(QCoreApplication.translate(
            "QgsFmvUtils", "Video info callback failed! : "), str(e))

    return location
コード例 #15
0
 def open_help():
     """ Open the online help. """
     QDesktopServices.openUrl(
         QUrl('https://github.com/ghtmtt/DataPlotly/blob/master/README.md'))
コード例 #16
0
 def show_help(self):
     #QDesktopServices.openUrl(QUrl("file:" + os.path.join(os.path.dirname(__file__), "help/html", "index.html"))
     QDesktopServices.openUrl(QUrl("https://github.com/rduivenvoorde/kit_dhis2_data_fetcher/"))
コード例 #17
0
 def __init__(self, url):
     self.url = QUrl(url)
     self.query = QUrlQuery()
コード例 #18
0
    def is_source_service_valid(self):
        res = False
        msg = {'text': '', 'level': Qgis.Warning}
        url = self.txt_service_endpoint.text().strip()
        if url:
            with OverrideCursor(Qt.WaitCursor):
                self.qgis_utils.status_bar_message_emitted.emit(
                    "Checking source service availability (this might take a while)...",
                    0)
                QCoreApplication.processEvents()
                if self.qgis_utils.is_connected(TEST_SERVER):

                    nam = QNetworkAccessManager()
                    request = QNetworkRequest(QUrl(url))
                    reply = nam.get(request)

                    loop = QEventLoop()
                    reply.finished.connect(loop.quit)
                    loop.exec_()

                    allData = reply.readAll()
                    response = QTextStream(allData, QIODevice.ReadOnly)
                    status = reply.attribute(
                        QNetworkRequest.HttpStatusCodeAttribute)
                    if status == 200:
                        try:
                            data = json.loads(response.readAll())
                            if 'id' in data and data[
                                    'id'] == SOURCE_SERVICE_EXPECTED_ID:
                                res = True
                                msg['text'] = QCoreApplication.translate(
                                    "SettingsDialog",
                                    "The tested service is valid to upload files!"
                                )
                                msg['level'] = Qgis.Info
                            else:
                                res = False
                                msg['text'] = QCoreApplication.translate(
                                    "SettingsDialog",
                                    "The tested upload service is not compatible: no valid 'id' found in response."
                                )
                        except json.decoder.JSONDecodeError as e:
                            res = False
                            msg['text'] = QCoreApplication.translate(
                                "SettingsDialog",
                                "Response from the tested service is not compatible: not valid JSON found."
                            )
                    else:
                        res = False
                        msg['text'] = QCoreApplication.translate(
                            "SettingsDialog",
                            "There was a problem connecting to the server. The server might be down or the service cannot be reached at the given URL."
                        )
                else:
                    res = False
                    msg['text'] = QCoreApplication.translate(
                        "SettingsDialog",
                        "There was a problem connecting to Internet.")

                self.qgis_utils.clear_status_bar_emitted.emit()
        else:
            res = False
            msg['text'] = QCoreApplication.translate(
                "SettingsDialog", "Not valid service URL to test!")

        return (res, msg)
コード例 #19
0
 def show_help(self):
     help_file = 'file:///%s/help/build/html/index.html' % os.path.dirname(
         __file__)
     QDesktopServices.openUrl(QUrl(help_file))
コード例 #20
0
    def run(field, value):
        """
        Run an action with only one value as parameter

        @param field:Type of the action
        @type field:str
        @param value:Value of the field for one entity
        @type value:str
        """

        if value == '':
            iface.messageBar().pushMessage(
                tr('Sorry man, this field \'{}\' is empty for this entity.'.
                   format(field)),
                level=Qgis.Warning,
                duration=7)
        else:

            if field in ['url', 'website', 'wikipedia', 'wikidata']:
                var = QDesktopServices()
                url = None

                if field == 'url' or field == 'website':
                    url = value

                if field == 'ref_UAI':
                    url = "http://www.education.gouv.fr/pid24302/annuaire-" \
                          "resultat-recherche.html?lycee_name=" + value

                if field == 'wikipedia':
                    url = "http://en.wikipedia.org/wiki/" + value

                if field == 'wikidata':
                    url = "http://www.wikidata.org/wiki/" + value

                var.openUrl(QUrl(url))

            elif field == 'mapillary':
                if 'go2mapillary' in plugins:
                    plugins['go2mapillary'].dockwidget.show()
                    plugins["go2mapillary"].mainAction.setChecked(False)
                    plugins['go2mapillary'].viewer.openLocation(value)
                else:
                    var = QDesktopServices()
                    url = 'https://www.mapillary.com/map/im/' + value
                    var.openUrl(QUrl(url))

            elif field == 'josm':
                import urllib.request, urllib.error, urllib.parse
                try:
                    url = 'http://localhost:8111/load_object?objects=' + value
                    urllib.request.urlopen(url).read()
                except urllib.error.URLError:
                    iface.messageBar().pushMessage(
                        tr('The JOSM remote seems to be disabled.'),
                        level=Qgis.Critical,
                        duration=7)

            # NOT USED
            elif field == 'rawedit':
                # url = QUrl("http://rawedit.openstreetmap.fr/edit/" + value)
                # web_browser = QWebView(None)
                # web_browser.load(url)
                # web_browser.show()
                pass
コード例 #21
0
ファイル: console.py プロジェクト: t0b3/QGIS
 def openHelpAPI(self):
     m = re.search(r'^([0-9]+)\.([0-9]+)\.', Qgis.QGIS_VERSION)
     if m:
         QDesktopServices.openUrl(
             QUrl('https://qgis.org/pyqgis/{}.{}/'.format(
                 m.group(1), m.group(2))))
コード例 #22
0
ファイル: console.py プロジェクト: zyhgit/QGIS
 def openHelpCookbook(self):
     m = re.search(r'^([0-9]+)\.([0-9]+)\.', Qgis.QGIS_VERSION)
     if m:
         QDesktopServices.openUrl(QUrl('https://docs.qgis.org/{}.{}/en/docs/pyqgis_developer_cookbook/index.html'.format(m.group(1), m.group(2))))
コード例 #23
0
 def test_requestUrl(self):
     """Test url"""
     request = QgsServerRequest('http://somesite.com/somepath', QgsServerRequest.GetMethod)
     self.assertEqual(request.url().toString(), 'http://somesite.com/somepath')
     request.setUrl(QUrl('http://someother.com/someotherpath'))
     self.assertEqual(request.url().toString(), 'http://someother.com/someotherpath')
コード例 #24
0
ファイル: taxtweb_dialog.py プロジェクト: huazhz/oq-irmt-qgis
 def point_to_taxonomy(self, url):
     qurl = QUrl("%s%s" % (self.parent().host, url))
     self.taxonomy_dlg.web_view.load(qurl)
     self.taxonomy_dlg.show()
     self.taxonomy_dlg.raise_()
コード例 #25
0
def getVideoLocationInfo(videoPath,
                         islocal=False,
                         klv_folder=None,
                         klv_index=0):
    """ Get basic location info about the video """
    location = []
    try:
        if islocal:
            dataFile = os.path.join(klv_folder, "0.0.klv")
            f = open(dataFile, "rb")
            stdout_data = f.read()
        else:
            p = _spawn([
                "-i",
                videoPath,
                "-ss",
                "00:00:00",
                "-to",
                "00:00:01",
                "-map",
                "0:d:" + str(klv_index),
                "-f",
                "data",
                "-",
            ])

            stdout_data, _ = p.communicate()
            # qgsu.showUserAndLogMessage("Video Loc info raw result", stdout_data, onlyLog=True)
        if stdout_data == b"":
            # qgsu.showUserAndLogMessage("Error interpreting klv data, metadata cannot be read.", "the parser did not recognize KLV data", level=QGis.Warning)
            return
        for packet in StreamParser(stdout_data):
            if isinstance(packet, UnknownElement):
                qgsu.showUserAndLogMessage(
                    "Error interpreting klv data, metadata cannot be read.",
                    "the parser did not recognize KLV data",
                    level=QGis.Warning,
                )
                continue
            packet.MetadataList()
            centerLat = packet.FrameCenterLatitude
            centerLon = packet.FrameCenterLongitude
            # Target maybe unavailable because of horizontal view
            if centerLat is None and centerLon is None:
                centerLat = packet.SensorLatitude
                centerLon = packet.SensorLongitude
            loc = "-"

            if Reverse_geocoding_url != "":
                try:
                    url = QUrl(
                        Reverse_geocoding_url.format(str(centerLat),
                                                     str(centerLon)))
                    request = QNetworkRequest(url)
                    reply = QgsNetworkAccessManager.instance().get(request)
                    loop = QEventLoop()
                    reply.finished.connect(loop.quit)
                    loop.exec_()
                    reply.finished.disconnect(loop.quit)
                    loop = None
                    result = reply.readAll()
                    data = json.loads(result.data())

                    if "village" in data["address"] and "state" in data[
                            "address"]:
                        loc = (data["address"]["village"] + ", " +
                               data["address"]["state"])
                    elif "town" in data["address"] and "state" in data[
                            "address"]:
                        loc = data["address"]["town"] + ", " + data["address"][
                            "state"]
                    else:
                        loc = data["display_name"]

                except Exception:
                    qgsu.showUserAndLogMessage(
                        "",
                        "getVideoLocationInfo: failed to get address from reverse geocoding service.",
                        onlyLog=True,
                    )

            location = [centerLat, centerLon, loc]

            qgsu.showUserAndLogMessage(
                "",
                "Got Location: lon: " + str(centerLon) + " lat: " +
                str(centerLat) + " location: " + str(loc),
                onlyLog=True,
            )

            break
        else:

            qgsu.showUserAndLogMessage(
                QCoreApplication.translate(
                    "QgsFmvUtils", "This video doesn't have Metadata ! : "))

    except Exception as e:
        qgsu.showUserAndLogMessage(
            QCoreApplication.translate("QgsFmvUtils",
                                       "Video info callback failed! : "),
            str(e),
        )

    return location
コード例 #26
0
 def open_help(self):
     '''Opens the html help file content with default browser'''
     #~ localHelpUrl = "https://github.com/3liz/QgisCadastrePlugin/blob/master/doc/index.rst"
     localHelpUrl = os.path.join(str(Path(__file__).resolve().parent), 'doc', 'index.html')
     QDesktopServices.openUrl( QUrl(localHelpUrl) )
コード例 #27
0
 def showWebsite(self):
     QDesktopServices.openUrl(QUrl('http://rivergis.com'))
コード例 #28
0
    def xmlDownloaded(self):
        """ populate the plugins object with the fetched data """
        reply = self.sender()
        reposName = reply.property('reposName')
        if reply.error() != QNetworkReply.NoError:                             # fetching failed
            self.mRepositories[reposName]["state"] = 3
            self.mRepositories[reposName]["error"] = reply.errorString()
            if reply.error() == QNetworkReply.OperationCanceledError:
                self.mRepositories[reposName]["error"] += "\n\n" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't canceled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window.")
        else:
            reposXML = QDomDocument()
            content = reply.readAll()
            # Fix lonely ampersands in metadata
            a = QByteArray()
            a.append("& ")
            b = QByteArray()
            b.append("&amp; ")
            content = content.replace(a, b)
            reposXML.setContent(content)
            pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
            if pluginNodes.size():
                for i in range(pluginNodes.size()):
                    fileName = pluginNodes.item(i).firstChildElement("file_name").text().strip()
                    if not fileName:
                        fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().strip().split("?")[0]).fileName()
                    name = fileName.partition(".")[0]
                    experimental = False
                    if pluginNodes.item(i).firstChildElement("experimental").text().strip().upper() in ["TRUE", "YES"]:
                        experimental = True
                    deprecated = False
                    if pluginNodes.item(i).firstChildElement("deprecated").text().strip().upper() in ["TRUE", "YES"]:
                        deprecated = True
                    trusted = False
                    if pluginNodes.item(i).firstChildElement("trusted").text().strip().upper() in ["TRUE", "YES"]:
                        trusted = True
                    icon = pluginNodes.item(i).firstChildElement("icon").text().strip()
                    if icon and not icon.startswith("http"):
                        icon = "http://%s/%s" % (QUrl(self.mRepositories[reposName]["url"]).host(), icon)

                    if pluginNodes.item(i).toElement().hasAttribute("plugin_id"):
                        plugin_id = pluginNodes.item(i).toElement().attribute("plugin_id")
                    else:
                        plugin_id = None

                    plugin = {
                        "id": name,
                        "plugin_id": plugin_id,
                        "name": pluginNodes.item(i).toElement().attribute("name"),
                        "version_available": pluginNodes.item(i).toElement().attribute("version"),
                        "description": pluginNodes.item(i).firstChildElement("description").text().strip(),
                        "about": pluginNodes.item(i).firstChildElement("about").text().strip(),
                        "author_name": pluginNodes.item(i).firstChildElement("author_name").text().strip(),
                        "homepage": pluginNodes.item(i).firstChildElement("homepage").text().strip(),
                        "download_url": pluginNodes.item(i).firstChildElement("download_url").text().strip(),
                        "category": pluginNodes.item(i).firstChildElement("category").text().strip(),
                        "tags": pluginNodes.item(i).firstChildElement("tags").text().strip(),
                        "changelog": pluginNodes.item(i).firstChildElement("changelog").text().strip(),
                        "author_email": pluginNodes.item(i).firstChildElement("author_email").text().strip(),
                        "tracker": pluginNodes.item(i).firstChildElement("tracker").text().strip(),
                        "code_repository": pluginNodes.item(i).firstChildElement("repository").text().strip(),
                        "downloads": pluginNodes.item(i).firstChildElement("downloads").text().strip(),
                        "average_vote": pluginNodes.item(i).firstChildElement("average_vote").text().strip(),
                        "rating_votes": pluginNodes.item(i).firstChildElement("rating_votes").text().strip(),
                        "icon": icon,
                        "experimental": experimental,
                        "deprecated": deprecated,
                        "trusted": trusted,
                        "filename": fileName,
                        "installed": False,
                        "available": True,
                        "status": "not installed",
                        "error": "",
                        "error_details": "",
                        "version_installed": "",
                        "zip_repository": reposName,
                        "library": "",
                        "readonly": False
                    }
                    qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().strip()
                    if not qgisMinimumVersion:
                        qgisMinimumVersion = "2"
                    qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip()
                    if not qgisMaximumVersion:
                        qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
                    # if compatible, add the plugin to the list
                    if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE", "YES"]:
                        if isCompatible(Qgis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
                            # add the plugin to the cache
                            plugins.addFromRepository(plugin)
                self.mRepositories[reposName]["state"] = 2
            else:
                # no plugin metadata found
                self.mRepositories[reposName]["state"] = 3
                if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200:
                    self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options.")
                else:
                    self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Status code:") + " %d %s" % (
                        reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
                        reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)
                    )

        self.repositoryFetched.emit(reposName)

        # is the checking done?
        if not self.fetchingInProgress():
            self.checkingDone.emit()

        reply.deleteLater()
コード例 #29
0
 def htmlUrl(self):
     """Helper to get the url of the html doc."""
     myPath = os.path.join(TEST_DATA_DIR, "test_html.html")
     myUrl = QUrl("file:///" + myPath)
     return myUrl
コード例 #30
0
 def _request_df_qlr_file(self):
     url_to_get = self.settings.value("df_qlr_url")
     self._qlr_network_fetcher.fetchContent(QUrl(url_to_get))