def test_invalid_url_error(urlutils_message_mock, url, valid, has_err_string):
    """Test invalid_url_error().

    Args:
        url: The URL to check.
        valid: Whether the QUrl is valid (isValid() == True).
        has_err_string: Whether the QUrl is expected to have errorString set.
    """
    qurl = QUrl(url)
    assert qurl.isValid() == valid
    if valid:
        with pytest.raises(ValueError):
            urlutils.invalid_url_error(0, qurl, '')
        assert not urlutils_message_mock.messages
    else:
        assert bool(qurl.errorString()) == has_err_string
        urlutils.invalid_url_error(0, qurl, 'frozzle')

        msg = urlutils_message_mock.getmsg(urlutils_message_mock.Level.error)
        if has_err_string:
            expected_text = ("Trying to frozzle with invalid URL - " +
                             qurl.errorString())
        else:
            expected_text = "Trying to frozzle with invalid URL"
        assert msg.text == expected_text
Exemple #2
0
    def resolve_url(self, baseurl):
        """Resolve the URL in the element's src/href attribute.

        Args:
            baseurl: The URL to base relative URLs on as QUrl.

        Return:
            A QUrl with the absolute URL, or None.
        """
        if baseurl.isRelative():
            raise ValueError("Need an absolute base URL!")

        for attr in ['href', 'src']:
            if attr in self:
                text = self[attr].strip()
                break
        else:
            return None

        url = QUrl(text)
        if not url.isValid():
            return None
        if url.isRelative():
            url = baseurl.resolved(url)
        qtutils.ensure_valid(url)
        return url
Exemple #3
0
 def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
     if not file_url.isValid():
         return
     path = file_url.toLocalFile()
     if not path:
         return
     self._container_registry.exportProfile(instance_id, path, file_type)
Exemple #4
0
    def _is_blocked(self, request_url: QUrl, first_party_url: QUrl = None) -> bool:
        """Check whether the given request is blocked."""
        if not self.enabled:
            return False

        if first_party_url is not None and not first_party_url.isValid():
            first_party_url = None

        qtutils.ensure_valid(request_url)

        if not config.get("content.blocking.enabled", url=first_party_url):
            return False

        if blockutils.is_whitelisted_url(request_url):
            return False

        host = request_url.host()

        if config.get("content.blocking.hosts.block_subdomains"):
            return any(
                hostname in self._blocked_hosts
                or hostname in self._config_blocked_hosts
                for hostname in urlutils.widened_hostnames(host)
            )
        else:
            return (
                host in self._blocked_hosts or host in self._config_blocked_hosts
            )
def test_data_url():
    """Test data_url() which can be used from templates."""
    data = jinja.render('test3.html')
    print(data)
    url = QUrl(data)
    assert url.isValid()
    assert data == 'data:text/plain;base64,Zm9v'  # 'foo'
Exemple #6
0
def blocklist_to_url(filename):
    """Get an example.com-URL with the given filename as path."""
    assert not os.path.isabs(filename), filename
    url = QUrl('http://example.com/')
    url.setPath('/' + filename)
    assert url.isValid(), url.errorString()
    return url
def test_invalid_url_error(message_mock, caplog, url, valid, has_err_string):
    """Test invalid_url_error().

    Args:
        url: The URL to check.
        valid: Whether the QUrl is valid (isValid() == True).
        has_err_string: Whether the QUrl is expected to have errorString set.
    """
    qurl = QUrl(url)
    assert qurl.isValid() == valid
    if valid:
        with pytest.raises(ValueError):
            urlutils.invalid_url_error(qurl, '')
        assert not message_mock.messages
    else:
        assert bool(qurl.errorString()) == has_err_string
        with caplog.at_level(logging.ERROR):
            urlutils.invalid_url_error(qurl, 'frozzle')

        msg = message_mock.getmsg(usertypes.MessageLevel.error)
        if has_err_string:
            expected_text = ("Trying to frozzle with invalid URL - " +
                             qurl.errorString())
        else:
            expected_text = "Trying to frozzle with invalid URL"
        assert msg.text == expected_text
