Adjust config.change_filter

This commit is contained in:
Florian Bruhin 2017-06-13 12:07:00 +02:00
parent b5110b07f0
commit 5ab2c89a37
15 changed files with 69 additions and 87 deletions

View File

@ -180,7 +180,7 @@ class HostBlocker:
self._config_blocked_hosts)
self._blocked_hosts = set()
self._done_count = 0
urls = config.val.content.host_block_lists
urls = config.val.content.host_blocking.lists
download_manager = objreg.get('qtnetwork-download-manager',
scope='window', window='last-focused')
if urls is None:
@ -292,11 +292,10 @@ class HostBlocker:
message.info("adblock: Read {} hosts from {} sources.".format(
len(self._blocked_hosts), self._done_count))
@config.change_filter('content', 'host-block-lists')
@config.change_filter('content.host-blocking.lists')
def on_config_changed(self):
"""Update files when the config changed."""
urls = config.val.content.host_block_lists
if urls is None:
if config.val.content.host_blocking.lists is None:
try:
os.remove(self._local_hosts_file)
except FileNotFoundError:

View File

@ -137,7 +137,7 @@ class WebEnginePage(QWebEnginePage):
self._set_bg_color()
objreg.get('config').changed.connect(self._set_bg_color)
@config.change_filter('colors', 'webpage.bg')
@config.change_filter('colors.webpage.bg')
def _set_bg_color(self):
col = config.val.colors.webpage.bg
if col is None:

View File

@ -42,10 +42,10 @@ class DiskCache(QNetworkDiskCache):
maxsize=self.maximumCacheSize(),
path=self.cacheDirectory())
@config.change_filter('storage', 'cache-size')
@config.change_filter('content.cache_size')
def _set_cache_size(self):
"""Set the cache size based on the config."""
size = config.val.storage.cache_size
size = config.val.content.cache_size
if size is None:
size = 1024 * 1024 * 50 # default from QNetworkDiskCachePrivate
# WORKAROUND for https://bugreports.qt.io/browse/QTBUG-59909

View File

@ -50,7 +50,7 @@ class RAMCookieJar(QNetworkCookieJar):
Return:
True if one or more cookies are set for 'url', otherwise False.
"""
if config.val.content.cookies_accept == 'never':
if config.val.content.cookies.accept == 'never':
return False
else:
self.changed.emit()
@ -77,7 +77,7 @@ class CookieJar(RAMCookieJar):
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')
config_opt='content.cookies.store')
def parse_cookies(self):
"""Parse cookies from lineparser and store them."""
@ -105,10 +105,10 @@ class CookieJar(RAMCookieJar):
self._lineparser.data = lines
self._lineparser.save()
@config.change_filter('content', 'cookies-store')
@config.change_filter('content.cookies.store')
def cookies_store_changed(self):
"""Delete stored cookies if cookies-store changed."""
if not config.val.content.cookies_store:
if not config.val.content.cookies.store:
self._lineparser.data = []
self._lineparser.save()
self.changed.emit()

View File

@ -107,7 +107,7 @@ class WebView(QWebView):
# deleted
pass
@config.change_filter('colors', 'webpage.bg')
@config.change_filter('colors.webpage.bg')
def _set_bg_color(self):
"""Set the webpage background color as configured."""
col = config.val.colors.webpage.bg

View File

@ -107,7 +107,7 @@ class UrlCompletionModel(base.BaseCompletionModel):
self._history_cat.rowCount() > self._max_history):
self._remove_oldest_history()
@config.change_filter('completion', 'timestamp-format')
@config.change_filter('completion.timestamp_format')
def reformat_timestamps(self):
"""Reformat the timestamps if the config option was changed."""
for i in range(self._history_cat.rowCount()):

View File

@ -62,30 +62,38 @@ class change_filter: # pylint: disable=invalid-name
much cleaner to implement.
Attributes:
_sectname: The section to be filtered.
_optname: The option to be filtered.
_option: An option or prefix to be filtered
_function: Whether a function rather than a method is decorated.
"""
def __init__(self, sectname, optname=None, function=False):
def __init__(self, option, function=False):
"""Save decorator arguments.
Gets called on parse-time with the decorator arguments.
Args:
sectname: The section to be filtered.
optname: The option to be filtered.
option: The option to be filtered.
function: Whether a function rather than a method is decorated.
"""
# FIXME:conf
# if sectname not in configdata.DATA:
# raise configexc.NoSectionError(sectname)
# if optname is not None and optname not in configdata.DATA[sectname]:
# raise configexc.NoOptionError(optname, sectname)
self._sectname = sectname
self._optname = optname
if (option not in configdata.DATA and
not configdata.is_valid_prefix(option)):
raise configexc.NoOptionError(option)
self._option = option
self._function = function
def _check_match(self, option):
"""Check if the given option matches the filter."""
if option is None:
# Called directly, not from a config change event.
return True
elif option == self._option:
return True
elif option.startswith(self._option + '.'):
# prefix match
return True
else:
return False
def __call__(self, func):
"""Filter calls to the decorated function.
@ -104,27 +112,13 @@ class change_filter: # pylint: disable=invalid-name
"""
if self._function:
@functools.wraps(func)
def wrapper(sectname=None, optname=None):
if sectname is None and optname is None:
# Called directly, not from a config change event.
return func()
elif sectname != self._sectname:
return
elif self._optname is not None and optname != self._optname:
return
else:
def wrapper(option=None):
if self._check_match(option):
return func()
else:
@functools.wraps(func)
def wrapper(wrapper_self, sectname=None, optname=None):
if sectname is None and optname is None:
# Called directly, not from a config change event.
return func(wrapper_self)
elif sectname != self._sectname:
return
elif self._optname is not None and optname != self._optname:
return
else:
def wrapper(wrapper_self, option=None):
if self._check_match(option):
return func(wrapper_self)
return wrapper

