def _get_hints_arg(self, *, origin_url: QUrl, icon: QImage) -> Dict[str, Any]: """Get the hints argument for present().""" origin_url_str = origin_url.toDisplayString() hints: Dict[str, Any] = { # Include the origin in case the user wants to do different things # with different origin's notifications. "x-qutebrowser-origin": origin_url_str, "desktop-entry": "org.qutebrowser.qutebrowser", } is_useful_origin = self._should_include_origin(origin_url) if self._capabilities.kde_origin_name and is_useful_origin: hints["x-kde-origin-name"] = origin_url_str if icon.isNull(): filename = 'icons/qutebrowser-64x64.png' icon = QImage.fromData(resources.read_file_binary(filename)) key = self._quirks.icon_key or "image-data" data = self._convert_image(icon) if data is not None: hints[key] = data return hints
def qute_resource(url: QUrl) -> _HandlerRet: """Handler for qute://resource.""" path = url.path().lstrip('/') mimetype = utils.guess_mimetype(path, fallback=True) try: data = resources.read_file_binary(path) except FileNotFoundError as e: raise NotFoundError(str(e)) return mimetype, data
def _init_icon(): """Initialize the icon of qutebrowser.""" fallback_icon = QIcon() for size in [16, 24, 32, 48, 64, 96, 128, 256, 512]: filename = 'icons/qutebrowser-{size}x{size}.png'.format(size=size) pixmap = QPixmap() pixmap.loadFromData(resources.read_file_binary(filename)) if pixmap.isNull(): log.init.warning("Failed to load {}".format(filename)) else: fallback_icon.addPixmap(pixmap) icon = QIcon.fromTheme('qutebrowser', fallback_icon) if icon.isNull(): log.init.warning("Failed to load icon") else: objects.qapp.setWindowIcon(icon)
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 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 = _SYSTEM_PATHS + [ # fallback os.path.join(standarddir.data(), 'pdfjs'), # hardcoded fallback for --temp-basedir os.path.expanduser('~/.local/share/qutebrowser/pdfjs/'), ] # First try a system wide installation # System installations might strip off the 'build/' or 'web/' prefixes. # qute 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 = resources.read_file_binary(res_path) 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
def _data_url(self, path: str) -> str: """Get a data: url for the broken qutebrowser logo.""" data = resources.read_file_binary(path) mimetype = utils.guess_mimetype(path) return urlutils.data_url(mimetype, data).toString()
def test_readfile_binary(self): """Read a test file in binary mode.""" content = resources.read_file_binary(os.path.join('utils', 'testfile')) assert content.splitlines()[0] == b"Hello World!"
def present( self, qt_notification: "QWebEngineNotification", *, replaces_id: Optional[int], ) -> int: """Shows a notification over DBus.""" if replaces_id is None: replaces_id = 0 # 0 is never a valid ID according to the spec actions = [] if self._capabilities.actions: actions = ['default', 'Activate'] # key, name actions_arg = QDBusArgument(actions, QMetaType.QStringList) origin_url_str = qt_notification.origin().toDisplayString() hints: Dict[str, Any] = { # Include the origin in case the user wants to do different things # with different origin's notifications. "x-qutebrowser-origin": origin_url_str, "desktop-entry": "org.qutebrowser.qutebrowser", } is_useful_origin = self._should_include_origin(qt_notification.origin()) if self._capabilities.kde_origin_name and is_useful_origin: hints["x-kde-origin-name"] = origin_url_str icon = qt_notification.icon() if icon.isNull(): filename = 'icons/qutebrowser-64x64.png' icon = QImage.fromData(resources.read_file_binary(filename)) key = self._quirks.icon_key or "image-data" data = self._convert_image(icon) if data is not None: hints[key] = data # Titles don't support markup (except with broken servers) title = qt_notification.title() if self._quirks.escape_title: title = html.escape(title, quote=False) reply = self.interface.call( QDBus.BlockWithGui, "Notify", "qutebrowser", # application name _as_uint32(replaces_id), # replaces notification id "", # icon name/file URL, we use image-data and friends instead. title, self._format_body(qt_notification.message(), qt_notification.origin()), actions_arg, hints, -1, # timeout; -1 means 'use default' ) self._verify_message(reply, "u", QDBusMessage.ReplyMessage) notification_id = reply.arguments()[0] if replaces_id not in [0, notification_id]: msg = ( f"Wanted to replace notification {replaces_id} but got new id " f"{notification_id}." ) if self._quirks.wrong_replaces_id: log.misc.debug(msg) else: log.misc.error(msg) if notification_id <= 0: self.error.emit(f"Got invalid notification id {notification_id}") return notification_id