Exemple #8
0
    def from_str(cls, line):
        """Parse a history line like '12345 http://example.com title'."""
        data = line.split(maxsplit=2)
        if len(data) == 2:
            atime, url = data
            title = ""
        elif len(data) == 3:
            atime, url, title = data
        else:
            raise ValueError("2 or 3 fields expected")

        url = QUrl(url)
        if not url.isValid():
            raise ValueError("Invalid URL: {}".format(url.errorString()))

        if atime.startswith('\0'):
            log.init.debug(
                "Removing NUL bytes from entry {!r} - see "
                "https://github.com/The-Compiler/qutebrowser/issues/"
                "670".format(data))
            atime = atime.lstrip('\0')

        if '-' in atime:
            atime, flags = atime.split('-')
        else:
            flags = ''

        if not set(flags).issubset('r'):
            raise ValueError("Invalid flags {!r}".format(flags))

        redirect = 'r' in flags

        return cls(atime, url, title, redirect=redirect)
Exemple #9
0
    def resolve_url(self, baseurl: QUrl) -> typing.Optional[QUrl]:
        """Resolve the URL in the element's src/href attribute.

        Args:
            baseurl: The URL to base relative URLs on as QUrl.

        Return:
            A QUrl with the absolute URL, or None.
        """
        if baseurl.isRelative():
            raise ValueError("Need an absolute base URL!")

        for attr in ['href', 'src']:
            if attr in self:
                text = self[attr].strip()
                break
        else:
            return None

        url = QUrl(text)
        if not url.isValid():
            return None
        if url.isRelative():
            url = baseurl.resolved(url)
        qtutils.ensure_valid(url)
        return url
    def __init__(self, qml):
        app = QGuiApplication(sys.argv)

        model = QmlModel()
        model.register()

        qmlUrl = QUrl(qml)
        assert qmlUrl.isValid()
        print(qmlUrl.path())
        # assert qmlUrl.isLocalFile()

        """
    Create an engine a reference to the window?
    
    window = QuickWindowFactory().create(qmlUrl=qmlUrl)
    window.show() # visible
    """
        engine = QQmlApplicationEngine()
        """
    Need this if no stdio, i.e. Android, OSX, iOS.
    OW, qWarnings to stdio.
    engine.warnings.connect(self.errors)
    """
        engine.load(qmlUrl)
        engine.quit.connect(app.quit)

        app.exec_()  # !!! C exec => Python exec_
        print("Application returned")
Exemple #11
0
 def importProfile(self, file_url: QUrl) -> Dict[str, str]:
     if not file_url.isValid():
         return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
     path = file_url.toLocalFile()
     if not path:
         return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
     return self._container_registry.importProfile(path)
Exemple #12
0
    def contextMenuEvent(self, evt):
        """
        Protected method handling context menu events.
        
        @param evt reference to the context menu event (QContextMenuEvent)
        """
        point = evt.globalPos()

        if self.__browser:
            point = self.__browser.mapFromGlobal(point)
            if not self.__browser.rect().contains(point, True):
                return
            link = QUrl(self.__browser.anchorAt(point))
        else:
            point = self.__result.mapFromGlobal(point)
            link = self.__result.linkAt(point)

        if link.isEmpty() or not link.isValid():
            return

        menu = QMenu()
        curTab = menu.addAction(self.tr("Open Link"))
        newTab = menu.addAction(self.tr("Open Link in New Tab"))
        menu.move(evt.globalPos())
        act = menu.exec_()
        if act == curTab:
            self.linkActivated.emit(link)
        elif act == newTab:
            self.__mw.newTab(link)
Exemple #13
0
 def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
     if not file_url.isValid():
         return
     path = file_url.toLocalFile()
     if not path:
         return
     self._container_registry.exportProfile(instance_id, path, file_type)
    def wait_for_load_finished_url(self,
                                   url,
                                   *,
                                   timeout=None,
                                   load_status='success'):
        """Wait until a URL has finished loading."""
        __tracebackhide__ = (
            lambda e: e.errisinstance(testprocess.WaitForTimeout))

        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000

        # We really need the same representation that the webview uses in its
        # __repr__
        qurl = QUrl(url)
        if not qurl.isValid():
            raise ValueError("Invalid URL {}: {}".format(
                url, qurl.errorString()))
        url = utils.elide(qurl.toDisplayString(QUrl.EncodeUnicode), 100)
        assert url

        pattern = re.compile(
            r"(load status for <qutebrowser\.browser\..* "
            r"tab_id=\d+ url='{url}/?'>: LoadStatus\.{load_status}|fetch: "
            r"PyQt5\.QtCore\.QUrl\('{url}'\) -> .*)".format(
                load_status=re.escape(load_status), url=re.escape(url)))

        try:
            self.wait_for(message=pattern, timeout=timeout)
        except testprocess.WaitForTimeout:
            raise testprocess.WaitForTimeout("Timed out while waiting for {} "
                                             "to be loaded".format(url))