View File

@ -672,6 +672,11 @@ def _read_yaml(yaml_data):
return parsed
def is_valid_prefix(prefix):
"""Check whether the given prefix is a valid prefix for some option."""
return any(key.startswith(prefix + '.') for key in DATA)
def init():
"""Initialize configdata from the YAML file."""
global DATA

View File

@ -68,10 +68,6 @@ class NewConfigManager(QObject):
raise UnknownOptionError(e)
return val.typ.from_py(val.default)
def is_valid_prefix(self, prefix):
"""Check whether the given prefix is a valid prefix for some option."""
return any(key.startswith(prefix + '.') for key in self._values)
class ConfigContainer:
@ -100,7 +96,7 @@ class ConfigContainer:
options.
"""
name = self._join(attr)
if self._manager.is_valid_prefix(name):
if configdata.is_valid_prefix(name):
return ConfigContainer(manager=self._manager, prefix=name)
# If it's not a valid prefix, this will raise NoOptionError.
self._manager.get(name)

View File

@ -144,9 +144,6 @@ class ModeManager(QObject):
self._parsers = {}
self.mode = usertypes.KeyMode.normal
self._releaseevents_to_pass = set()
self._forward_unbound_keys = config.get(
'input', 'forward-unbound-keys')
objreg.get('config').changed.connect(self.set_forward_unbound_keys)
def __repr__(self):
return utils.get_repr(self, mode=self.mode)
@ -171,10 +168,12 @@ class ModeManager(QObject):
event.modifiers() not in [Qt.NoModifier, Qt.ShiftModifier] or
not event.text().strip())
forward_unbound_keys = config.val.input.forward_unbound_keys
if handled:
filter_this = True
elif (parser.passthrough or self._forward_unbound_keys == 'all' or
(self._forward_unbound_keys == 'auto' and is_non_alnum)):
elif (parser.passthrough or forward_unbound_keys == 'all' or
(forward_unbound_keys == 'auto' and is_non_alnum)):
filter_this = False
else:
filter_this = True
@ -187,7 +186,7 @@ class ModeManager(QObject):
log.modes.debug("handled: {}, forward-unbound-keys: {}, "
"passthrough: {}, is_non_alnum: {} --> "
"filter: {} (focused: {!r})".format(
handled, self._forward_unbound_keys,
handled, forward_unbound_keys,
parser.passthrough, is_non_alnum, filter_this,
focus_widget))
return filter_this
@ -313,12 +312,6 @@ class ModeManager(QObject):
raise ValueError("Can't leave normal mode!")
self.leave(self.mode, 'leave current')
@config.change_filter('input', 'forward-unbound-keys')
def set_forward_unbound_keys(self):
"""Update local setting when config changed."""
self._forward_unbound_keys = config.get(
'input', 'forward-unbound-keys')
def eventFilter(self, event):
"""Filter all events based on the currently set mode.

View File

@ -95,12 +95,11 @@ class MessageView(QWidget):
# The width isn't really relevant as we're expanding anyways.
return QSize(-1, height)
@config.change_filter('ui', 'message-timeout')
@config.change_filter('messages.timeout')
def _set_clear_timer_interval(self):
"""Configure self._clear_timer according to the config."""
interval = config.val.ui.message_timeout
if interval != 0:
self._clear_timer.setInterval(interval)
if config.val.messages.timeout != 0:
self._clear_timer.setInterval(config.val.messages.timeout)
@pyqtSlot()
def clear_messages(self):

View File

