def init(args): """Initialize the config. Args: args: The argparse namespace. """ confdir = standarddir.get(QStandardPaths.ConfigLocation, args) try: app = objreg.get('app') config_obj = ConfigManager(confdir, 'qutebrowser.conf', app) except (configtypes.ValidationError, NoOptionError, NoSectionError, UnknownSectionError, InterpolationSyntaxError, configparser.InterpolationError, configparser.DuplicateSectionError, configparser.DuplicateOptionError, configparser.ParsingError) as e: log.init.exception(e) errstr = "Error while reading config:" if hasattr(e, 'section') and hasattr(e, 'option'): errstr += "\n\n{} -> {}:".format(e.section, e.option) errstr += "\n{}".format(e) msgbox = QMessageBox(QMessageBox.Critical, "Error while reading config!", errstr) msgbox.exec_() # We didn't really initialize much so far, so we just quit hard. sys.exit(1) else: objreg.register('config', config_obj) try: key_config = keyconfparser.KeyConfigParser(confdir, 'keys.conf') except keyconfparser.KeyConfigError as e: log.init.exception(e) errstr = "Error while reading key config:\n" if e.lineno is not None: errstr += "In line {}: ".format(e.lineno) errstr += str(e) msgbox = QMessageBox(QMessageBox.Critical, "Error while reading key config!", errstr) msgbox.exec_() # We didn't really initialize much so far, so we just quit hard. sys.exit(1) else: objreg.register('key-config', key_config) datadir = standarddir.get(QStandardPaths.DataLocation, args) state_config = iniparsers.ReadWriteConfigParser(datadir, 'state') objreg.register('state-config', state_config) # We need to import this here because lineparser needs config. from qutebrowser.config import lineparser command_history = lineparser.LineConfigParser( datadir, 'cmd-history', ('completion', 'history-length')) objreg.register('command-history', command_history)
def init(args): """Initialize the config. Args: args: The argparse namespace. """ confdir = standarddir.get(QStandardPaths.ConfigLocation, args) try: app = objreg.get('app') config_obj = ConfigManager(confdir, 'qutebrowser.conf', app) except (configexc.Error, configparser.Error) as e: log.init.exception(e) errstr = "Error while reading config:" try: errstr += "\n\n{} -> {}:".format( e.section, e.option) # pylint: disable=no-member except AttributeError: pass errstr += "\n{}".format(e) msgbox = QMessageBox(QMessageBox.Critical, "Error while reading config!", errstr) msgbox.exec_() # We didn't really initialize much so far, so we just quit hard. sys.exit(1) else: objreg.register('config', config_obj) try: key_config = keyconf.KeyConfigParser(confdir, 'keys.conf') except keyconf.KeyConfigError as e: log.init.exception(e) errstr = "Error while reading key config:\n" if e.lineno is not None: errstr += "In line {}: ".format(e.lineno) errstr += str(e) msgbox = QMessageBox(QMessageBox.Critical, "Error while reading key config!", errstr) msgbox.exec_() # We didn't really initialize much so far, so we just quit hard. sys.exit(1) else: objreg.register('key-config', key_config) datadir = standarddir.get(QStandardPaths.DataLocation, args) state_config = ini.ReadWriteConfigParser(datadir, 'state') objreg.register('state-config', state_config) # We need to import this here because lineparser needs config. from qutebrowser.config.parsers import line command_history = line.LineConfigParser(datadir, 'cmd-history', ('completion', 'history-length')) objreg.register('command-history', command_history)
def run(self, cmd, *args, env=None): rundir = standarddir.get(QStandardPaths.RuntimeLocation) try: # tempfile.mktemp is deprecated and discouraged, but we use it here # to create a FIFO since the only other alternative would be to # create a directory and place the FIFO there, which sucks. Since # os.kfifo will raise an exception anyways when the path doesn't # exist, it shouldn't be a big issue. self._filepath = tempfile.mktemp(prefix='userscript-', dir=rundir) os.mkfifo(self._filepath) # pylint: disable=no-member except OSError as e: message.error(self._win_id, "Error while creating FIFO: {}".format( e)) return self._reader = _BlockingFIFOReader(self._filepath) self._thread = QThread(self) self._reader.moveToThread(self._thread) self._reader.got_line.connect(self.got_cmd) self._thread.started.connect(self._reader.read) self._reader.finished.connect(self.on_reader_finished) self._thread.finished.connect(self.on_thread_finished) self._run_process(cmd, *args, env=env) self._thread.start()
def __init__(self): self.blocked_hosts = set() self._in_progress = [] self._done_count = 0 data_dir = standarddir.get(QStandardPaths.DataLocation) self._hosts_file = os.path.join(data_dir, 'blocked-hosts') objreg.get('config').changed.connect(self.on_config_changed)
def test_data(self): """Test data dir with XDG_DATA_HOME not set.""" with helpers.environ_set_temp('HOME', self.temp_dir): cur_dir = standarddir.get(QStandardPaths.DataLocation) self.assertEqual( cur_dir, os.path.join(self.temp_dir, '.local', 'share', 'qutebrowser'))
def test_config(self): """Test config dir with XDG_CONFIG_HOME not set.""" with helpers.environ_set_temp('HOME', self.temp_dir): cur_dir = standarddir.get( QStandardPaths.ConfigLocation) self.assertEqual(cur_dir, os.path.join(self.temp_dir, '.config', 'qutebrowser'))
def init(): """Initialize the global QWebSettings.""" cachedir = standarddir.get(QStandardPaths.CacheLocation) QWebSettings.setIconDatabasePath(cachedir) QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cachedir, 'application-cache')) datadir = standarddir.get(QStandardPaths.DataLocation) QWebSettings.globalSettings().setLocalStoragePath( os.path.join(datadir, 'local-storage')) QWebSettings.setOfflineStoragePath(os.path.join(datadir, 'offline-storage')) global settings settings = QWebSettings.globalSettings() for sectname, section in MAPPINGS.items(): for optname, (typ, arg) in section.items(): value = config.get(sectname, optname) _set_setting(typ, arg, value) objreg.get('config').changed.connect(update_settings)
def __init__(self, parent=None): super().__init__(parent) datadir = standarddir.get(QStandardPaths.DataLocation) self._linecp = lineparser.LineConfigParser(datadir, 'cookies', binary=True) cookies = [] for line in self._linecp: cookies += QNetworkCookie.parseCookies(line) self.setAllCookies(cookies) objreg.get('config').changed.connect(self.cookies_store_changed)
def _init_crashlogfile(self): """Start a new logfile and redirect faulthandler to it.""" path = standarddir.get(QStandardPaths.DataLocation) logname = os.path.join(path, 'crash.log') try: self._crashlogfile = open(logname, 'w', encoding='ascii') except OSError: log.init.exception("Error while opening crash log file!") else: earlyinit.init_faulthandler(self._crashlogfile)
def init(): """Initialize the global QWebSettings.""" cachedir = standarddir.get(QStandardPaths.CacheLocation) QWebSettings.setIconDatabasePath(cachedir) QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cachedir, 'application-cache')) datadir = standarddir.get(QStandardPaths.DataLocation) QWebSettings.globalSettings().setLocalStoragePath( os.path.join(datadir, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(datadir, 'offline-storage')) global settings settings = QWebSettings.globalSettings() for sectname, section in MAPPINGS.items(): for optname, (typ, arg) in section.items(): value = config.get(sectname, optname) _set_setting(typ, arg, value) objreg.get('config').changed.connect(update_settings)
def __init__(self, parent=None): """Initialize and read quickmarks.""" super().__init__(parent) self.marks = collections.OrderedDict() confdir = standarddir.get(QStandardPaths.ConfigLocation) self._linecp = lineparser.LineConfigParser(confdir, 'quickmarks') for line in self._linecp: try: key, url = line.rsplit(maxsplit=1) except ValueError: message.error(0, "Invalid quickmark '{}'".format(line)) else: self.marks[key] = url
def set_filename(self, filename): """Set the filename to save the download to. Args: filename: The full filename to save the download to. None: special value to stop the download. """ if self._filename is not None: raise ValueError("Filename was already set! filename: {}, " "existing: {}".format(filename, self._filename)) filename = os.path.expanduser(filename) if os.path.isabs(filename) and os.path.isdir(filename): # We got an absolute directory from the user, so we save it under # the default filename in that directory. self._filename = os.path.join(filename, self.basename) elif os.path.isabs(filename): # We got an absolute filename from the user, so we save it under # that filename. self._filename = filename self.basename = os.path.basename(self._filename) else: # We only got a filename (without directory) from the user, so we # save it under that filename in the default directory. download_dir = config.get('storage', 'download-directory') if download_dir is None: download_dir = standarddir.get( QStandardPaths.DownloadLocation) self._filename = os.path.join(download_dir, filename) self.basename = filename log.downloads.debug("Setting filename to {}".format(filename)) try: self._fileobj = open(self._filename, 'wb') if self._do_delayed_write: # Downloading to the buffer in RAM has already finished so we # write out the data and clean up now. self.delayed_write() else: # Since the buffer already might be full, on_ready_read might # not be called at all anymore, so we force it here to flush # the buffer and continue receiving new data. self.on_ready_read() except OSError as e: self._die(e.strerror)
def set_filename(self, filename): """Set the filename to save the download to. Args: filename: The full filename to save the download to. None: special value to stop the download. """ if self.fileobj is not None: raise ValueError("fileobj was already set! filename: {}, " "existing: {}, fileobj {}".format( filename, self._filename, self.fileobj)) filename = os.path.expanduser(filename) # Remove chars which can't be encoded in the filename encoding. # See https://github.com/The-Compiler/qutebrowser/issues/427 encoding = sys.getfilesystemencoding() filename = utils.force_encoding(filename, encoding) if os.path.isabs(filename) and os.path.isdir(filename): # We got an absolute directory from the user, so we save it under # the default filename in that directory. self._filename = os.path.join(filename, self.basename) elif os.path.isabs(filename): # We got an absolute filename from the user, so we save it under # that filename. self._filename = filename self.basename = os.path.basename(self._filename) else: # We only got a filename (without directory) from the user, so we # save it under that filename in the default directory. download_dir = config.get('storage', 'download-directory') if download_dir is None: download_dir = standarddir.get( QStandardPaths.DownloadLocation) self._filename = os.path.join(download_dir, filename) self.basename = filename log.downloads.debug("Setting filename to {}".format(filename)) if os.path.isfile(self._filename): # The file already exists, so ask the user if it should be # overwritten. self._ask_overwrite_question() else: self._create_fileobj()
def _handle_segfault(self): """Handle a segfault from a previous run.""" path = standarddir.get(QStandardPaths.DataLocation) logname = os.path.join(path, 'crash.log') # First check if an old logfile exists. if os.path.exists(logname): with open(logname, 'r', encoding='ascii') as f: data = f.read() try: os.remove(logname) except PermissionError: log.init.warning("Could not remove crash log!") else: self._init_crashlogfile() if data: # Crashlog exists and has data in it, so something crashed # previously. self._crashdlg = crash.FatalCrashDialog(self._args.debug, data) self._crashdlg.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()
def set_filename(self, filename): """Set the filename to save the download to. Args: filename: The full filename to save the download to. None: special value to stop the download. """ if self.fileobj is not None: raise ValueError("fileobj was already set! filename: {}, " "existing: {}, fileobj {}".format( filename, self._filename, self.fileobj)) filename = os.path.expanduser(filename) if os.path.isabs(filename) and os.path.isdir(filename): # We got an absolute directory from the user, so we save it under # the default filename in that directory. self._filename = os.path.join(filename, self.basename) elif os.path.isabs(filename): # We got an absolute filename from the user, so we save it under # that filename. self._filename = filename self.basename = os.path.basename(self._filename) else: # We only got a filename (without directory) from the user, so we # save it under that filename in the default directory. download_dir = config.get('storage', 'download-directory') if download_dir is None: download_dir = standarddir.get( QStandardPaths.DownloadLocation) self._filename = os.path.join(download_dir, filename) self.basename = filename log.downloads.debug("Setting filename to {}".format(filename)) try: fileobj = open(self._filename, 'wb') except OSError as e: self._die(e.strerror) else: self.set_fileobj(fileobj)
def _handle_segfault(self): """Handle a segfault from a previous run.""" path = standarddir.get(QStandardPaths.DataLocation) logname = os.path.join(path, '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._crashdlg = crashdialog.get_fatal_crash_dialog( self._args.debug, data) self._crashdlg.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 test_data(self): """Test data dir with XDG_DATA_HOME not set.""" with helpers.environ_set_temp('HOME', self.temp_dir): cur_dir = standarddir.get(QStandardPaths.DataLocation) self.assertEqual(cur_dir, os.path.join(self.temp_dir, '.local', 'share', 'qutebrowser'))
def test_cache(self): """Test cache dir with XDG_CACHE_HOME not set.""" with helpers.environ_set_temp('HOME', self.temp_dir): cur_dir = standarddir.get(QStandardPaths.CacheLocation) self.assertEqual( cur_dir, os.path.join(self.temp_dir, '.cache', 'qutebrowser'))
def test_cache(self): """Test cache dir.""" cur_dir = standarddir.get(QStandardPaths.CacheLocation) self.assertEqual( cur_dir.split(os.sep)[-2:], ['qutebrowser_test', 'cache'], cur_dir)
def __init__(self, parent=None): super().__init__(parent) cache_dir = standarddir.get(QStandardPaths.CacheLocation) self.setCacheDirectory(os.path.join(cache_dir, 'http')) self.setMaximumCacheSize(config.get('storage', 'cache-size'))
def test_data_explicit(self): """Test data dir with XDG_DATA_HOME explicitely set.""" with helpers.environ_set_temp('XDG_DATA_HOME', self.temp_dir): cur_dir = standarddir.get(QStandardPaths.DataLocation) self.assertEqual(cur_dir, os.path.join(self.temp_dir, 'qutebrowser'))
def test_data(self): """Test data dir.""" cur_dir = standarddir.get(QStandardPaths.DataLocation) self.assertEqual(cur_dir.split(os.sep)[-2:], ['qutebrowser_test', 'data'], cur_dir)
def test_config(self): """Test config dir.""" cur_dir = standarddir.get(QStandardPaths.ConfigLocation) self.assertEqual(cur_dir.split(os.sep)[-1], 'qutebrowser_test', cur_dir)
def test_cache(self): """Test cache dir.""" cur_dir = standarddir.get(QStandardPaths.CacheLocation) self.assertEqual(cur_dir.split(os.sep)[-2:], ['qutebrowser_test', 'cache'], cur_dir)
def test_config(self): """Test config dir with XDG_CONFIG_HOME not set.""" with helpers.environ_set_temp('HOME', self.temp_dir): cur_dir = standarddir.get(QStandardPaths.ConfigLocation) self.assertEqual( cur_dir, os.path.join(self.temp_dir, '.config', 'qutebrowser'))
def test_config(self): """Test config dir.""" cur_dir = standarddir.get(QStandardPaths.ConfigLocation) self.assertEqual( cur_dir.split(os.sep)[-1], 'qutebrowser_test', cur_dir)
def _init_crashlogfile(self): """Start a new logfile and redirect faulthandler to it.""" path = standarddir.get(QStandardPaths.DataLocation) logname = os.path.join(path, 'crash.log') self._crashlogfile = open(logname, 'w', encoding='ascii') earlyinit.init_faulthandler(self._crashlogfile)
def test_cache(self): """Test cache dir with XDG_CACHE_HOME not set.""" with helpers.environ_set_temp('HOME', self.temp_dir): cur_dir = standarddir.get(QStandardPaths.CacheLocation) self.assertEqual(cur_dir, os.path.join(self.temp_dir, '.cache', 'qutebrowser'))
def test_data(self): """Test data dir.""" cur_dir = standarddir.get(QStandardPaths.DataLocation) self.assertEqual( cur_dir.split(os.sep)[-2:], ['qutebrowser_test', 'data'], cur_dir)