def test_data_url():
    """Test data_url() which can be used from templates."""
    data = jinja.render('test3.html')
    print(data)
    url = QUrl(data)
    assert url.isValid()
    assert data == 'data:text/plain;base64,Zm9v'  # 'foo'
def blocklist_to_url(filename):
    """Get an example.com-URL with the given filename as path."""
    assert not os.path.isabs(filename), filename
    url = QUrl('http://example.com/')
    url.setPath('/' + filename)
    assert url.isValid(), url.errorString()
    return url
Exemple #17
0
    def from_str(cls, line):
        """Parse a history line like '12345 http://example.com title'."""
        data = line.split(maxsplit=2)
        if len(data) == 2:
            atime, url = data
            title = ""
        elif len(data) == 3:
            atime, url, title = data
        else:
            raise ValueError("2 or 3 fields expected")

        url = QUrl(url)
        if not url.isValid():
            raise ValueError("Invalid URL: {}".format(url.errorString()))

        if atime.startswith('\0'):
            log.init.debug(
                "Removing NUL bytes from entry {!r} - see "
                "https://github.com/The-Compiler/qutebrowser/issues/"
                "670".format(data))
            atime = atime.lstrip('\0')

        if '-' in atime:
            atime, flags = atime.split('-')
        else:
            flags = ''

        if not set(flags).issubset('r'):
            raise ValueError("Invalid flags {!r}".format(flags))

        redirect = 'r' in flags

        return cls(atime, url, title, redirect=redirect)
Exemple #18
0
 def contextMenuEvent(self, evt):
     """
     Protected method handling context menu events.
     
     @param evt reference to the context menu event (QContextMenuEvent)
     """
     point = evt.globalPos()
     
     if self.__browser:
         point = self.__browser.mapFromGlobal(point)
         if not self.__browser.rect().contains(point, True):
             return
         link = QUrl(self.__browser.anchorAt(point))
     else:
         point = self.__result.mapFromGlobal(point)
         link = self.__result.linkAt(point)
     
     if link.isEmpty() or not link.isValid():
         return
     
     menu = QMenu()
     curTab = menu.addAction(self.tr("Open Link"))
     newTab = menu.addAction(self.tr("Open Link in New Tab"))
     menu.move(evt.globalPos())
     act = menu.exec_()
     if act == curTab:
         self.linkActivated.emit(link)
     elif act == newTab:
         self.__mw.newTab(link)
Exemple #19
0
    def acceptNavigationRequest(self,
                                url: QUrl,
                                typ: QWebEnginePage.NavigationType,
                                is_main_frame: bool):
        """Override acceptNavigationRequest to handle clicked links.

        Setting linkDelegationPolicy to DelegateAllLinks and using a slot bound
        to linkClicked won't work correctly, because when in a frameset, we
        have no idea in which frame the link should be opened.

        Checks if it should open it in a tab (middle-click or control) or not,
        and then conditionally opens the URL. Opening it in a new tab/window
        is handled in the slot connected to link_clicked.
        """
        target = self._tabdata.combined_target()
        log.webview.debug("navigation request: url {}, type {}, "
                          "target {}, is_main_frame {}".format(
                              url.toDisplayString(),
                              debug.qenum_key(QWebEnginePage, typ),
                              target, is_main_frame))

        if typ != QWebEnginePage.NavigationTypeLinkClicked:
            return True

        self.link_clicked.emit(url)

        return url.isValid() and target == usertypes.ClickTarget.normal
