Refactor objreg.get('config') calls

This commit is contained in:
Florian Bruhin 2017-06-14 21:42:36 +02:00
parent cc0e66fe7b
commit 51474724e5
25 changed files with 113 additions and 113 deletions

View File

@ -114,12 +114,12 @@ class HostBlocker:
data_dir = standarddir.data() data_dir = standarddir.data()
self._local_hosts_file = os.path.join(data_dir, 'blocked-hosts') self._local_hosts_file = os.path.join(data_dir, 'blocked-hosts')
self.on_config_changed() self._update_files()
config_dir = standarddir.config() config_dir = standarddir.config()
self._config_hosts_file = os.path.join(config_dir, 'blocked-hosts') self._config_hosts_file = os.path.join(config_dir, 'blocked-hosts')
objreg.get('config').changed.connect(self.on_config_changed) config.instance.changed.connect(self._update_files)
def is_blocked(self, url): def is_blocked(self, url):
"""Check if the given URL (as QUrl) is blocked.""" """Check if the given URL (as QUrl) is blocked."""
@ -293,7 +293,7 @@ class HostBlocker:
len(self._blocked_hosts), self._done_count)) len(self._blocked_hosts), self._done_count))
@config.change_filter('content.host_blocking.lists') @config.change_filter('content.host_blocking.lists')
def on_config_changed(self): def _update_files(self):
"""Update files when the config changed.""" """Update files when the config changed."""
if config.val.content.host_blocking.lists is None: if config.val.content.host_blocking.lists is None:
try: try:

View File

@ -251,7 +251,7 @@ class AbstractZoom(QObject):
self._win_id = win_id self._win_id = win_id
self._default_zoom_changed = False self._default_zoom_changed = False
self._init_neighborlist() self._init_neighborlist()
objreg.get('config').changed.connect(self._on_config_changed) config.instance.changed.connect(self._on_config_changed)
# # FIXME:qtwebengine is this needed? # # FIXME:qtwebengine is this needed?
# # For some reason, this signal doesn't get disconnected automatically # # For some reason, this signal doesn't get disconnected automatically

View File

@ -36,7 +36,7 @@ from PyQt5.QtWebEngineWidgets import (QWebEngineSettings, QWebEngineProfile,
from qutebrowser.browser import shared from qutebrowser.browser import shared
from qutebrowser.config import config, websettings from qutebrowser.config import config, websettings
from qutebrowser.utils import objreg, utils, standarddir, javascript, qtutils from qutebrowser.utils import utils, standarddir, javascript, qtutils
# The default QWebEngineProfile # The default QWebEngineProfile
@ -166,7 +166,7 @@ def _set_user_agent(profile):
profile.setHttpUserAgent(config.val.content.user_agent) profile.setHttpUserAgent(config.val.content.user_agent)
def update_settings(option): def _update_settings(option):
"""Update global settings when qwebsettings changed.""" """Update global settings when qwebsettings changed."""
websettings.update_mappings(MAPPINGS, option) websettings.update_mappings(MAPPINGS, option)
if option in ['scrollbar.hide', 'content.user_stylesheet']: if option in ['scrollbar.hide', 'content.user_stylesheet']:
@ -215,7 +215,7 @@ def init(args):
Attribute(QWebEngineSettings.FullScreenSupportEnabled).set(True) Attribute(QWebEngineSettings.FullScreenSupportEnabled).set(True)
websettings.init_mappings(MAPPINGS) websettings.init_mappings(MAPPINGS)
objreg.get('config').changed.connect(update_settings) config.instance.changed.connect(_update_settings)
def shutdown(): def shutdown():

View File

@ -28,8 +28,7 @@ from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from qutebrowser.browser import shared from qutebrowser.browser import shared
from qutebrowser.browser.webengine import certificateerror, webenginesettings from qutebrowser.browser.webengine import certificateerror, webenginesettings
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import (log, debug, usertypes, jinja, urlutils, message, from qutebrowser.utils import log, debug, usertypes, jinja, urlutils, message
objreg)
class WebEngineView(QWebEngineView): class WebEngineView(QWebEngineView):
@ -135,7 +134,7 @@ class WebEnginePage(QWebEnginePage):
self._on_feature_permission_requested) self._on_feature_permission_requested)
self._theme_color = theme_color self._theme_color = theme_color
self._set_bg_color() self._set_bg_color()
objreg.get('config').changed.connect(self._set_bg_color) config.instance.changed.connect(self._set_bg_color)
@config.change_filter('colors.webpage.bg') @config.change_filter('colors.webpage.bg')
def _set_bg_color(self): def _set_bg_color(self):

View File

