Esempio n. 1
0
def _asciidoc_fallback_path(html_path):
    """Fall back to plaintext asciidoc if the HTML is unavailable."""
    path = html_path.replace('.html', '.asciidoc')
    try:
        return utils.read_file(path)
    except OSError:
        return None
Esempio n. 2
0
    def __init__(self, pac_str):
        """Create a PAC resolver.

        Args:
            pac_str: JavaScript code containing PAC resolver.
        """
        self._engine = QJSEngine()

        self._engine.installExtensions(QJSEngine.ConsoleExtension)

        self._ctx = _PACContext(self._engine)
        self._engine.globalObject().setProperty(
            "PAC", self._engine.newQObject(self._ctx))
        self._evaluate(_PACContext.JS_DEFINITIONS, "pac_js_definitions")
        self._evaluate(utils.read_file("javascript/pac_utils.js"), "pac_utils")
        proxy_config = self._engine.newObject()
        proxy_config.setProperty("bindings", self._engine.newObject())
        self._engine.globalObject().setProperty("ProxyConfig", proxy_config)

        self._evaluate(pac_str, "pac")
        global_js_object = self._engine.globalObject()
        self._resolver = global_js_object.property("FindProxyForURL")
        if not self._resolver.isCallable():
            err = "Cannot resolve FindProxyForURL function, got '{}' instead"
            raise EvalProxyError(err.format(self._resolver.toString()))
Esempio n. 3
0
def glimpse_help(url):
    """Handler for glimpse://help."""
    urlpath = url.path()
    if not urlpath or urlpath == '/':
        urlpath = 'index.html'
    else:
        urlpath = urlpath.lstrip('/')
    if not docutils.docs_up_to_date(urlpath):
        message.error("Your documentation is outdated! Please re-run "
                      "scripts/asciidoc2html.py.")

    path = 'html/doc/{}'.format(urlpath)
    if not urlpath.endswith('.html'):
        try:
            bdata = utils.read_file(path, binary=True)
        except OSError as e:
            raise SchemeOSError(e)
        mimetype = utils.guess_mimetype(urlpath)
        return mimetype, bdata

    try:
        data = utils.read_file(path)
    except OSError:
        asciidoc = _asciidoc_fallback_path(path)

        if asciidoc is None:
            raise

        preamble = textwrap.dedent("""
            There was an error loading the documentation!

            This most likely means the documentation was not generated
            properly. If you are running glimpsebrowser from the git repository,
            please (re)run scripts/asciidoc2html.py and reload this page.

            If you're running a released version this is a bug, please use
            :report to report it.

            Falling back to the plaintext version.

            ---------------------------------------------------------------


        """)
        return 'text/plain', (preamble + asciidoc).encode('utf-8')
    else:
        return 'text/html', data
Esempio n. 4
0
def glimpse_javascript(url):
    """Handler for glimpse://javascript.

    Return content of file given as query parameter.
    """
    path = url.path()
    if path:
        path = "javascript" + os.sep.join(path.split('/'))
        return 'text/html', utils.read_file(path, binary=False)
    else:
        raise UrlInvalidError("No file specified")
Esempio n. 5
0
 def get_source(self, _env, template):
     path = os.path.join(self._subdir, template)
     try:
         source = utils.read_file(path)
     except OSError as e:
         source = html_fallback.replace("%ERROR%", html.escape(str(e)))
         source = source.replace("%FILE%", html.escape(template))
         log.misc.exception(
             "The {} template could not be loaded from {}".format(
                 template, path))
     # Currently we don't implement auto-reloading, so we always return True
     # for up-to-date.
     return source, path, lambda: True
Esempio n. 6
0
def get_pdfjs_res_and_path(path):
    """Get a pdf.js resource in binary format.

    Returns a (content, path) tuple, where content is the file content and path
    is the path where the file was found. If path is None, the bundled version
    was used.

    Args:
        path: The path inside the pdfjs directory.
    """
    path = path.lstrip('/')
    content = None
    file_path = None

    system_paths = [
        # Debian pdf.js-common
        # Arch Linux pdfjs (AUR)
        '/usr/share/pdf.js/',
        # Flatpak (Flathub)
        '/app/share/pdf.js/',
        # Arch Linux pdf.js (AUR)
        '/usr/share/javascript/pdf.js/',
        # Debian libjs-pdf
        '/usr/share/javascript/pdf/',
        # fallback
        os.path.join(standarddir.data(), 'pdfjs'),
        # hardcoded fallback for --temp-basedir
        os.path.expanduser('~/.local/share/glimpsebrowser/pdfjs/'),
    ]

    # First try a system wide installation
    # System installations might strip off the 'build/' or 'web/' prefixes.
    # glimpse expects them, so we need to adjust for it.
    names_to_try = [path, _remove_prefix(path)]
    for system_path in system_paths:
        content, file_path = _read_from_system(system_path, names_to_try)
        if content is not None:
            break

    # Fallback to bundled pdf.js
    if content is None:
        res_path = '3rdparty/pdfjs/{}'.format(path)
        try:
            content = utils.read_file(res_path, binary=True)
        except FileNotFoundError:
            raise PDFJSNotFound(path) from None
        except OSError as e:
            log.misc.warning("OSError while reading PDF.js file: {}".format(e))
            raise PDFJSNotFound(path) from None

    return content, file_path
Esempio n. 7
0
    def _on_mode_entered(self, mode):
        if mode != usertypes.KeyMode.caret:
            return

        self.selection_enabled = self._widget.hasSelection()
        self.selection_toggled.emit(self.selection_enabled)
        settings = self._widget.settings()
        settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True)

        if self._widget.isVisible():
            # Sometimes the caret isn't immediately visible, but unfocusing
            # and refocusing it fixes that.
            self._widget.clearFocus()
            self._widget.setFocus(Qt.OtherFocusReason)

            # Move the caret to the first element in the viewport if there
            # isn't any text which is already selected.
            #
            # Note: We can't use hasSelection() here, as that's always
            # true in caret mode.
            if not self.selection_enabled:
                self._widget.page().currentFrame().evaluateJavaScript(
                    utils.read_file('javascript/position_caret.js'))
Esempio n. 8
0
def _git_str():
    """Try to find out git version.

    Return:
        string containing the git commit ID.
        None if there was an error or we're not in a git repo.
    """
    # First try via subprocess if possible
    commit = None
    if not hasattr(sys, "frozen"):
        try:
            gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   os.path.pardir, os.path.pardir)
        except (NameError, OSError):
            log.misc.exception("Error while getting git path")
        else:
            commit = _git_str_subprocess(gitpath)
    if commit is not None:
        return commit
    # If that fails, check the git-commit-id file.
    try:
        return utils.read_file('git-commit-id')
    except (OSError, ImportError):
        return None
Esempio n. 9
0
def glimpse_gpl(_url):
    """Handler for glimpse://gpl. Return HTML content as string."""
    return 'text/html', utils.read_file('html/license.html')
Esempio n. 10
0
 def _data_url(self, path):
     """Get a data: url for the broken glimpsebrowser logo."""
     data = utils.read_file(path, binary=True)
     filename = utils.resource_filename(path)
     mimetype = utils.guess_mimetype(filename)
     return urlutils.data_url(mimetype, data).toString()