Exemple #20
0
    def wait_for_load_finished_url(self, url, *, timeout=None,
                                   load_status='success'):
        """Wait until a URL has finished loading."""
        __tracebackhide__ = (lambda e: e.errisinstance(
            testprocess.WaitForTimeout))

        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000

        # We really need the same representation that the webview uses in its
        # __repr__
        qurl = QUrl(url)
        if not qurl.isValid():
            raise ValueError("Invalid URL {}: {}".format(url,
                                                         qurl.errorString()))
        url = utils.elide(qurl.toDisplayString(QUrl.EncodeUnicode), 100)
        assert url

        pattern = re.compile(
            r"(load status for <qutebrowser\.browser\..* "
            r"tab_id=\d+ url='{url}/?'>: LoadStatus\.{load_status}|fetch: "
            r"PyQt5\.QtCore\.QUrl\('{url}'\) -> .*)".format(
                load_status=re.escape(load_status), url=re.escape(url)))

        try:
            self.wait_for(message=pattern, timeout=timeout)
        except testprocess.WaitForTimeout:
            raise testprocess.WaitForTimeout("Timed out while waiting for {} "
                                             "to be loaded".format(url))
Exemple #21
0
 def readLocalFile(self,
                   file: QUrl,
                   add_to_recent_files_hint: bool = True) -> None:
     if not file.isValid():
         return
     if add_to_recent_files_hint:
         self._add_to_recent_files_hints.append(file)
     self._readLocalFile(file)
    def test_strip(self, url_suffix):
        url_base = 'https://example.com/test'
        url = QUrl(url_base + url_suffix)
        assert url.isValid()

        stripped = navigate.strip(url, count=1)
        assert stripped.isValid()
        assert stripped == QUrl(url_base)
Exemple #23
0
 def setUrl(self, url):
     """
     Public slot to set the xmlrpc handler URL.
     
     @param url xmlrpc handler URL (string or QUrl)
     """
     url = QUrl(url)
     if url.isValid():
         self.__request.setUrl(url)
Exemple #24
0
    def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
        if not file_url.isValid():
            return
        path = file_url.toLocalFile()
        if not path:
            return

        container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
        self._container_registry.exportQualityProfile(container_list, path, file_type)
 def setUrl(self, url):
     """
     Public slot to set the xmlrpc handler URL.
     
     @param url xmlrpc handler URL (string or QUrl)
     """
     url = QUrl(url)
     if url.isValid():
         self.__request.setUrl(url)
Exemple #26
0
    def importProfile(self, file_url: QUrl) -> Dict[str, str]:
        """Import single profile, file_url does not have to end with curaprofile"""

        if not file_url.isValid():
            return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
        path = file_url.toLocalFile()
        if not path:
            return {"status": "error", "message": catalog.i18nc("@info:status", "Invalid file URL:") + " " + str(file_url)}
        return cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().importProfile(path)
Exemple #27
0
    def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
        if not file_url.isValid():
            return
        path = file_url.toLocalFile()
        if not path:
            return

        container_list = [n.getContainer() for n in quality_changes_group.getAllNodes() if n.getContainer() is not None]
        self._container_registry.exportQualityProfile(container_list, path, file_type)
Exemple #28
0
def is_special_url(url: QUrl) -> bool:
    """Return True if url is an about:... or other special URL.

    Args:
        url: The URL as QUrl.
    """
    if not url.isValid():
        return False
    special_schemes = ('about', 'qute', 'file')
    return url.scheme() in special_schemes
