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

View File

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