Get rid of _tabs attribute in CommandDispatcher.

This commit is contained in:
Florian Bruhin 2014-09-24 20:21:43 +02:00
parent 5e8144fafa
commit b119100321
2 changed files with 72 additions and 62 deletions

View File

@ -55,21 +55,31 @@ class CommandDispatcher:
_editor: The ExternalEditor object. _editor: The ExternalEditor object.
""" """
def __init__(self, parent): def __init__(self):
"""Constructor.
Args:
parent: The TabbedBrowser for this dispatcher.
"""
self._tabs = parent
self._editor = None self._editor = None
def __repr__(self): def __repr__(self):
return '<{}>'.format(self.__class__.__name__) return '<{}>'.format(self.__class__.__name__)
def _count(self):
"""Convenience method to get the widget count."""
return objreg.get('tabbed-browser').count()
def _set_current_index(self, idx):
"""Convenience method to set the current widget index."""
return objreg.get('tabbed-browser').setCurrentIndex(idx)
def _current_index(self):
"""Convenience method to get the current widget index."""
return objreg.get('tabbed-browser').currentIndex()
def _current_url(self):
"""Convenience method to get the current url."""
return objreg.get('tabbed-browser').current_url()
def _current_widget(self): def _current_widget(self):
"""Get the currently active widget from a command.""" """Get the currently active widget from a command."""
widget = self._tabs.currentWidget() widget = objreg.get('tabbed-browser').currentWidget()
if widget is None: if widget is None:
raise cmdexc.CommandError("No WebView available yet!") raise cmdexc.CommandError("No WebView available yet!")
return widget return widget
@ -82,12 +92,13 @@ class CommandDispatcher:
tab: Whether to open in a new tab. tab: Whether to open in a new tab.
background: Whether to open in the background. background: Whether to open in the background.
""" """
tabbed_browser = objreg.get('tabbed-browser')
if tab and background: if tab and background:
raise cmdexc.CommandError("Only one of -t/-b can be given!") raise cmdexc.CommandError("Only one of -t/-b can be given!")
elif tab: elif tab:
self._tabs.tabopen(url, background=False, explicit=True) tabbed_browser.tabopen(url, background=False, explicit=True)
elif background: elif background:
self._tabs.tabopen(url, background=True, explicit=True) tabbed_browser.tabopen(url, background=True, explicit=True)
else: else:
widget = self._current_widget() widget = self._current_widget()
widget.openurl(url) widget.openurl(url)
@ -103,15 +114,15 @@ class CommandDispatcher:
The widget with the given tab ID if count is given. The widget with the given tab ID if count is given.
None if no widget was found. None if no widget was found.
""" """
tabbed_browser = objreg.get('tabbed-browser')
if count is None: if count is None:
return self._tabs.currentWidget() return tabbed_browser.currentWidget()
elif 1 <= count <= self._tabs.count(): elif 1 <= count <= self._count():
cmdutils.check_overflow(count + 1, 'int') cmdutils.check_overflow(count + 1, 'int')
return self._tabs.widget(count - 1) return tabbed_browser.widget(count - 1)
else: else:
return None return None
def _scroll_percent(self, perc=None, count=None, orientation=None): def _scroll_percent(self, perc=None, count=None, orientation=None):
"""Inner logic for scroll_percent_(x|y). """Inner logic for scroll_percent_(x|y).
@ -140,7 +151,7 @@ class CommandDispatcher:
if idx is None: if idx is None:
return 0 return 0
elif idx == 0: elif idx == 0:
return self._tabs.count() - 1 return self._count() - 1
else: else:
return idx - 1 return idx - 1
@ -156,9 +167,9 @@ class CommandDispatcher:
# gets called from tab_move which has delta set to None by default. # gets called from tab_move which has delta set to None by default.
delta = 1 delta = 1
if direction == '-': if direction == '-':
return self._tabs.currentIndex() - delta return self._current_index() - delta
elif direction == '+': elif direction == '+':
return self._tabs.currentIndex() + delta return self._current_index() + delta
def _tab_focus_last(self): def _tab_focus_last(self):
"""Select the tab which was last focused.""" """Select the tab which was last focused."""
@ -166,10 +177,10 @@ class CommandDispatcher:
tab = objreg.get('last-focused-tab') tab = objreg.get('last-focused-tab')
except KeyError: except KeyError:
raise cmdexc.CommandError("No last focused tab!") raise cmdexc.CommandError("No last focused tab!")
idx = self._tabs.indexOf(tab) idx = objreg.get('tabbed-browser').indexOf(tab)
if idx == -1: if idx == -1:
raise cmdexc.CommandError("Last focused tab vanished!") raise cmdexc.CommandError("Last focused tab vanished!")
self._tabs.setCurrentIndex(idx) self._set_current_index(idx)
def _editor_cleanup(self, oshandle, filename): def _editor_cleanup(self, oshandle, filename):
"""Clean up temporary file when the editor was closed.""" """Clean up temporary file when the editor was closed."""
@ -193,7 +204,7 @@ class CommandDispatcher:
tab = self._cntwidget(count) tab = self._cntwidget(count)
if tab is None: if tab is None:
return return
self._tabs.close_tab(tab) objreg.get('tabbed-browser').close_tab(tab)
@cmdutils.register(instance='command-dispatcher', name='open', @cmdutils.register(instance='command-dispatcher', name='open',
split=False) split=False)
@ -210,17 +221,15 @@ class CommandDispatcher:
url = urlutils.fuzzy_url(url) url = urlutils.fuzzy_url(url)
except urlutils.FuzzyUrlError as e: except urlutils.FuzzyUrlError as e:
raise cmdexc.CommandError(e) raise cmdexc.CommandError(e)
if tab: if tab or bg:
self._tabs.tabopen(url, background=False, explicit=True) self._open(url, tab, bg)
elif bg:
self._tabs.tabopen(url, background=True, explicit=True)
else: else:
curtab = self._cntwidget(count) curtab = self._cntwidget(count)
if curtab is None: if curtab is None:
if count is None: if count is None:
# We want to open a URL in the current tab, but none exists # We want to open a URL in the current tab, but none exists
# yet. # yet.
self._tabs.tabopen(url) objreg.get('tabbed-browser').tabopen(url)
else: else:
# Explicit count with a tab that doesn't exist. # Explicit count with a tab that doesn't exist.
return return
@ -334,8 +343,8 @@ class CommandDispatcher:
frame = widget.page().mainFrame() frame = widget.page().mainFrame()
if frame is None: if frame is None:
raise cmdexc.CommandError("No frame focused!") raise cmdexc.CommandError("No frame focused!")
widget.hintmanager.start(frame, self._tabs.current_url(), group, widget.hintmanager.start(frame, self._current_url(), group, target,
target, *args) *args)
@cmdutils.register(instance='command-dispatcher', hide=True) @cmdutils.register(instance='command-dispatcher', hide=True)
def follow_hint(self): def follow_hint(self):
@ -412,7 +421,7 @@ class CommandDispatcher:
""" """
widget = self._current_widget() widget = self._current_widget()
frame = widget.page().currentFrame() frame = widget.page().currentFrame()
url = self._tabs.current_url() url = self._current_url()
if frame is None: if frame is None:
raise cmdexc.CommandError("No frame focused!") raise cmdexc.CommandError("No frame focused!")
if where == 'prev': if where == 'prev':
@ -487,9 +496,9 @@ class CommandDispatcher:
""" """
clipboard = QApplication.clipboard() clipboard = QApplication.clipboard()
if title: if title:
s = self._tabs.tabText(self._tabs.currentIndex()) s = objreg.get('tabbed-browser').tabText(self._current_index())
else: else:
s = self._tabs.current_url().toString( s = self._current_url().toString(
QUrl.FullyEncoded | QUrl.RemovePassword) QUrl.FullyEncoded | QUrl.RemovePassword)
if sel and clipboard.supportsSelection(): if sel and clipboard.supportsSelection():
mode = QClipboard.Selection mode = QClipboard.Selection
@ -543,17 +552,18 @@ class CommandDispatcher:
@cmdutils.register(instance='command-dispatcher') @cmdutils.register(instance='command-dispatcher')
def tab_only(self): def tab_only(self):
"""Close all tabs except for the current one.""" """Close all tabs except for the current one."""
for tab in self._tabs.widgets(): tabbed_browser = objreg.get('tabbed-browser')
for tab in tabbed_browser.widgets():
if tab is self._current_widget(): if tab is self._current_widget():
continue continue
self._tabs.close_tab(tab) tabbed_browser.close_tab(tab)
@cmdutils.register(instance='command-dispatcher') @cmdutils.register(instance='command-dispatcher')
def undo(self): def undo(self):
"""Re-open a closed tab (optionally skipping [count] closed tabs).""" """Re-open a closed tab (optionally skipping [count] closed tabs)."""
url_stack = objreg.get('url-stack', None) url_stack = objreg.get('url-stack', None)
if url_stack: if url_stack:
self._tabs.tabopen(url_stack.pop()) objreg.get('tabbed-browser').tabopen(url_stack.pop())
else: else:
raise cmdexc.CommandError("Nothing to undo!") raise cmdexc.CommandError("Nothing to undo!")
@ -564,11 +574,11 @@ class CommandDispatcher:
Args: Args:
count: How many tabs to switch back. count: How many tabs to switch back.
""" """
newidx = self._tabs.currentIndex() - count newidx = self._current_index() - count
if newidx >= 0: if newidx >= 0:
self._tabs.setCurrentIndex(newidx) self._set_current_index(newidx)
elif config.get('tabs', 'wrap'): elif config.get('tabs', 'wrap'):
self._tabs.setCurrentIndex(newidx % self._tabs.count()) self._set_current_index(newidx % self._count())
else: else:
raise cmdexc.CommandError("First tab") raise cmdexc.CommandError("First tab")
@ -579,11 +589,11 @@ class CommandDispatcher:
Args: Args:
count: How many tabs to switch forward. count: How many tabs to switch forward.
""" """
newidx = self._tabs.currentIndex() + count newidx = self._current_index() + count
if newidx < self._tabs.count(): if newidx < self._count():
self._tabs.setCurrentIndex(newidx) self._set_current_index(newidx)
elif config.get('tabs', 'wrap'): elif config.get('tabs', 'wrap'):
self._tabs.setCurrentIndex(newidx % self._tabs.count()) self._set_current_index(newidx % self._count())
else: else:
raise cmdexc.CommandError("Last tab") raise cmdexc.CommandError("Last tab")
@ -627,12 +637,12 @@ class CommandDispatcher:
return return
try: try:
idx = cmdutils.arg_or_count(index, count, default=1, idx = cmdutils.arg_or_count(index, count, default=1,
countzero=self._tabs.count()) countzero=self._count())
except ValueError as e: except ValueError as e:
raise cmdexc.CommandError(e) raise cmdexc.CommandError(e)
cmdutils.check_overflow(idx + 1, 'int') cmdutils.check_overflow(idx + 1, 'int')
if 1 <= idx <= self._tabs.count(): if 1 <= idx <= self._count():
self._tabs.setCurrentIndex(idx - 1) self._set_current_index(idx - 1)
else: else:
raise cmdexc.CommandError("There's no tab with index {}!".format( raise cmdexc.CommandError("There's no tab with index {}!".format(
idx)) idx))
@ -658,22 +668,23 @@ class CommandDispatcher:
else: else:
raise cmdexc.CommandError("Invalid direction '{}'!".format( raise cmdexc.CommandError("Invalid direction '{}'!".format(
direction)) direction))
if not 0 <= new_idx < self._tabs.count(): if not 0 <= new_idx < self._count():
raise cmdexc.CommandError("Can't move tab to position {}!".format( raise cmdexc.CommandError("Can't move tab to position {}!".format(
new_idx)) new_idx))
tabbed_browser = objreg.get('tabbed-browser')
tab = self._current_widget() tab = self._current_widget()
cur_idx = self._tabs.currentIndex() cur_idx = self._current_index()
icon = self._tabs.tabIcon(cur_idx) icon = tabbed_browser.tabIcon(cur_idx)
label = self._tabs.tabText(cur_idx) label = tabbed_browser.tabText(cur_idx)
cmdutils.check_overflow(cur_idx, 'int') cmdutils.check_overflow(cur_idx, 'int')
cmdutils.check_overflow(new_idx, 'int') cmdutils.check_overflow(new_idx, 'int')
self._tabs.setUpdatesEnabled(False) tabbed_browser.setUpdatesEnabled(False)
try: try:
self._tabs.removeTab(cur_idx) tabbed_browser.removeTab(cur_idx)
self._tabs.insertTab(new_idx, tab, icon, label) tabbed_browser.insertTab(new_idx, tab, icon, label)
self._tabs.setCurrentIndex(new_idx) self._set_current_index(new_idx)
finally: finally:
self._tabs.setUpdatesEnabled(True) tabbed_browser.setUpdatesEnabled(True)
@cmdutils.register(instance='command-dispatcher', split=False) @cmdutils.register(instance='command-dispatcher', split=False)
def spawn(self, *args): def spawn(self, *args):
@ -706,13 +717,12 @@ class CommandDispatcher:
cmd: The userscript to run. cmd: The userscript to run.
args: Arguments to pass to the userscript. args: Arguments to pass to the userscript.
""" """
url = self._tabs.current_url() userscripts.run(cmd, *args, url=self._current_url())
userscripts.run(cmd, *args, url=url)
@cmdutils.register(instance='command-dispatcher') @cmdutils.register(instance='command-dispatcher')
def quickmark_save(self): def quickmark_save(self):
"""Save the current page as a quickmark.""" """Save the current page as a quickmark."""
quickmarks.prompt_save(self._tabs.current_url()) quickmarks.prompt_save(self._current_url())
@cmdutils.register(instance='command-dispatcher') @cmdutils.register(instance='command-dispatcher')
def quickmark_load(self, name, tab=False, bg=False): def quickmark_load(self, name, tab=False, bg=False):
@ -756,7 +766,8 @@ class CommandDispatcher:
def download_page(self): def download_page(self):
"""Download the current page.""" """Download the current page."""
page = self._current_widget().page() page = self._current_widget().page()
self._tabs.download_get.emit(self._tabs.current_url(), page) tabbed_browser = objreg.get('tabbed-browser')
tabbed_browser.download_get.emit(self._current_url(), page)
@cmdutils.register(instance='command-dispatcher') @cmdutils.register(instance='command-dispatcher')
def view_source(self): def view_source(self):
@ -767,14 +778,13 @@ class CommandDispatcher:
if widget.viewing_source: if widget.viewing_source:
raise cmdexc.CommandError("Already viewing source!") raise cmdexc.CommandError("Already viewing source!")
frame = widget.page().currentFrame() frame = widget.page().currentFrame()
url = self._tabs.current_url()
html = frame.toHtml() html = frame.toHtml()
lexer = pygments.lexers.HtmlLexer() lexer = pygments.lexers.HtmlLexer()
formatter = pygments.formatters.HtmlFormatter( formatter = pygments.formatters.HtmlFormatter(
full=True, linenos='table') full=True, linenos='table')
highlighted = pygments.highlight(html, lexer, formatter) highlighted = pygments.highlight(html, lexer, formatter)
tab = self._tabs.tabopen(explicit=True) tab = objreg.get('tabbed-browser').tabopen(explicit=True)
tab.setHtml(highlighted, url) tab.setHtml(highlighted, self._current_url())
tab.viewing_source = True tab.viewing_source = True
@cmdutils.register(instance='command-dispatcher', name='help', @cmdutils.register(instance='command-dispatcher', name='help',
@ -840,7 +850,7 @@ class CommandDispatcher:
text = str(elem) text = str(elem)
else: else:
text = elem.evaluateJavaScript('this.value') text = elem.evaluateJavaScript('this.value')
self._editor = editor.ExternalEditor(self._tabs) self._editor = editor.ExternalEditor(objreg.get('tabbed-browser'))
self._editor.editing_finished.connect( self._editor.editing_finished.connect(
partial(self.on_editing_finished, elem)) partial(self.on_editing_finished, elem))
self._editor.edit(text) self._editor.edit(text)

View File

@ -27,7 +27,7 @@ from PyQt5.QtGui import QIcon
from PyQt5.QtWebKitWidgets import QWebPage from PyQt5.QtWebKitWidgets import QWebPage
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc
from qutebrowser.keyinput import modeman from qutebrowser.keyinput import modeman
from qutebrowser.widgets import tabwidget, webview from qutebrowser.widgets import tabwidget, webview
from qutebrowser.browser import signalfilter, commands from qutebrowser.browser import signalfilter, commands
@ -109,7 +109,7 @@ class TabbedBrowser(tabwidget.TabWidget):
self._url_stack = [] self._url_stack = []
objreg.register('url-stack', self._url_stack) objreg.register('url-stack', self._url_stack)
self._filter = signalfilter.SignalFilter(self) self._filter = signalfilter.SignalFilter(self)
dispatcher = commands.CommandDispatcher(self) dispatcher = commands.CommandDispatcher()
objreg.register('command-dispatcher', dispatcher) objreg.register('command-dispatcher', dispatcher)
self._now_focused = None self._now_focused = None
# FIXME adjust this to font size # FIXME adjust this to font size