Esempio n. 1
0
def _generate_pdfjs_script(url):
    """Generate the script that shows the pdf with pdf.js.

    Args:
        url: The url of the pdf page as QUrl.
    """
    return ('PDFJS.verbosity = PDFJS.VERBOSITY_LEVELS.info;\n'
            'PDFView.open("{url}");\n').format(
                url=webelem.javascript_escape(url.toString(QUrl.FullyEncoded)))
Esempio n. 2
0
def _generate_pdfjs_script(url):
    """Generate the script that shows the pdf with pdf.js.

    Args:
        url: The url of the pdf page as QUrl.
    """
    return (
        'PDFJS.verbosity = PDFJS.VERBOSITY_LEVELS.info;\n'
        'PDFView.open("{url}");\n'
    ).format(url=webelem.javascript_escape(url.toString(QUrl.FullyEncoded)))
Esempio n. 3
0
 def click_element(self, text):
     """Click the element with the given text."""
     # Use Javascript and XPath to find the right element, use console.log
     # to return an error (no element found, ambiguous element)
     script = (
         "var _es = document.evaluate('//*[text()={text}]', document, "
         "null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);"
         'if (_es.snapshotLength == 0) {{ console.log("qute:no elems"); }} '
         'else if (_es.snapshotLength > 1) {{ console.log("qute:ambiguous '
         'elems") }} '
         'else {{ console.log("qute:okay"); _es.snapshotItem(0).click() }}'
     ).format(text=webelem.javascript_escape(_xpath_escape(text)))
     self.send_cmd(":jseval " + script)
     message = self.wait_for_js("qute:*").message
     if message.endswith("qute:no elems"):
         raise ValueError("No element with {!r} found".format(text))
     elif message.endswith("qute:ambiguous elems"):
         raise ValueError("Element with {!r} is not unique".format(text))
     elif not message.endswith("qute:okay"):
         raise ValueError("Invalid response from qutebrowser: {}".format(message))
Esempio n. 4
0
    def on_editing_finished(self, elem, text):
        """Write the editor text into the form field and clean up tempfile.

        Callback for QProcess when the editor was closed.

        Args:
            elem: The WebElementWrapper which was modified.
            text: The new text to insert.
        """
        try:
            if elem.is_content_editable():
                log.misc.debug("Filling element {} via setPlainText.".format(
                    elem.debug_text()))
                elem.setPlainText(text)
            else:
                log.misc.debug("Filling element {} via javascript.".format(
                    elem.debug_text()))
                text = webelem.javascript_escape(text)
                elem.evaluateJavaScript("this.value='{}'".format(text))
        except webelem.IsNullError:
            raise cmdexc.CommandError("Element vanished while editing!")
Esempio n. 5
0
    def on_editing_finished(self, elem, text):
        """Write the editor text into the form field and clean up tempfile.

        Callback for QProcess when the editor was closed.

        Args:
            elem: The WebElementWrapper which was modified.
            text: The new text to insert.
        """
        try:
            if elem.is_content_editable():
                log.misc.debug("Filling element {} via setPlainText.".format(
                    elem.debug_text()))
                elem.setPlainText(text)
            else:
                log.misc.debug("Filling element {} via javascript.".format(
                    elem.debug_text()))
                text = webelem.javascript_escape(text)
                elem.evaluateJavaScript("this.value='{}'".format(text))
        except webelem.IsNullError:
            raise cmdexc.CommandError("Element vanished while editing!")
Esempio n. 6
0
 def click_element(self, text):
     """Click the element with the given text."""
     # Use Javascript and XPath to find the right element, use console.log
     # to return an error (no element found, ambiguous element)
     script = (
         'var _es = document.evaluate(\'//*[text()={text}]\', document, '
         'null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);'
         'if (_es.snapshotLength == 0) {{ console.log("qute:no elems"); }} '
         'else if (_es.snapshotLength > 1) {{ console.log("qute:ambiguous '
         'elems") }} '
         'else {{ console.log("qute:okay"); _es.snapshotItem(0).click() }}'
     ).format(text=webelem.javascript_escape(_xpath_escape(text)))
     self.send_cmd(':jseval ' + script)
     message = self.wait_for_js('qute:*').message
     if message.endswith('qute:no elems'):
         raise ValueError('No element with {!r} found'.format(text))
     elif message.endswith('qute:ambiguous elems'):
         raise ValueError('Element with {!r} is not unique'.format(text))
     elif not message.endswith('qute:okay'):
         raise ValueError(
             'Invalid response from qutebrowser: {}'.format(message))
