Пример #1
0
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
Пример #2
0
def test_addGetDisplayComponent():
    stage = Stage()
    stage.addDisplayComponent("BLORP", "location")
    assert stage.getDisplayComponent("BLORP") == QUrl.fromLocalFile("location")

    stage.addDisplayComponent("MEEP!", QUrl.fromLocalFile("MEEP"))
    assert stage.getDisplayComponent("MEEP!") == QUrl.fromLocalFile("MEEP")
Пример #3
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))
Пример #4
0
 def open_file(self, file_name):
     if len(file_name) > 0:
         url = QUrl()
         self.media_player.setMedia(QMediaContent(url.fromLocalFile(file_name)))
         self.play_button.setEnabled(True)
         self.show()
         self.play()
Пример #5
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)
Пример #6
0
    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()
Пример #7
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)
Пример #8
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)
Пример #9
0
 def _load_tab(self, new_tab, data):
     """Load yaml data into a newly opened tab."""
     entries = []
     for histentry in data['history']:
         user_data = {}
         if 'zoom' in data:
             user_data['zoom'] = data['zoom']
         if 'scroll-pos' in data:
             pos = data['scroll-pos']
             user_data['scroll-pos'] = QPoint(pos['x'], pos['y'])
         active = histentry.get('active', False)
         url = QUrl.fromEncoded(histentry['url'].encode('ascii'))
         if 'original-url' in histentry:
             orig_url = QUrl.fromEncoded(
                 histentry['original-url'].encode('ascii'))
         else:
             orig_url = url
         entry = tabhistory.TabHistoryItem(
             url=url, original_url=orig_url, title=histentry['title'],
             active=active, user_data=user_data)
         entries.append(entry)
         if active:
             new_tab.titleChanged.emit(histentry['title'])
     try:
         new_tab.page().load_history(entries)
     except ValueError as e:
         raise SessionError(e)
Пример #10
0
 def save(self, url=None, encoding=None):
     """Saves the document to the specified or current url.
     
     Currently only local files are supported. An IOError is raised
     when trying to save a nonlocal URL.
     
     If saving succeeds and an url was specified, the url is made the
     current url (by calling setUrl() internally).
     
     """
     if url is None:
         url = QUrl()
     u = url if not url.isEmpty() else self.url()
     filename = u.toLocalFile()
     # currently, we do not support non-local files
     if not filename:
         raise IOError("not a local file")
     # keep the url if specified when we didn't have one, even if saving
     # would fail
     if self.url().isEmpty() and not url.isEmpty():
         self.setUrl(url)
     with self.saving(), app.documentSaving(self):
         with open(filename, "wb") as f:
             f.write(self.encodedText())
             f.flush()
             os.fsync(f.fileno())
         self.setModified(False)
         if not url.isEmpty():
             self.setUrl(url)
     self.saved()
     app.documentSaved(self)
Пример #11
0
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'
Пример #12
0
 def command(self, command):
     """Perform one command."""
     command = command.split()
     cmd = command[0]
     args = command[1:]
     
     win = app.activeWindow()
     if not win:
         import mainwindow
         win = mainwindow.MainWindow()
         win.show()
     
     if cmd == b'open':
         url = QUrl.fromEncoded(args[0])
         win.openUrl(url, self.encoding)
             
     elif cmd == b'encoding':
         self.encoding = str(args[0])
     elif cmd == b'activate_window':
         win.activateWindow()
         win.raise_()
     elif cmd == b'set_current':
         url = QUrl.fromEncoded(args[0])
         try:
             win.setCurrentDocument(app.openUrl(url)) # already loaded
         except IOError:
             pass
     elif cmd == b'set_cursor':
         line, column = map(int, args)
         cursor = win.textCursor()
         pos = cursor.document().findBlockByNumber(line - 1).position() + column
         cursor.setPosition(pos)
         win.currentView().setTextCursor(cursor)
     elif cmd == b'bye':
         self.close()
Пример #13
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
Пример #14
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)
Пример #15
0
    def load(self, url=None, encoding=None, keepUndo=False):
        """Load the specified or current url (if None was specified).

        Currently only local files are supported. An IOError is raised
        when trying to load a nonlocal URL.

        If loading succeeds and an url was specified, the url is made the
        current url (by calling setUrl() internally).

        If keepUndo is True, the loading can be undone (with Ctrl-Z).

        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        text = self.load_data(u, encoding or self._encoding)
        if keepUndo:
            c = QTextCursor(self)
            c.select(QTextCursor.Document)
            c.insertText(text)
        else:
            self.setPlainText(text)
        self.setModified(False)
        if not url.isEmpty():
            self.setUrl(url)
Пример #16
0
    def save(self, url=None, encoding=None):
        """Saves the document to the specified or current url.

        Currently only local files are supported. An IOError is raised
        when trying to save a nonlocal URL.

        If saving succeeds and an url was specified, the url is made the
        current url (by calling setUrl() internally).

        This method is never called directly but only from the overriding
        subclass methods that make further specific use of the modified results.

        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        filename = u.toLocalFile()
        # currently, we do not support non-local files
        if not filename:
            raise IOError("not a local file")
        # keep the url if specified when we didn't have one, even if saving
        # would fail
        if self.url().isEmpty() and not url.isEmpty():
            self.setUrl(url)
        return url, filename
Пример #17
0
def test_failed_dl_update(config_stub, basedir, download_stub,
                          data_tmpdir, tmpdir, win_registry):
    """One blocklist fails to download.

    Ensure hosts from this list are not blocked.
    """
    dl_fail_blocklist = QUrl(create_blocklist(tmpdir,
                                              blocked_hosts=CLEAN_HOSTS,
                                              name='download_will_fail',
                                              line_format='one_per_line'))
    hosts_to_block = generic_blocklists(tmpdir) + [dl_fail_blocklist]
    config_stub.data = {
        'content': {
            'host-block-lists': hosts_to_block,
            'host-blocking-enabled': True,
            'host-blocking-whitelist': None,
        }
    }
    host_blocker = adblock.HostBlocker()
    host_blocker.adblock_update(0)
    while host_blocker._in_progress:
        current_download = host_blocker._in_progress[0]
        # if current download is the file we want to fail, make it fail
        if current_download.name == dl_fail_blocklist.path():
            current_download.successful = False
        current_download.finished.emit()
    host_blocker.read_hosts()
    assert_urls(host_blocker, whitelisted=[])
Пример #18
0
    def _on_history_trigger(self):
        try:
            self._widget.page()
        except RuntimeError:
            # Looks like this slot can be triggered on destroyed tabs:
            # https://crashes.qutebrowser.org/view/3abffbed (Qt 5.9.1)
            # wrapped C/C++ object of type WebEngineView has been deleted
            log.misc.debug("Ignoring history trigger for destroyed tab")
            return

        url = self.url()
        requested_url = self.url(requested=True)

        # Don't save the title if it's generated from the URL
        title = self.title()
        title_url = QUrl(url)
        title_url.setScheme('')
        if title == title_url.toDisplayString(QUrl.RemoveScheme).strip('/'):
            title = ""

        # Don't add history entry if the URL is invalid anyways
        if not url.isValid():
            log.misc.debug("Ignoring invalid URL being added to history")
            return

        self.add_history_item.emit(url, requested_url, title)