Exemple #29
0
def main():
    import sys

    app = QApplication(sys.argv)

    QQuickWindow.setDefaultAlphaBuffer(True)

    QCoreApplication.setApplicationName("Photosurface")
    QCoreApplication.setOrganizationName("QtProject")
    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("Qt Quick Demo - Photo Surface")
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument("directory",
                                 "The image directory or URL to show.")
    parser.process(app)

    initialUrl = QUrl()
    if parser.positionalArguments():
        initialUrl = QUrl.fromUserInput(parser.positionalArguments()[0],
                                        QDir.currentPath(),
                                        QUrl.AssumeLocalFile)
        if not initialUrl.isValid():
            print(
                'Invalid argument: "',
                parser.positionalArguments()[0],
                '": ',
                initialUrl.errorString(),
            )
            sys.exit(1)

    nameFilters = imageNameFilters()

    engine = QQmlApplicationEngine()
    context: QQmlContext = engine.rootContext()

    picturesLocationUrl = QUrl.fromLocalFile(QDir.homePath())
    picturesLocations = QStandardPaths.standardLocations(
        QStandardPaths.PicturesLocation)
    if picturesLocations:
        picturesLocationUrl = QUrl.fromLocalFile(picturesLocations[0])
        if not initialUrl and QDir(picturesLocations[0]).entryInfoList(
                nameFilters, QDir.Files):
            initialUrl = picturesLocationUrl

    context.setContextProperty("contextPicturesLocation", picturesLocationUrl)
    context.setContextProperty("contextInitialUrl", initialUrl)
    context.setContextProperty("contextImageNameFilters", nameFilters)

    engine.load(QUrl("qrc:///photosurface.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
Exemple #30
0
    def onItemClicked(self, idx):
        item = self.model.itemFromIndex(idx)

        if isinstance(item, AtomFeedEntryItem):
            url = QUrl(item.entry.id)
            if url.isValid():
                self.webView.load(url)

            self.model.markEntryAsRead(item)
            item.setFont(self.fontRead)
            item.parent().updateTitle()
Exemple #31
0
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise configexc.ValidationError(value, "may not be empty!")
     if "{}" not in value:
         raise configexc.ValidationError(value, 'must contain "{}"')
     url = QUrl(value.replace("{}", "foobar"))
     if not url.isValid():
         raise configexc.ValidationError(value, "invalid url, {}".format(url.errorString()))
Exemple #32
0
    def test_hypothesis(self, source):
        scheme = 'javascript:'
        url = QUrl(scheme + urllib.parse.quote(source))
        hypothesis.assume(url.isValid())

        try:
            parsed = urlutils.parse_javascript_url(url)
        except urlutils.Error:
            pass
        else:
            assert parsed == source
Exemple #33
0
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise ValidationError(value, "may not be empty!")
     if '{}' not in value:
         raise ValidationError(value, "must contain \"{}\"")
     url = QUrl(value.replace('{}', 'foobar'))
     if not url.isValid():
         raise ValidationError(value,
                               "invalid url, {}".format(url.errorString()))
Exemple #34
0
def invalid_url_error(url: QUrl, action: str) -> None:
    """Display an error message for a URL.

    Args:
        action: The action which was interrupted by the error.
    """
    if url.isValid():
        raise ValueError("Calling invalid_url_error with valid URL {}".format(
            url.toDisplayString()))
    errstring = get_errstring(url,
                              "Trying to {} with invalid URL".format(action))
    message.error(errstring)
Exemple #35
0
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise configexc.ValidationError(value, "may not be empty!")
     if '{}' not in value:
         raise configexc.ValidationError(value, "must contain \"{}\"")
     url = QUrl(value.replace('{}', 'foobar'))
     if not url.isValid():
         raise configexc.ValidationError(value, "invalid url, {}".format(
             url.errorString()))
Exemple #36
0
 def qmlFilenameToQUrl(self, qmlSubpath):
   
   root_url = 'qrc:' if self._root.startswith(':') else self._root
   print("root_url: ", root_url)
   #url = QUrl(root_url + '/' + self._appPackageName + qmlSubpath)
   url = QUrl(root_url + qmlSubpath)
   
   print("urlToQMLResource", url)
   assert url.isValid()
   #print(url.path())
   #assert url.isLocalFile()
   return url
Exemple #37
0
def _has_explicit_scheme(url: QUrl):
    """Check if a url has an explicit scheme given.

    Args:
        url: The URL as QUrl.
    """
    # Note that generic URI syntax actually would allow a second colon
    # after the scheme delimiter. Since we don't know of any URIs
    # using this and want to support e.g. searching for scoped C++
    # symbols, we treat this as not a URI anyways.
    return (url.isValid() and url.scheme() and (url.host() or url.path())
            and " " not in url.path() and not url.path().startswith(":"))
Exemple #38
0
def test_whitespace_hosts(host):
    """Test that whitespace dot hosts are invalid.

    This is a deviation from Chromium.
    """
    template = 'https://{}/*'
    url = QUrl(template.format(host))
    assert not url.isValid()

    with pytest.raises(urlmatch.ParseError,
                       match='Invalid host|Pattern without host'):
        urlmatch.UrlPattern(template.format(host))
Exemple #39
0
    def qmlFilenameToQUrl(self, qmlSubpath):

        root_url = 'qrc:' if self._root.startswith(':') else self._root
        print("root_url: ", root_url)
        #url = QUrl(root_url + '/' + self._appPackageName + qmlSubpath)
        url = QUrl(root_url + qmlSubpath)

        print("urlToQMLResource", url)
        assert url.isValid()
        #print(url.path())
        #assert url.isLocalFile()
        return url
Exemple #40
0
    def exportQualityChangesGroup(self, quality_changes_group: "QualityChangesGroup", file_url: QUrl, file_type: str) -> None:
        if not file_url.isValid():
            return
        path = file_url.toLocalFile()
        if not path:
            return

        container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
        container_list = [cast(InstanceContainer, container_registry.findContainers(id = quality_changes_group.metadata_for_global["id"])[0])]  # type: List[InstanceContainer]
        for metadata in quality_changes_group.metadata_per_extruder.values():
            container_list.append(cast(InstanceContainer, container_registry.findContainers(id = metadata["id"])[0]))
        cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry().exportQualityProfile(container_list, path, file_type)
Exemple #41
0
def get(name):
    """Get the URL of the quickmark named name as a QUrl."""
    if name not in marks:
        raise cmdexc.CommandError(
            "Quickmark '{}' does not exist!".format(name))
    urlstr = marks[name]
    url = QUrl(urlstr)
    if not url.isValid():
        raise cmdexc.CommandError(
            "Invalid URL for quickmark {}: {} ({})".format(name, urlstr,
                                                           url.errorString()))
    return url
Exemple #42
0
 def addToPlaylist(self, fileNames):
     for name in fileNames:
         fileInfo = QFileInfo(name)
         if fileInfo.exists():
             url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
             if fileInfo.suffix().lower() == 'm3u':
                 self.playlist.load(url)
             else:
                 self.playlist.addMedia(QMediaContent(url))
         else:
             url = QUrl(name)
             if url.isValid():
                 self.playlist.addMedia(QMediaContent(url))
Exemple #43
0
 def openOnStart(self, name):
     fileInfo = QFileInfo(name)
     if fileInfo.exists():
         url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
         if fileInfo.suffix().lower() == 'm3u':
             self.playlist.load(url)
         else:
             self.playlist.addMedia(QMediaContent(url))
     else:
         url = QUrl(name)
         if url.isValid():
             self.playlist.addMedia(QMediaContent(url))
     print("added Files to playlist")
Exemple #44
0
 def addToPlaylist(self, fileNames):
     for name in fileNames:
         fileInfo = QFileInfo(name)
         if fileInfo.exists():
             url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
             if fileInfo.suffix().lower() == 'm3u':
                 self.playlist.load(url)
             else:
                 self.playlist.addMedia(QMediaContent(url))
         else:
             url = QUrl(name)
             if url.isValid():
                 self.playlist.addMedia(QMediaContent(url))
Exemple #45
0
    def __init__(self, connections=None, parent=None):
        """
        Constructor
        
        @param connections list of database connections to add
            (list of strings)
        @param parent reference to the parent widget (QWidget)
        """
        super(SqlBrowser, self).__init__(parent)
        self.setObjectName("SqlBrowser")

        if connections is None:
            connections = []

        self.setWindowTitle(self.tr("SQL Browser"))
        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))

        self.setStyle(Preferences.getUI("Style"),
                      Preferences.getUI("StyleSheet"))

        from .SqlBrowserWidget import SqlBrowserWidget
        self.__browser = SqlBrowserWidget(self)
        self.setCentralWidget(self.__browser)

        self.__browser.statusMessage.connect(self.statusBar().showMessage)

        self.__initActions()
        self.__initMenus()
        self.__initToolbars()

        self.resize(self.__browser.size())

        self.__warnings = []

        for connection in connections:
            url = QUrl(connection, QUrl.TolerantMode)
            if not url.isValid():
                self.__warnings.append(
                    self.tr("Invalid URL: {0}").format(connection))
                continue

            err = self.__browser.addConnection(url.scheme(), url.path(),
                                               url.userName(), url.password(),
                                               url.host(), url.port(-1))
            if err.type() != QSqlError.NoError:
                self.__warnings.append(
                    self.tr("Unable to open connection: {0}".format(
                        err.text())))

        QTimer.singleShot(0, self.__uiStartUp)