@ -24,7 +24,7 @@ import os.path
from PyQt5.QtNetwork import QNetworkDiskCache from PyQt5.QtNetwork import QNetworkDiskCache
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import utils, objreg, qtutils from qutebrowser.utils import utils, qtutils
class DiskCache(QNetworkDiskCache): class DiskCache(QNetworkDiskCache):
@ -35,7 +35,7 @@ class DiskCache(QNetworkDiskCache):
super().__init__(parent) super().__init__(parent)
self.setCacheDirectory(os.path.join(cache_dir, 'http')) self.setCacheDirectory(os.path.join(cache_dir, 'http'))
self._set_cache_size() self._set_cache_size()
objreg.get('config').changed.connect(self._set_cache_size) config.instance.changed.connect(self._set_cache_size)
def __repr__(self): def __repr__(self):
return utils.get_repr(self, size=self.cacheSize(), return utils.get_repr(self, size=self.cacheSize(),

View File

@ -74,7 +74,7 @@ class CookieJar(RAMCookieJar):
self._lineparser = lineparser.LineParser( self._lineparser = lineparser.LineParser(
standarddir.data(), 'cookies', binary=True, parent=self) standarddir.data(), 'cookies', binary=True, parent=self)
self.parse_cookies() self.parse_cookies()
objreg.get('config').changed.connect(self.cookies_store_changed) config.instance.changed.connect(self._on_cookies_store_changed)
objreg.get('save-manager').add_saveable( objreg.get('save-manager').add_saveable(
'cookies', self.save, self.changed, 'cookies', self.save, self.changed,
config_opt='content.cookies.store') config_opt='content.cookies.store')
@ -106,7 +106,7 @@ class CookieJar(RAMCookieJar):
self._lineparser.save() self._lineparser.save()
@config.change_filter('content.cookies.store') @config.change_filter('content.cookies.store')
def cookies_store_changed(self): def _on_cookies_store_changed(self):
"""Delete stored cookies if cookies-store changed.""" """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.data = []

View File

@ -83,6 +83,7 @@ class JSBridge(QObject):
message.error("Refusing to disable javascript via qute://settings " message.error("Refusing to disable javascript via qute://settings "
"as it needs javascript support.") "as it needs javascript support.")
return return
# FIXME:conf
try: try:
objreg.get('config').set('conf', sectname, optname, value) objreg.get('config').set('conf', sectname, optname, value)
except (configexc.Error, configparser.Error) as e: except (configexc.Error, configparser.Error) as e:

View File

@ -33,7 +33,7 @@ from PyQt5.QtGui import QFont
from PyQt5.QtWebKit import QWebSettings from PyQt5.QtWebKit import QWebSettings
from qutebrowser.config import config, websettings from qutebrowser.config import config, websettings
from qutebrowser.utils import standarddir, objreg, urlutils, qtutils from qutebrowser.utils import standarddir, urlutils, qtutils
from qutebrowser.browser import shared from qutebrowser.browser import shared
@ -111,7 +111,7 @@ def _set_user_stylesheet():
QWebSettings.globalSettings().setUserStyleSheetUrl(url) QWebSettings.globalSettings().setUserStyleSheetUrl(url)
def update_settings(option): def _update_settings(option):
"""Update global settings when qwebsettings changed.""" """Update global settings when qwebsettings changed."""
if option in ['scrollbar.hide', 'content.user_stylesheet']: if option in ['scrollbar.hide', 'content.user_stylesheet']:
_set_user_stylesheet() _set_user_stylesheet()
@ -140,7 +140,7 @@ def init(_args):
websettings.init_mappings(MAPPINGS) websettings.init_mappings(MAPPINGS)
_set_user_stylesheet() _set_user_stylesheet()
objreg.get('config').changed.connect(update_settings) config.instance.changed.connect(_update_settings)
def shutdown(): def shutdown():

View File

@ -88,7 +88,7 @@ class WebView(QWebView):
window=win_id) window=win_id)
mode_manager.entered.connect(self.on_mode_entered) mode_manager.entered.connect(self.on_mode_entered)
mode_manager.left.connect(self.on_mode_left) mode_manager.left.connect(self.on_mode_left)
objreg.get('config').changed.connect(self._set_bg_color) config.instance.changed.connect(self._set_bg_color)
def __repr__(self): def __repr__(self):
url = utils.elide(self.url().toDisplayString(QUrl.EncodeUnicode), 100) url = utils.elide(self.url().toDisplayString(QUrl.EncodeUnicode), 100)

View File

@ -29,7 +29,7 @@ from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QItemSelectionModel, QSize
from qutebrowser.config import config, style from qutebrowser.config import config, style
from qutebrowser.completion import completiondelegate from qutebrowser.completion import completiondelegate
from qutebrowser.completion.models import base from qutebrowser.completion.models import base
from qutebrowser.utils import utils, usertypes, objreg from qutebrowser.utils import utils, usertypes
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc, cmdutils
@ -109,8 +109,8 @@ class CompletionView(QTreeView):
super().__init__(parent) super().__init__(parent)
self._win_id = win_id self._win_id = win_id
# FIXME handle new aliases. # FIXME handle new aliases.
# objreg.get('config').changed.connect(self.init_command_completion) # config.instance.changed.connect(self.init_command_completion)
objreg.get('config').changed.connect(self._on_config_changed) config.instance.changed.connect(self._on_config_changed)
self._column_widths = base.BaseCompletionModel.COLUMN_WIDTHS self._column_widths = base.BaseCompletionModel.COLUMN_WIDTHS
self._active = False self._active = False

View File

@ -22,7 +22,7 @@
from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtCore import pyqtSlot, Qt
from qutebrowser.config import config, configdata from qutebrowser.config import config, configdata
from qutebrowser.utils import log, qtutils, objreg from qutebrowser.utils import log, qtutils
from qutebrowser.completion.models import base from qutebrowser.completion.models import base
@ -63,7 +63,7 @@ class SettingOptionCompletionModel(base.BaseCompletionModel):
sectdata = configdata.DATA[section] sectdata = configdata.DATA[section]
self._misc_items = {} self._misc_items = {}
self._section = section self._section = section
objreg.get('config').changed.connect(self.update_misc_column) config.instance.changed.connect(self._update_misc_column)
for name in sectdata: for name in sectdata:
try: try:
desc = sectdata.descriptions[name] desc = sectdata.descriptions[name]
@ -79,7 +79,7 @@ class SettingOptionCompletionModel(base.BaseCompletionModel):
self._misc_items[name] = miscitem self._misc_items[name] = miscitem
@pyqtSlot(str, str) @pyqtSlot(str, str)
def update_misc_column(self, section, option): def _update_misc_column(self, section, option):
"""Update misc column when config changed.""" """Update misc column when config changed."""
if section != self._section: if section != self._section:
return return
@ -117,7 +117,7 @@ class SettingValueCompletionModel(base.BaseCompletionModel):
super().__init__(parent) super().__init__(parent)
self._section = section self._section = section
self._option = option self._option = option
objreg.get('config').changed.connect(self.update_current_value) config.instance.changed.connect(self._update_current_value)
cur_cat = self.new_category("Current/Default", sort=0) cur_cat = self.new_category("Current/Default", sort=0)
value = config.get(section, option, raw=True) value = config.get(section, option, raw=True)
if not value: if not value:
@ -143,7 +143,7 @@ class SettingValueCompletionModel(base.BaseCompletionModel):
self.new_item(cat, val, desc) self.new_item(cat, val, desc)
@pyqtSlot(str, str) @pyqtSlot(str, str)
def update_current_value(self, section, option): def _update_current_value(self, section, option):
"""Update current value when config changed.""" """Update current value when config changed."""
if (section, option) != (self._section, self._option): if (section, option) != (self._section, self._option):
return return

View File

@ -193,4 +193,4 @@ def init():
keyconf.changed.connect( keyconf.changed.connect(
functools.partial(update, [usertypes.Completion.bind])) functools.partial(update, [usertypes.Completion.bind]))
objreg.get('config').changed.connect(_update_aliases) config.instance.changed.connect(_update_aliases)

View File

@ -76,7 +76,7 @@ class UrlCompletionModel(base.BaseCompletionModel):
self._history.add_completion_item.connect(self.on_history_item_added) self._history.add_completion_item.connect(self.on_history_item_added)
self._history.cleared.connect(self.on_history_cleared) self._history.cleared.connect(self.on_history_cleared)
objreg.get('config').changed.connect(self.reformat_timestamps) config.instance.changed.connect(self._reformat_timestamps)
def _fmt_atime(self, atime): def _fmt_atime(self, atime):
"""Format an atime to a human-readable string.""" """Format an atime to a human-readable string."""
@ -108,7 +108,7 @@ class UrlCompletionModel(base.BaseCompletionModel):
self._remove_oldest_history() self._remove_oldest_history()
@config.change_filter('completion.timestamp_format') @config.change_filter('completion.timestamp_format')
def reformat_timestamps(self): def _reformat_timestamps(self):
"""Reformat the timestamps if the config option was changed.""" """Reformat the timestamps if the config option was changed."""
for i in range(self._history_cat.rowCount()): for i in range(self._history_cat.rowCount()):
url_item = self._history_cat.child(i, self.URL_COLUMN) url_item = self._history_cat.child(i, self.URL_COLUMN)

View File

@ -60,7 +60,7 @@ instance = None
def get(*args, **kwargs): def get(*args, **kwargs):
"""Convenience method to call get(...) of the config instance.""" """Convenience method to call get(...) of the config instance."""
return objreg.get('config').get(*args, **kwargs) return instance.get(*args, **kwargs)
def _init_main_config(parent=None): def _init_main_config(parent=None):
@ -89,7 +89,7 @@ def _init_main_config(parent=None):
sys.exit(usertypes.Exit.err_config) sys.exit(usertypes.Exit.err_config)
else: else:
objreg.register('config', config_obj) objreg.register('config', config_obj)
filename = os.path.join(standarddir.config(), 'qutebrowser.conf')
save_manager = objreg.get('save-manager') save_manager = objreg.get('save-manager')
save_manager.add_saveable( save_manager.add_saveable(
'config', config_obj.save, config_obj.changed, 'config', config_obj.save, config_obj.changed,
@ -153,7 +153,7 @@ def _init_misc():
command_history = lineparser.LimitLineParser( command_history = lineparser.LimitLineParser(
standarddir.data(), 'cmd-history', standarddir.data(), 'cmd-history',
limit='completion.cmd_history_max_items', limit='completion.cmd_history_max_items',
parent=objreg.get('config')) parent=instance)
objreg.register('command-history', command_history) objreg.register('command-history', command_history)
save_manager.add_saveable('command-history', command_history.save, save_manager.add_saveable('command-history', command_history.save,
command_history.changed) command_history.changed)

View File

@ -24,7 +24,7 @@ import functools
import sip import sip
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import log, objreg, jinja from qutebrowser.utils import log, jinja
@functools.lru_cache(maxsize=16) @functools.lru_cache(maxsize=16)
@ -54,8 +54,7 @@ def set_register_stylesheet(obj):
log.config.vdebug("stylesheet for {}: {}".format( log.config.vdebug("stylesheet for {}: {}".format(
obj.__class__.__name__, qss)) obj.__class__.__name__, qss))
obj.setStyleSheet(qss) obj.setStyleSheet(qss)
objreg.get('config').changed.connect( config.instance.changed.connect(functools.partial(_update_stylesheet, obj))
functools.partial(_update_stylesheet, obj))
def _update_stylesheet(obj): def _update_stylesheet(obj):

View File

@ -213,7 +213,7 @@ class MainWindow(QWidget):
# resizing will fail. Therefore, we use singleShot QTimers to make sure # resizing will fail. Therefore, we use singleShot QTimers to make sure
# we defer this until everything else is initialized. # we defer this until everything else is initialized.
QTimer.singleShot(0, self._connect_overlay_signals) QTimer.singleShot(0, self._connect_overlay_signals)
objreg.get('config').changed.connect(self.on_config_changed) config.instance.changed.connect(self._on_config_changed)
objreg.get("app").new_window.emit(self) objreg.get("app").new_window.emit(self)
@ -324,7 +324,7 @@ class MainWindow(QWidget):
return utils.get_repr(self) return utils.get_repr(self)
@pyqtSlot(str) @pyqtSlot(str)
def on_config_changed(self, option): def _on_config_changed(self, option):
"""Resize the completion if related config options changed.""" """Resize the completion if related config options changed."""
if option == 'statusbar.padding': if option == 'statusbar.padding':
self._update_overlay_geometries() self._update_overlay_geometries()

View File

@ -24,7 +24,7 @@ from PyQt5.QtCore import pyqtSlot, pyqtSignal, QTimer, Qt, QSize
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
from qutebrowser.config import config, style from qutebrowser.config import config, style
from qutebrowser.utils import usertypes, objreg from qutebrowser.utils import usertypes
class Message(QLabel): class Message(QLabel):
@ -84,7 +84,7 @@ class MessageView(QWidget):
self._clear_timer = QTimer() self._clear_timer = QTimer()
self._clear_timer.timeout.connect(self.clear_messages) self._clear_timer.timeout.connect(self.clear_messages)
self._set_clear_timer_interval() self._set_clear_timer_interval()
objreg.get('config').changed.connect(self._set_clear_timer_interval) config.instance.changed.connect(self._set_clear_timer_interval)
self._last_text = None self._last_text = None
self._messages = [] self._messages = []

View File

@ -193,7 +193,7 @@ class StatusBar(QWidget):
self.prog = progress.Progress(self) self.prog = progress.Progress(self)
self._hbox.addWidget(self.prog) self._hbox.addWidget(self.prog)
objreg.get('config').changed.connect(self._on_config_changed) config.instance.changed.connect(self._on_config_changed)
QTimer.singleShot(0, self.maybe_hide) QTimer.singleShot(0, self.maybe_hide)
def __repr__(self): def __repr__(self):

View File

@ -122,13 +122,20 @@ class TabbedBrowser(tabwidget.TabWidget):
self._global_marks = {} self._global_marks = {}
self.default_window_icon = self.window().windowIcon() self.default_window_icon = self.window().windowIcon()
self.private = private self.private = private
objreg.get('config').changed.connect(self.update_favicons) config.instance.changed.connect(self._on_config_changed)
objreg.get('config').changed.connect(self.update_window_title)
objreg.get('config').changed.connect(self.update_tab_titles)
def __repr__(self): def __repr__(self):
return utils.get_repr(self, count=self.count()) return utils.get_repr(self, count=self.count())
@pyqtSlot(str)
def _on_config_changed(self, option):
if option == 'tabs.favicons.show':
self._update_favicons()
elif option == 'window.title_format':
self._update_window_title()
elif option in ['tabs.title.format', 'tabs.title.format_pinned']:
self._update_tab_titles()
def _tab_index(self, tab): def _tab_index(self, tab):
"""Get the index of a given tab. """Get the index of a given tab.
@ -159,8 +166,7 @@ class TabbedBrowser(tabwidget.TabWidget):
widgets.append(widget) widgets.append(widget)
return widgets return widgets
@config.change_filter('window.title_format') def _update_window_title(self):
def update_window_title(self):
"""Change the window title to match the current tab.""" """Change the window title to match the current tab."""
idx = self.currentIndex() idx = self.currentIndex()
if idx == -1: if idx == -1:
@ -485,8 +491,7 @@ class TabbedBrowser(tabwidget.TabWidget):
self._tab_insert_idx_right)) self._tab_insert_idx_right))
return idx return idx
@config.change_filter('tabs.favicons.show') def _update_favicons(self):
def update_favicons(self):
"""Update favicons when config was changed.""" """Update favicons when config was changed."""
for i, tab in enumerate(self.widgets()): for i, tab in enumerate(self.widgets()):
if config.val.tabs.favicons.show: if config.val.tabs.favicons.show:
@ -510,7 +515,7 @@ class TabbedBrowser(tabwidget.TabWidget):
except TabDeletedError: except TabDeletedError:
# We can get signals for tabs we already deleted... # We can get signals for tabs we already deleted...
return return
self.update_tab_title(idx) self._update_tab_title(idx)
if tab.data.keep_icon: if tab.data.keep_icon:
tab.data.keep_icon = False tab.data.keep_icon = False
else: else:
@ -519,7 +524,7 @@ class TabbedBrowser(tabwidget.TabWidget):
config.val.tabs.favicons.show): config.val.tabs.favicons.show):
self.window().setWindowIcon(self.default_window_icon) self.window().setWindowIcon(self.default_window_icon)
if idx == self.currentIndex(): if idx == self.currentIndex():
self.update_window_title() self._update_window_title()
@pyqtSlot() @pyqtSlot()
def on_cur_load_started(self): def on_cur_load_started(self):
@ -551,7 +556,7 @@ class TabbedBrowser(tabwidget.TabWidget):
idx, text)) idx, text))
self.set_page_title(idx, text) self.set_page_title(idx, text)
if idx == self.currentIndex(): if idx == self.currentIndex():
self.update_window_title() self._update_window_title()
@pyqtSlot(browsertab.AbstractTab, QUrl) @pyqtSlot(browsertab.AbstractTab, QUrl)
def on_url_changed(self, tab, url): def on_url_changed(self, tab, url):
@ -625,7 +630,7 @@ class TabbedBrowser(tabwidget.TabWidget):
scope='window', window=self._win_id) scope='window', window=self._win_id)
self._now_focused = tab self._now_focused = tab
self.current_tab_changed.emit(tab) self.current_tab_changed.emit(tab)
QTimer.singleShot(0, self.update_window_title) QTimer.singleShot(0, self._update_window_title)
self._tab_insert_idx_left = self.currentIndex() self._tab_insert_idx_left = self.currentIndex()
self._tab_insert_idx_right = self.currentIndex() + 1 self._tab_insert_idx_right = self.currentIndex() + 1
@ -646,9 +651,9 @@ class TabbedBrowser(tabwidget.TabWidget):
system = config.val.colors.tabs.indicator.system system = config.val.colors.tabs.indicator.system
color = utils.interpolate_color(start, stop, perc, system) color = utils.interpolate_color(start, stop, perc, system)
self.set_tab_indicator_color(idx, color) self.set_tab_indicator_color(idx, color)
self.update_tab_title(idx) self._update_tab_title(idx)
if idx == self.currentIndex(): if idx == self.currentIndex():
self.update_window_title() self._update_window_title()
def on_load_finished(self, tab, ok): def on_load_finished(self, tab, ok):
"""Adjust tab indicator when loading finished.""" """Adjust tab indicator when loading finished."""
@ -665,9 +670,9 @@ class TabbedBrowser(tabwidget.TabWidget):
else: else:
color = config.val.colors.tabs.indicator.error color = config.val.colors.tabs.indicator.error
self.set_tab_indicator_color(idx, color) self.set_tab_indicator_color(idx, color)
self.update_tab_title(idx) self._update_tab_title(idx)
if idx == self.currentIndex(): if idx == self.currentIndex():
self.update_window_title() self._update_window_title()
@pyqtSlot() @pyqtSlot()
def on_scroll_pos_changed(self): def on_scroll_pos_changed(self):
@ -678,8 +683,8 @@ class TabbedBrowser(tabwidget.TabWidget):
log.webview.debug("Not updating scroll position because index is " log.webview.debug("Not updating scroll position because index is "
"-1") "-1")
return return
self.update_window_title() self._update_window_title()
self.update_tab_title(idx) self._update_tab_title(idx)
def _on_renderer_process_terminated(self, tab, status, code): def _on_renderer_process_terminated(self, tab, status, code):
"""Show an error when a renderer process terminated.""" """Show an error when a renderer process terminated."""

View File

@ -57,18 +57,18 @@ class TabWidget(QTabWidget):
self.setTabBar(bar) self.setTabBar(bar)
bar.tabCloseRequested.connect(self.tabCloseRequested) bar.tabCloseRequested.connect(self.tabCloseRequested)
bar.tabMoved.connect(functools.partial( bar.tabMoved.connect(functools.partial(
QTimer.singleShot, 0, self.update_tab_titles)) QTimer.singleShot, 0, self._update_tab_titles))
bar.currentChanged.connect(self._on_current_changed) bar.currentChanged.connect(self._on_current_changed)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.setDocumentMode(True) self.setDocumentMode(True)
self.setElideMode(Qt.ElideRight) self.setElideMode(Qt.ElideRight)
self.setUsesScrollButtons(True) self.setUsesScrollButtons(True)
bar.setDrawBase(False) bar.setDrawBase(False)
self.init_config() self._init_config()
objreg.get('config').changed.connect(self.init_config) config.instance.changed.connect(self._init_config)
@config.change_filter('tabs') @config.change_filter('tabs')
def init_config(self): def _init_config(self):
"""Initialize attributes based on the config.""" """Initialize attributes based on the config."""
if self is None: # pragma: no cover if self is None: # pragma: no cover
# WORKAROUND for PyQt 5.2 # WORKAROUND for PyQt 5.2
@ -116,7 +116,7 @@ class TabWidget(QTabWidget):
bar.set_tab_data(idx, 'pinned', pinned) bar.set_tab_data(idx, 'pinned', pinned)
tab.data.pinned = pinned tab.data.pinned = pinned
self.update_tab_title(idx) self._update_tab_title(idx)
bar.refresh() bar.refresh()
@ -127,13 +127,13 @@ class TabWidget(QTabWidget):
def set_page_title(self, idx, title): def set_page_title(self, idx, title):
"""Set the tab title user data.""" """Set the tab title user data."""
self.tabBar().set_tab_data(idx, 'page-title', title) self.tabBar().set_tab_data(idx, 'page-title', title)
self.update_tab_title(idx) self._update_tab_title(idx)
def page_title(self, idx): def page_title(self, idx):
"""Get the tab title user data.""" """Get the tab title user data."""
return self.tabBar().page_title(idx) return self.tabBar().page_title(idx)
def update_tab_title(self, idx): def _update_tab_title(self, idx):
"""Update the tab text for the given tab.""" """Update the tab text for the given tab."""
tab = self.widget(idx) tab = self.widget(idx)
fields = self.get_tab_fields(idx) fields = self.get_tab_fields(idx)
@ -189,21 +189,20 @@ class TabWidget(QTabWidget):
fields['scroll_pos'] = scroll_pos fields['scroll_pos'] = scroll_pos
return fields return fields
def update_tab_titles(self, option='tabs.title.format'): def _update_tab_titles(self):
"""Update all texts.""" """Update all texts."""
if option in ['tabs.title.format', 'tabs.title.format_pinned']: for idx in range(self.count()):
for idx in range(self.count()): self._update_tab_title(idx)
self.update_tab_title(idx)
def tabInserted(self, idx): def tabInserted(self, idx):
"""Update titles when a tab was inserted.""" """Update titles when a tab was inserted."""
super().tabInserted(idx) super().tabInserted(idx)
self.update_tab_titles() self._update_tab_titles()
def tabRemoved(self, idx): def tabRemoved(self, idx):
"""Update titles when a tab was removed.""" """Update titles when a tab was removed."""
super().tabRemoved(idx) super().tabRemoved(idx)
self.update_tab_titles() self._update_tab_titles()
def addTab(self, page, icon_or_text, text_or_empty=None): def addTab(self, page, icon_or_text, text_or_empty=None):
"""Override addTab to use our own text setting logic. """Override addTab to use our own text setting logic.
@ -304,24 +303,17 @@ class TabBar(QTabBar):
super().__init__(parent) super().__init__(parent)
self._win_id = win_id self._win_id = win_id
self.setStyle(TabBarStyle()) self.setStyle(TabBarStyle())
self.set_font() self._set_font()
config_obj = objreg.get('config') config.instance.changed.connect(self._on_config_changed)
config_obj.changed.connect(self.set_font)
config_obj.changed.connect(self.set_icon_size)
self.vertical = False self.vertical = False
self._auto_hide_timer = QTimer() self._auto_hide_timer = QTimer()
self._auto_hide_timer.setSingleShot(True) self._auto_hide_timer.setSingleShot(True)
self._auto_hide_timer.setInterval(
config.val.tabs.show_switching_delay)
self._auto_hide_timer.timeout.connect(self.maybe_hide) self._auto_hide_timer.timeout.connect(self.maybe_hide)
self._on_show_switching_delay_changed()
self.setAutoFillBackground(True) self.setAutoFillBackground(True)
self.set_colors() self._set_colors()
self.pinned_count = 0 self.pinned_count = 0
config_obj.changed.connect(self.set_colors)
QTimer.singleShot(0, self.maybe_hide) QTimer.singleShot(0, self.maybe_hide)
config_obj.changed.connect(self.on_tab_colors_changed)
config_obj.changed.connect(self.on_show_switching_delay_changed)
config_obj.changed.connect(self.tabs_show)
def __repr__(self): def __repr__(self):
return utils.get_repr(self, count=self.count()) return utils.get_repr(self, count=self.count())
@ -330,13 +322,23 @@ class TabBar(QTabBar):
"""Get the current tab object.""" """Get the current tab object."""
return self.parent().currentWidget() return self.parent().currentWidget()
@config.change_filter('tabs.show') @pyqtSlot(str)
def tabs_show(self): def _on_config_changed(self, option):
"""Hide or show tab bar if needed when tabs->show got changed.""" if option == 'fonts.tabbar':
self.maybe_hide() self._set_font()
elif option == 'tabs.favicons.scale':
self._set_icon_size()
elif option == 'colors.tabs.bar.bg':
self._set_colors()
elif option == 'tabs.show_switching_delay':
self._on_show_switching_delay_changed()
elif option == 'tabs.show':
self.maybe_hide()
@config.change_filter('tabs.show_switching_delay') if option.startswith('colors.tabs.'):
def on_show_switching_delay_changed(self): self.update()
def _on_show_switching_delay_changed(self):
"""Set timer interval when tabs->show-switching-delay got changed.""" """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)
@ -405,32 +407,23 @@ class TabBar(QTabBar):
# code sets layoutDirty so it actually relayouts the tabs. # code sets layoutDirty so it actually relayouts the tabs.
self.setIconSize(self.iconSize()) self.setIconSize(self.iconSize())
@config.change_filter('fonts.tabbar') def _set_font(self):
def set_font(self):
"""Set the tab bar font.""" """Set the tab bar font."""
self.setFont(config.val.fonts.tabbar) self.setFont(config.val.fonts.tabbar)
self.set_icon_size() self._set_icon_size()
@config.change_filter('tabs.favicons.scale') def _set_icon_size(self):
def set_icon_size(self):
"""Set the tab bar favicon size.""" """Set the tab bar favicon size."""
size = self.fontMetrics().height() - 2 size = self.fontMetrics().height() - 2
size *= config.val.tabs.favicons.scale size *= config.val.tabs.favicons.scale
self.setIconSize(QSize(size, size)) self.setIconSize(QSize(size, size))
@config.change_filter('colors.tabs.bar.bg') def _set_colors(self):
def set_colors(self):
"""Set the tab bar colors.""" """Set the tab bar colors."""
p = self.palette() p = self.palette()
p.setColor(QPalette.Window, config.val.colors.tabs.bar.bg) p.setColor(QPalette.Window, config.val.colors.tabs.bar.bg)
self.setPalette(p) self.setPalette(p)
@pyqtSlot(str)
def on_tab_colors_changed(self, option):
"""Set the tab colors."""
if option.startswith('colors.tabs.'):
self.update()
def mousePressEvent(self, e): def mousePressEvent(self, e):
"""Override mousePressEvent to close tabs if configured.""" """Override mousePressEvent to close tabs if configured."""
button = config.val.tabs.close_mouse_button button = config.val.tabs.close_mouse_button

View File

@ -51,8 +51,8 @@ class ConsoleLineEdit(miscwidgets.CommandLineEdit):
_namespace: The local namespace of the interpreter. _namespace: The local namespace of the interpreter.
""" """
super().__init__(parent=parent) super().__init__(parent=parent)
self.update_font() self._update_font()
objreg.get('config').changed.connect(self.update_font) config.instance.changed.connect(self._update_font)
self._history = cmdhistory.History(parent=self) self._history = cmdhistory.History(parent=self)
self.returnPressed.connect(self.on_return_pressed) self.returnPressed.connect(self.on_return_pressed)
@ -103,7 +103,7 @@ class ConsoleLineEdit(miscwidgets.CommandLineEdit):
super().keyPressEvent(e) super().keyPressEvent(e)
@config.change_filter('fonts.debug_console') @config.change_filter('fonts.debug_console')
def update_font(self): def _update_font(self):
"""Set the correct font.""" """Set the correct font."""
self.setFont(config.val.fonts.debug_console) self.setFont(config.val.fonts.debug_console)
@ -116,15 +116,15 @@ class ConsoleTextEdit(QTextEdit):
super().__init__(parent) super().__init__(parent)
self.setAcceptRichText(False) self.setAcceptRichText(False)
self.setReadOnly(True) self.setReadOnly(True)
objreg.get('config').changed.connect(self.update_font) config.instance.changed.connect(self._update_font)
self.update_font() self._update_font()
self.setFocusPolicy(Qt.ClickFocus) self.setFocusPolicy(Qt.ClickFocus)
def __repr__(self): def __repr__(self):
return utils.get_repr(self) return utils.get_repr(self)
@config.change_filter('fonts.debug_console') @config.change_filter('fonts.debug_console')
def update_font(self): def _update_font(self):
"""Update font when config changed.""" """Update font when config changed."""
self.setFont(config.val.fonts.debug_console) self.setFont(config.val.fonts.debug_console)

View File

@ -255,6 +255,7 @@ class _CrashDialog(QDialog):
except Exception: except Exception:
self._crash_info.append(("Version info", traceback.format_exc())) self._crash_info.append(("Version info", traceback.format_exc()))
try: try:
# FIXME:conf
conf = objreg.get('config') conf = objreg.get('config')
self._crash_info.append(("Config", conf.dump_userconfig())) self._crash_info.append(("Config", conf.dump_userconfig()))
except Exception: except Exception:
@ -635,6 +636,7 @@ def dump_exception_info(exc, pages, cmdhist, qobjects):
traceback.print_exc() traceback.print_exc()
print("\n---- Config ----", file=sys.stderr) print("\n---- Config ----", file=sys.stderr)
try: try:
# FIXME:conf
conf = objreg.get('config') conf = objreg.get('config')
print(conf.dump_userconfig(), file=sys.stderr) print(conf.dump_userconfig(), file=sys.stderr)
except Exception: except Exception:

View File

@ -26,7 +26,7 @@ import contextlib
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from qutebrowser.utils import log, utils, objreg, qtutils from qutebrowser.utils import log, utils, qtutils
from qutebrowser.config import config from qutebrowser.config import config
@ -278,7 +278,7 @@ class LimitLineParser(LineParser):
super().__init__(configdir, fname, binary=binary, parent=parent) super().__init__(configdir, fname, binary=binary, parent=parent)
self._limit = limit self._limit = limit
if limit is not None and configdir is not None: if limit is not None and configdir is not None:
objreg.get('config').changed.connect(self.cleanup_file) config.instance.changed.connect(self._cleanup_file)
def __repr__(self): def __repr__(self):
return utils.get_repr(self, constructor=True, return utils.get_repr(self, constructor=True,
@ -286,7 +286,7 @@ class LimitLineParser(LineParser):
limit=self._limit, binary=self._binary) limit=self._limit, binary=self._binary)
@pyqtSlot(str) @pyqtSlot(str)
def cleanup_file(self, option): def _cleanup_file(self, option):
"""Delete the file if the limit was changed to 0.""" """Delete the file if the limit was changed to 0."""
assert self._configfile is not None assert self._configfile is not None
if option != self._limit: if option != self._limit:

View File

@ -26,7 +26,7 @@ from PyQt5.QtCore import pyqtSlot, QObject, QTimer
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.commands import cmdutils from qutebrowser.commands import cmdutils
from qutebrowser.utils import utils, log, message, objreg, usertypes from qutebrowser.utils import utils, log, message, usertypes
class Saveable: class Saveable:
@ -123,11 +123,11 @@ class SaveManager(QObject):
We don't do this in __init__ because the config needs to be initialized We don't do this in __init__ because the config needs to be initialized
first, but the config needs the save manager. first, but the config needs the save manager.
""" """
self.set_autosave_interval() self._set_autosave_interval()
objreg.get('config').changed.connect(self.set_autosave_interval) config.instance.changed.connect(self._set_autosave_interval)
@config.change_filter('auto_save.interval') @config.change_filter('auto_save.interval')
def set_autosave_interval(self): def _set_autosave_interval(self):
"""Set the auto-save interval.""" """Set the auto-save interval."""
interval = config.val.auto_save.interval interval = config.val.auto_save.interval
if interval == 0: if interval == 0:

View File

@ -168,6 +168,7 @@ def debug_all_objects():
@cmdutils.register(debug=True) @cmdutils.register(debug=True)
def debug_cache_stats(): def debug_cache_stats():
"""Print LRU cache stats.""" """Print LRU cache stats."""
# FIXME:conf
config_info = objreg.get('config').get.cache_info() config_info = objreg.get('config').get.cache_info()
style_info = style.get_stylesheet.cache_info() style_info = style.get_stylesheet.cache_info()
log.misc.debug('config: {}'.format(config_info)) log.misc.debug('config: {}'.format(config_info))