Пример #19
0
    def registerObjects(self, engine):
        engine.rootContext().setContextProperty("Printer", self)
        engine.rootContext().setContextProperty("CuraApplication", self)
        self._print_information = PrintInformation.PrintInformation()
        engine.rootContext().setContextProperty("PrintInformation", self._print_information)
        self._cura_actions = CuraActions.CuraActions(self)
        engine.rootContext().setContextProperty("CuraActions", self._cura_actions)

        qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")

        qmlRegisterType(cura.Settings.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")

        qmlRegisterType(cura.Settings.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
        qmlRegisterSingletonType(cura.Settings.ProfilesModel, "Cura", 1, 0, "ProfilesModel", cura.Settings.ProfilesModel.createProfilesModel)
        qmlRegisterType(cura.Settings.QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
        qmlRegisterType(cura.Settings.UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
        qmlRegisterType(cura.Settings.MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
        qmlRegisterType(cura.Settings.QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
        qmlRegisterType(cura.Settings.MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")

        qmlRegisterSingletonType(cura.Settings.ContainerManager, "Cura", 1, 0, "ContainerManager", cura.Settings.ContainerManager.createContainerManager)

        # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
        actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
        qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")

        engine.rootContext().setContextProperty("ExtruderManager", cura.Settings.ExtruderManager.getInstance())

        for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
            type_name = os.path.splitext(os.path.basename(path))[0]
            if type_name in ("Cura", "Actions"):
                continue

            qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
Пример #20
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)
Пример #21
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)
Пример #22
0
 def keyPressEvent(self, evt):
     """
     Protected method to handle key presses.
     
     @param evt reference to the key press event (QKeyEvent)
     """
     if evt.key() == Qt.Key_Escape and self.__browser is not None:
         self.setText(
             str(self.__browser.url().toEncoded(), encoding="utf-8"))
         self.selectAll()
         return
     
     currentText = self.text().strip()
     if evt.key() in [Qt.Key_Enter, Qt.Key_Return] and \
        not currentText.lower().startswith("http://"):
         append = ""
         if evt.modifiers() == Qt.KeyboardModifiers(Qt.ControlModifier):
             append = ".com"
         elif evt.modifiers() == Qt.KeyboardModifiers(
                 Qt.ControlModifier | Qt.ShiftModifier):
             append = ".org"
         elif evt.modifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier):
             append = ".net"
         
         if append != "":
             url = QUrl("http://www." + currentText)
             host = url.host()
             if not host.lower().endswith(append):
                 host += append
                 url.setHost(host)
                 self.setText(url.toString())
     
     E5LineEdit.keyPressEvent(self, evt)
Пример #23
0
    def registerObjects(self, engine):
        engine.rootContext().setContextProperty("Printer", self)
        engine.rootContext().setContextProperty("CuraApplication", self)
        self._print_information = PrintInformation.PrintInformation()
        engine.rootContext().setContextProperty("PrintInformation", self._print_information)
        self._cura_actions = CuraActions.CuraActions(self)
        engine.rootContext().setContextProperty("CuraActions", self._cura_actions)

        qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")

        qmlRegisterType(cura.Settings.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")

        qmlRegisterType(cura.Settings.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
        qmlRegisterType(cura.Settings.MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")

        qmlRegisterSingletonType(cura.Settings.ContainerManager, "Cura", 1, 0, "ContainerManager", cura.Settings.ContainerManager.createContainerManager)

        qmlRegisterSingletonType(QUrl.fromLocalFile(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")), "Cura", 1, 0, "Actions")

        engine.rootContext().setContextProperty("ExtruderManager", cura.Settings.ExtruderManager.getInstance())

        for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
            type_name = os.path.splitext(os.path.basename(path))[0]
            if type_name in ("Cura", "Actions"):
                continue

            qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
Пример #24
0
 def getData(self):
     """
     Public method to get the data entered into the dialog.
     
     @return tuple giving the default and default push URLs (tuple of
         two strings)
     """
     defaultUrl = QUrl.fromUserInput(self.defaultUrlEdit.text())
     username = self.defaultUserEdit.text()
     password = self.defaultPasswordEdit.text()
     if username:
         defaultUrl.setUserName(username)
     if password:
         defaultUrl.setPassword(password)
     if not defaultUrl.isValid():
         defaultUrl = ""
     else:
         defaultUrl = defaultUrl.toString()
     
     defaultPushUrl = QUrl.fromUserInput(self.defaultPushUrlEdit.text())
     username = self.defaultPushUserEdit.text()
     password = self.defaultPushPasswordEdit.text()
     if username:
         defaultPushUrl.setUserName(username)
     if password:
         defaultPushUrl.setPassword(password)
     if not defaultPushUrl.isValid():
         defaultPushUrl = ""
     else:
         defaultPushUrl = defaultPushUrl.toString()
     
     return defaultUrl, defaultPushUrl
Пример #25
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
Пример #26
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)
Пример #27
0
def fuzzy_url(urlstr):
    """Get a QUrl based on an user input which is URL or search term.

    Args:
        urlstr: URL to load as a string.

    Return:
        A target QUrl to a searchpage or the original URL.
    """
    path = os.path.abspath(os.path.expanduser(urlstr))
    stripped = urlstr.strip()
    if os.path.exists(path):
        log.url.debug("URL is a local file")
        url = QUrl.fromLocalFile(path)
    elif (not _has_explicit_scheme(QUrl(urlstr)) and
            os.path.exists(os.path.abspath(path))):
        # We do this here rather than in the first block because we first want
        # to make sure it's not an URL like http://, because os.path.abspath
        # would mangle that.
        log.url.debug("URL is a relative local file")
        url = QUrl.fromLocalFile(os.path.abspath(path))
    elif is_url(stripped):
        # probably an address
        log.url.debug("URL is a fuzzy address")
        url = qurl_from_user_input(urlstr)
    else:  # probably a search term
        log.url.debug("URL is a fuzzy search term")
        try:
            url = _get_search_url(urlstr)
        except ValueError:  # invalid search engine
            url = qurl_from_user_input(stripped)
    log.url.debug("Converting fuzzy term {} to URL -> {}".format(
                  urlstr, url.toDisplayString()))
    qtutils.ensure_valid(url)
    return url
Пример #28
0
    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")
Пример #29
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
Пример #30
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
Пример #31
0
def test_on_load_status_changed(url_widget, status, expected):
    """Test text when status is changed."""
    url_widget.set_url(QUrl('www.example.com'))
    url_widget.on_load_status_changed(status.name)
    assert url_widget._urltype == expected
Пример #32
0
 def mouseDoubleClickEvent(self, event):
     # 双击图片得到图片的URL,也可以用来放大显示
     super(TextBrowser, self).mouseDoubleClickEvent(event)
     url = self.anchorAt(event.pos())
     if url:
         print('url:', url, self.document().resource(QTextDocument.ImageResource, QUrl(url)))
Пример #33
0
 def openBugReportPage(self) -> None:
     event = CallFunctionEvent(self._openUrl, [
         QUrl("https://gitlab.com/stereotech/steslicer/ste-slicer/issues")
     ], {})
     steslicer.SteSlicerApplication.SteSlicerApplication.getInstance(
     ).functionEvent(event)
Пример #34
0
 def _menu_api(self):
     QDesktopServices.openUrl(QUrl('https://igio90.github.io/Dwarf/'))
    def server_slot(self, clientState):
        # The switch state echoed back by the client.
        print("Replica state is", clientState)

    def _timeout(self):
        # Note that we don't decorate this callable so that it doesn't get
        # exposed in a replica.
        self.currState = not self.currState

        print("Source state is", self.currState)


if __name__ == '__main__':

    app = QCoreApplication(sys.argv)

    # Create the simple switch.
    srcSwitch = SimpleSwitch()

    # Create the node that hosts the registry.  This could be in a separate
    # process.
    regNode = QRemoteObjectRegistryHost(QUrl('local:registry'))

    # Create the host object node.  This will connect to the registry node
    # rather than to a client.
    srcNode = QRemoteObjectHost(QUrl('local:replica'), QUrl('local:registry'))

    # Enable remoting.
    srcNode.enableRemoting(srcSwitch, 'SimpleSwitch')

    sys.exit(app.exec_())
Пример #36
0
    def __init__(self, pathObj, caption, icons, parent=None):
        """Helpview initialize with text.

        Arguments:
            pathObj -- a path object for the help file
            caption -- the window caption
            icons -- dict of view icons
        """
        QMainWindow.__init__(self, parent)
        self.setAttribute(Qt.WA_QuitOnClose, False)
        self.setWindowFlags(Qt.Window)
        self.setStatusBar(QStatusBar())
        self.textView = HelpViewer(self)
        self.setCentralWidget(self.textView)
        self.textView.setSearchPaths([str(pathObj.parent)])
        self.textView.setSource(QUrl(pathObj.as_uri()))
        self.resize(520, 440)
        self.setWindowTitle(caption)
        tools = self.addToolBar(_('Tools'))
        self.menu = QMenu(self.textView)
        self.textView.highlighted[str].connect(self.showLink)

        backAct = QAction(_('&Back'), self)
        backAct.setIcon(icons['helpback'])
        tools.addAction(backAct)
        self.menu.addAction(backAct)
        backAct.triggered.connect(self.textView.backward)
        backAct.setEnabled(False)
        self.textView.backwardAvailable.connect(backAct.setEnabled)

        forwardAct = QAction(_('&Forward'), self)
        forwardAct.setIcon(icons['helpforward'])
        tools.addAction(forwardAct)
        self.menu.addAction(forwardAct)
        forwardAct.triggered.connect(self.textView.forward)
        forwardAct.setEnabled(False)
        self.textView.forwardAvailable.connect(forwardAct.setEnabled)

        homeAct = QAction(_('&Home'), self)
        homeAct.setIcon(icons['helphome'])
        tools.addAction(homeAct)
        self.menu.addAction(homeAct)
        homeAct.triggered.connect(self.textView.home)

        tools.addSeparator()
        tools.addSeparator()
        findLabel = QLabel(_(' Find: '), self)
        tools.addWidget(findLabel)
        self.findEdit = QLineEdit(self)
        tools.addWidget(self.findEdit)
        self.findEdit.textEdited.connect(self.findTextChanged)
        self.findEdit.returnPressed.connect(self.findNext)

        self.findPreviousAct = QAction(_('Find &Previous'), self)
        self.findPreviousAct.setIcon(icons['helpprevious'])
        tools.addAction(self.findPreviousAct)
        self.menu.addAction(self.findPreviousAct)
        self.findPreviousAct.triggered.connect(self.findPrevious)
        self.findPreviousAct.setEnabled(False)

        self.findNextAct = QAction(_('Find &Next'), self)
        self.findNextAct.setIcon(icons['helpnext'])
        tools.addAction(self.findNextAct)
        self.menu.addAction(self.findNextAct)
        self.findNextAct.triggered.connect(self.findNext)
        self.findNextAct.setEnabled(False)
Пример #37
0
 def _menu_slack(self):
     QDesktopServices.openUrl(
         QUrl('https://join.slack.com/t/resecret/shared_invite'
              '/enQtMzc1NTg4MzE3NjA1LTlkNzYxNTIwYTc2ZTYyOWY1MT'
              'Q1NzBiN2ZhYjQwYmY0ZmRhODQ0NDE3NmRmZjFiMmE1MDYwN'
              'WJlNDVjZDcwNGE'))
Пример #38
0
    def test_set_no_args(self, commands, tabbed_browser_stubs):
        """Run ':set'.

        Should open qute://settings."""
        commands.set(win_id=0)
        assert tabbed_browser_stubs[0].loaded_url == QUrl('qute://settings')
Пример #39
0
def test_diff(commands, tabbed_browser_stubs):
    """Run ':config-diff'.

    Should open qute://configdiff."""
    commands.config_diff(win_id=0)
    assert tabbed_browser_stubs[0].loaded_url == QUrl('qute://configdiff')
Пример #40
0
def data_url(mimetype, data):
    """Get a data: QUrl for the given data."""
    b64 = base64.b64encode(data).decode('ascii')
    url = QUrl('data:{};base64,{}'.format(mimetype, b64))
    qtutils.ensure_valid(url)
    return url
Пример #41
0
class TestBind:
    """Tests for :bind and :unbind."""
    @pytest.fixture
    def no_bindings(self):
        """Get a dict with no bindings."""
        return {'normal': {}}

    @pytest.mark.parametrize("mode, url", [
        ("normal", QUrl("qute://bindings")),
        ("passthrough", QUrl("qute://bindings#passthrough")),
    ])
    def test_bind_no_args(self, commands, config_stub, no_bindings,
                          tabbed_browser_stubs, mode, url):
        """Run ':bind'.

        Should open qute://bindings."""
        config_stub.val.bindings.default = no_bindings
        config_stub.val.bindings.commands = no_bindings
        commands.bind(win_id=0, mode=mode)
        assert tabbed_browser_stubs[0].loaded_url == url

    @pytest.mark.parametrize('command', ['nop', 'nope'])
    def test_bind(self, commands, config_stub, no_bindings, key_config_stub,
                  yaml_value, command):
        """Simple :bind test (and aliases)."""
        config_stub.val.aliases = {'nope': 'nop'}
        config_stub.val.bindings.default = no_bindings
        config_stub.val.bindings.commands = no_bindings

        commands.bind(0, 'a', command)
        assert key_config_stub.get_command(keyseq('a'), 'normal') == command
        yaml_bindings = yaml_value('bindings.commands')['normal']
        assert yaml_bindings['a'] == command

    @pytest.mark.parametrize(
        'key, mode, expected',
        [
            # Simple
            ('a', 'normal', "a is bound to 'message-info a' in normal mode"),
            # Alias
            ('b', 'normal', "b is bound to 'mib' in normal mode"),
            # Custom binding
            ('c', 'normal', "c is bound to 'message-info c' in normal mode"),
            # Special key
            ('<Ctrl-X>', 'normal',
             "<Ctrl+x> is bound to 'message-info C-x' in normal mode"),
            # unbound
            ('x', 'normal', "x is unbound in normal mode"),
            # non-default mode
            ('x', 'caret', "x is bound to 'nop' in caret mode"),
        ])
    def test_bind_print(self, commands, config_stub, message_mock, key, mode,
                        expected):
        """Run ':bind key'.

        Should print the binding.
        """
        config_stub.val.aliases = {'mib': 'message-info b'}
        config_stub.val.bindings.default = {
            'normal': {
                'a': 'message-info a',
                'b': 'mib',
                '<Ctrl+x>': 'message-info C-x'
            },
            'caret': {
                'x': 'nop'
            }
        }
        config_stub.val.bindings.commands = {'normal': {'c': 'message-info c'}}

        commands.bind(0, key, mode=mode)

        msg = message_mock.getmsg(usertypes.MessageLevel.info)
        assert msg.text == expected

    @pytest.mark.parametrize(
        'command, args, kwargs, expected',
        [
            # :bind --mode=wrongmode a nop
            ('bind', ['a', 'nop'], {
                'mode': 'wrongmode'
            }, 'Invalid mode wrongmode!'),
            # :bind --mode=wrongmode a
            ('bind', ['a'], {
                'mode': 'wrongmode'
            }, 'Invalid mode wrongmode!'),
            # :bind --default --mode=wrongmode a
            ('bind', ['a'], {
                'mode': 'wrongmode',
                'default': True
            }, 'Invalid mode wrongmode!'),
            # :bind --default foobar
            ('bind', ['foobar'], {
                'default': True
            }, "Can't find binding 'foobar' in normal mode"),
            # :bind <blub> nop
            ('bind', ['<blub>', 'nop'
                      ], {}, "Could not parse '<blub>': Got invalid key!"),
            # :unbind foobar
            ('unbind', ['foobar'
                        ], {}, "Can't find binding 'foobar' in normal mode"),
            # :unbind --mode=wrongmode x
            ('unbind', ['x'], {
                'mode': 'wrongmode'
            }, 'Invalid mode wrongmode!'),
            # :unbind <blub>
            ('unbind', ['<blub>'
                        ], {}, "Could not parse '<blub>': Got invalid key!"),
        ])
    def test_bind_invalid(self, commands, command, args, kwargs, expected):
        """Run various wrong :bind/:unbind invocations.

        Should show an error.
        """
        if command == 'bind':
            func = functools.partial(commands.bind, 0)
        elif command == 'unbind':
            func = commands.unbind

        with pytest.raises(cmdutils.CommandError, match=expected):
            func(*args, **kwargs)

    @pytest.mark.parametrize('key', ['a', 'b', '<Ctrl-X>'])
    def test_bind_duplicate(self, commands, config_stub, key_config_stub, key):
        """Run ':bind' with a key which already has been bound.'.

        Also tests for https://github.com/qutebrowser/qutebrowser/issues/1544
        """
        config_stub.val.bindings.default = {
            'normal': {
                'a': 'nop',
                '<Ctrl+x>': 'nop'
            }
        }
        config_stub.val.bindings.commands = {
            'normal': {
                'b': 'nop'
            },
        }

        commands.bind(0, key, 'message-info foo', mode='normal')
        command = key_config_stub.get_command(keyseq(key), 'normal')
        assert command == 'message-info foo'

    def test_bind_none(self, commands, config_stub):
        config_stub.val.bindings.commands = None
        commands.bind(0, ',x', 'nop')

    def test_bind_default(self, commands, key_config_stub, config_stub):
        """Bind a key to its default."""
        default_cmd = 'message-info default'
        bound_cmd = 'message-info bound'
        config_stub.val.bindings.default = {'normal': {'a': default_cmd}}
        config_stub.val.bindings.commands = {'normal': {'a': bound_cmd}}
        command = key_config_stub.get_command(keyseq('a'), mode='normal')
        assert command == bound_cmd

        commands.bind(0, 'a', mode='normal', default=True)

        command = key_config_stub.get_command(keyseq('a'), mode='normal')
        assert command == default_cmd

    def test_unbind_none(self, commands, config_stub):
        config_stub.val.bindings.commands = None
        commands.unbind('H')

    @pytest.mark.parametrize(
        'key, normalized',
        [
            ('a', 'a'),  # default bindings
            ('b', 'b'),  # custom bindings
            ('c', 'c'),  # :bind then :unbind
            ('<Ctrl-X>', '<Ctrl+x>')  # normalized special binding
        ])
    def test_unbind(self, commands, key_config_stub, config_stub, yaml_value,
                    key, normalized):
        config_stub.val.bindings.default = {
            'normal': {
                'a': 'nop',
                '<ctrl+x>': 'nop'
            },
            'caret': {
                'a': 'nop',
                '<ctrl+x>': 'nop'
            },
        }
        config_stub.val.bindings.commands = {
            'normal': {
                'b': 'nop'
            },
            'caret': {
                'b': 'nop'
            },
        }
        if key == 'c':
            # Test :bind and :unbind
            commands.bind(0, key, 'nop')

        commands.unbind(key)
        assert key_config_stub.get_command(keyseq(key), 'normal') is None

        yaml_bindings = yaml_value('bindings.commands')['normal']
        if key in 'bc':
            # Custom binding
            assert normalized not in yaml_bindings
        else:
            assert yaml_bindings[normalized] is None
 def videoyuOynat(self, video):
     self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(video)))
     self.mediaPlayer.play()
Пример #43
0
    def _onGetPrinterDataFinished(self, reply):
        status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        if status_code == 200:
            try:
                result = json.loads(bytes(reply.readAll()).decode("utf-8"))
            except json.decoder.JSONDecodeError:
                Logger.log(
                    "w",
                    "Received an invalid printer state message: Not valid JSON."
                )
                return

            if not self._printers:
                # Quickest way to get the firmware version is to grab it from the zeroconf.
                firmware_version = self._properties.get(
                    b"firmware_version", b"").decode("utf-8")
                self._printers = [
                    PrinterOutputModel(
                        output_controller=self._output_controller,
                        number_of_extruders=self._number_of_extruders,
                        firmware_version=firmware_version)
                ]
                self._printers[0].setCameraUrl(
                    QUrl("http://" + self._address + ":8080/?action=stream"))
                for extruder in self._printers[0].extruders:
                    extruder.activeMaterialChanged.connect(
                        self.materialIdChanged)
                    extruder.hotendIDChanged.connect(self.hotendIdChanged)
                self.printersChanged.emit()

            # LegacyUM3 always has a single printer.
            printer = self._printers[0]
            printer.updateBedTemperature(
                result["bed"]["temperature"]["current"])
            printer.updateTargetBedTemperature(
                result["bed"]["temperature"]["target"])
            printer.updateState(result["status"])

            try:
                # If we're still handling the request, we should ignore remote for a bit.
                if not printer.getController().isPreheatRequestInProgress():
                    printer.updateIsPreheating(
                        result["bed"]["pre_heat"]["active"])
            except KeyError:
                # Older firmwares don't support preheating, so we need to fake it.
                pass

            head_position = result["heads"][0]["position"]
            printer.updateHeadPosition(head_position["x"], head_position["y"],
                                       head_position["z"])

            for index in range(0, self._number_of_extruders):
                temperatures = result["heads"][0]["extruders"][index][
                    "hotend"]["temperature"]
                extruder = printer.extruders[index]
                extruder.updateTargetHotendTemperature(temperatures["target"])
                extruder.updateHotendTemperature(temperatures["current"])

                material_guid = result["heads"][0]["extruders"][index][
                    "active_material"]["guid"]

                if extruder.activeMaterial is None or extruder.activeMaterial.guid != material_guid:
                    # Find matching material (as we need to set brand, type & color)
                    containers = ContainerRegistry.getInstance(
                    ).findInstanceContainers(type="material",
                                             GUID=material_guid)
                    if containers:
                        color = containers[0].getMetaDataEntry("color_code")
                        brand = containers[0].getMetaDataEntry("brand")
                        material_type = containers[0].getMetaDataEntry(
                            "material")
                        name = containers[0].getName()
                    else:
                        # Unknown material.
                        color = "#00000000"
                        brand = "Unknown"
                        material_type = "Unknown"
                        name = "Unknown"
                    material = MaterialOutputModel(guid=material_guid,
                                                   type=material_type,
                                                   brand=brand,
                                                   color=color,
                                                   name=name)
                    extruder.updateActiveMaterial(material)

                try:
                    hotend_id = result["heads"][0]["extruders"][index][
                        "hotend"]["id"]
                except KeyError:
                    hotend_id = ""
                printer.extruders[index].updateHotendID(hotend_id)

        else:
            Logger.log(
                "w",
                "Got status code {status_code} while trying to get printer data"
                .format(status_code=status_code))
Пример #44
0
 def on_anchor_clicked(self, url):
     QDesktopServices.openUrl(QUrl(url))
Пример #45
0
    (usertypes.LoadStatus.success, url.UrlType.success),
    (usertypes.LoadStatus.success_https, url.UrlType.success_https),
    (usertypes.LoadStatus.error, url.UrlType.error),
    (usertypes.LoadStatus.warn, url.UrlType.warn),
    (usertypes.LoadStatus.loading, url.UrlType.normal),
    (usertypes.LoadStatus.none, url.UrlType.normal)
])
def test_on_load_status_changed(url_widget, status, expected):
    """Test text when status is changed."""
    url_widget.set_url(QUrl('www.example.com'))
    url_widget.on_load_status_changed(status.name)
    assert url_widget._urltype == expected


@pytest.mark.parametrize('load_status, qurl', [
    (url.UrlType.success, QUrl('http://abc123.com/this/awesome/url.html')),
    (url.UrlType.success, QUrl('http://reddit.com/r/linux')),
    (url.UrlType.success, QUrl('http://ä.com/')),
    (url.UrlType.success_https, QUrl('www.google.com')),
    (url.UrlType.success_https, QUrl('https://supersecret.gov/nsa/files.txt')),
    (url.UrlType.warn, QUrl('www.shadysite.org/some/file/with/issues.htm')),
    (url.UrlType.error, QUrl('invalid::/url')),
    (url.UrlType.error, QUrl()),
])
def test_on_tab_changed(url_widget, fake_web_tab, load_status, qurl):
    tab_widget = fake_web_tab(load_status=load_status, url=qurl)
    url_widget.on_tab_changed(tab_widget)

    assert url_widget._urltype == load_status
    if not qurl.isValid():
        expected = ''
Пример #46
0
from MySharedObject import MySharedObject
from PyQt5.QtWebChannel import QWebChannel
import sys

# 创建一个 application实例
app = QApplication(sys.argv)
win = QWidget()
win.setWindowTitle('Web页面中的JavaScript与 QWebEngineView交互例子')

# 创建一个垂直布局器
layout = QVBoxLayout()
win.setLayout(layout)

# 创建一个 QWebEngineView 对象
view = QWebEngineView()
htmlUrl = 'http://localhost/'
view.load(QUrl(htmlUrl))

# 创建一个 QWebChannel对象,用来传递pyqt参数到JavaScript
channel = QWebChannel()
myObj = MySharedObject()
channel.registerObject("bridge", myObj)
view.page().setWebChannel(channel)

# 把QWebView和button加载到layout布局中
layout.addWidget(view)

# 显示窗口和运行app
win.show()
sys.exit(app.exec_())
Пример #47
0
    print('result is: ', result)


def t(a):
    print('status: ', a)

    # viewPage.runJavaScript('var img=document.querySelector(".captcha_render");var canvas=document.createElement("canvas");canvas.width=img.width;canvas.height=img.height;var ctx=canvas.getContext("2d");ctx.drawImage(img,0,0);var dataURL=canvas.toDataURL("image/png");dataURL;',p)
    # viewPage.runJavaScript('window.a1a = "omid";',p)
    # viewPage.runJavaScript('"hi "+a1a;',stat)
    # viewPage.printToPdf('nic.pdf')
    # viewPage.printToPdf('t11111111111.pdf')
    # size = viewPage.contentsSize().toSize()
    # image = QImage(size, QImage.Format_ARGB32)
    # region = QRegion(0,0,size.width(), size.height())
    # painter = QPainter(image)
    # viewPage.view().render(painter, QPoint(), region)
    # painter.end()
    # image.save("test.png", "PNG", 80)
    print('saved!')


Page.loadFinished.connect(t)

Page.load(QUrl('https://google.com/'))

# image = QImage(page.contentsSize(),QImage.Format_ARGB32)
# painter = QPainter(image)
# page.ren


app.exec()
Пример #48
0
 def set_html(self, html: str, base_url: QUrl = QUrl()) -> None:
     raise NotImplementedError
Пример #49
0
 def play(self, url):
     self.media_player.setMedia(QMediaContent(QUrl.fromLocalFile(url)))
     self.media_player.play()
Пример #50
0
 def _on_url_changed(self, url: QUrl) -> None:
     """Update title when URL has changed and no title is available."""
     if url.isValid() and not self.title():
         self.title_changed.emit(url.toDisplayString())
     self.url_changed.emit(url)
Пример #51
0
 def _menu_documentation(self):
     QDesktopServices.openUrl(QUrl('http://www.giovanni-rocca.com/dwarf/'))
Пример #52
0
 def _on_before_load_started(self, url: QUrl) -> None:
     """Adjust the title if we are going to visit a URL soon."""
     qtutils.ensure_valid(url)
     url_string = url.toDisplayString()
     log.webview.debug("Going to start loading: {}".format(url_string))
     self.title_changed.emit(url_string)
Пример #53
0
 def _menu_github(self):
     QDesktopServices.openUrl(QUrl('https://github.com/iGio90/Dwarf'))
Пример #54
0
def openHtmlPage(page_name, html_contents):
    target = os.path.join(tempfile.gettempdir(), page_name)
    with open(target, "w", encoding="utf-8") as fhandle:
        fhandle.write(html_contents)
    QDesktopServices.openUrl(QUrl.fromLocalFile(target))
Пример #55
0
class ResourceUrlSchemeHandler(QWebEngineUrlSchemeHandler):
    schemeName = QByteArray().append("voce-resources")
    origin = QUrl("voce-resources:")
    GET = QByteArray().append("GET")
    POST = QByteArray().append("POST")

    cssUrl = QUrl("voce-resources://css")
    jsUrl = QUrl("voce-resources://js")
    fontsUrl = QUrl("voce-resources://fonts")
    imagesUrl = QUrl("voce-resources://img")
    vendorsUrl = QUrl("voce-resources://vendors")
    globalUrl = QUrl("voce-resources://global")

    def __init__(self, parent=None):
        super(ResourceUrlSchemeHandler, self).__init__(parent)
        self.rsrc_dir = os.path.join(vocebrowser.LOCAL_HTML_DIR, "resources")

    @classmethod
    def registerVoceUrlScheme(cls):
        voceUrlScheme = QWebEngineUrlScheme(cls.schemeName)
        voceUrlScheme.setFlags(QWebEngineUrlScheme.SecureScheme
                               | QWebEngineUrlScheme.LocalScheme
                               | QWebEngineUrlScheme.LocalAccessAllowed)
        QWebEngineUrlScheme.registerScheme(voceUrlScheme)

    def getRelativePath(self, path):
        if not path:
            return None
        elif len(path) == 1:
            if path == '/':
                return None
            else:
                return path
        elif path[0] == '/':
            return path[1:]
        else:
            return path

    def requestStarted(self, request):
        url = request.requestUrl()
        relativePath = self.getRelativePath(url.path())
        host = url.host()

        if host == self.cssUrl.host() and relativePath != None:
            file = QFile(os.path.join(self.rsrc_dir, host, relativePath),
                         request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/css", file)

        elif host == self.jsUrl.host() and relativePath != None:
            file = QFile(os.path.join(self.rsrc_dir, host, relativePath),
                         request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/javascript", file)

        elif host == self.imagesUrl.host() and relativePath != None:
            file = QFile(os.path.join(self.rsrc_dir, host, relativePath),
                         request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"", file)

        elif host == self.fontsUrl.host() and relativePath != None:
            file = QFile(os.path.join(self.rsrc_dir, host, relativePath),
                         request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"", file)

        elif host == self.globalUrl.host() and relativePath != None:
            file = QFile(os.path.join(self.rsrc_dir, relativePath), request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"", file)

        elif host == self.vendorsUrl.host() and relativePath != None:
            file = QFile(os.path.join(self.rsrc_dir, host, relativePath),
                         request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"", file)

        else:
            request.fail(QWebEngineUrlRequestJob.UrlNotFound)
Пример #56
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # save from garbage collection
        self.windows.append(self)

        # state
        self.filename = None
        self.result = None
        self.modelDescription = None
        self.variables = dict()
        self.selectedVariables = set()
        self.startValues = dict()
        self.simulationThread = None
        # self.progressDialog = None
        self.plotUpdateTimer = QTimer(self)
        self.plotUpdateTimer.timeout.connect(self.updatePlotData)
        self.curves = []

        # UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # set the window size to 85% of the available space
        geo = QApplication.desktop().availableGeometry()
        width = min(geo.width() * 0.85, 1100.0)
        height = min(geo.height() * 0.85, 900.0)
        self.resize(width, height)

        # hide the variables
        self.ui.dockWidget.hide()

        # toolbar
        self.stopTimeLineEdit = QLineEdit("1")
        self.stopTimeLineEdit.setToolTip("Stop time")
        self.stopTimeLineEdit.setFixedWidth(50)
        self.stopTimeValidator = QDoubleValidator(self)
        self.stopTimeValidator.setBottom(0)
        self.stopTimeLineEdit.setValidator(self.stopTimeValidator)

        self.ui.toolBar.addWidget(self.stopTimeLineEdit)

        spacer = QWidget(self)
        spacer.setFixedWidth(10)
        self.ui.toolBar.addWidget(spacer)

        self.fmiTypeComboBox = QComboBox(self)
        self.fmiTypeComboBox.addItem("Co-Simulation")
        self.fmiTypeComboBox.setToolTip("FMI type")
        self.fmiTypeComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.ui.toolBar.addWidget(self.fmiTypeComboBox)

        # disable widgets
        self.ui.actionSettings.setEnabled(False)
        self.ui.actionShowLog.setEnabled(False)
        self.ui.actionShowResults.setEnabled(False)
        self.ui.actionSimulate.setEnabled(False)
        self.ui.actionSaveResult.setEnabled(False)
        self.ui.actionSavePlottedResult.setEnabled(False)
        self.stopTimeLineEdit.setEnabled(False)
        self.fmiTypeComboBox.setEnabled(False)

        # hide the dock's title bar
        self.ui.dockWidget.setTitleBarWidget(QWidget())

        self.ui.tableView.setMinimumWidth(500)

        self.tableModel = VariablesTableModel(self.selectedVariables, self.startValues)
        self.tableFilterModel = VariablesFilterModel()
        self.tableFilterModel.setSourceModel(self.tableModel)
        self.tableFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.ui.tableView.setModel(self.tableFilterModel)

        self.treeModel = VariablesTreeModel(self.selectedVariables, self.startValues)
        self.treeFilterModel = VariablesFilterModel()
        self.treeFilterModel.setSourceModel(self.treeModel)
        self.treeFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.ui.treeView.setModel(self.treeFilterModel)

        for i, (w, n) in enumerate(zip(VariablesModel.COLUMN_WIDTHS, VariablesModel.COLUMN_NAMES)):
            self.ui.treeView.setColumnWidth(i, w)
            self.ui.tableView.setColumnWidth(i, w)

            if n in ['Value Reference', 'Initial', 'Causality', 'Variability']:
                self.ui.treeView.setColumnHidden(i, True)
                self.ui.tableView.setColumnHidden(i, True)

        # populate the recent files list
        settings = QSettings()
        recent_files = settings.value("recentFiles", defaultValue=[])
        recent_files = self.removeDuplicates(recent_files)
        vbox = QVBoxLayout()

        if recent_files:
            added = set()
            for file in recent_files[:5]:
                link = QLabel('<a href="%s" style="text-decoration: none">%s</a>' % (file, os.path.basename(file)))
                link.setToolTip(file)
                link.linkActivated.connect(self.load)
                vbox.addWidget(link)
                added.add(file)

        self.ui.recentFilesGroupBox.setLayout(vbox)
        self.ui.recentFilesGroupBox.setVisible(len(recent_files) > 0)

        # settings page
        self.inputFileMenu = QMenu()
        self.inputFileMenu.addAction("New input file...", self.createInputFile)
        self.inputFileMenu.addSeparator()
        self.inputFileMenu.addAction("Show in Explorer", self.showInputFileInExplorer)
        self.inputFileMenu.addAction("Open in default application", self.openInputFile)
        self.ui.selectInputButton.setMenu(self.inputFileMenu)

        # log page
        self.log = Log(self)
        self.logFilterModel = LogMessagesFilterProxyModel(self)
        self.logFilterModel.setSourceModel(self.log)
        self.logFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.ui.logTreeView.setModel(self.logFilterModel)
        self.ui.clearLogButton.clicked.connect(self.log.clear)

        self.log.numberOfDebugMessagesChanged.connect(lambda n: self.ui.showDebugMessagesButton.setText(str(n)))
        self.log.numberOfInfoMessagesChanged.connect(lambda n: self.ui.showInfoMessagesButton.setText(str(n)))
        self.log.numberOfWarningMessagesChanged.connect(lambda n: self.ui.showWarningMessagesButton.setText(str(n)))
        self.log.numberOfErrorMessagesChanged.connect(lambda n: self.ui.showErrorMessagesButton.setText(str(n)))

        self.ui.logFilterLineEdit.textChanged.connect(self.logFilterModel.setFilterFixedString)

        self.ui.showDebugMessagesButton.toggled.connect(self.logFilterModel.setShowDebugMessages)
        self.ui.showInfoMessagesButton.toggled.connect(self.logFilterModel.setShowInfoMessages)
        self.ui.showWarningMessagesButton.toggled.connect(self.logFilterModel.setShowWarningMessages)
        self.ui.showErrorMessagesButton.toggled.connect(self.logFilterModel.setShowErrorMessages)

        # context menu
        self.contextMenu = QMenu()
        self.actionExpandAll = self.contextMenu.addAction("Expand all")
        self.actionExpandAll.triggered.connect(self.ui.treeView.expandAll)
        self.actionCollapseAll = self.contextMenu.addAction("Collapse all")
        self.actionCollapseAll.triggered.connect(self.ui.treeView.collapseAll)
        self.contextMenu.addSeparator()
        self.actionCopyVariableName = self.contextMenu.addAction("Copy Variable Name", self.copyVariableName)
        self.actionCopyValueReference = self.contextMenu.addAction("Copy Value Reference", self.copyValueReference)
        self.contextMenu.addSeparator()
        self.actionEditTable = self.contextMenu.addAction("Edit Table", self.editTable)
        self.contextMenu.addSeparator()
        self.columnsMenu = self.contextMenu.addMenu('Columns')
        for column in ['Value Reference', 'Initial', 'Causality', 'Variability']:
            action = self.columnsMenu.addAction(column)
            action.setCheckable(True)
            action.toggled.connect(lambda show, col=column: self.showColumn(col, show))

        # file menu
        self.ui.actionExit.triggered.connect(QApplication.closeAllWindows)
        self.ui.actionLoadStartValues.triggered.connect(self.loadStartValues)
        self.ui.actionReload.triggered.connect(lambda: self.load(self.filename))
        self.ui.actionSaveChanges.triggered.connect(self.saveChanges)

        # help menu
        self.ui.actionOpenFMI1SpecCS.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v1.0/FMI_for_CoSimulation_v1.0.1.pdf')))
        self.ui.actionOpenFMI1SpecME.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v1.0/FMI_for_ModelExchange_v1.0.1.pdf')))
        self.ui.actionOpenFMI2Spec.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v2.0/FMI_for_ModelExchange_and_CoSimulation_v2.0.pdf')))
        self.ui.actionOpenTestFMUs.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://trac.fmi-standard.org/browser/branches/public/Test_FMUs')))
        self.ui.actionOpenWebsite.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/CATIA-Systems/FMPy')))
        self.ui.actionShowReleaseNotes.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/CATIA-Systems/FMPy/blob/master/CHANGELOG.md')))

        # filter menu
        self.filterMenu = QMenu()
        self.filterMenu.addAction(self.ui.actionFilterInputs)
        self.filterMenu.addAction(self.ui.actionFilterOutputs)
        self.filterMenu.addAction(self.ui.actionFilterParameters)
        self.filterMenu.addAction(self.ui.actionFilterCalculatedParameters)
        self.filterMenu.addAction(self.ui.actionFilterIndependentVariables)
        self.filterMenu.addAction(self.ui.actionFilterLocalVariables)
        self.ui.filterToolButton.setMenu(self.filterMenu)

        # status bar
        self.statusIconLabel = ClickableLabel(self)
        self.statusIconLabel.setStyleSheet("QLabel { margin-left: 5px; }")
        self.statusIconLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage))
        self.ui.statusBar.addPermanentWidget(self.statusIconLabel)

        self.statusTextLabel = ClickableLabel(self)
        self.statusTextLabel.setMinimumWidth(10)
        self.statusTextLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage))
        self.ui.statusBar.addPermanentWidget(self.statusTextLabel)

        self.ui.statusBar.addPermanentWidget(QWidget(self), 1)  # spacer

        self.simulationProgressBar = QProgressBar(self)
        self.simulationProgressBar.setFixedHeight(18)
        self.ui.statusBar.addPermanentWidget(self.simulationProgressBar)
        self.simulationProgressBar.setVisible(False)

        # connect signals and slots
        self.ui.actionNewWindow.triggered.connect(self.newWindow)
        self.ui.openButton.clicked.connect(self.open)
        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionSaveResult.triggered.connect(self.saveResult)
        self.ui.actionSavePlottedResult.triggered.connect(lambda: self.saveResult(plotted=True))
        self.ui.actionSimulate.triggered.connect(self.startSimulation)
        self.ui.actionSettings.triggered.connect(lambda: self.setCurrentPage(self.ui.settingsPage))
        self.ui.actionShowLog.triggered.connect(lambda: self.setCurrentPage(self.ui.logPage))
        self.ui.actionShowResults.triggered.connect(lambda: self.setCurrentPage(self.ui.resultPage))
        self.fmiTypeComboBox.currentTextChanged.connect(self.updateSimulationSettings)
        self.ui.solverComboBox.currentTextChanged.connect(self.updateSimulationSettings)
        self.variableSelected.connect(self.updatePlotLayout)
        self.variableDeselected.connect(self.updatePlotLayout)
        self.tableModel.variableSelected.connect(self.selectVariable)
        self.tableModel.variableDeselected.connect(self.deselectVariable)
        self.treeModel.variableSelected.connect(self.selectVariable)
        self.treeModel.variableDeselected.connect(self.deselectVariable)
        self.ui.filterLineEdit.textChanged.connect(self.treeFilterModel.setFilterFixedString)
        self.ui.filterLineEdit.textChanged.connect(self.tableFilterModel.setFilterFixedString)
        self.ui.filterToolButton.toggled.connect(self.treeFilterModel.setFilterByCausality)
        self.ui.filterToolButton.toggled.connect(self.tableFilterModel.setFilterByCausality)
        self.log.currentMessageChanged.connect(self.setStatusMessage)
        self.ui.selectInputButton.clicked.connect(self.selectInputFile)
        self.ui.actionShowAboutDialog.triggered.connect(self.showAboutDialog)

        if os.name == 'nt':
            self.ui.actionCreateDesktopShortcut.triggered.connect(self.createDesktopShortcut)
            self.ui.actionAddFileAssociation.triggered.connect(self.addFileAssociation)
        else:
            self.ui.actionCreateDesktopShortcut.setEnabled(False)
            self.ui.actionAddFileAssociation.setEnabled(False)

        self.ui.tableViewToolButton.toggled.connect(lambda show: self.ui.variablesStackedWidget.setCurrentWidget(self.ui.tablePage if show else self.ui.treePage))

        for model in [self.treeFilterModel, self.tableFilterModel]:
            self.ui.actionFilterInputs.triggered.connect(model.setFilterInputs)
            self.ui.actionFilterOutputs.triggered.connect(model.setFilterOutputs)
            self.ui.actionFilterParameters.triggered.connect(model.setFilterParameters)
            self.ui.actionFilterCalculatedParameters.triggered.connect(model.setFilterCalculatedParameters)
            self.ui.actionFilterIndependentVariables.triggered.connect(model.setFilterIndependentVariables)
            self.ui.actionFilterLocalVariables.triggered.connect(model.setFilterLocalVariables)

        self.ui.treeView.customContextMenuRequested.connect(self.showContextMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.showContextMenu)
Пример #57
0
 def openPrinterControlPanel(self) -> None:
     Logger.log("d", "Opening printer control panel...")
     QDesktopServices.openUrl(QUrl("http://" + self._address + "/printers"))
Пример #58
0
class VoceUrlSchemeHandler(QWebEngineUrlSchemeHandler):

    schemeName = QByteArray().append("voce")
    origin = QUrl("voce:")
    GET = QByteArray().append("GET")
    POST = QByteArray().append("POST")
    homeUrl = QUrl("voce://welcome")
    newtabUrl = QUrl("voce://newtab")
    settingsUrl = QUrl("voce://settings")
    bookmarksUrl = QUrl("voce://bookmarks")
    downloadsUrl = QUrl("voce://downloads")
    historyUrl = QUrl("voce://history")
    versionUrl = QUrl("voce://version")
    aboutUrl = QUrl("voce://about")

    def __init__(self, parent=None):
        super(VoceUrlSchemeHandler, self).__init__(parent)

    @classmethod
    def registerVoceUrlScheme(cls):
        voceUrlScheme = QWebEngineUrlScheme(cls.schemeName)
        voceUrlScheme.setFlags(QWebEngineUrlScheme.SecureScheme
                               | QWebEngineUrlScheme.LocalScheme
                               | QWebEngineUrlScheme.LocalAccessAllowed)
        QWebEngineUrlScheme.registerScheme(voceUrlScheme)

    def requestStarted(self, request):
        method = request.requestMethod()
        url = request.requestUrl()
        initiator = request.initiator()

        if method == self.GET and url.host() == self.homeUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR, 'welcome.html'),
                request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.newtabUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR, 'newtab/index.html'),
                request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.settingsUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR,
                             'settings/index.html'), request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.downloadsUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR,
                             'downloads/index.html'), request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.historyUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR, 'history/index.html'),
                request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.bookmarksUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR,
                             'bookmarks/index.html'), request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.versionUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR, 'version/index.html'),
                request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        elif method == self.GET and url.host() == self.aboutUrl.host():
            file = QFile(
                os.path.join(vocebrowser.LOCAL_HTML_DIR, 'about/index.html'),
                request)
            file.open(QIODevice.ReadOnly)
            request.reply(b"text/html", file)

        else:
            request.fail(QWebEngineUrlRequestJob.UrlNotFound)