@ -159,7 +159,7 @@ class TabbedBrowser(tabwidget.TabWidget):
widgets.append(widget)
return widgets
@config.change_filter('ui', 'window-title-format')
@config.change_filter('window.title_format')
def update_window_title(self):
"""Change the window title to match the current tab."""
idx = self.currentIndex()
@ -170,8 +170,8 @@ class TabbedBrowser(tabwidget.TabWidget):
fields = self.get_tab_fields(idx)
fields['id'] = self._win_id
fmt = config.val.ui.window_title_format
self.window().setWindowTitle(fmt.format(**fields))
title = config.val.window.title_format.format(**fields)
self.window().setWindowTitle(title)
def _connect_tab_signals(self, tab):
"""Set up the needed signals for tab."""
@ -485,19 +485,17 @@ class TabbedBrowser(tabwidget.TabWidget):
self._tab_insert_idx_right))
return idx
@config.change_filter('tabs', 'show-favicons')
@config.change_filter('tabs.favicons.show')
def update_favicons(self):
"""Update favicons when config was changed."""
show = config.val.tabs.show_favicons
tabs_are_wins = config.val.tabs.tabs_are_windows
for i, tab in enumerate(self.widgets()):
if show:
if config.val.tabs.favicons.show:
self.setTabIcon(i, tab.icon())
if tabs_are_wins:
if config.val.tabs.tabs_are_windows:
self.window().setWindowIcon(tab.icon())
else:
self.setTabIcon(i, QIcon())
if tabs_are_wins:
if config.val.tabs.tabs_are_windows:
self.window().setWindowIcon(self.default_window_icon)
@pyqtSlot()

View File

@ -331,22 +331,20 @@ class TabBar(QTabBar):
"""Get the current tab object."""
return self.parent().currentWidget()
@config.change_filter('tabs', 'show')
@config.change_filter('tabs.show')
def tabs_show(self):
"""Hide or show tab bar if needed when tabs->show got changed."""
self.maybe_hide()
@config.change_filter('tabs', 'show-switching-delay')
@config.change_filter('tabs.show_switching_delay')
def on_show_switching_delay_changed(self):
"""Set timer interval when tabs->show-switching-delay got changed."""
self._auto_hide_timer.setInterval(
config.val.tabs.show_switching_delay)
self._auto_hide_timer.setInterval(config.val.tabs.show_switching_delay)
def on_current_changed(self):
"""Show tab bar when current tab got changed."""
self.maybe_hide() # for fullscreen tabs
show = config.val.tabs.show
if show == 'switching':
if config.val.tabs.show == 'switching':
self.show()
self._auto_hide_timer.start()
@ -408,24 +406,24 @@ class TabBar(QTabBar):
# code sets layoutDirty so it actually relayouts the tabs.
self.setIconSize(self.iconSize())
@config.change_filter('fonts', 'tabbar')
@config.change_filter('fonts.tabbar')
def set_font(self):
"""Set the tab bar font."""
self.setFont(config.val.fonts.tabbar)
self.set_icon_size()
@config.change_filter('tabs', 'favicon-scale')
@config.change_filter('tabs.favicon.scale')
def set_icon_size(self):
"""Set the tab bar favicon size."""
size = self.fontMetrics().height() - 2
size *= config.val.tabs.favicon_scale
size *= config.val.tabs.favicon.scale
self.setIconSize(QSize(size, size))
@config.change_filter('colors', 'tabs.bg.bar')
@config.change_filter('colors.tabs.bar.bg')
def set_colors(self):
"""Set the tab bar colors."""
p = self.palette()
p.setColor(QPalette.Window, config.val.colors.tabs.bg.bar)
p.setColor(QPalette.Window, config.val.colors.tabs.bar.bg)
self.setPalette(p)
@pyqtSlot(str, str)

View File

@ -102,7 +102,7 @@ class ConsoleLineEdit(miscwidgets.CommandLineEdit):
else:
super().keyPressEvent(e)
@config.change_filter('fonts', 'debug-console')
@config.change_filter('fonts.debug_console')
def update_font(self):
"""Set the correct font."""
self.setFont(config.val.fonts.debug_console)
@ -123,7 +123,7 @@ class ConsoleTextEdit(QTextEdit):
def __repr__(self):
return utils.get_repr(self)
@config.change_filter('fonts', 'debug-console')
@config.change_filter('fonts.debug_console')
def update_font(self):
"""Update font when config changed."""
self.setFont(config.val.fonts.debug_console)

View File

@ -126,7 +126,7 @@ class SaveManager(QObject):
self.set_autosave_interval()
objreg.get('config').changed.connect(self.set_autosave_interval)
@config.change_filter('general', 'auto-save-interval')
@config.change_filter('auto_save.interval')
def set_autosave_interval(self):
"""Set the auto-save interval."""
interval = config.val.auto_save.interval