Use a QObject for quickmarks and add a changed signal.

See #189.
This commit is contained in:
Florian Bruhin 2014-10-15 16:55:55 +02:00
parent e8fa8fadce
commit 74839d7aff
3 changed files with 99 additions and 84 deletions

View File

@ -151,7 +151,8 @@ class Application(QApplication):
log.init.debug("Initializing websettings...") log.init.debug("Initializing websettings...")
websettings.init() websettings.init()
log.init.debug("Initializing quickmarks...") log.init.debug("Initializing quickmarks...")
quickmarks.init() quickmark_manager = quickmarks.QuickmarkManager()
objreg.register('quickmark-manager', quickmark_manager)
log.init.debug("Initializing proxy...") log.init.debug("Initializing proxy...")
proxy.init() proxy.init()
log.init.debug("Initializing cookies...") log.init.debug("Initializing cookies...")
@ -663,14 +664,19 @@ class Application(QApplication):
pass pass
else: else:
to_save.append(("keyconfig", key_config.save)) to_save.append(("keyconfig", key_config.save))
to_save += [("window geometry", self._save_geometry), to_save += [("window geometry", self._save_geometry)]
("quickmarks", quickmarks.save)]
try: try:
command_history = objreg.get('command-history') command_history = objreg.get('command-history')
except KeyError: except KeyError:
pass pass
else: else:
to_save.append(("command history", command_history.save)) to_save.append(("command history", command_history.save))
try:
quickmark_manager = objreg.get('quickmark-manager')
except KeyError:
pass
else:
to_save.append(("command history", quickmark_manager.save))
try: try:
state_config = objreg.get('state-config') state_config = objreg.get('state-config')
except KeyError: except KeyError:

View File