Exemple #46
0
    def _is_blocked(self, request_url: QUrl,
                    first_party_url: QUrl = None) -> bool:
        """Check whether the given request is blocked."""
        if first_party_url is not None and not first_party_url.isValid():
            first_party_url = None

        if not config.get('content.host_blocking.enabled',
                          url=first_party_url):
            return False

        host = request_url.host()
        return ((host in self._blocked_hosts or
                 host in self._config_blocked_hosts) and
                not _is_whitelisted_url(request_url))
Exemple #47
0
    def _is_blocked(self, request_url: QUrl,
                    first_party_url: QUrl = None) -> bool:
        """Check whether the given request is blocked."""
        if first_party_url is not None and not first_party_url.isValid():
            first_party_url = None

        if not config.get('content.host_blocking.enabled',
                          url=first_party_url):
            return False

        host = request_url.host()
        return ((host in self._blocked_hosts or
                 host in self._config_blocked_hosts) and
                not _is_whitelisted_url(request_url))
Exemple #48
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     elif value in self.valid_values:
         return
     url = QUrl(value)
     if not url.isValid():
         raise configexc.ValidationError(value, "invalid url, {}".format(
             url.errorString()))
     elif url.scheme() not in self.PROXY_TYPES:
         raise configexc.ValidationError(value, "must be a proxy URL "
                                         "(http://... or socks://...) or "
                                         "system/none!")