Esempio n. 7
0
    def _test_escape_hexlified(self, text, qtbot, webframe):
        """Test conversion by hexlifying in javascript.

        Since the conversion of QStrings to Python strings is broken in some
        older PyQt versions in some corner cases, we load a HTML file which
        generates an MD5 of the escaped text and use that for comparisons.
        """
        escaped = webelem.javascript_escape(text)
        path = os.path.join(os.path.dirname(__file__), "test_webelem_jsescape.html")
        with open(path, encoding="utf-8") as f:
            html_source = f.read().replace("%INPUT%", escaped)

        with qtbot.waitSignal(webframe.loadFinished) as blocker:
            webframe.setHtml(html_source)
        assert blocker.args == [True]

        result = webframe.evaluateJavaScript("window.qute_test_result")
        assert result is not None
        assert "|" in result
        result_md5, result_text = result.split("|", maxsplit=1)
        text_md5 = binascii.hexlify(text.encode("utf-8")).decode("ascii")
        assert result_md5 == text_md5, result_text
Esempio n. 8
0
    def _test_escape_hexlified(self, text, qtbot, webframe):
        """Test conversion by hexlifying in javascript.

        Since the conversion of QStrings to Python strings is broken in some
        older PyQt versions in some corner cases, we load a HTML file which
        generates an MD5 of the escaped text and use that for comparisons.
        """
        escaped = webelem.javascript_escape(text)
        path = os.path.join(os.path.dirname(__file__),
                            'test_webelem_jsescape.html')
        with open(path, encoding='utf-8') as f:
            html_source = f.read().replace('%INPUT%', escaped)

        with qtbot.waitSignal(webframe.loadFinished, raising=True):
            webframe.setHtml(html_source)

        result = webframe.evaluateJavaScript('window.qute_test_result')
        assert result is not None
        assert '|' in result
        result_md5, result_text = result.split('|', maxsplit=1)
        text_md5 = binascii.hexlify(text.encode('utf-8')).decode('ascii')
        assert result_md5 == text_md5, result_text
Esempio n. 9
0
 def _test_escape_simple(self, text, webframe):
     """Test conversion by using evaluateJavaScript."""
     escaped = webelem.javascript_escape(text)
     result = webframe.evaluateJavaScript('"{}";'.format(escaped))
     assert result == text
Esempio n. 10
0
 def test_fake_escape(self, before, after):
     """Test javascript escaping with some expected outcomes."""
     assert webelem.javascript_escape(before) == after
Esempio n. 11
0
 def _test_escape_simple(self, text, webframe):
     """Test conversion by using evaluateJavaScript."""
     escaped = webelem.javascript_escape(text)
     result = webframe.evaluateJavaScript('"{}";'.format(escaped))
     assert result == text
Esempio n. 12
0
 def test_fake_escape(self, before, after):
     """Test javascript escaping with some expected outcomes."""
     assert webelem.javascript_escape(before) == after
Esempio n. 13
0
 def test_fake_escape(self):
     """Test javascript escaping."""
     for before, after in self.STRINGS:
         with self.subTest(before=before):
             self.assertEqual(webelem.javascript_escape(before), after)
Esempio n. 14
0
 def test_fake_escape(self, before, after):
     """Test javascript escaping."""
     assert webelem.javascript_escape(before) == after
Esempio n. 15
0
 def test_fake_escape(self, before, after):
     """Test javascript escaping."""
     assert webelem.javascript_escape(before) == after
Esempio n. 16
0
 def test_fake_escape(self):
     """Test javascript escaping."""
     for before, after in self.STRINGS:
         with self.subTest(before=before):
             self.assertEqual(webelem.javascript_escape(before), after)