@ -36,7 +36,7 @@ import pygments.formatters
from qutebrowser.commands import userscripts, cmdexc, cmdutils from qutebrowser.commands import userscripts, cmdexc, cmdutils
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.browser import quickmarks, webelem from qutebrowser.browser import webelem
from qutebrowser.utils import (message, editor, usertypes, log, qtutils, from qutebrowser.utils import (message, editor, usertypes, log, qtutils,
urlutils, objreg, utils) urlutils, objreg, utils)
@ -815,7 +815,8 @@ class CommandDispatcher:
@cmdutils.register(instance='command-dispatcher', scope='window') @cmdutils.register(instance='command-dispatcher', scope='window')
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._win_id, self._current_url()) quickmark_manager = objreg.get('quickmark-manager')
quickmark_manager.prompt_save(self._win_id, self._current_url())
@cmdutils.register(instance='command-dispatcher', scope='window') @cmdutils.register(instance='command-dispatcher', scope='window')
def quickmark_load(self, name, tab=False, bg=False, window=False): def quickmark_load(self, name, tab=False, bg=False, window=False):
@ -827,7 +828,7 @@ class CommandDispatcher:
bg: Load the quickmark in a new background tab. bg: Load the quickmark in a new background tab.
window: Load the quickmark in a new window. window: Load the quickmark in a new window.
""" """
url = quickmarks.get(name) url = objreg.get('quickmark-manager').get(name)
self._open(url, tab, bg, window) self._open(url, tab, bg, window)
@cmdutils.register(instance='command-dispatcher', name='inspector', @cmdutils.register(instance='command-dispatcher', name='inspector',

View File

@ -27,38 +27,46 @@ to a file on shutdown, so it makes semse to keep them as strings here.
import functools import functools
import collections import collections
from PyQt5.QtCore import QStandardPaths, QUrl from PyQt5.QtCore import pyqtSignal, QStandardPaths, QUrl, QObject
from qutebrowser.utils import message, usertypes, urlutils, standarddir from qutebrowser.utils import message, usertypes, urlutils, standarddir
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.config import lineparser from qutebrowser.config import lineparser
marks = collections.OrderedDict() class QuickmarkManager(QObject):
linecp = None
"""Manager for quickmarks.
Attributes:
marks: An OrderedDict of all quickmarks.
_linecp: The LineConfigParser used for the quickmarks.
"""
changed = pyqtSignal()
def __init__(self, parent=None):
"""Initialize and read quickmarks."""
super().__init__(parent)
self.marks = collections.OrderedDict()
def init():
"""Read quickmarks from the config file."""
global linecp
confdir = standarddir.get(QStandardPaths.ConfigLocation) confdir = standarddir.get(QStandardPaths.ConfigLocation)
linecp = lineparser.LineConfigParser(confdir, 'quickmarks') self._linecp = lineparser.LineConfigParser(confdir, 'quickmarks')
for line in linecp: for line in self._linecp:
try: try:
key, url = line.rsplit(maxsplit=1) key, url = line.rsplit(maxsplit=1)
except ValueError: except ValueError:
message.error(0, "Invalid quickmark '{}'".format(line)) message.error(0, "Invalid quickmark '{}'".format(line))
else: else:
marks[key] = url self.marks[key] = url
def save(self):
def save():
"""Save the quickmarks to disk.""" """Save the quickmarks to disk."""
linecp.data = [' '.join(tpl) for tpl in marks.items()] self._linecp.data = [' '.join(tpl) for tpl in self.marks.items()]
linecp.save() self._linecp.save()
def prompt_save(self, win_id, url):
def prompt_save(win_id, url):
"""Prompt for a new quickmark name to be added and add it. """Prompt for a new quickmark name to be added and add it.
Args: Args:
@ -69,12 +77,12 @@ def prompt_save(win_id, url):
urlutils.invalid_url_error(win_id, url, "save quickmark") urlutils.invalid_url_error(win_id, url, "save quickmark")
return return
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
message.ask_async(win_id, "Add quickmark:", usertypes.PromptMode.text, message.ask_async(
functools.partial(quickmark_add, win_id, urlstr)) win_id, "Add quickmark:", usertypes.PromptMode.text,
functools.partial(self.quickmark_add, win_id, urlstr))
@cmdutils.register(instance='quickmark-manager')
@cmdutils.register() def quickmark_add(self, win_id: {'special': 'win_id'}, url, name):
def quickmark_add(win_id: {'special': 'win_id'}, url, name):
"""Add a new quickmark. """Add a new quickmark.
Args: Args:
@ -82,8 +90,8 @@ def quickmark_add(win_id: {'special': 'win_id'}, url, name):
url: The url to add as quickmark. url: The url to add as quickmark.
name: The name for the new quickmark. name: The name for the new quickmark.
""" """
# We don't raise cmdexc.CommandError here as this can be called async via # We don't raise cmdexc.CommandError here as this can be called async
# prompt_save. # via prompt_save.
if not name: if not name:
message.error(win_id, "Can't set mark with empty name!") message.error(win_id, "Can't set mark with empty name!")
return return
@ -93,25 +101,25 @@ def quickmark_add(win_id: {'special': 'win_id'}, url, name):
def set_mark(): def set_mark():
"""Really set the quickmark.""" """Really set the quickmark."""
marks[name] = url self.marks[name] = url
self.changed.emit()
if name in marks: if name in self.marks:
message.confirm_async(win_id, "Override existing quickmark?", set_mark, message.confirm_async(
default=True) win_id, "Override existing quickmark?", set_mark, default=True)
else: else:
set_mark() set_mark()
def get(self, name):
def get(name):
"""Get the URL of the quickmark named name as a QUrl.""" """Get the URL of the quickmark named name as a QUrl."""
if name not in marks: if name not in self.marks:
raise cmdexc.CommandError( raise cmdexc.CommandError(
"Quickmark '{}' does not exist!".format(name)) "Quickmark '{}' does not exist!".format(name))
urlstr = marks[name] urlstr = self.marks[name]
try: try:
url = urlutils.fuzzy_url(urlstr) url = urlutils.fuzzy_url(urlstr)
except urlutils.FuzzyUrlError: except urlutils.FuzzyUrlError:
raise cmdexc.CommandError( raise cmdexc.CommandError(
"Invalid URL for quickmark {}: {} ({})".format(name, urlstr, "Invalid URL for quickmark {}: {} ({})".format(
url.errorString())) name, urlstr, url.errorString()))
return url return url