Exemple #49
0
    def quickmark_load(self, name, tab=False, bg=False):
        """Load a quickmark.

        Args:
            name: The name of the quickmark to load.
            tab: Load the quickmark in a new tab.
            bg: Load the quickmark in a new background tab.
        """
        urlstr = quickmarks.get(name)
        url = QUrl(urlstr)
        if not url.isValid():
            raise cmdexc.CommandError("Invalid URL {} ({})".format(
                urlstr, url.errorString()))
        self._open(url, tab, bg)
Exemple #50
0
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise ValidationError(value, "may not be empty!")
     if value in self.valid_values:
         return
     url = QUrl(value)
     if not url.isValid():
         raise ValidationError(value, "invalid url, {}".format(
             url.errorString()))
     elif url.scheme() not in self.PROXY_TYPES:
         raise ValidationError(value, "must be a proxy URL (http://... or "
                                      "socks://...) or system/none!")
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise ValidationError(value, "may not be empty!")
     if value in self.valid_values:
         return
     url = QUrl(value)
     if not url.isValid():
         raise ValidationError(value, "invalid url, {}".format(
             url.errorString()))
     elif url.scheme() not in self.PROXY_TYPES:
         raise ValidationError(value, "must be a proxy URL (http://... or "
                                      "socks://...) or system/none!")
Exemple #52
0
    def validate(self, value):
        self._basic_validation(value)
        if not value:
            return
        elif '{}' not in value:
            raise configexc.ValidationError(value, "must contain \"{}\"")
        try:
            value.format("")
        except KeyError:
            raise configexc.ValidationError(
                value, "may not contain {...} (use {{ and }} for literal {/})")

        url = QUrl(value.replace('{}', 'foobar'))
        if not url.isValid():
            raise configexc.ValidationError(value, "invalid url, {}".format(
                url.errorString()))
def test_resource_url():
    """Test resource_url() which can be used from templates."""
    data = jinja.render('test2.html')
    print(data)
    url = QUrl(data)
    assert url.isValid()
    assert url.scheme() == 'file'

    path = url.path()

    if os.name == "nt":
        path = path.lstrip('/')
        path = path.replace('/', os.sep)

    with open(path, 'r', encoding='utf-8') as f:
        assert f.read().splitlines()[0] == "Hello World!"
Exemple #54
0
 def __init__(self, connections=[], parent=None):
     """
     Constructor
     
     @param connections list of database connections to add
         (list of strings)
     @param parent reference to the parent widget (QWidget)
     """
     super(SqlBrowser, self).__init__(parent)
     self.setObjectName("SqlBrowser")
     
     self.setWindowTitle(self.tr("SQL Browser"))
     self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
     
     self.setStyle(Preferences.getUI("Style"),
                   Preferences.getUI("StyleSheet"))
     
     from .SqlBrowserWidget import SqlBrowserWidget
     self.__browser = SqlBrowserWidget(self)
     self.setCentralWidget(self.__browser)
     
     self.__browser.statusMessage.connect(self.statusBar().showMessage)
     
     self.__initActions()
     self.__initMenus()
     self.__initToolbars()
     
     self.resize(self.__browser.size())
     
     self.__warnings = []
     
     for connection in connections:
         url = QUrl(connection, QUrl.TolerantMode)
         if not url.isValid():
             self.__warnings.append(
                 self.tr("Invalid URL: {0}").format(connection))
             continue
         
         err = self.__browser.addConnection(url.scheme(), url.path(),
                                            url.userName(), url.password(),
                                            url.host(), url.port(-1))
         if err.type() != QSqlError.NoError:
             self.__warnings.append(
                 self.tr("Unable to open connection: {0}".format(
                     err.text())))
     
     QTimer.singleShot(0, self.__uiStartUp)
