Example #1
0
 def test_file_pathsep(self, sep):
     url = QUrl('qute://pdfjs/file')
     query = QUrlQuery()
     query.addQueryItem('filename', 'foo{}bar'.format(sep))
     url.setQuery(query)
     with pytest.raises(qutescheme.RequestDeniedError):
         qutescheme.data_for_url(url)
Example #2
0
 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)
Example #3
0
 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)
Example #4
0
 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)
Example #5
0
def encode_uri(ds_uri, schema_name, project_name=None):
    u = QUrl()
    urlQuery = QUrlQuery()

    u.setScheme("postgresql")
    u.setHost(ds_uri.host())
    if ds_uri.port() != '':
        u.setPort(int(ds_uri.port()))
    if ds_uri.username() != '':
        u.setUserName(ds_uri.username())
    if ds_uri.password() != '':
        u.setPassword(ds_uri.password())

    if ds_uri.service() != '':
        urlQuery.addQueryItem("service", ds_uri.service())
    if ds_uri.authConfigId() != '':
        urlQuery.addQueryItem("authcfg", ds_uri.authConfigId())
    if ds_uri.sslMode() != QgsDataSourceUri.SslPrefer:
        urlQuery.addQueryItem("sslmode", QgsDataSourceUri.encodeSslMode(ds_uri.sslMode()))

    urlQuery.addQueryItem("dbname", ds_uri.database())

    urlQuery.addQueryItem("schema", schema_name)
    if project_name:
        urlQuery.addQueryItem("project", project_name)

    u.setQuery(urlQuery)
    return str(u.toEncoded(), 'utf-8')
