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(resources.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()))
def _asciidoc_fallback_path(html_path: str) -> Optional[str]: """Fall back to plaintext asciidoc if the HTML is unavailable.""" path = html_path.replace('.html', '.asciidoc') try: return resources.read_file(path) except OSError: return None
def _on_mode_entered(self, mode): if mode != usertypes.KeyMode.caret: return if self._widget.hasSelection(): self._selection_state = browsertab.SelectionState.normal else: self._selection_state = browsertab.SelectionState.none self.selection_toggled.emit(self._selection_state) 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 self._selection_state is browsertab.SelectionState.none: self._widget.page().currentFrame().evaluateJavaScript( resources.read_file('javascript/position_caret.js'))
def qute_javascript(url: QUrl) -> _HandlerRet: """Handler for qute://javascript. Return content of file given as query parameter. """ path = url.path() if path: path = "javascript" + os.sep.join(path.split('/')) return 'text/html', resources.read_file(path) else: raise UrlInvalidError("No file specified")
def get_source(self, _env: jinja2.Environment, template: str) -> Tuple[str, str, Callable[[], bool]]: path = os.path.join(self._subdir, template) try: source = resources.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
def qute_help(url: QUrl) -> _HandlerRet: """Handler for qute://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 = resources.read_file_binary(path) except OSError as e: raise SchemeOSError(e) mimetype = utils.guess_mimetype(urlpath) return mimetype, bdata try: data = resources.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 qutebrowser 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
def _git_str() -> Optional[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 resources.read_file('git-commit-id') except (OSError, ImportError): return None
def test_readfile(self): """Read a test file.""" content = resources.read_file(os.path.join('utils', 'testfile')) assert content.splitlines()[0] == "Hello World!"
def test_read_cached_file(self, mocker, filename): resources.preload() m = mocker.patch( 'qutebrowser.utils.resources.importlib_resources.files') resources.read_file(filename) m.assert_not_called()
def _open_special_pages(args): """Open special notification pages which are only shown once. Args: args: The argparse namespace. """ if args.basedir is not None: # With --basedir given, don't open anything. return general_sect = configfiles.state['general'] tabbed_browser = objreg.get('tabbed-browser', scope='window', window='last-focused') pages = [ # state, condition, URL ('quickstart-done', True, 'https://www.qutebrowser.org/quickstart.html' ), ('config-migration-shown', os.path.exists(os.path.join(standarddir.config(), 'qutebrowser.conf')), 'qute://help/configuring.html'), ('webkit-warning-shown', objects.backend == usertypes.Backend.QtWebKit, 'qute://warning/webkit'), ('session-warning-shown', qtutils.version_check('5.15', compiled=False), 'qute://warning/sessions'), ] if 'quickstart-done' not in general_sect: # New users aren't going to be affected by the Qt 5.15 session change much, as # they aren't used to qutebrowser saving the full back/forward history in # sessions. general_sect['session-warning-shown'] = '1' for state, condition, url in pages: if general_sect.get(state) != '1' and condition: tabbed_browser.tabopen(QUrl(url), background=False) general_sect[state] = '1' # Show changelog on new releases change = configfiles.state.qutebrowser_version_changed if change == configfiles.VersionChange.equal: return setting = config.val.changelog_after_upgrade if not change.matches_filter(setting): log.init.debug( f"Showing changelog is disabled (setting {setting}, change {change})" ) return try: changelog = resources.read_file('html/doc/changelog.html') except OSError as e: log.init.warning(f"Not showing changelog due to {e}") return qbversion = qutebrowser.__version__ if f'id="v{qbversion}"' not in changelog: log.init.warning("Not showing changelog (anchor not found)") return message.info( f"Showing changelog after upgrade to qutebrowser v{qbversion}.") changelog_url = f'qute://help/changelog.html#v{qbversion}' tabbed_browser.tabopen(QUrl(changelog_url), background=False)
def qute_gpl(_url: QUrl) -> _HandlerRet: """Handler for qute://gpl. Return HTML content as string.""" return 'text/html', resources.read_file('html/license.html')
def init() -> None: """Initialize configdata from the YAML file.""" global DATA, MIGRATIONS DATA, MIGRATIONS = _read_yaml(resources.read_file('config/configdata.yml'))