def test_system_datadir_unsupportedos(self, monkeypatch, tmpdir, fake_args): """Test that system-wide path is not used on non-Linux OS.""" fake_args.basedir = str(tmpdir) monkeypatch.setattr('sys.platform', "potato") standarddir._init_dirs(fake_args) assert standarddir.data(system=True) == standarddir.data()
def run_async(tab, cmd, *args, win_id, env, verbose=False): """Run a userscript after dumping page html/source. Raises: UnsupportedError if userscripts are not supported on the current platform. Args: tab: The WebKitTab/WebEngineTab to get the source from. cmd: The userscript binary to run. *args: The arguments to pass to the userscript. win_id: The window id the userscript is executed in. env: A dictionary of variables to add to the process environment. verbose: Show notifications when the command started/exited. """ tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) commandrunner = runners.CommandRunner(win_id, parent=tabbed_browser) if os.name == 'posix': runner = _POSIXUserscriptRunner(win_id, tabbed_browser) elif os.name == 'nt': # pragma: no cover runner = _WindowsUserscriptRunner(win_id, tabbed_browser) else: # pragma: no cover raise UnsupportedError runner.got_cmd.connect( lambda cmd: log.commands.debug("Got userscript command: {}".format(cmd))) runner.got_cmd.connect(commandrunner.run_safely) user_agent = config.get('network', 'user-agent') if user_agent is not None: env['QUTE_USER_AGENT'] = user_agent config_dir = standarddir.config() if config_dir is not None: env['QUTE_CONFIG_DIR'] = config_dir data_dir = standarddir.data() if data_dir is not None: env['QUTE_DATA_DIR'] = data_dir download_dir = downloads.download_dir() if download_dir is not None: env['QUTE_DOWNLOAD_DIR'] = download_dir cmd_path = os.path.expanduser(cmd) # if cmd is not given as an absolute path, look it up # ~/.local/share/qutebrowser/userscripts (or $XDG_DATA_DIR) if not os.path.isabs(cmd_path): log.misc.debug("{} is no absolute path".format(cmd_path)) cmd_path = os.path.join(standarddir.data(), "userscripts", cmd) if not os.path.exists(cmd_path): cmd_path = os.path.join(standarddir.system_data(), "userscripts", cmd) log.misc.debug("Userscript to run: {}".format(cmd_path)) runner.finished.connect(commandrunner.deleteLater) runner.finished.connect(runner.deleteLater) runner.prepare_run(cmd_path, *args, env=env, verbose=verbose) tab.dump_async(runner.store_html) tab.dump_async(runner.store_text, plain=True)
def test_system_datadir_not_exist_linux(self, monkeypatch, tmpdir, fake_args): """Test that system-wide path isn't used on linux if path not exist.""" fake_args.basedir = str(tmpdir) monkeypatch.setattr(os.path, 'exists', lambda path: False) standarddir._init_dirs(fake_args) assert standarddir.data(system=True) == standarddir.data()
def _init_misc(): """Initialize misc. config-related files.""" save_manager = objreg.get('save-manager') state_config = ini.ReadWriteConfigParser(standarddir.data(), 'state') for sect in ['general', 'geometry']: try: state_config.add_section(sect) except configparser.DuplicateSectionError: pass # See commit a98060e020a4ba83b663813a4b9404edb47f28ad. state_config['general'].pop('fooled', None) objreg.register('state-config', state_config) save_manager.add_saveable('state-config', state_config.save) # We need to import this here because lineparser needs config. from qutebrowser.misc import lineparser command_history = lineparser.LimitLineParser( standarddir.data(), 'cmd-history', limit=('completion', 'cmd-history-max-items'), parent=objreg.get('config')) objreg.register('command-history', command_history) save_manager.add_saveable('command-history', command_history.save, command_history.changed) # Set the QSettings path to something like # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/qutebrowser/qutebrowser/issues/515 path = os.path.join(standarddir.config(), 'qsettings') for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: QSettings.setPath(fmt, QSettings.UserScope, path)
def __init__(self, parent=None): super().__init__(parent) self._current = None data_dir = standarddir.data() if data_dir is None: self._base_path = None else: self._base_path = os.path.join(standarddir.data(), 'sessions') self._last_window_session = None self.did_load = False if self._base_path is not None and not os.path.exists(self._base_path): os.mkdir(self._base_path)
def __init__(self) -> None: super().__init__() self._filename = os.path.join(standarddir.data(), 'state') self.read(self._filename, encoding='utf-8') self.qt_version_changed = False self.qtwe_version_changed = False self.qutebrowser_version_changed = VersionChange.unknown self._set_changed_attributes() for sect in ['general', 'geometry', 'inspector']: try: self.add_section(sect) except configparser.DuplicateSectionError: pass deleted_keys = [ ('general', 'fooled'), ('general', 'backend-warning-shown'), ('general', 'old-qt-warning-shown'), ('geometry', 'inspector'), ] for sect, key in deleted_keys: self[sect].pop(key, None) self['general']['qt_version'] = qVersion() self['general']['qtwe_version'] = self._qtwe_version_str() self['general']['version'] = qutebrowser.__version__
def import_txt(self): """Import a history text file into sqlite if it exists. In older versions of qutebrowser, history was stored in a text format. This converts that file into the new sqlite format and moves it to a backup location. """ path = os.path.join(standarddir.data(), 'history') if not os.path.isfile(path): return def action(): with debug.log_time(log.init, 'Import old history file to sqlite'): try: self._read(path) except ValueError as ex: message.error('Failed to import history: {}'.format(ex)) else: bakpath = path + '.bak' message.info('History import complete. Moving {} to {}' .format(path, bakpath)) os.rename(path, bakpath) # delay to give message time to appear before locking down for import message.info('Converting {} to sqlite...'.format(path)) QTimer.singleShot(100, action)
def generate_pdfjs_page(filename, url): """Return the html content of a page that displays a file with pdfjs. Returns a string. Args: filename: The filename of the PDF to open. url: The URL being opened. """ if not is_available(): pdfjs_dir = os.path.join(standarddir.data(), 'pdfjs') return jinja.render('no_pdfjs.html', url=url.toDisplayString(), title="PDF.js not found", pdfjs_dir=pdfjs_dir) html = get_pdfjs_res('web/viewer.html').decode('utf-8') script = _generate_pdfjs_script(filename) html = html.replace('</body>', '</body><script>{}</script>'.format(script)) # WORKAROUND for the fact that PDF.js tries to use the Fetch API even with # qute:// URLs. pdfjs_script = '<script src="../build/pdf.js"></script>' html = html.replace(pdfjs_script, '<script>window.Response = undefined;</script>\n' + pdfjs_script) return html
def _read_history(self): """Read the initial history.""" if standarddir.data() is None: return with self._lineparser.open(): for line in self._lineparser: data = line.rstrip().split(maxsplit=1) if not data: # empty line continue elif len(data) != 2: # other malformed line log.init.warning("Invalid history entry {!r}!".format( line)) continue atime, url = data if atime.startswith('\0'): log.init.warning( "Removing NUL bytes from entry {!r} - see " "https://github.com/The-Compiler/qutebrowser/issues/" "670".format(data)) atime = atime.lstrip('\0') # This de-duplicates history entries; only the latest # entry for each URL is kept. If you want to keep # information about previous hits change the items in # old_urls to be lists or change HistoryEntry to have a # list of atimes. self._history_dict[url] = HistoryEntry(atime, url) self._history_dict.move_to_end(url)
def dictionary_dir(old=False): """Return the path (str) to the QtWebEngine's dictionaries directory.""" if qtutils.version_check('5.10', compiled=False) and not old: datapath = standarddir.data() else: datapath = QLibraryInfo.location(QLibraryInfo.DataPath) return os.path.join(datapath, 'qtwebengine_dictionaries')
def __init__(self) -> None: super().__init__() self._filename = os.path.join(standarddir.data(), 'state') self.read(self._filename, encoding='utf-8') qt_version = qVersion() # We handle this here, so we can avoid setting qt_version_changed if # the config is brand new, but can still set it when qt_version wasn't # there before... if 'general' in self: old_qt_version = self['general'].get('qt_version', None) self.qt_version_changed = old_qt_version != qt_version else: self.qt_version_changed = False for sect in ['general', 'geometry', 'inspector']: try: self.add_section(sect) except configparser.DuplicateSectionError: pass deleted_keys = [ ('general', 'fooled'), ('general', 'backend-warning-shown'), ('geometry', 'inspector'), ] for sect, key in deleted_keys: self[sect].pop(key, None) self['general']['qt_version'] = qt_version self['general']['version'] = qutebrowser.__version__
def __init__(self, parent=None): super().__init__(parent) self._lineparser = lineparser.AppendLineParser( standarddir.data(), 'history', parent=self) self._history_dict = collections.OrderedDict() with self._lineparser.open(): for line in self._lineparser: data = line.rstrip().split(maxsplit=1) if not data: # empty line continue elif len(data) != 2: # other malformed line log.init.warning("Invalid history entry {!r}!".format( line)) continue atime, url = data # This de-duplicates history entries; only the latest # entry for each URL is kept. If you want to keep # information about previous hits change the items in # old_urls to be lists or change HistoryEntry to have a # list of atimes. self._history_dict[url] = HistoryEntry(atime, url) self._history_dict.move_to_end(url) self._new_history = [] self._saved_count = 0 objreg.get('save-manager').add_saveable( 'history', self.save, self.item_added)
def generate_pdfjs_page(filename, url): """Return the html content of a page that displays a file with pdfjs. Returns a string. Args: filename: The filename of the PDF to open. url: The URL being opened. """ if not is_available(): pdfjs_dir = os.path.join(standarddir.data(), 'pdfjs') return jinja.render('no_pdfjs.html', url=url.toDisplayString(), title="PDF.js not found", pdfjs_dir=pdfjs_dir) html = get_pdfjs_res('web/viewer.html').decode('utf-8') script = _generate_pdfjs_script(filename) html = html.replace('</body>', '</body><script>{}</script>'.format(script)) # WORKAROUND for the fact that PDF.js tries to use the Fetch API even with # qute:// URLs. pdfjs_script = '<script src="../build/pdf.js"></script>' html = html.replace( pdfjs_script, '<script>window.Response = undefined;</script>\n' + pdfjs_script) return html
def test_system_datadir_unsupportedos(self, monkeypatch, tmpdir, fake_args): """Test that system-wide path is not used on non-Linux OS.""" fake_args.basedir = str(tmpdir) standarddir.init(fake_args) monkeypatch.setattr('sys.platform', "potato") assert standarddir.system_data() == standarddir.data()
def test_system_datadir_not_exist_linux(self, monkeypatch, tmpdir, fake_args): """Test that system-wide path isn't used on linux if path not exist.""" fake_args.basedir = str(tmpdir) standarddir.init(fake_args) monkeypatch.setattr(os.path, 'exists', lambda path: False) assert standarddir.system_data() == standarddir.data()
def handle_segfault(self): """Handle a segfault from a previous run.""" data_dir = standarddir.data() if data_dir is None: return logname = os.path.join(data_dir, 'crash.log') try: # First check if an old logfile exists. if os.path.exists(logname): with open(logname, 'r', encoding='ascii') as f: data = f.read() os.remove(logname) self._init_crashlogfile() if data: # Crashlog exists and has data in it, so something crashed # previously. self._crash_dialog = crashdialog.get_fatal_crash_dialog( self._args.debug, data) self._crash_dialog.show() else: # There's no log file, so we can use this to display crashes to # the user on the next start. self._init_crashlogfile() except OSError: log.init.exception("Error while handling crash log file!") self._init_crashlogfile()
def import_txt(self): """Import a history text file into sqlite if it exists. In older versions of qutebrowser, history was stored in a text format. This converts that file into the new sqlite format and moves it to a backup location. """ path = os.path.join(standarddir.data(), 'history') if not os.path.isfile(path): return def action(): with debug.log_time(log.init, 'Import old history file to sqlite'): try: self._read(path) except ValueError as ex: message.error('Failed to import history: {}'.format(ex)) else: bakpath = path + '.bak' message.info( 'History import complete. Moving {} to {}'.format( path, bakpath)) os.rename(path, bakpath) # delay to give message time to appear before locking down for import message.info('Converting {} to sqlite...'.format(path)) QTimer.singleShot(100, action)
def _handle_serviceworker_nuking(self) -> None: """Nuke the service workers directory if the Qt version changed. WORKAROUND for: https://bugreports.qt.io/browse/QTBUG-72532 https://bugreports.qt.io/browse/QTBUG-82105 """ if ('serviceworker_workaround' not in configfiles.state['general'] and qtutils.version_check('5.14', compiled=False)): # Nuke the service worker directory once for every install with Qt # 5.14, given that it seems to cause a variety of segfaults. configfiles.state['general']['serviceworker_workaround'] = '514' affected = True else: # Otherwise, just nuke it when the Qt version changed. affected = configfiles.state.qt_version_changed if not affected: return service_worker_dir = os.path.join(standarddir.data(), 'webengine', 'Service Worker') bak_dir = service_worker_dir + '-bak' if not os.path.exists(service_worker_dir): return log.init.info("Qt version changed, removing service workers") # Keep one backup around - we're not 100% sure what persistent data # could be in there, but this folder can grow to ~300 MB. if os.path.exists(bak_dir): shutil.rmtree(bak_dir) shutil.move(service_worker_dir, bak_dir)
def dictionary_dir(old=False): """Return the path (str) to the QtWebEngine's dictionaries directory.""" if can_use_data_path() and not old: datapath = standarddir.data() else: datapath = QLibraryInfo.location(QLibraryInfo.DataPath) return os.path.join(datapath, 'qtwebengine_dictionaries')
def __init__(self, parent=None): super().__init__(parent) self._base_path = os.path.join(standarddir.data(), 'sessions') self._last_window_session = None self.did_load = False if not os.path.exists(self._base_path): os.mkdir(self._base_path)
def run_async(tab, cmd, *args, win_id, env, verbose=False): """Run a userscript after dumping page html/source. Raises: UnsupportedError if userscripts are not supported on the current platform. NotFoundError if the command could not be found. Args: tab: The WebKitTab/WebEngineTab to get the source from. cmd: The userscript binary to run. *args: The arguments to pass to the userscript. win_id: The window id the userscript is executed in. env: A dictionary of variables to add to the process environment. verbose: Show notifications when the command started/exited. """ tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) commandrunner = runners.CommandRunner(win_id, parent=tabbed_browser) if os.name == 'posix': runner = _POSIXUserscriptRunner(tabbed_browser) elif os.name == 'nt': # pragma: no cover runner = _WindowsUserscriptRunner(tabbed_browser) else: # pragma: no cover raise UnsupportedError runner.got_cmd.connect(lambda cmd: log.commands.debug( "Got userscript command: {}".format(cmd))) runner.got_cmd.connect(commandrunner.run_safely) user_agent = config.get('network', 'user-agent') if user_agent is not None: env['QUTE_USER_AGENT'] = user_agent config_dir = standarddir.config() if config_dir is not None: env['QUTE_CONFIG_DIR'] = config_dir data_dir = standarddir.data() if data_dir is not None: env['QUTE_DATA_DIR'] = data_dir download_dir = downloads.download_dir() if download_dir is not None: env['QUTE_DOWNLOAD_DIR'] = download_dir cmd_path = os.path.expanduser(cmd) # if cmd is not given as an absolute path, look it up # ~/.local/share/qutebrowser/userscripts (or $XDG_DATA_DIR) if not os.path.isabs(cmd_path): log.misc.debug("{} is no absolute path".format(cmd_path)) cmd_path = _lookup_path(cmd) elif not os.path.exists(cmd_path): raise NotFoundError(cmd_path) log.misc.debug("Userscript to run: {}".format(cmd_path)) runner.finished.connect(commandrunner.deleteLater) runner.finished.connect(runner.deleteLater) runner.prepare_run(cmd_path, *args, env=env, verbose=verbose) tab.dump_async(runner.store_html) tab.dump_async(runner.store_text, plain=True)
def _init_default_profile(): """Init the default QWebEngineProfile.""" global default_profile default_profile = QWebEngineProfile.defaultProfile() init_user_agent() default_profile.setter = ProfileSetter( # type: ignore[attr-defined] default_profile) default_profile.setCachePath(os.path.join(standarddir.cache(), 'webengine')) default_profile.setPersistentStoragePath( os.path.join(standarddir.data(), 'webengine')) default_profile.setter.init_profile() default_profile.setter.set_persistent_cookie_policy() _qute_scheme_handler.install(default_profile) _req_interceptor.install(default_profile) _download_manager.install(default_profile) cookies.install_filter(default_profile) # Clear visited links on web history clear history.web_history.history_cleared.connect( default_profile.clearAllVisitedLinks) history.web_history.url_cleared.connect( lambda url, profile=default_profile: profile.clearVisitedLinks([url]))
def run(cmd, *args, win_id, env, verbose=False): """Convenience method to run a userscript. Args: cmd: The userscript binary to run. *args: The arguments to pass to the userscript. win_id: The window id the userscript is executed in. env: A dictionary of variables to add to the process environment. verbose: Show notifications when the command started/exited. """ tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) commandrunner = runners.CommandRunner(win_id, tabbed_browser) runner = UserscriptRunner(win_id, tabbed_browser) runner.got_cmd.connect(lambda cmd: log.commands.debug( "Got userscript command: {}".format(cmd))) runner.got_cmd.connect(commandrunner.run_safely) user_agent = config.get('network', 'user-agent') if user_agent is not None: env['QUTE_USER_AGENT'] = user_agent cmd = os.path.expanduser(cmd) # if cmd is not given as an absolute path, look it up # ~/.local/share/qutebrowser/userscripts (or $XDG_DATA_DIR) if not os.path.isabs(cmd): log.misc.debug("{} is no absolute path".format(cmd)) cmd = os.path.join(standarddir.data(), "userscripts", cmd) runner.run(cmd, *args, env=env, verbose=verbose) runner.finished.connect(commandrunner.deleteLater) runner.finished.connect(runner.deleteLater)
def test_datadir(self, testcase): """Test --datadir.""" args = types.SimpleNamespace(confdir=None, cachedir=None, datadir=testcase.arg) standarddir.init(args) assert standarddir.data() == testcase.expected
def run(cmd, *args, win_id, env, verbose=False): """Convenience method to run a userscript. Args: cmd: The userscript binary to run. *args: The arguments to pass to the userscript. win_id: The window id the userscript is executed in. env: A dictionary of variables to add to the process environment. verbose: Show notifications when the command started/exited. """ tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) commandrunner = runners.CommandRunner(win_id, tabbed_browser) runner = UserscriptRunner(win_id, tabbed_browser) runner.got_cmd.connect( lambda cmd: log.commands.debug("Got userscript command: {}".format( cmd))) runner.got_cmd.connect(commandrunner.run_safely) user_agent = config.get('network', 'user-agent') if user_agent is not None: env['QUTE_USER_AGENT'] = user_agent cmd = os.path.expanduser(cmd) # if cmd is not given as an absolute path, look it up # ~/.local/share/qutebrowser/userscripts (or $XDG_DATA_DIR) if not os.path.isabs(cmd): log.misc.debug("{} is no absolute path".format(cmd)) cmd = os.path.join(standarddir.data(), "userscripts", cmd) runner.run(cmd, *args, env=env, verbose=verbose) runner.finished.connect(commandrunner.deleteLater) runner.finished.connect(runner.deleteLater)
def test_data(self, monkeypatch, tmpdir): """Test data dir with XDG_DATA_HOME not set.""" monkeypatch.setenv('HOME', str(tmpdir)) monkeypatch.delenv('XDG_DATA_HOME', raising=False) standarddir.init(None) expected = tmpdir / '.local' / 'share' / 'qutebrowser_test' assert standarddir.data() == str(expected)
def init(): """Initialize the global QWebSettings.""" cache_path = standarddir.cache() data_path = standarddir.data() if config.get('general', 'private-browsing') or cache_path is None: QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(cache_path) if cache_path is not None: QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cache_path, 'application-cache')) if data_path is not None: QWebSettings.globalSettings().setLocalStoragePath( os.path.join(data_path, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(data_path, 'offline-storage')) for sectname, section in MAPPINGS.items(): for optname, mapping in section.items(): default = mapping.save_default() log.config.vdebug("Saved default for {} -> {}: {!r}".format( sectname, optname, default)) value = config.get(sectname, optname) log.config.vdebug("Setting {} -> {} to {!r}".format( sectname, optname, value)) mapping.set(value) objreg.get('config').changed.connect(update_settings)
def run_async(tab, cmd, *args, win_id, env, verbose=False, output_messages=False): """Run a userscript after dumping page html/source. Raises: UnsupportedError if userscripts are not supported on the current platform. NotFoundError if the command could not be found. Args: tab: The WebKitTab/WebEngineTab to get the source from. cmd: The userscript binary to run. *args: The arguments to pass to the userscript. win_id: The window id the userscript is executed in. env: A dictionary of variables to add to the process environment. verbose: Show notifications when the command started/exited. output_messages: Show the output as messages. """ tb = objreg.get('tabbed-browser', scope='window', window=win_id) commandrunner = runners.CommandRunner(win_id, parent=tb) if utils.is_posix: runner = _POSIXUserscriptRunner(tb) # type: _BaseUserscriptRunner elif utils.is_windows: # pragma: no cover runner = _WindowsUserscriptRunner(tb) else: # pragma: no cover raise UnsupportedError runner.got_cmd.connect( lambda cmd: log.commands.debug("Got userscript command: {}".format(cmd))) runner.got_cmd.connect(commandrunner.run_safely) env['QUTE_USER_AGENT'] = websettings.user_agent() env['QUTE_CONFIG_DIR'] = standarddir.config() env['QUTE_DATA_DIR'] = standarddir.data() env['QUTE_DOWNLOAD_DIR'] = downloads.download_dir() env['QUTE_COMMANDLINE_TEXT'] = objreg.get('status-command', scope='window', window=win_id).text() cmd_path = os.path.expanduser(cmd) # if cmd is not given as an absolute path, look it up # ~/.local/share/qutebrowser/userscripts (or $XDG_DATA_HOME) if not os.path.isabs(cmd_path): log.misc.debug("{} is no absolute path".format(cmd_path)) cmd_path = _lookup_path(cmd) elif not os.path.exists(cmd_path): raise NotFoundError(cmd_path) log.misc.debug("Userscript to run: {}".format(cmd_path)) runner.finished.connect(commandrunner.deleteLater) runner.finished.connect(runner.deleteLater) runner.prepare_run(cmd_path, *args, env=env, verbose=verbose, output_messages=output_messages) tab.dump_async(runner.store_html) tab.dump_async(runner.store_text, plain=True) return runner
def run_async(tab, cmd, *args, win_id, env, verbose=False): """Run a userscript after dumping page html/source. Raises: UnsupportedError if userscripts are not supported on the current platform. NotFoundError if the command could not be found. Args: tab: The WebKitTab/WebEngineTab to get the source from. cmd: The userscript binary to run. *args: The arguments to pass to the userscript. win_id: The window id the userscript is executed in. env: A dictionary of variables to add to the process environment. verbose: Show notifications when the command started/exited. """ tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) commandrunner = runners.CommandRunner(win_id, parent=tabbed_browser) if utils.is_posix: runner = _POSIXUserscriptRunner(tabbed_browser) elif utils.is_windows: # pragma: no cover runner = _WindowsUserscriptRunner(tabbed_browser) else: # pragma: no cover raise UnsupportedError runner.got_cmd.connect( lambda cmd: log.commands.debug("Got userscript command: {}".format(cmd))) runner.got_cmd.connect(commandrunner.run_safely) user_agent = config.val.content.headers.user_agent if user_agent is not None: env['QUTE_USER_AGENT'] = user_agent env['QUTE_CONFIG_DIR'] = standarddir.config() env['QUTE_DATA_DIR'] = standarddir.data() env['QUTE_DOWNLOAD_DIR'] = downloads.download_dir() env['QUTE_COMMANDLINE_TEXT'] = objreg.get('status-command', scope='window', window=win_id).text() cmd_path = os.path.expanduser(cmd) # if cmd is not given as an absolute path, look it up # ~/.local/share/qutebrowser/userscripts (or $XDG_DATA_HOME) if not os.path.isabs(cmd_path): log.misc.debug("{} is no absolute path".format(cmd_path)) cmd_path = _lookup_path(cmd) elif not os.path.exists(cmd_path): raise NotFoundError(cmd_path) log.misc.debug("Userscript to run: {}".format(cmd_path)) runner.finished.connect(commandrunner.deleteLater) runner.finished.connect(runner.deleteLater) runner.prepare_run(cmd_path, *args, env=env, verbose=verbose) tab.dump_async(runner.store_html) tab.dump_async(runner.store_text, plain=True) return runner
def test_data(self): """Test data dir with XDG_DATA_HOME not set.""" env = {'HOME': self.temp_dir, 'XDG_DATA_HOME': None} with helpers.environ_set_temp(env): standarddir.init(None) expected = os.path.join(self.temp_dir, '.local', 'share', 'qutebrowser') self.assertEqual(standarddir.data(), expected)
def __init__(self, parent=None): super().__init__(parent) self._current = None self._base_path = os.path.join(standarddir.data(), 'sessions') self._last_window_session = None self.did_load = False if not os.path.exists(self._base_path): os.mkdir(self._base_path)
def test_system_datadir_exist_linux(self, monkeypatch, tmpdir, is_flatpak, expected): """Test that /usr/share/qute_test is used if path exists.""" monkeypatch.setenv('XDG_DATA_HOME', str(tmpdir)) monkeypatch.setattr(os.path, 'exists', lambda path: True) monkeypatch.setattr(version, 'is_flatpak', lambda: is_flatpak) standarddir._init_data(args=None) assert standarddir.data(system=True) == expected
def _path_info() -> Mapping[str, str]: """Get info about important path names. Return: A dictionary of descriptive to actual path names. """ info = { 'config': standarddir.config(), 'data': standarddir.data(), 'cache': standarddir.cache(), 'runtime': standarddir.runtime(), } if standarddir.config() != standarddir.config(auto=True): info['auto config'] = standarddir.config(auto=True) if standarddir.data() != standarddir.data(system=True): info['system data'] = standarddir.data(system=True) return info
def _path_info(): """Get info about important path names. Return: A dictionary of descriptive to actual path names. """ info = { 'config': standarddir.config(), 'data': standarddir.data(), 'cache': standarddir.cache(), 'runtime': standarddir.runtime(), } if standarddir.config() != standarddir.config(auto=True): info['auto config'] = standarddir.config(auto=True) if standarddir.data() != standarddir.data(system=True): info['system data'] = standarddir.data(system=True) return info
def _init_crashlogfile(self): """Start a new logfile and redirect faulthandler to it.""" logname = os.path.join(standarddir.data(), 'crash.log') try: self._crash_log_file = open(logname, 'w', encoding='ascii') except OSError: log.init.exception("Error while opening crash log file!") else: earlyinit.init_faulthandler(self._crash_log_file)
def init(parent=None): """Initialize sessions. Args: parent: The parent to use for the SessionManager. """ data_dir = standarddir.data() if data_dir is None: base_path = None else: base_path = os.path.join(standarddir.data(), 'sessions') try: os.mkdir(base_path) except FileExistsError: pass session_manager = SessionManager(base_path, parent) objreg.register('session-manager', session_manager)
def init(): """Initialize the LimitLineParser storing the history.""" save_manager = objreg.get('save-manager') command_history = lineparser.LimitLineParser( standarddir.data(), 'cmd-history', limit='completion.cmd_history_max_items') objreg.register('command-history', command_history) save_manager.add_saveable('command-history', command_history.save, command_history.changed)
def __init__(self): self._blocked_hosts = set() self._in_progress = [] self._done_count = 0 data_dir = standarddir.data() if data_dir is None: self._hosts_file = None else: self._hosts_file = os.path.join(data_dir, 'blocked-hosts') objreg.get('config').changed.connect(self.on_config_changed)
def __init__(self, parent=None): super().__init__(parent) self._initial_read_started = False self._initial_read_done = False self._lineparser = lineparser.AppendLineParser(standarddir.data(), "history", parent=self) self._history_dict = collections.OrderedDict() self._temp_history = collections.OrderedDict() self._new_history = [] self._saved_count = 0 objreg.get("save-manager").add_saveable("history", self.save, self.item_added)
def __init__(self, parent=None): super().__init__(parent) self._lineparser = lineparser.AppendLineParser( standarddir.data(), 'history', parent=self) self._history_dict = collections.OrderedDict() self._read_history() self._new_history = [] self._saved_count = 0 objreg.get('save-manager').add_saveable( 'history', self.save, self.item_added)
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 to bundled pdf.js on windows ## os.path.join(os.getcwd(), '3rdparty', 'pdfjs'), # 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 = utils.read_file(file_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
def __init__(self, parent=None): super().__init__(parent) self._lineparser = lineparser.LineParser( standarddir.data(), 'cookies', binary=True, parent=self) cookies = [] for line in self._lineparser: cookies += QNetworkCookie.parseCookies(line) self.setAllCookies(cookies) objreg.get('config').changed.connect(self.cookies_store_changed) objreg.get('save-manager').add_saveable( 'cookies', self.save, self.changed, config_opt=('content', 'cookies-store'))
def init(parent=None): """Initialize the web history. Args: parent: The parent to use for WebHistory. """ history = WebHistory(hist_dir=standarddir.data(), hist_name='history', parent=parent) objreg.register('web-history', history) interface = WebHistoryInterface(history, parent=history) QWebHistoryInterface.setDefaultInterface(interface)
def test_get_fake_windows_equal_dir(data_subdir, config_subdir, expected, monkeypatch, tmpdir): """Test _get with a fake Windows OS with equal data/config dirs.""" locations = { QStandardPaths.DataLocation: str(tmpdir / data_subdir), QStandardPaths.ConfigLocation: str(tmpdir / config_subdir), } monkeypatch.setattr(standarddir.os, 'name', 'nt') monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation', locations.get) expected = str(tmpdir / expected) assert standarddir.data() == expected
def test_fake_haiku(tmpdir, monkeypatch): """Test getting data dir on HaikuOS.""" locations = { QStandardPaths.DataLocation: '', QStandardPaths.ConfigLocation: str(tmpdir / 'config' / APPNAME), } monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation', locations.get) monkeypatch.setattr(standarddir.sys, 'platform', 'haiku1') standarddir._init_data(args=None) assert standarddir.data() == str(tmpdir / 'config' / APPNAME / 'data')
def __init__( self, conf: config.Config, keyconfig: config.KeyConfig, warn_autoconfig: bool, ): self._config = conf self._keyconfig = keyconfig self.errors: List[configexc.ConfigErrorDesc] = [] self.configdir = pathlib.Path(standarddir.config()) self.datadir = pathlib.Path(standarddir.data()) self._warn_autoconfig = warn_autoconfig
def _lookup_path(cmd): """Search userscript directories for given command. Raises: NotFoundError if the command could not be found. Args: cmd: The command to look for. Returns: A path to the userscript. """ directories = [ os.path.join(standarddir.data(), "userscripts"), os.path.join(standarddir.data(system=True), "userscripts"), ] for directory in directories: cmd_path = os.path.join(directory, cmd) if os.path.exists(cmd_path): return cmd_path raise NotFoundError(cmd, directories)
def _init_crashlogfile(self): """Start a new logfile and redirect faulthandler to it.""" assert not self._args.no_err_windows data_dir = standarddir.data() if data_dir is None: return logname = os.path.join(data_dir, 'crash.log') try: self._crash_log_file = open(logname, 'w', encoding='ascii') except OSError: log.init.exception("Error while opening crash log file!") else: earlyinit.init_faulthandler(self._crash_log_file)
def __init__(self) -> None: super().__init__() self._filename = os.path.join(standarddir.data(), 'state') self.read(self._filename, encoding='utf-8') for sect in ['general', 'geometry']: try: self.add_section(sect) except configparser.DuplicateSectionError: pass deleted_keys = ['fooled', 'backend-warning-shown'] for key in deleted_keys: self['general'].pop(key, None)
def __init__(self, parent=None, *, line_parser=None): super().__init__(parent) if line_parser: self._lineparser = line_parser else: self._lineparser = lineparser.LineParser( standarddir.data(), 'cookies', binary=True, parent=self) self.parse_cookies() config.instance.changed.connect(self._on_cookies_store_changed) objreg.get('save-manager').add_saveable( 'cookies', self.save, self.changed, config_opt='content.cookies.store')
def init(args): """Initialize the global QWebSettings.""" if args.enable_webengine_inspector: os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = str(utils.random_port()) profile = QWebEngineProfile.defaultProfile() profile.setCachePath(os.path.join(standarddir.cache(), 'webengine')) profile.setPersistentStoragePath( os.path.join(standarddir.data(), 'webengine')) _init_stylesheet(profile) websettings.init_mappings(MAPPINGS) objreg.get('config').changed.connect(update_settings)