Exemple #55
0
def test_resource_url():
    """Test resource_url() which can be used from templates."""
    template = jinja.env.get_template("test2.html")
    data = template.render()  # pylint: disable=no-member
    print(data)
    url = QUrl(data)
    assert url.isValid()
    assert url.scheme() == "file"

    path = url.path()

    if os.name == "nt":
        path = path.lstrip("/")
        path = path.replace("/", os.sep)

    with open(path, "r", encoding="utf-8") as f:
        assert f.read().splitlines()[0] == "Hello World!"
Exemple #56
0
 def __addFeed(self):
     """
     Private slot to add a RSS feed.
     """
     button = self.sender()
     urlString = button.feed[1]
     url = QUrl(urlString)
     if not url.host():
         if not urlString.startswith("/"):
             urlString = "/" + urlString
         urlString = self.__browser.url().host() + urlString
         tmpUrl = QUrl(urlString)
         if not tmpUrl.scheme():
             urlString = "http://" + urlString
         tmpUrl = QUrl(urlString)
         if not tmpUrl.scheme() or not tmpUrl.host():
             return
     if not url.isValid():
         return
     
     if button.feed[0]:
         title = button.feed[0]
     else:
         title = self.__browser.url().host()
     
     import Helpviewer.HelpWindow
     feedsManager = Helpviewer.HelpWindow.HelpWindow.feedsManager()
     if feedsManager.addFeed(urlString, title, self.__browser.icon()):
         if Helpviewer.HelpWindow.HelpWindow.notificationsEnabled():
             Helpviewer.HelpWindow.HelpWindow.showNotification(
                 UI.PixmapCache.getPixmap("rss48.png"),
                 self.tr("Add RSS Feed"),
                 self.tr("""The feed was added successfully."""))
         else:
             E5MessageBox.information(
                 self,
                 self.tr("Add RSS Feed"),
                 self.tr("""The feed was added successfully."""))
     else:
         E5MessageBox.warning(
             self,
             self.tr("Add RSS Feed"),
             self.tr("""The feed was already added before."""))
         
     self.close()
Exemple #57
0
    def set_hover_url(self, link):
        """Setter to be used as a Qt slot.

        Saves old shown URL in self._old_url and restores it later if a link is
        "un-hovered" when it gets called with empty parameters.

        Args:
            link: The link which was hovered (string)
        """
        if link:
            qurl = QUrl(link)
            if qurl.isValid():
                self._hover_url = qurl.toDisplayString()
            else:
                self._hover_url = link
        else:
            self._hover_url = None
        self._update_url()
Exemple #58
0
    def set_hover_url(self, link):
        """Setter to be used as a Qt slot.

        Saves old shown URL in self._old_url and restores it later if a link is
        "un-hovered" when it gets called with empty parameters.

        Args:
            link: The link which was hovered (string)
        """
        if link:
            qurl = QUrl(link)
            if qurl.isValid():
                self._hover_url = urlutils.safe_display_string(qurl)
            else:
                self._hover_url = '(invalid URL!) {}'.format(link)
        else:
            self._hover_url = None
        self._update_url()
    def acceptNavigationRequest(self,
                                url: QUrl,
                                typ: QWebEnginePage.NavigationType,
                                is_main_frame: bool):
        """Override acceptNavigationRequest to handle clicked links.

        This only show an error on invalid links - everything else is handled
        in createWindow.
        """
        log.webview.debug("navigation request: url {}, type {}, is_main_frame "
                          "{}".format(url.toDisplayString(),
                                      debug.qenum_key(QWebEnginePage, typ),
                                      is_main_frame))
        if (typ == QWebEnginePage.NavigationTypeLinkClicked and
                not url.isValid()):
            msg = urlutils.get_errstring(url, "Invalid link clicked")
            message.error(msg)
            return False
        return True