def _find_installed(self, code): local_filename = spell.local_filename(code) if not local_filename: message.warning( "Language {} is not installed - see scripts/dictcli.py " "in qutebrowser's sources".format(code)) return local_filename
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = '/'.join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format( self.name, mode_names)) elif self._not_modes is not None and curmode in self._not_modes: mode_names = '/'.join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError( "{}: This command is not allowed in {} mode.".format( self.name, mode_names)) used_backend = usertypes.arg2backend[objreg.get('args').backend] if self.backend is not None and used_backend != self.backend: raise cmdexc.PrerequisitesError("{}: Only available with {} " "backend.".format( self.name, self.backend.name)) if self.deprecated: message.warning('{} is deprecated - {}'.format( self.name, self.deprecated))
def message_warning(text): """Show a warning message in the statusbar. Args: text: The text to show. """ message.warning(text)
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = '/'.join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format( self.name, mode_names)) elif self._not_modes is not None and curmode in self._not_modes: mode_names = '/'.join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError( "{}: This command is not allowed in {} mode.".format( self.name, mode_names)) if self._needs_js and not QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): raise cmdexc.PrerequisitesError( "{}: This command needs javascript enabled.".format(self.name)) if self.deprecated: message.warning(win_id, '{} is deprecated - {}'.format( self.name, self.deprecated))
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = '/'.join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format( self.name, mode_names)) elif self._not_modes is not None and curmode in self._not_modes: mode_names = '/'.join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError( "{}: This command is not allowed in {} mode.".format( self.name, mode_names)) if self._needs_js and not QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): raise cmdexc.PrerequisitesError( "{}: This command needs javascript enabled.".format(self.name)) if self.deprecated: message.warning( win_id, '{} is deprecated - {}'.format(self.name, self.deprecated))
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get("mode-manager", scope="window", window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = "/".join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format(self.name, mode_names) ) elif self._not_modes is not None and curmode in self._not_modes: mode_names = "/".join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError("{}: This command is not allowed in {} mode.".format(self.name, mode_names)) used_backend = usertypes.arg2backend[objreg.get("args").backend] if self.backend is not None and used_backend != self.backend: raise cmdexc.PrerequisitesError( "{}: Only available with {} " "backend.".format(self.name, self.backend.name) ) if self.deprecated: message.warning(win_id, "{} is deprecated - {}".format(self.name, self.deprecated))
def _check_prerequisites(self, win_id, count): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) self.validate_mode(mode_manager.mode) used_backend = usertypes.arg2backend[objreg.get('args').backend] if self.backend is not None and used_backend != self.backend: raise cmdexc.PrerequisitesError("{}: Only available with {} " "backend.".format( self.name, self.backend.name)) if count == 0 and not self._zero_count: raise cmdexc.PrerequisitesError( "{}: A zero count is not allowed for this command!".format( self.name)) if self.deprecated: message.warning('{} is deprecated - {}'.format( self.name, self.deprecated))
def _find_installed(self, code): installed_file = spell.installed_file(code) if not installed_file: message.warning( "Language {} is not installed - see scripts/install_dict.py " "in qutebrowser's sources".format(code)) return installed_file
def version(filename): """Extract the version number from the dictionary file name.""" match = _DICT_VERSION_RE.fullmatch(filename) if match is None: message.warning( "Found a dictionary with a malformed name: {}".format(filename)) return None return tuple(int(n) for n in match.group('version').split('-'))
def version(filename): """Extract the version number from the dictionary file name.""" match = dict_version_re.match(filename) if match is None: message.warning( "Found a dictionary with a malformed name: {}".format(filename)) return None return tuple(int(n) for n in match.group('version').split('-'))
def _init_private_browsing(): if config.get('general', 'private-browsing'): if qtutils.is_qtwebkit_ng(qWebKitVersion()): message.warning("Private browsing is not fully implemented by " "QtWebKit-NG!") QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(standarddir.cache())
def open_file(filename: str, cmdline: str = None) -> None: """Open the given file. If cmdline is not given, downloads.open_dispatcher is used. If open_dispatcher is unset, the system's default application is used. Args: filename: The filename to open. cmdline: The command to use as string. A `{}` is expanded to the filename. None means to use the system's default application or `downloads.open_dispatcher` if set. If no `{}` is found, the filename is appended to the cmdline. """ # Import late to avoid circular imports: # - usertypes -> utils -> guiprocess -> message -> usertypes # - usertypes -> utils -> config -> configdata -> configtypes -> # cmdutils -> command -> message -> usertypes from qutebrowser.config import config from qutebrowser.misc import guiprocess from qutebrowser.utils import version, message # the default program to open downloads with - will be empty string # if we want to use the default override = config.val.downloads.open_dispatcher if version.is_sandboxed(): if cmdline: message.error("Cannot spawn download dispatcher from sandbox") return if override: message.warning("Ignoring download dispatcher from config in " "sandbox environment") override = None # precedence order: cmdline > downloads.open_dispatcher > openUrl if cmdline is None and not override: log.misc.debug("Opening {} with the system application" .format(filename)) url = QUrl.fromLocalFile(filename) QDesktopServices.openUrl(url) return if cmdline is None and override: cmdline = override assert cmdline is not None cmd, *args = shlex.split(cmdline) args = [arg.replace('{}', filename) for arg in args] if '{}' not in cmdline: args.append(filename) log.misc.debug("Opening {} with {}" .format(filename, [cmd] + args)) proc = guiprocess.GUIProcess(what='open-file') proc.start_detached(cmd, args)
def search(self, text, flags): """Search for text in the current page. Args: text: The text to search for. flags: The QWebPage::FindFlags. """ log.webview.debug("Searching with text '{}' and flags " "0x{:04x}.".format(text, int(flags))) old_scroll_pos = self.scroll_pos flags = QWebPage.FindFlags(flags) found = self.findText(text, flags) backward = flags & QWebPage.FindBackward if not found and not flags & QWebPage.HighlightAllOccurrences and text: # User disabled wrapping; but findText() just returns False. If we # have a selection, we know there's a match *somewhere* on the page if (not flags & QWebPage.FindWrapsAroundDocument and self.hasSelection()): if not backward: message.warning(self.win_id, "Search hit BOTTOM without " "match for: {}".format(text), immediately=True) else: message.warning(self.win_id, "Search hit TOP without " "match for: {}".format(text), immediately=True) else: message.error(self.win_id, "Text '{}' not found on " "page!".format(text), immediately=True) else: def check_scroll_pos(): """Check if the scroll position got smaller and show info.""" if not backward and self.scroll_pos < old_scroll_pos: message.info(self.win_id, "Search hit BOTTOM, continuing " "at TOP", immediately=True) elif backward and self.scroll_pos > old_scroll_pos: message.info(self.win_id, "Search hit TOP, continuing at " "BOTTOM", immediately=True) # We first want QWebPage to refresh. QTimer.singleShot(0, check_scroll_pos)
def _set_dictionary_language(profile, warn=True): filenames = [] for code in config.val.spellcheck.languages or []: local_filename = spell.local_filename(code) if not local_filename: if warn: message.warning( "Language {} is not installed - see scripts/dictcli.py " "in qutebrowser's sources".format(code)) continue filenames.append(local_filename) log.config.debug("Found dicts: {}".format(filenames)) profile.setSpellCheckLanguages(filenames)
def set_dictionary_language(self, warn=True): """Load the given dictionaries.""" filenames = [] for code in config.val.spellcheck.languages or []: local_filename = spell.local_filename(code) if not local_filename: if warn: message.warning("Language {} is not installed - see " "scripts/dictcli.py in qutebrowser's " "sources".format(code)) continue filenames.append(local_filename) log.config.debug("Found dicts: {}".format(filenames)) self._profile.setSpellCheckLanguages(filenames)
def set_dictionary_language(self, warn=True): """Load the given dictionaries.""" filenames = [] for code in config.val.spellcheck.languages or []: local_filename = spell.local_filename(code) if not local_filename: if warn: message.warning("Language {} is not installed - see " "scripts/dictcli.py in qutebrowser's " "sources".format(code)) continue filenames.append(local_filename) log.config.debug("Found dicts: {}".format(filenames)) self._profile.setSpellCheckLanguages(filenames) self._profile.setSpellCheckEnabled(bool(filenames))
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ from qutebrowser.keyinput import modeman mode_manager = modeman.instance(win_id) self.validate_mode(mode_manager.mode) if self.backend is not None and objects.backend != self.backend: raise cmdexc.PrerequisitesError("{}: Only available with {} " "backend.".format( self.name, self.backend.name)) if self.deprecated: message.warning(f'{self.name} is deprecated - {self.deprecated}')
def set_dictionary_language(self): """Load the given dictionaries.""" filenames = [] for code in config.val.spellcheck.languages or []: local_filename = spell.local_filename(code) if not local_filename: if not self._profile.isOffTheRecord(): message.warning("Language {} is not installed - see " "scripts/dictcli.py in qutebrowser's " "sources".format(code)) continue filenames.append(os.path.splitext(local_filename)[0]) log.config.debug("Found dicts: {}".format(filenames)) self._profile.setSpellCheckLanguages(filenames) self._profile.setSpellCheckEnabled(bool(filenames))
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) self.validate_mode(mode_manager.mode) if self.backend is not None and objects.backend != self.backend: raise cmdexc.PrerequisitesError( "{}: Only available with {} " "backend.".format(self.name, self.backend.name)) if self.deprecated: message.warning('{} is deprecated - {}'.format(self.name, self.deprecated))
def download_remove(self, all_=False, count=0): """Remove the last/[count]th download from the list. Args: all_: Deprecated argument for removing all finished downloads. count: The index of the download to cancel. """ if all_: message.warning(self._win_id, ":download-remove --all is " "deprecated - use :download-clear instead!") self.download_clear() else: try: download = self.downloads[count - 1] except IndexError: self.raise_no_download(count) if not download.done: if not count: count = len(self.downloads) raise cmdexc.CommandError("Download {} is not done!" .format(count)) self.remove_item(download)
def _handle_old_rapid_targets(self, win_id): """Switch to the new way for rapid hinting with a rapid target. Args: win_id: The window ID to display the warning in. DEPRECATED. """ old_rapid_targets = { Target.rapid: Target.tab_bg, Target.rapid_win: Target.window, } target = self._context.target if target in old_rapid_targets: self._context.target = old_rapid_targets[target] self._context.rapid = True name = target.name.replace('_', '-') group_name = self._context.group.name.replace('_', '-') new_name = self._context.target.name.replace('_', '-') message.warning( win_id, ':hint with target {} is deprecated, use :hint ' '--rapid {} {} instead!'.format(name, group_name, new_name))
def choose_file(multiple: bool) -> List[str]: """Select file(s) for uploading, using external command defined in config. Args: multiple: Should selecting multiple files be allowed. Return: A list of selected file paths, or empty list if no file is selected. If multiple is False, the return value will have at most 1 item. """ handle = tempfile.NamedTemporaryFile(prefix='qutebrowser-fileselect-', delete=False) handle.close() tmpfilename = handle.name with utils.cleanup_file(tmpfilename): if multiple: command = config.val.fileselect.multiple_files.command else: command = config.val.fileselect.single_file.command proc = guiprocess.GUIProcess(what='choose-file') proc.start(command[0], [arg.replace('{}', tmpfilename) for arg in command[1:]]) loop = qtutils.EventLoop() proc.finished.connect(lambda _code, _status: loop.exit()) loop.exec() try: with open(tmpfilename, mode='r', encoding=sys.getfilesystemencoding()) as f: selected_files = f.read().splitlines() except OSError as e: message.error(f"Failed to open tempfile {tmpfilename} ({e})!") selected_files = [] if not multiple: if len(selected_files) > 1: message.warning("More than one file chosen, using only the first") return selected_files[:1] return selected_files
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = '/'.join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format( self.name, mode_names)) elif self._not_modes is not None and curmode in self._not_modes: mode_names = '/'.join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError( "{}: This command is not allowed in {} mode.".format( self.name, mode_names)) if self._needs_js and not QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): raise cmdexc.PrerequisitesError( "{}: This command needs javascript enabled.".format(self.name)) backend_mapping = { 'webkit': usertypes.Backend.QtWebKit, 'webengine': usertypes.Backend.QtWebEngine, } used_backend = backend_mapping[objreg.get('args').backend] if self.backend is not None and used_backend != self.backend: raise cmdexc.PrerequisitesError( "{}: Only available with {} " "backend.".format(self.name, self.backend.name)) if self.deprecated: message.warning(win_id, '{} is deprecated - {}'.format( self.name, self.deprecated))
def _execute_fileselect_command( command: List[str], multiple: bool, tmpfilename: Optional[str] = None) -> List[str]: """Execute external command to choose file. Args: multiple: Should selecting multiple files be allowed. tmpfilename: Path to the temporary file if used, otherwise None. Return: A list of selected file paths, or empty list if no file is selected. If multiple is False, the return value will have at most 1 item. """ proc = guiprocess.GUIProcess(what='choose-file') proc.start(command[0], command[1:]) loop = qtutils.EventLoop() proc.finished.connect(lambda _code, _status: loop.exit()) loop.exec() if tmpfilename is None: selected_files = proc.final_stdout.splitlines() else: try: with open(tmpfilename, mode='r', encoding=sys.getfilesystemencoding()) as f: selected_files = f.read().splitlines() except OSError as e: message.error(f"Failed to open tempfile {tmpfilename} ({e})!") selected_files = [] if not multiple: if len(selected_files) > 1: message.warning("More than one file chosen, using only the first") return selected_files[:1] return selected_files
def _check_prerequisites(self, win_id, count): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) self.validate_mode(mode_manager.mode) used_backend = usertypes.arg2backend[objreg.get('args').backend] if self.backend is not None and used_backend != self.backend: raise cmdexc.PrerequisitesError( "{}: Only available with {} " "backend.".format(self.name, self.backend.name)) if count == 0 and not self._zero_count: raise cmdexc.PrerequisitesError( "{}: A zero count is not allowed for this command!" .format(self.name)) if self.deprecated: message.warning('{} is deprecated - {}'.format(self.name, self.deprecated))
def _validated_selected_files( qb_mode: FileSelectionMode, selected_files: List[str], ) -> Iterator[str]: """Validates selected files if they are. * Of correct type * Of correct number * Existent Args: qb_mode: File selection mode used selected_files: files selected Return: List of selected files that pass the checks. """ if qb_mode != FileSelectionMode.multiple_files: if len(selected_files) > 1: message.warning( "More than one file/folder chosen, using only the first") selected_files = selected_files[:1] for selected_file in selected_files: if not os.path.exists(selected_file): message.warning(f"Ignoring non-existent file '{selected_file}'") continue if qb_mode == FileSelectionMode.folder: if not os.path.isdir(selected_file): message.warning( f"Expected folder but got file, ignoring '{selected_file}'" ) continue else: # pylint: disable=else-if-used if not os.path.isfile(selected_file): message.warning( f"Expected file but got folder, ignoring '{selected_file}'" ) continue yield selected_file