Example #6
0
 def refresh_access_token(self, callback):
     refresh_token = config.persist["oauth_refresh_token"]
     log.debug("OAuth: refreshing access_token with a refresh_token %s",
               refresh_token)
     host, port = config.setting['server_host'], config.setting[
         'server_port']
     path = "/oauth2/token"
     url = QUrl()
     url_query = QUrlQuery()
     url_query.addQueryItem("grant_type", "refresh_token")
     url_query.addQueryItem("refresh_token", refresh_token)
     url_query.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url_query.addQueryItem("client_secret",
                            MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url.setQuery(url_query.query(QUrl.FullyEncoded))
     data = string_(url.query())
     self.xmlws.post(host,
                     port,
                     path,
                     data,
                     partial(self.on_refresh_access_token_finished,
                             callback),
                     xml=False,
                     mblogin=True,
                     priority=True,
                     important=True)
def encode_uri(ds_uri, schema_name, project_name=None):
    u = QUrl()
    urlQuery = QUrlQuery()

    u.setScheme("postgresql")
    u.setHost(ds_uri.host())
    if ds_uri.port() != '':
        u.setPort(int(ds_uri.port()))
    if ds_uri.username() != '':
        u.setUserName(ds_uri.username())
    if ds_uri.password() != '':
        u.setPassword(ds_uri.password())

    if ds_uri.service() != '':
        urlQuery.addQueryItem("service", ds_uri.service())
    if ds_uri.authConfigId() != '':
        urlQuery.addQueryItem("authcfg", ds_uri.authConfigId())
    if ds_uri.sslMode() != QgsDataSourceUri.SslPrefer:
        urlQuery.addQueryItem("sslmode", QgsDataSourceUri.encodeSslMode(ds_uri.sslMode()))

    urlQuery.addQueryItem("dbname", ds_uri.database())

    urlQuery.addQueryItem("schema", schema_name)
    if project_name:
        urlQuery.addQueryItem("project", project_name)

    u.setQuery(urlQuery)
    return str(u.toEncoded(), 'utf-8')
Example #8
0
 def test_file_pathsep(self, sep):
     url = QUrl('qute://pdfjs/file')
     query = QUrlQuery()
     query.addQueryItem('filename', 'foo{}bar'.format(sep))
     url.setQuery(query)
     with pytest.raises(qutescheme.RequestDeniedError):
         qutescheme.data_for_url(url)
Example #9
0
def _render_header(title, mode, phrase, filters):
    r = []
    r.append(ADV_HEADER)
    r.append('<h1>{0}</h1>'.format(title))
    r.append('<ul class="nav">\n')

    modes = [(name, spec) for (name, spec) in MODE_DICT.items()]
    modes.sort(key=itemgetter(0))

    for (name, spec) in modes:
        href = QUrl('search:///')
        urlquery = QUrlQuery()
        if phrase:
            urlquery.addQueryItem('phrase', phrase)
        if filters:
            urlquery.addQueryItem('filters', filters)
        urlquery.addQueryItem('mode', name)
        href.setQuery(urlquery)
        if name != mode:
            r.append('<li><a href="{href}">{title}</a></li>\n'.format(
                href=href.toEncoded(), title=spec['title']))
        else:
            r.append('<li><span class="sel">{title}<span></li>\n'.format(
                href=href.toEncoded(), title=spec['title']))

    r.append('</ul>\n')

    return ''.join(r)
Example #10
0
 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
Example #11
0
 def url_with_param(url, params) -> str:
     url = QUrl(url)
     q = QUrlQuery(url)
     for key, value in params.items():
         q.addQueryItem(key, value)
     url.setQuery(q)
     return url.url()
Example #12
0
    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
Example #13
0
 def getRemoteTiles(self):
     query = QUrlQuery()
     url = QUrl(f"{self.url}/search")
     query.addQueryItem("q", self.search_str)
     query.addQueryItem("f", "pjson")
     url.setQuery(query.query())
     response = QgsNetworkAccessManager.blockingGet(
         QNetworkRequest(QUrl(url)))
     if response.error() != QNetworkReply.NoError:
         raise Exception(response.errorString())
     responsejson = json.loads(response.content().data())
     LOG.debug("response from data repository: %s" % responsejson)
     tiles = []
     for result in responsejson["results"]:
         itemid = result["id"]
         timestamp = self.dataTimestamp(itemid)
         if timestamp is None:
             status = self.NOT_INSTALLED
         elif timestamp < result["modified"]:
             status = self.UPDATABLE
         else:
             status = self.UP_TO_DATE
         tile = dict(result)
         tile["status"] = status
         tiles.append(tile)
     return tiles
Example #14
0
 def exchange_authorization_code(self, authorization_code, scopes,
                                 callback):
     log.debug(
         "OAuth: exchanging authorization_code %s for an access_token",
         authorization_code)
     host, port = config.setting['server_host'], config.setting[
         'server_port']
     path = "/oauth2/token"
     url = QUrl()
     url_query = QUrlQuery()
     url_query.addQueryItem("grant_type", "authorization_code")
     url_query.addQueryItem("code", authorization_code)
     url_query.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url_query.addQueryItem("client_secret",
                            MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url_query.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
     url.setQuery(url_query.query(QUrl.FullyEncoded))
     data = string_(url.query())
     self.xmlws.post(host,
                     port,
                     path,
                     data,
                     partial(self.on_exchange_authorization_code_finished,
                             scopes, callback),
                     xml=False,
                     mblogin=True,
                     priority=True,
                     important=True)
    def getHttp(self, uri, params):
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            rq = QUrl(uri)
            q = QUrlQuery()
            for (k, v) in params.items():
                q.addQueryItem(k, v)

            rq.setQuery(q)
            req = QNetworkRequest(rq)

            try:
                reply = self.nominatim_networkAccessManager.blockingGet(req)
                resource = reply.content().data().decode('utf8')
                r = json.loads(resource)

                if (isinstance(r, list)):
                    self.populateTable(r)
                else:
                    self.populateTable([r])
            except:
                self.tableResult.clearContents()

        finally:
            QgsApplication.restoreOverrideCursor()
Example #16
0
    def init(main_widget, my_id='', oppenent_id=''):
        WebChatFrame.q_widget = QtWidgets.QWidget()
        WebChatFrame.q_widget.show()
        WebChatFrame.q_widget.setFixedSize(300, 600)
        WebChatFrame.q_widget.move(
            main_widget.mapToGlobal(QPoint(main_widget.width() + 1, -23)))
        horizontalLayout = QtWidgets.QHBoxLayout(WebChatFrame.q_widget)
        horizontalLayout.setContentsMargins(0, 0, 0, 0)

        view = QtWebEngineWidgets.QWebEngineView(WebChatFrame.q_widget)
        horizontalLayout.addWidget(view)
        view.settings().setAttribute(
            QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
        view.settings().setAttribute(
            QtWebEngineWidgets.QWebEngineSettings.JavascriptEnabled, True)

        url = QUrl(WebChatFrame.url + '/chat')

        urldata = QUrlQuery()
        urldata.addQueryItem('my_id', my_id)
        urldata.addQueryItem('oppenent_id', oppenent_id)
        url.setQuery(urldata)

        view.setUrl(url)
        view.show()
Example #17
0
def _generate_pdfjs_script(filename):
    """Generate the script that shows the pdf with pdf.js.

    Args:
        filename: The name of the file to open.
    """
    url = QUrl('qute://pdfjs/file')
    url_query = QUrlQuery()
    url_query.addQueryItem('filename', filename)
    url.setQuery(url_query)

    return jinja.js_environment.from_string("""
        document.addEventListener("DOMContentLoaded", function() {
          {% if disable_create_object_url %}
          PDFJS.disableCreateObjectURL = true;
          {% endif %}
          PDFJS.verbosity = PDFJS.VERBOSITY_LEVELS.info;

          const viewer = window.PDFView || window.PDFViewerApplication;
          viewer.open("{{ url }}");
        });
    """).render(
        url=javascript.string_escape(url.toString(QUrl.FullyEncoded)),
        # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-70420
        disable_create_object_url=(
            not qtutils.version_check('5.12')
            and not qtutils.version_check('5.7.1', exact=True, compiled=False)
            and objects.backend == usertypes.Backend.QtWebEngine))
Example #18
0
 def exchange_authorization_code(self, authorization_code, scopes,
                                 callback):
     log.debug(
         "OAuth: exchanging authorization_code %s for an access_token",
         authorization_code)
     path = "/oauth2/token"
     url = QUrl()
     url_query = QUrlQuery()
     url_query.addQueryItem("grant_type", "authorization_code")
     url_query.addQueryItem("code", authorization_code)
     url_query.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url_query.addQueryItem("client_secret",
                            MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url_query.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
     url.setQuery(url_query.query(QUrl.FullyEncoded))
     data = url.query()
     self.webservice.post(
         self.host,
         self.port,
         path,
         data,
         partial(self.on_exchange_authorization_code_finished, scopes,
                 callback),
         mblogin=True,
         priority=True,
         important=True,
         request_mimetype="application/x-www-form-urlencoded")
Example #19
0
def _generate_pdfjs_script(filename):
    """Generate the script that shows the pdf with pdf.js.

    Args:
        filename: The name of the file to open.
    """
    url = QUrl('qute://pdfjs/file')
    url_query = QUrlQuery()
    url_query.addQueryItem('filename', filename)
    url.setQuery(url_query)

    js_url = javascript.to_js(
        url.toString(QUrl.FullyEncoded))  # type: ignore[arg-type]

    return jinja.js_environment.from_string("""
        document.addEventListener("DOMContentLoaded", function() {
          if (typeof window.PDFJS !== 'undefined') {
              // v1.x
              window.PDFJS.verbosity = window.PDFJS.VERBOSITY_LEVELS.info;
          } else {
              // v2.x
              const options = window.PDFViewerApplicationOptions;
              options.set('verbosity', pdfjsLib.VerbosityLevel.INFOS);
          }

          const viewer = window.PDFView || window.PDFViewerApplication;
          viewer.open({{ url }});
        });
    """).render(url=js_url)
Example #20
0
 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 getHttp(self, uri, params):
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            rq = QUrl(uri)
            q = QUrlQuery()
            for (k, v) in params.items():
                q.addQueryItem(k, v)

            rq.setQuery(q)
            req = QNetworkRequest(rq)

            try:
                reply = self.nominatim_networkAccessManager.blockingGet(req)
                resource = reply.content().data().decode('utf8')
                r = json.loads(resource)

                if (isinstance(r, list)):
                    self.populateTable(r)
                else:
                    self.populateTable([r])
            except:
                self.tableResult.clearContents()

        finally:
            QgsApplication.restoreOverrideCursor()
Example #22
0
def get_main_url(filename):
    """Get the URL to be opened to view a local PDF."""
    url = QUrl('qute://pdfjs/web/viewer.html')
    query = QUrlQuery()
    query.addQueryItem('filename', filename)  # read from our JS
    query.addQueryItem('file', '')  # to avoid pdfjs opening the default PDF
    url.setQuery(query)
    return url
Example #23
0
def get_main_url(filename):
    """Get the URL to be opened to view a local PDF."""
    url = QUrl('qute://pdfjs/web/viewer.html')
    query = QUrlQuery()
    query.addQueryItem('filename', filename)  # read from our JS
    query.addQueryItem('file', '')  # to avoid pdfjs opening the default PDF
    url.setQuery(query)
    return url
Example #24
0
File: test.py Project: yqfcpy/QtRes
 def test3(self):
   url = QUrl("http://localhost:18080/user")
   query = QUrlQuery()
   query.addQueryItem("username", "yqfcpy");
   query.addQueryItem("password", "111111");
   url.setQuery(query.query())
   print(query.query())
   print(url)
Example #25
0
    def addEngineFromForm(self, res, view):
        """
        Public method to add a new search engine from a form.
        
        @param res result of the JavaScript run on by
            WebBrowserView.__addSearchEngine()
        @type dict or None
        @param view reference to the web browser view
        @type WebBrowserView
        """
        if not res:
            return

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

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

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

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

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

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

            searchUrlQuery.addQueryItem(name, value)

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

        actionUrl.setQuery(searchUrlQuery)

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

        self.__addEngineByEngine(engine)
Example #26
0
 def create_request(self, text):
     url = QUrl("http://toolbarqueries.google.com/complete/search")
     query = QUrlQuery()
     query.addQueryItem("q", text)
     query.addQueryItem("output", "toolbar")
     query.addQueryItem("hl", "en")
     url.setQuery(query)
     request = QNetworkRequest(url)
     return request
Example #27
0
def email(subject, body):
    """Opens the e-mail composer with the given subject and body, with version information added to it."""
    subject = "[{0} {1}] {2}".format(appinfo.appname, appinfo.version, subject)
    body = "{0}\n\n{1}\n\n".format(debuginfo.version_info_string(' -- '), body)
    url = QUrl("mailto:" + appinfo.maintainer_email)
    query = QUrlQuery()
    query.addQueryItem("subject", subject)
    query.addQueryItem("body", body)
    url.setQuery(query)
    helpers.openUrl(url, "email")
Example #28
0
 def load_account_page(self, account, tab=None, task=None):
     self.tab = tab
     self.task = task
     self.account = account
     url = QUrl(account.server.settings_url)
     url_query = QUrlQuery()
     for name, value in self.query_items:
         url_query.addQueryItem(name, value)
     url.setQuery(url_query)
     self.load(url)
Example #29
0
def get_main_url(filename: str, original_url: QUrl) -> QUrl:
    """Get the URL to be opened to view a local PDF."""
    url = QUrl('qute://pdfjs/web/viewer.html')
    query = QUrlQuery()
    query.addQueryItem('filename', filename)  # read from our JS
    query.addQueryItem('file', '')  # to avoid pdfjs opening the default PDF
    urlstr = original_url.toString(QUrl.FullyEncoded)  # type: ignore[arg-type]
    query.addQueryItem('source', urlstr)
    url.setQuery(query)
    return url
Example #30
0
def email(subject, body):
    """Opens the e-mail composer with the given subject and body, with version information added to it."""
    subject = "[{0} {1}] {2}".format(appinfo.appname, appinfo.version, subject)
    body = "{0}\n\n{1}\n\n".format(debuginfo.version_info_string(' -- '), body)
    url = QUrl("mailto:" + appinfo.maintainer_email)
    query = QUrlQuery()
    query.addQueryItem("subject", subject)
    query.addQueryItem("body", body)
    url.setQuery(query)
    helpers.openUrl(url, "email")
Example #31
0
def data_for_url(url):
    """Get the data to show for the given URL.

    Args:
        url: The QUrl to show.

    Return:
        A (mimetype, data) tuple.
    """
    norm_url = url.adjusted(QUrl.NormalizePathSegments
                            | QUrl.StripTrailingSlash)
    if norm_url != url:
        raise Redirect(norm_url)

    path = url.path()
    host = url.host()
    query = urlutils.query_string(url)
    # A url like "qute:foo" is split as "scheme:path", not "scheme:host".
    log.misc.debug("url: {}, path: {}, host {}".format(url.toDisplayString(),
                                                       path, host))
    if not path or not host:
        new_url = QUrl()
        new_url.setScheme('qute')
        # When path is absent, e.g. qute://help (with no trailing slash)
        if host:
            new_url.setHost(host)
        # When host is absent, e.g. qute:help
        else:
            new_url.setHost(path)

        new_url.setPath('/')
        if query:
            new_url.setQuery(query)
        if new_url.host():  # path was a valid host
            raise Redirect(new_url)

    try:
        handler = _HANDLERS[host]
    except KeyError:
        raise NoHandlerFound(url)

    try:
        mimetype, data = handler(url)
    except OSError as e:
        # FIXME:qtwebengine how to handle this?
        raise QuteSchemeOSError(e)
    except QuteSchemeError as e:
        raise

    assert mimetype is not None, url
    if mimetype == 'text/html' and isinstance(data, str):
        # We let handlers return HTML as text
        data = data.encode('utf-8', errors='xmlcharrefreplace')

    return mimetype, data
Example #32
0
def data_for_url(url):
    """Get the data to show for the given URL.

    Args:
        url: The QUrl to show.

    Return:
        A (mimetype, data) tuple.
    """
    norm_url = url.adjusted(QUrl.NormalizePathSegments |
                            QUrl.StripTrailingSlash)
    if norm_url != url:
        raise Redirect(norm_url)

    path = url.path()
    host = url.host()
    query = urlutils.query_string(url)
    # A url like "qute:foo" is split as "scheme:path", not "scheme:host".
    log.misc.debug("url: {}, path: {}, host {}".format(
        url.toDisplayString(), path, host))
    if not path or not host:
        new_url = QUrl()
        new_url.setScheme('qute')
        # When path is absent, e.g. qute://help (with no trailing slash)
        if host:
            new_url.setHost(host)
        # When host is absent, e.g. qute:help
        else:
            new_url.setHost(path)

        new_url.setPath('/')
        if query:
            new_url.setQuery(query)
        if new_url.host():  # path was a valid host
            raise Redirect(new_url)

    try:
        handler = _HANDLERS[host]
    except KeyError:
        raise NoHandlerFound(url)

    try:
        mimetype, data = handler(url)
    except OSError as e:
        # FIXME:qtwebengine how to handle this?
        raise QuteSchemeOSError(e)
    except QuteSchemeError as e:
        raise

    assert mimetype is not None, url
    if mimetype == 'text/html' and isinstance(data, str):
        # We let handlers return HTML as text
        data = data.encode('utf-8', errors='xmlcharrefreplace')

    return mimetype, data
Example #33
0
def data_for_url(url: QUrl):
    """Get the data to show for the given URL.

    Args:
        url: The QUrl to show.

    Return:
        A (mimetype, data) tuple.
    """
    norm_url = url.adjusted(QUrl.NormalizePathSegments
                            | QUrl.StripTrailingSlash)
    if norm_url != url:
        raise Redirect(norm_url)

    path = url.path()
    host = url.host()
    query = urlutils.query_string(url)
    # A url like "luminos:foo" is split as "scheme:path", not "scheme:host".

    if not path or not host:
        new_url = QUrl()
        new_url.setScheme("luminos")
        # When path is absent, e.g. luminos://help (with no trailing slash)
        if host:
            new_url.setHost(host)
        # When host is absent, e.g. luminos:help
        else:
            new_url.setHost(path)

        new_url.setPath("/")
        if query:
            new_url.setQuery(query)
        if new_url.host():  # path was a valid host
            raise Redirect(new_url)

    try:
        handler = _HANDLERS[host]
    except KeyError:
        raise NotFoundError("No handler found for {}".format(
            url.toDisplayString()))

    try:
        mimetype, data = handler(url)
    except OSError as e:
        raise SchemeOSError(e)

    assert mimetype is not None, url
    if mimetype == "text/html" and isinstance(data, str):
        # We let handlers return HTML as text
        data = data.encode("utf-8", errors="xmlcharrefreplace")

    return mimetype, data
Example #34
0
 def get(self, url: str, param: dict = None):
     # 创建一个请求
     path = QUrl(url)
     if param != None:
         query = QUrlQuery()
         for item in param.items():
             query.addQueryItem(item[0], str(item[1]))
         path.setQuery(query.query())
     req = QtNetwork.QNetworkRequest(path)
     self.nam = QtNetwork.QNetworkAccessManager()
     self.nam.finished.connect(self.handleResponse)
     # 使用get请求 如果有参数的话 写一个data 放到get里
     self.nam.get(req)
Example #35
0
File: test.py Project: yqfcpy/QtRes
 def test6(self):
   a1 = 0.111111111111111111111111
   b1 = 0.111111111111111111111111
   print(a1 + b1)
   return None
   dic = {"username": "******", "password": 123456}
   path = QUrl("http://localhost:18080/user")
   query = QUrlQuery()
   if 1 != 2:
     for item in dic.items():
       query.addQueryItem(item[0], item[1])
     path.setQuery(query.query())
   log.info(path)
def build_papercdcase_url(artist, album, tracks):
    url = QUrl(PAPERCDCASE_URL)
    # papercdcase.com does not deal well with unicode characters :(
    url_query = QUrlQuery()
    url_query.addQueryItem('artist',
                           urlencode(textencoding.asciipunct(artist)))
    url_query.addQueryItem('title', urlencode(textencoding.asciipunct(album)))
    i = 1
    for track in tracks:
        url_query.addQueryItem('track' + str(i),
                               urlencode(textencoding.asciipunct(track)))
        i += 1
    url.setQuery(url_query)
    return url.toString(QUrl.FullyEncoded)
Example #37
0
 def post(self, url: str, jsonBody: dict, param: dict = None):
     path = QUrl(url)
     sendData = QJsonDocument(jsonBody)
     if param != None:
         queryParams = QUrlQuery()
         for item in param.items():
             queryParams.addQueryItem(item[0], str(item[1]))
         path.setQuery(queryParams.query())
     req = QtNetwork.QNetworkRequest(path)
     # 设置头信息是json这里可以不写
     # req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/json")
     self.nam = QtNetwork.QNetworkAccessManager()
     self.nam.finished.connect(self.handleResponse)
     self.nam.post(req, sendData.toJson())
Example #38
0
def exceptHook(type_, value, tback):
    stack = ''.join(traceback.format_exception(type_, value, tback))

    title = QApplication.translate("ExcpHook", "System error")
    text = QApplication.translate(
        "ExcpHook", "A system error occurred.\n"
        "Do you want to send an error message to the author?")
    msgBox = QMessageBox(QMessageBox.Information, title, text)
    msgBox.setDetailedText(stack)
    msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    if msgBox.exec_() == QMessageBox.Yes:
        line = traceback.extract_tb(tback)[-1]
        subject = "[v%s] %s - %s:%d" % (version.Version, type_.__name__,
                                        line[0], line[1])

        errorMessage = []
        # errorMessage.append(QApplication.translate(
        #    "ExcpHook",
        #    "PLEASE ADD A COMMENT, IT WILL HELP IN SOLVING THE PROBLEM"))
        # errorMessage.append('')
        errorMessage.append("%s: %s" % (version.AppName, version.Version))
        errorMessage.append(
            "OS: %s %s (%s)" %
            (platform.system(), platform.release(), platform.version()))
        errorMessage.append(
            "Python: %s (%s)" %
            (platform.python_version(), platform.architecture()[0]))
        errorMessage.append("Qt: %s" % PYQT_VERSION_STR)
        try:
            errorMessage.append("Locale: %s" % Settings()['locale'])
        except:
            pass

        errorMessage.append('')
        errorMessage.append(stack)

        url = QUrl('http://opennumismat.idea.informer.com/proj/')
        query = QUrlQuery()
        query.addQueryItem('mod', 'add')
        query.addQueryItem('cat', '3')
        query.addQueryItem('idea', subject)
        query.addQueryItem('descr', '\n'.join(errorMessage))
        url.setQuery(query)

        executor = QDesktopServices()
        executor.openUrl(url)

    # Call the default handler
    sys.__excepthook__(type_, value, tback)
Example #39
0
def exceptHook(type_, value, tback):
    stack = ''.join(traceback.format_exception(type_, value, tback))

    title = QApplication.translate("ExcpHook", "System error")
    text = QApplication.translate("ExcpHook",
                        "A system error occurred.\n"
                        "Do you want to send an error message to the author?")
    msgBox = QMessageBox(QMessageBox.Information, title, text)
    msgBox.setDetailedText(stack)
    msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    if msgBox.exec_() == QMessageBox.Yes:
        line = traceback.extract_tb(tback)[-1]
        subject = "[v%s] %s - %s:%d" % (version.Version, type_.__name__,
                                        line[0], line[1])

        errorMessage = []
        # errorMessage.append(QApplication.translate(
        #    "ExcpHook",
        #    "PLEASE ADD A COMMENT, IT WILL HELP IN SOLVING THE PROBLEM"))
        # errorMessage.append('')
        errorMessage.append("%s: %s" % (version.AppName, version.Version))
        errorMessage.append("OS: %s %s (%s)" % (platform.system(),
                                                platform.release(),
                                                platform.version()))
        errorMessage.append("Python: %s (%s)" % (platform.python_version(),
                                                 platform.architecture()[0]))
        errorMessage.append("Qt: %s" % PYQT_VERSION_STR)
        try:
            errorMessage.append("Locale: %s" % Settings()['locale'])
        except:
            pass

        errorMessage.append('')
        errorMessage.append(stack)

        url = QUrl('http://opennumismat.idea.informer.com/proj/')
        query = QUrlQuery()
        query.addQueryItem('mod', 'add')
        query.addQueryItem('cat', '3')
        query.addQueryItem('idea', subject)
        query.addQueryItem('descr', '\n'.join(errorMessage))
        url.setQuery(query)

        executor = QDesktopServices()
        executor.openUrl(url)

    # Call the default handler
    sys.__excepthook__(type_, value, tback)
Example #40
0
 def exchange_authorization_code(self, authorization_code, scopes, callback):
     log.debug("OAuth: exchanging authorization_code %s for an access_token", authorization_code)
     host, port = config.setting['server_host'], config.setting['server_port']
     path = "/oauth2/token"
     url = QUrl()
     url_query = QUrlQuery()
     url_query.addQueryItem("grant_type", "authorization_code")
     url_query.addQueryItem("code", authorization_code)
     url_query.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url_query.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url_query.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
     url.setQuery(url_query.query(QUrl.FullyEncoded))
     data = string_(url.query())
     self.webservice.post(host, port, path, data,
                     partial(self.on_exchange_authorization_code_finished, scopes, callback),
                     parse_response_type=None, mblogin=True, priority=True, important=True)
Example #41
0
 def refresh_access_token(self, callback):
     refresh_token = config.persist["oauth_refresh_token"]
     log.debug("OAuth: refreshing access_token with a refresh_token %s", refresh_token)
     host, port = config.setting['server_host'], config.setting['server_port']
     path = "/oauth2/token"
     url = QUrl()
     url_query = QUrlQuery()
     url_query.addQueryItem("grant_type", "refresh_token")
     url_query.addQueryItem("refresh_token", refresh_token)
     url_query.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID)
     url_query.addQueryItem("client_secret", MUSICBRAINZ_OAUTH_CLIENT_SECRET)
     url.setQuery(url_query.query(QUrl.FullyEncoded))
     data = string_(url.query())
     self.webservice.post(host, port, path, data,
                     partial(self.on_refresh_access_token_finished, callback),
                     parse_response_type=None, mblogin=True, priority=True, important=True)
Example #42
0
 def load_account_page(self, account, tab=None, task=None, reset_history=False, set_home=False):
     self.tab = tab
     self.task = task
     self.account = account
     url = QUrl(account.server.settings_url)
     url_query = QUrlQuery()
     for name, value in self.query_items:
         url_query.addQueryItem(name, value)
     url.setQuery(url_query)
     if set_home:
         self.homepage = url
     if reset_history:
         self.history().clear()
         self.page().mainFrame().evaluateJavaScript('window.location.replace("{}");'.format(url.toString()))  # this will replace the current url in the history
     else:
         self.load(url)
Example #43
0
 def load_account_page(self, account, tab=None, task=None, reset_history=False, set_home=False):
     self.tab = tab
     self.task = task
     self.account = account
     url = QUrl(account.server.settings_url)
     url_query = QUrlQuery()
     for name, value in self.query_items:
         url_query.addQueryItem(name, value)
     url.setQuery(url_query)
     if set_home:
         self.homepage = url
     if reset_history:
         self.history().clear()
         self.page().mainFrame().evaluateJavaScript('window.location.replace("{}");'.format(url.toString()))  # this will replace the current url in the history
     else:
         self.load(url)
Example #44
0
    def loadMessages(self, skip=None, beforeId=None, afterId=None, limit=50):
        logger.debug("listMessages")
        url = QUrl(
            GITTER_API + "/rooms/{}/chatMessages".format(self.id)
        )
        query = QUrlQuery()
        if skip:
            query.addQueryItem("skip", str(skip))
        if beforeId:
            query.addQueryItem("beforeId", str(beforeId))
        if afterId:
            query.addQueryItem("afterId", str(afterId))
        elif self._messages.last_id:
            query.addQueryItem("afterId", str(self._messages.last_id()))
        if limit:
            query.addQueryItem("limit", str(limit))

        url.setQuery(query)
        req = makeRequest(url, self._auth)
        reply = self._net.get(req)
        reply.finished.connect(lambda: self.readMessages(reply))
Example #45
0
 def __stripUrl(self, url):
     """
     Private method to strip off all unneeded parts of a URL.
     
     @param url URL to be stripped (QUrl)
     @return stripped URL (QUrl)
     """
     cleanUrl = QUrl(url)
     if qVersion() >= "5.0.0":
         cleanUrl.setQuery("")
     else:
         cleanUrl.setQueryItems([])
     cleanUrl.setUserInfo("")
     
     authority = cleanUrl.authority()
     if authority.startswith("@"):
         authority = authority[1:]
     cleanUrl = QUrl("{0}://{1}{2}".format(
         cleanUrl.scheme(), authority, cleanUrl.path()))
     cleanUrl.setFragment("")
     return cleanUrl
Example #46
0
def exceptHook(type_, value, tback):
    stack = ''.join(traceback.format_exception(type_, value, tback))

    title = QApplication.translate("ExcpHook", "System error")
    text = QApplication.translate("ExcpHook",
                        "A system error occurred.\n"
                        "Do you want to send an error message to the author\n"
                        "(Google account required)?")
    msgBox = QMessageBox(QMessageBox.Information, title, text)
    msgBox.setDetailedText(stack)
    msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    if msgBox.exec_() == QMessageBox.Yes:
        line = traceback.extract_tb(tback, 1)[0]
        subject = "[v%s] %s - %s:%d" % (version.Version, type_.__name__,
                                        line[0], line[1])

        errorMessage = []
        errorMessage.append("%s: %s" % (version.AppName, version.Version))
        errorMessage.append("OS: %s %s %s (%s)" % (platform.system(),
                                                   platform.release(),
                                                   platform.architecture()[0],
                                                   platform.version()))
        errorMessage.append("Python: %s" % platform.python_version())
        errorMessage.append("Qt: %s" % PYQT_VERSION_STR)
        errorMessage.append('')
        errorMessage.append(stack)

        url = QUrl('https://code.google.com/p/open-numismat/issues/entry')
        query = QUrlQuery()
        query.addQueryItem('summary', subject)
        query.addQueryItem('comment', '\n'.join(errorMessage))
        url.setQuery(query)

        executor = QDesktopServices()
        executor.openUrl(url)

    # Call the default handler
    sys.__excepthook__(type_, value, tback)
Example #47
0
def _generate_pdfjs_script(filename):
    """Generate the script that shows the pdf with pdf.js.

    Args:
        filename: The name of the file to open.
    """
    url = QUrl('qute://pdfjs/file')
    url_query = QUrlQuery()
    url_query.addQueryItem('filename', filename)
    url.setQuery(url_query)

    return jinja.js_environment.from_string("""
        document.addEventListener("DOMContentLoaded", function() {
          if (typeof window.PDFJS !== 'undefined') {
              // v1.x
              {% if disable_create_object_url %}
              window.PDFJS.disableCreateObjectURL = true;
              {% endif %}
              window.PDFJS.verbosity = window.PDFJS.VERBOSITY_LEVELS.info;
          } else {
              // v2.x
              const options = window.PDFViewerApplicationOptions;
              {% if disable_create_object_url %}
              options.set('disableCreateObjectURL', true);
              {% endif %}
              options.set('verbosity', pdfjsLib.VerbosityLevel.INFOS);
          }

          const viewer = window.PDFView || window.PDFViewerApplication;
          viewer.open({{ url }});
        });
    """).render(
        url=javascript.to_js(url.toString(QUrl.FullyEncoded)),
        # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-70420
        disable_create_object_url=(
            not qtutils.version_check('5.12') and
            not qtutils.version_check('5.7.1', exact=True, compiled=False) and
            objects.backend == usertypes.Backend.QtWebEngine))
Example #48
0
    def _sendRequest(self, url, params, headers={}):
        if self.asynchonous:

            if self.reply is not None:
                self.reply.finished.disconnect(self.reply_finished)
                self.reply.abort()
                self.reply = None

            url = QUrl(url)
            q = QUrlQuery(url)
            for key, value in params.items():
                q.addQueryItem(key, value)
            url.setQuery(q)
            QgsLogger.debug('Request: {}'.format(url.toEncoded()))
            request = QNetworkRequest(url)
            for key, value in headers.items():
                request.setRawHeader(key, value)
            self.reply = QgsNetworkAccessManager.instance().get(request)
            self.reply.finished.connect(self.reply_finished)

        else:
            response = urlopen(self.url + '?' + urllib.urlencode(params))
            data = json.load(response)
            self.load_data(data)
Example #49
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     self.contents.clear()
     
     if not self.logEntries:
         self.errors.append(self.tr("No log available for '{0}'")
                            .format(self.filename))
         self.errorGroup.show()
         return
     
     html = ""
     
     if self.initialText:
         for line in self.initialText:
             html += Utilities.html_encode(line.strip())
             html += '<br />\n'
         html += '{0}<br/>\n'.format(80 * "=")
         
     for entry in self.logEntries:
         fileCopies = {}
         if entry["file_copies"]:
             for fentry in entry["file_copies"].split(", "):
                 newName, oldName = fentry[:-1].split(" (")
                 fileCopies[newName] = oldName
         
         rev, hexRev = entry["change"].split(":")
         dstr = '<p><b>{0} {1}</b>'.format(self.revString, entry["change"])
         if entry["parents"]:
             parents = entry["parents"].split()
         else:
             parents = self.__getParents(rev)
         for parent in parents:
             url = QUrl()
             url.setScheme("file")
             url.setPath(self.filename)
             if qVersion() >= "5.0.0":
                 query = parent.split(":")[0] + '_' + rev
                 url.setQuery(query)
             else:
                 query = QByteArray()
                 query.append(parent.split(":")[0]).append('_').append(rev)
                 url.setEncodedQuery(query)
             dstr += ' [<a href="{0}" name="{1}" id="{1}">{2}</a>]'.format(
                 url.toString(), query,
                 self.tr('diff to {0}').format(parent),
             )
         dstr += '<br />\n'
         html += dstr
         
         if "phase" in entry:
             html += self.tr("Phase: {0}<br />\n")\
                 .format(entry["phase"])
         
         html += self.tr("Branch: {0}<br />\n")\
             .format(entry["branches"])
         
         html += self.tr("Tags: {0}<br />\n").format(entry["tags"])
         
         if "bookmarks" in entry:
             html += self.tr("Bookmarks: {0}<br />\n")\
                 .format(entry["bookmarks"])
         
         html += self.tr("Parents: {0}<br />\n")\
             .format(entry["parents"])
         
         html += self.tr('<i>Author: {0}</i><br />\n')\
             .format(Utilities.html_encode(entry["user"]))
         
         date, time = entry["date"].split()[:2]
         html += self.tr('<i>Date: {0}, {1}</i><br />\n')\
             .format(date, time)
         
         for line in entry["description"]:
             html += Utilities.html_encode(line.strip())
             html += '<br />\n'
         
         if entry["file_adds"]:
             html += '<br />\n'
             for f in entry["file_adds"].strip().split(", "):
                 if f in fileCopies:
                     html += self.tr(
                         'Added {0} (copied from {1})<br />\n')\
                         .format(Utilities.html_encode(f),
                                 Utilities.html_encode(fileCopies[f]))
                 else:
                     html += self.tr('Added {0}<br />\n')\
                         .format(Utilities.html_encode(f))
         
         if entry["files_mods"]:
             html += '<br />\n'
             for f in entry["files_mods"].strip().split(", "):
                 html += self.tr('Modified {0}<br />\n')\
                     .format(Utilities.html_encode(f))
         
         if entry["file_dels"]:
             html += '<br />\n'
             for f in entry["file_dels"].strip().split(", "):
                 html += self.tr('Deleted {0}<br />\n')\
                     .format(Utilities.html_encode(f))
         
         html += '</p>{0}<br/>\n'.format(60 * "=")
     
     self.contents.setHtml(html)
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()
Example #50
0
 def __procFinished(self, exitCode, exitStatus):
     """
     Private slot connected to the finished signal.
     
     @param exitCode exit code of the process (integer)
     @param exitStatus exit status of the process (QProcess.ExitStatus)
     """
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     self.contents.clear()
     
     lvers = 1
     for s in self.buf:
         rev_match = False
         if self.rx_rev.exactMatch(s):
             ver = self.rx_rev.cap(1)
             author = self.rx_rev.cap(2)
             date = self.rx_rev.cap(3)
             # number of lines is ignored
             rev_match = True
         elif self.rx_rev2.exactMatch(s):
             ver = self.rx_rev2.cap(1)
             author = self.rx_rev2.cap(2)
             date = self.rx_rev2.cap(3)
             # number of lines is ignored
             rev_match = True
         
         if rev_match:
             dstr = '<b>{0} {1}</b>'.format(self.revString, ver)
             try:
                 lv = self.revisions[lvers]
                 lvers += 1
                 url = QUrl()
                 url.setScheme("file")
                 url.setPath(self.filename)
                 if qVersion() >= "5.0.0":
                     query = lv + '_' + ver
                     url.setQuery(query)
                 else:
                     query = QByteArray()
                     query.append(lv).append('_').append(ver)
                     url.setEncodedQuery(query)
                 dstr += ' [<a href="{0}" name="{1}">{2}</a>]'.format(
                     url.toString(), query,
                     self.tr('diff to {0}').format(lv),
                 )
             except IndexError:
                 pass
             dstr += '<br />\n'
             self.contents.insertHtml(dstr)
             
             dstr = self.tr('<i>author: {0}</i><br />\n').format(author)
             self.contents.insertHtml(dstr)
             
             dstr = self.tr('<i>date: {0}</i><br />\n').format(date)
             self.contents.insertHtml(dstr)
         
         elif self.rx_sep.exactMatch(s) or self.rx_sep2.exactMatch(s):
             self.contents.insertHtml('<hr />\n')
         
         elif self.rx_flags.exactMatch(s):
             dstr = self.flags[self.rx_flags.cap(1)]
             dstr += self.rx_flags.cap(2)
             dstr += '<br />\n'
             self.contents.insertHtml(dstr)
         
         elif self.rx_changed.exactMatch(s):
             dstr = '<br />{0}<br />\n'.format(s)
             self.contents.insertHtml(dstr)
         
         else:
             if s == "":
                 s = self.contents.insertHtml('<br />\n')
             else:
                 self.contents.insertHtml(Utilities.html_encode(s))
                 self.contents.insertHtml('<br />\n')
     
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()
Example #51
0
 def formatUrl(self, endpoint, params={}):
     url = QUrl(DIVI_HOST + endpoint)
     qr = QUrlQuery()
     qr.setQueryItems(list(params.items()))
     url.setQuery( qr )
     return url
Example #52
0
    def start(self, fn, noEntries=0):
        """
        Public slot to start the svn log command.
        
        @param fn filename to show the log for (string)
        @param noEntries number of entries to show (integer)
        """
        self.errorGroup.hide()

        fetchLimit = 10

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()

        self.filename = fn
        dname, fname = self.vcs.splitPath(fn)

        opts = self.vcs.options["global"] + self.vcs.options["log"]
        verbose = "--verbose" in opts

        self.activateWindow()
        self.raise_()

        locker = QMutexLocker(self.vcs.vcsExecutionMutex)
        cwd = os.getcwd()
        os.chdir(dname)
        try:
            nextRev = 0
            fetched = 0
            logs = []
            limit = noEntries or 9999999
            while fetched < limit:
                flimit = min(fetchLimit, limit - fetched)
                if fetched == 0:
                    revstart = pysvn.Revision(pysvn.opt_revision_kind.head)
                else:
                    revstart = pysvn.Revision(pysvn.opt_revision_kind.number, nextRev)
                allLogs = self.client.log(
                    fname,
                    revision_start=revstart,
                    discover_changed_paths=verbose,
                    limit=flimit + 1,
                    strict_node_history=False,
                )
                if len(allLogs) <= flimit or self._clientCancelCallback():
                    logs.extend(allLogs)
                    break
                else:
                    logs.extend(allLogs[:-1])
                    nextRev = allLogs[-1]["revision"].number
                    fetched += fetchLimit
            locker.unlock()

            self.contents.clear()
            self.__pegRev = None
            for log in logs:
                ver = "{0:d}".format(log["revision"].number)
                dstr = "<b>{0} {1}</b>".format(self.revString, ver)
                if self.__pegRev is None:
                    self.__pegRev = int(ver)
                try:
                    lv = "{0:d}".format(logs[logs.index(log) + 1]["revision"].number)
                    url = QUrl()
                    url.setScheme("file")
                    url.setPath(self.filename)
                    query = lv + "_" + ver
                    url.setQuery(query)
                    dstr += ' [<a href="{0}" name="{1}">{2}</a>]'.format(
                        url.toString(), query, self.tr("diff to {0}").format(lv)
                    )
                except IndexError:
                    pass
                dstr += "<br />\n"
                self.contents.insertHtml(dstr)

                author = log["author"]
                message = log["message"]
                if sys.version_info[0] == 2:
                    author = author.decode("utf-8")
                    message = message.decode("utf-8")
                dstr = self.tr("<i>author: {0}</i><br />\n").format(author)
                self.contents.insertHtml(dstr)

                dstr = self.tr("<i>date: {0}</i><br />\n").format(formatTime(log["date"]))
                self.contents.insertHtml(dstr)

                self.contents.insertHtml("<br />\n")

                for line in message.splitlines():
                    self.contents.insertHtml(Utilities.html_encode(line))
                    self.contents.insertHtml("<br />\n")

                if len(log["changed_paths"]) > 0:
                    self.contents.insertHtml("<br />\n")
                    for changeInfo in log["changed_paths"]:
                        action = changeInfo["action"]
                        path = changeInfo["path"]
                        if sys.version_info[0] == 2:
                            action = action.decode("utf-8")
                            path = path.decode("utf-8")
                        dstr = "{0} {1}".format(self.flags[action], path)
                        if changeInfo["copyfrom_path"] is not None:
                            copyfrom_path = changeInfo["copyfrom_path"]
                            if sys.version_info[0] == 2:
                                copyfrom_path = copyfrom_path.decode("utf-8")
                            dstr += self.tr(" (copied from {0}, revision {1})").format(
                                copyfrom_path, changeInfo["copyfrom_revision"].number
                            )
                        dstr += "<br />\n"
                        self.contents.insertHtml(dstr)

                self.contents.insertHtml("<hr /><br />\n")
        except pysvn.ClientError as e:
            locker.unlock()
            self.__showError(e.args[0])
        os.chdir(cwd)
        self.__finish()