Пример #59
0
 def clickAction_ProgramHelp(self):
     self.startfilepath=os.getcwd() +"/PyStudy_web/Pystudy.html"
     self.exampleView.load(QUrl.fromLocalFile(self.startfilepath))
Пример #60
0
    def update_frame(self, data, text, url, mime, pbresp=None):
        self.setEnabled(False)  # prevent from taking focus

        out_mime = 'text/plain; charset=utf-8'

        if 'image' in mime:
            out_mime = mime

        elif 'html' in mime:
            if '/embed' in url:
                text = text.replace('<head>',
                                    '<head><script>opener=1</script>')
            out_mime = 'text/html; charset=utf-8'
            data = text

        elif 'json' in mime:
            if text.startswith(")]}'\n"):
                text = text[5:]
            if text.endswith('/*""*/'):
                text = text[:-6]

            text = text.replace('[,',
                                '[null,').replace(',]', ',null]').replace(
                                    ',,', ',null,').replace(',,', ',null,')

            try:
                data = dumps(loads(text), indent=4)
            except Exception:
                pass

        elif 'protobuf' in mime:
            data = self.parse_protobuf(data, pbresp)

        elif 'kmz' in mime:
            with ZipFile(BytesIO(data)) as fd:
                if fd.namelist() == ['doc.kml']:
                    data = parseString(
                        fd.read('doc.kml')).toprettyxml(indent='    ')
                else:
                    data = '\n'.join(fd.namelist())

        elif data.startswith(b'XHR1'):
            data = BytesIO(data[4:])
            out = b''

            while True:
                header = data.read(6)
                if not header:
                    break
                size, index = unpack('>IBx', header)

                dec = bytes([i ^ 0x9b for i in data.read(size - 2)])
                if dec.startswith(b'\x78\x9c'):
                    dec = decompress(dec)

                out += b'%d %s\n' % (index, b'-' * 15)
                out += self.parse_protobuf(dec, pbresp)

            data = out

        elif 'text/' in mime:
            pass

        else:
            for key in (0x9b, 0x5f):
                dec = bytes([i ^ key for i in data])

                try:
                    dec = decompress(dec, -15)
                except Exception:
                    try:
                        dec = decompress(dec)
                    except Exception:
                        pass

                dec = self.parse_protobuf(dec, pbresp)
                if dec:
                    break

            if not dec:
                dec = run(['hexdump', '-C'], input=data, stdout=PIPE).stdout

            data = dec[:500000]

        if type(data) == str:
            data = data.encode('utf8')
        self.setContent(QByteArray(data), out_mime, QUrl(url))

        self.setEnabled(True)