From 28caf457072036ba8cdda7399133fa9358759b1a Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 21 May 2015 18:17:22 -0400 Subject: [PATCH 01/47] First version of bookmarks. --- .gitignore | 1 + qutebrowser/app.py | 5 +- qutebrowser/browser/bookmarks.py | 136 +++++++++++++++++++++ qutebrowser/browser/commands.py | 10 ++ qutebrowser/completion/models/instances.py | 20 +++ qutebrowser/completion/models/urlmodel.py | 47 +++++-- qutebrowser/utils/usertypes.py | 3 +- 7 files changed, 213 insertions(+), 9 deletions(-) create mode 100644 qutebrowser/browser/bookmarks.py diff --git a/.gitignore b/.gitignore index f3ff3652a..ee9b26169 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ __pycache__ *.pyc +*.swp /build /dist /qutebrowser.egg-info diff --git a/qutebrowser/app.py b/qutebrowser/app.py index 64c277c9f..867a24d52 100644 --- a/qutebrowser/app.py +++ b/qutebrowser/app.py @@ -44,7 +44,7 @@ import qutebrowser.resources # pylint: disable=unused-import from qutebrowser.completion.models import instances as completionmodels from qutebrowser.commands import cmdutils, runners, cmdexc from qutebrowser.config import style, config, websettings, configexc -from qutebrowser.browser import quickmarks, cookies, cache, adblock, history +from qutebrowser.browser import bookmarks, quickmarks, cookies, cache, adblock, history from qutebrowser.browser.network import qutescheme, proxy, networkmanager from qutebrowser.mainwindow import mainwindow from qutebrowser.misc import readline, ipc, savemanager, sessions, crashsignal @@ -413,6 +413,9 @@ def _init_modules(args, crash_handler): log.init.debug("Initializing quickmarks...") quickmark_manager = quickmarks.QuickmarkManager(qApp) objreg.register('quickmark-manager', quickmark_manager) + log.init.debug("Initializing bookmarks...") + bookmark_manager = bookmarks.BookmarkManager(qApp) + objreg.register('bookmark-manager', bookmark_manager) log.init.debug("Initializing proxy...") proxy.init() log.init.debug("Initializing cookies...") diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py new file mode 100644 index 000000000..d1693b358 --- /dev/null +++ b/qutebrowser/browser/bookmarks.py @@ -0,0 +1,136 @@ +# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: + +# Copyright 2014-2015 Florian Bruhin (The Compiler) +# Copyright 2015 Antoni Boucher +# +# This file is part of qutebrowser. +# +# qutebrowser is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# qutebrowser is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with qutebrowser. If not, see . + +"""Manager for bookmarks. + +Note we violate our general QUrl rule by storing url strings in the marks +OrderedDict. This is because we read them from a file at start and write them +to a file on shutdown, so it makes sense to keep them as strings here. +""" + +import os.path +import functools +import collections + +from PyQt5.QtCore import pyqtSignal, QUrl, QObject + +from qutebrowser.utils import message, usertypes, urlutils, standarddir, objreg +from qutebrowser.commands import cmdexc, cmdutils +from qutebrowser.misc import lineparser + + +class BookmarkManager(QObject): + + """Manager for bookmarks. + + Attributes: + marks: An OrderedDict of all bookmarks. + _lineparser: The LineParser used for the bookmarks, or None + (when qutebrowser is started with -c ''). + + Signals: + changed: Emitted when anything changed. + added: Emitted when a new bookmark was added. + arg 0: The name of the bookmark. + arg 1: The URL of the bookmark, as string. + removed: Emitted when an existing bookmark was removed. + arg 0: The name of the bookmark. + """ + + changed = pyqtSignal() + added = pyqtSignal(str, str) + removed = pyqtSignal(str) + + def __init__(self, parent=None): + """Initialize and read bookmarks.""" + super().__init__(parent) + + self.marks = collections.OrderedDict() + + if standarddir.config() is None: + self._lineparser = None + else: + self._lineparser = lineparser.LineParser( + standarddir.config(), 'bookmarks', parent=self) + for line in self._lineparser: + if not line.strip(): + # Ignore empty or whitespace-only lines. + continue + try: + key, url = line.rsplit(maxsplit=1) + except ValueError: + message.error(0, "Invalid bookmark '{}'".format(line)) + else: + self.marks[key] = url + filename = os.path.join(standarddir.config(), 'bookmarks') + objreg.get('save-manager').add_saveable( + 'bookmark-manager', self.save, self.changed, + filename=filename) + + def save(self): + """Save the bookmarks to disk.""" + if self._lineparser is not None: + self._lineparser.data = [' '.join(tpl) + for tpl in self.marks.items()] + self._lineparser.save() + + @cmdutils.register(instance='bookmark-manager', win_id='win_id') + def bookmark_add(self, win_id, url, name): + """Add a new bookmark. + + Args: + win_id: The window ID to display the errors in. + url: The url to add as bookmark. + name: The name for the new bookmark. + """ + if not url.isValid(): + urlutils.invalid_url_error(win_id, url, "save quickmark") + return + urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + + # We don't raise cmdexc.CommandError here as this can be called async + # via prompt_save. + if not name: + message.error(win_id, "Can't set mark with empty name!") + return + if not urlstr: + message.error(win_id, "Can't set mark with empty URL!") + return + + self.marks[name] = urlstr + self.changed.emit() + self.added.emit(name, urlstr) + message.info(win_id, "Bookmarks added") + + @cmdutils.register(instance='bookmark-manager', maxsplit=0, + completion=[usertypes.Completion.bookmark_by_name]) + def bookmark_del(self, name): + """Delete a bookmark. + + Args: + name: The name of the bookmark to delete. + """ + try: + del self.marks[name] + except KeyError: + raise cmdexc.CommandError("Bookmark '{}' not found!".format(name)) + else: + self.changed.emit() + self.removed.emit(name) diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 0c01260d7..41b379c51 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -99,6 +99,10 @@ class CommandDispatcher: msg += "!" raise cmdexc.CommandError(msg) + def _current_title(self): + """Convenience method to get the current title.""" + return self._tabbed_browser.page_title(self._current_index()) + def _current_widget(self): """Get the currently active widget from a command.""" widget = self._tabbed_browser.currentWidget() @@ -985,6 +989,12 @@ class CommandDispatcher: url = objreg.get('quickmark-manager').get(name) self._open(url, tab, bg, window) + @cmdutils.register(instance='command-dispatcher', scope='window') + def bookmark_save(self): + """Save the current page as a bookmark.""" + bookmark_manager = objreg.get('bookmark-manager') + bookmark_manager.bookmark_add(self._win_id, self._current_url(), self._current_title()) + @cmdutils.register(instance='command-dispatcher', name='inspector', scope='window') def toggle_inspector(self): diff --git a/qutebrowser/completion/models/instances.py b/qutebrowser/completion/models/instances.py index 85998357f..50e73cab5 100644 --- a/qutebrowser/completion/models/instances.py +++ b/qutebrowser/completion/models/instances.py @@ -106,6 +106,20 @@ def init_quickmark_completions(): model = _init_model(miscmodels.QuickmarkCompletionModel, 'name') _instances[usertypes.Completion.quickmark_by_name] = model +@pyqtSlot() +def init_bookmark_completions(): + """Initialize bookmark completion models.""" + log.completion.debug("Initializing bookmark completion.") + try: + _instances[usertypes.Completion.bookmark_by_url].deleteLater() + _instances[usertypes.Completion.bookmark_by_name].deleteLater() + except KeyError: + pass + model = _init_model(miscmodels.BookmarkCompletionModel, 'url') + _instances[usertypes.Completion.bookmark_by_url] = model + model = _init_model(miscmodels.BookmarkCompletionModel, 'name') + _instances[usertypes.Completion.bookmark_by_name] = model + @pyqtSlot() def init_session_completion(): @@ -128,6 +142,8 @@ INITIALIZERS = { usertypes.Completion.value: _init_setting_completions, usertypes.Completion.quickmark_by_url: init_quickmark_completions, usertypes.Completion.quickmark_by_name: init_quickmark_completions, + usertypes.Completion.bookmark_by_url: init_bookmark_completions, + usertypes.Completion.bookmark_by_name: init_bookmark_completions, usertypes.Completion.sessions: init_session_completion, } @@ -165,6 +181,10 @@ def init(): quickmark_manager.changed.connect( functools.partial(update, [usertypes.Completion.quickmark_by_url, usertypes.Completion.quickmark_by_name])) + bookmark_manager = objreg.get('bookmark-manager') + bookmark_manager.changed.connect( + functools.partial(update, [usertypes.Completion.bookmark_by_url, + usertypes.Completion.bookmark_by_name])) session_manager = objreg.get('session-manager') session_manager.update_completion.connect( functools.partial(update, [usertypes.Completion.sessions])) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index e8898ec85..4927ec65a 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -30,7 +30,7 @@ from qutebrowser.config import config class UrlCompletionModel(base.BaseCompletionModel): - """A model which combines quickmarks and web history URLs. + """A model which combines bookmarks, quickmarks and web history URLs. Used for the `open` command.""" @@ -40,14 +40,15 @@ class UrlCompletionModel(base.BaseCompletionModel): super().__init__(parent) self._quickmark_cat = self.new_category("Quickmarks") + self._bookmark_cat = self.new_category("Bookmarks") self._history_cat = self.new_category("History") - quickmark_manager = objreg.get('quickmark-manager') - quickmarks = quickmark_manager.marks.items() - for qm_name, qm_url in quickmarks: - self._add_quickmark_entry(qm_name, qm_url) - quickmark_manager.added.connect(self.on_quickmark_added) - quickmark_manager.removed.connect(self.on_quickmark_removed) + bookmark_manager = objreg.get('bookmark-manager') + bookmarks = bookmark_manager.marks.items() + for bm_name, bm_url in bookmarks: + self._add_bookmark_entry(bm_name, bm_url) + bookmark_manager.added.connect(self.on_bookmark_added) + bookmark_manager.removed.connect(self.on_bookmark_removed) self._history = objreg.get('web-history') max_history = config.get('completion', 'web-history-max-items') @@ -81,6 +82,15 @@ class UrlCompletionModel(base.BaseCompletionModel): """ self.new_item(self._quickmark_cat, url, name) + def _add_bookmark_entry(self, name, url): + """Add a new bookmark entry to the completion. + + Args: + name: The name of the new bookmark. + url: The URL of the new bookmark. + """ + self.new_item(self._bookmark_cat, url, name) + @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): """Reformat the timestamps if the config option was changed.""" @@ -126,3 +136,26 @@ class UrlCompletionModel(base.BaseCompletionModel): if name_item.data(Qt.DisplayRole) == name: self._quickmark_cat.removeRow(i) break + + @pyqtSlot(str, str) + def on_bookmark_added(self, name, url): + """Called when a bookmark has been added by the user. + + Args: + name: The name of the new bookmark. + url: The url of the new bookmark, as string. + """ + self._add_bookmark_entry(name, url) + + @pyqtSlot(str) + def on_bookmark_removed(self, name): + """Called when a bookmark has been removed by the user. + + Args: + name: The name of the bookmark which has been removed. + """ + for i in range(self._bookmark_cat.rowCount()): + name_item = self._bookmark_cat.child(i, 1) + if name_item.data(Qt.DisplayRole) == name: + self._bookmark_cat.removeRow(i) + break diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index 5d19ad515..3de7012f4 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -237,7 +237,8 @@ KeyMode = enum('KeyMode', ['normal', 'hint', 'command', 'yesno', 'prompt', # Available command completions Completion = enum('Completion', ['command', 'section', 'option', 'value', 'helptopic', 'quickmark_by_url', - 'quickmark_by_name', 'url', 'sessions']) + 'quickmark_by_name', 'bookmark_by_url', + 'bookmark_by_name', 'url', 'sessions']) # Exit statuses for errors. Needs to be an int for sys.exit. From 2c0c2e220e127bedea0136ed669e5994359ac925 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 21 May 2015 19:38:30 -0400 Subject: [PATCH 02/47] Fixed style issue. --- qutebrowser/app.py | 3 +- qutebrowser/browser/bookmarks.py | 41 ++++++++++----------- qutebrowser/browser/commands.py | 3 +- qutebrowser/completion/models/instances.py | 11 +++--- qutebrowser/completion/models/miscmodels.py | 21 +++++++++++ qutebrowser/completion/models/urlmodel.py | 26 ++++++------- qutebrowser/utils/usertypes.py | 2 +- 7 files changed, 65 insertions(+), 42 deletions(-) diff --git a/qutebrowser/app.py b/qutebrowser/app.py index 867a24d52..b755b0239 100644 --- a/qutebrowser/app.py +++ b/qutebrowser/app.py @@ -44,7 +44,8 @@ import qutebrowser.resources # pylint: disable=unused-import from qutebrowser.completion.models import instances as completionmodels from qutebrowser.commands import cmdutils, runners, cmdexc from qutebrowser.config import style, config, websettings, configexc -from qutebrowser.browser import bookmarks, quickmarks, cookies, cache, adblock, history +from qutebrowser.browser import (bookmarks, quickmarks, cookies, cache, + adblock, history) from qutebrowser.browser.network import qutescheme, proxy, networkmanager from qutebrowser.mainwindow import mainwindow from qutebrowser.misc import readline, ipc, savemanager, sessions, crashsignal diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index d1693b358..aac331015 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -20,13 +20,12 @@ """Manager for bookmarks. -Note we violate our general QUrl rule by storing url strings in the marks +Note we violate our general QUrl rule by storing url strings in the bookmarks OrderedDict. This is because we read them from a file at start and write them to a file on shutdown, so it makes sense to keep them as strings here. """ import os.path -import functools import collections from PyQt5.QtCore import pyqtSignal, QUrl, QObject @@ -41,17 +40,17 @@ class BookmarkManager(QObject): """Manager for bookmarks. Attributes: - marks: An OrderedDict of all bookmarks. + bookmarks: An OrderedDict of all bookmarks. _lineparser: The LineParser used for the bookmarks, or None (when qutebrowser is started with -c ''). Signals: changed: Emitted when anything changed. added: Emitted when a new bookmark was added. - arg 0: The name of the bookmark. + arg 0: The title of the bookmark. arg 1: The URL of the bookmark, as string. removed: Emitted when an existing bookmark was removed. - arg 0: The name of the bookmark. + arg 0: The title of the bookmark. """ changed = pyqtSignal() @@ -62,7 +61,7 @@ class BookmarkManager(QObject): """Initialize and read bookmarks.""" super().__init__(parent) - self.marks = collections.OrderedDict() + self.bookmarks = collections.OrderedDict() if standarddir.config() is None: self._lineparser = None @@ -74,11 +73,11 @@ class BookmarkManager(QObject): # Ignore empty or whitespace-only lines. continue try: - key, url = line.rsplit(maxsplit=1) + url, title = line.split(maxsplit=1) except ValueError: message.error(0, "Invalid bookmark '{}'".format(line)) else: - self.marks[key] = url + self.bookmarks[url] = title filename = os.path.join(standarddir.config(), 'bookmarks') objreg.get('save-manager').add_saveable( 'bookmark-manager', self.save, self.changed, @@ -88,17 +87,17 @@ class BookmarkManager(QObject): """Save the bookmarks to disk.""" if self._lineparser is not None: self._lineparser.data = [' '.join(tpl) - for tpl in self.marks.items()] + for tpl in self.bookmarks.items()] self._lineparser.save() @cmdutils.register(instance='bookmark-manager', win_id='win_id') - def bookmark_add(self, win_id, url, name): + def bookmark_add(self, win_id, url, title): """Add a new bookmark. Args: win_id: The window ID to display the errors in. url: The url to add as bookmark. - name: The name for the new bookmark. + title: The title for the new bookmark. """ if not url.isValid(): urlutils.invalid_url_error(win_id, url, "save quickmark") @@ -107,30 +106,30 @@ class BookmarkManager(QObject): # We don't raise cmdexc.CommandError here as this can be called async # via prompt_save. - if not name: - message.error(win_id, "Can't set mark with empty name!") + if not title: + message.error(win_id, "Can't set mark with empty title!") return if not urlstr: message.error(win_id, "Can't set mark with empty URL!") return - self.marks[name] = urlstr + self.bookmarks[urlstr] = title self.changed.emit() - self.added.emit(name, urlstr) + self.added.emit(title, urlstr) message.info(win_id, "Bookmarks added") @cmdutils.register(instance='bookmark-manager', maxsplit=0, - completion=[usertypes.Completion.bookmark_by_name]) - def bookmark_del(self, name): + completion=[usertypes.Completion.bookmark_by_title]) + def bookmark_del(self, url): """Delete a bookmark. Args: - name: The name of the bookmark to delete. + url: The url of the bookmark to delete. """ try: - del self.marks[name] + del self.bookmarks[url] except KeyError: - raise cmdexc.CommandError("Bookmark '{}' not found!".format(name)) + raise cmdexc.CommandError("Bookmark '{}' not found!".format(url)) else: self.changed.emit() - self.removed.emit(name) + self.removed.emit(url) diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 41b379c51..42400f38a 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -993,7 +993,8 @@ class CommandDispatcher: def bookmark_save(self): """Save the current page as a bookmark.""" bookmark_manager = objreg.get('bookmark-manager') - bookmark_manager.bookmark_add(self._win_id, self._current_url(), self._current_title()) + bookmark_manager.bookmark_add(self._win_id, self._current_url(), + self._current_title()) @cmdutils.register(instance='command-dispatcher', name='inspector', scope='window') diff --git a/qutebrowser/completion/models/instances.py b/qutebrowser/completion/models/instances.py index 50e73cab5..2277cf5b9 100644 --- a/qutebrowser/completion/models/instances.py +++ b/qutebrowser/completion/models/instances.py @@ -106,19 +106,20 @@ def init_quickmark_completions(): model = _init_model(miscmodels.QuickmarkCompletionModel, 'name') _instances[usertypes.Completion.quickmark_by_name] = model + @pyqtSlot() def init_bookmark_completions(): """Initialize bookmark completion models.""" log.completion.debug("Initializing bookmark completion.") try: _instances[usertypes.Completion.bookmark_by_url].deleteLater() - _instances[usertypes.Completion.bookmark_by_name].deleteLater() + _instances[usertypes.Completion.bookmark_by_title].deleteLater() except KeyError: pass model = _init_model(miscmodels.BookmarkCompletionModel, 'url') _instances[usertypes.Completion.bookmark_by_url] = model - model = _init_model(miscmodels.BookmarkCompletionModel, 'name') - _instances[usertypes.Completion.bookmark_by_name] = model + model = _init_model(miscmodels.BookmarkCompletionModel, 'title') + _instances[usertypes.Completion.bookmark_by_title] = model @pyqtSlot() @@ -143,7 +144,7 @@ INITIALIZERS = { usertypes.Completion.quickmark_by_url: init_quickmark_completions, usertypes.Completion.quickmark_by_name: init_quickmark_completions, usertypes.Completion.bookmark_by_url: init_bookmark_completions, - usertypes.Completion.bookmark_by_name: init_bookmark_completions, + usertypes.Completion.bookmark_by_title: init_bookmark_completions, usertypes.Completion.sessions: init_session_completion, } @@ -184,7 +185,7 @@ def init(): bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.changed.connect( functools.partial(update, [usertypes.Completion.bookmark_by_url, - usertypes.Completion.bookmark_by_name])) + usertypes.Completion.bookmark_by_title])) session_manager = objreg.get('session-manager') session_manager.update_completion.connect( functools.partial(update, [usertypes.Completion.sessions])) diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index f9af679ce..faea69269 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -111,6 +111,27 @@ class QuickmarkCompletionModel(base.BaseCompletionModel): match_field)) +class BookmarkCompletionModel(base.BaseCompletionModel): + + """A CompletionModel filled with all bookmarks.""" + + # pylint: disable=abstract-method + + def __init__(self, match_field='url', parent=None): + super().__init__(parent) + cat = self.new_category("Bookmarks") + bookmarks = objreg.get('bookmark-manager').bookmarks.items() + if match_field == 'url': + for bm_url, bm_title in bookmarks: + self.new_item(cat, bm_url, bm_title) + elif match_field == 'title': + for bm_url, bm_title in bookmarks: + self.new_item(cat, bm_title, bm_url) + else: + raise ValueError("Invalid value '{}' for match_field!".format( + match_field)) + + class SessionCompletionModel(base.BaseCompletionModel): """A CompletionModel filled with session names.""" diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 4927ec65a..eacd1aebd 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -44,9 +44,9 @@ class UrlCompletionModel(base.BaseCompletionModel): self._history_cat = self.new_category("History") bookmark_manager = objreg.get('bookmark-manager') - bookmarks = bookmark_manager.marks.items() - for bm_name, bm_url in bookmarks: - self._add_bookmark_entry(bm_name, bm_url) + bookmarks = bookmark_manager.bookmarks.items() + for bm_url, bm_title in bookmarks: + self._add_bookmark_entry(bm_title, bm_url) bookmark_manager.added.connect(self.on_bookmark_added) bookmark_manager.removed.connect(self.on_bookmark_removed) @@ -82,14 +82,14 @@ class UrlCompletionModel(base.BaseCompletionModel): """ self.new_item(self._quickmark_cat, url, name) - def _add_bookmark_entry(self, name, url): + def _add_bookmark_entry(self, title, url): """Add a new bookmark entry to the completion. Args: - name: The name of the new bookmark. + title: The title of the new bookmark. url: The URL of the new bookmark. """ - self.new_item(self._bookmark_cat, url, name) + self.new_item(self._bookmark_cat, url, title) @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): @@ -138,24 +138,24 @@ class UrlCompletionModel(base.BaseCompletionModel): break @pyqtSlot(str, str) - def on_bookmark_added(self, name, url): + def on_bookmark_added(self, title, url): """Called when a bookmark has been added by the user. Args: - name: The name of the new bookmark. + title: The title of the new bookmark. url: The url of the new bookmark, as string. """ - self._add_bookmark_entry(name, url) + self._add_bookmark_entry(title, url) @pyqtSlot(str) - def on_bookmark_removed(self, name): + def on_bookmark_removed(self, url): """Called when a bookmark has been removed by the user. Args: - name: The name of the bookmark which has been removed. + url: The url of the bookmark which has been removed. """ for i in range(self._bookmark_cat.rowCount()): - name_item = self._bookmark_cat.child(i, 1) - if name_item.data(Qt.DisplayRole) == name: + url_item = self._bookmark_cat.child(i, 1) + if url_item.data(Qt.DisplayRole) == url: self._bookmark_cat.removeRow(i) break diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index 3de7012f4..2ee55e96f 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -238,7 +238,7 @@ KeyMode = enum('KeyMode', ['normal', 'hint', 'command', 'yesno', 'prompt', Completion = enum('Completion', ['command', 'section', 'option', 'value', 'helptopic', 'quickmark_by_url', 'quickmark_by_name', 'bookmark_by_url', - 'bookmark_by_name', 'url', 'sessions']) + 'bookmark_by_title', 'url', 'sessions']) # Exit statuses for errors. Needs to be an int for sys.exit. From 0ee7e40e69fa922bb5a0b2ac3a0595b5be721893 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 23 May 2015 15:57:52 -0400 Subject: [PATCH 03/47] Fixed broken quickmarks completion. --- qutebrowser/completion/models/urlmodel.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index eacd1aebd..55b7c4ddb 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -43,6 +43,13 @@ class UrlCompletionModel(base.BaseCompletionModel): self._bookmark_cat = self.new_category("Bookmarks") self._history_cat = self.new_category("History") + quickmark_manager = objreg.get('quickmark-manager') + quickmarks = quickmark_manager.marks.items() + for qm_name, qm_url in quickmarks: + self._add_quickmark_entry(qm_name, qm_url) + quickmark_manager.added.connect(self.on_quickmark_added) + quickmark_manager.removed.connect(self.on_quickmark_removed) + bookmark_manager = objreg.get('bookmark-manager') bookmarks = bookmark_manager.bookmarks.items() for bm_url, bm_title in bookmarks: From aaf35536a7714478c451635413bf22966a4a8bbc Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 23 May 2015 16:02:02 -0400 Subject: [PATCH 04/47] Removed unused commands and renamed bookmark-save command. --- qutebrowser/browser/bookmarks.py | 3 --- qutebrowser/browser/commands.py | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index aac331015..dd0fb3439 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -90,7 +90,6 @@ class BookmarkManager(QObject): for tpl in self.bookmarks.items()] self._lineparser.save() - @cmdutils.register(instance='bookmark-manager', win_id='win_id') def bookmark_add(self, win_id, url, title): """Add a new bookmark. @@ -118,8 +117,6 @@ class BookmarkManager(QObject): self.added.emit(title, urlstr) message.info(win_id, "Bookmarks added") - @cmdutils.register(instance='bookmark-manager', maxsplit=0, - completion=[usertypes.Completion.bookmark_by_title]) def bookmark_del(self, url): """Delete a bookmark. diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 42400f38a..6238e549c 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -990,7 +990,7 @@ class CommandDispatcher: self._open(url, tab, bg, window) @cmdutils.register(instance='command-dispatcher', scope='window') - def bookmark_save(self): + def bookmark(self): """Save the current page as a bookmark.""" bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.bookmark_add(self._win_id, self._current_url(), From ece32e930c35693b93fa91d0c7e2ba17c98f23cb Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 24 May 2015 19:07:57 -0400 Subject: [PATCH 05/47] Added bookmarks command. --- qutebrowser/browser/bookmarks.py | 4 ++-- qutebrowser/browser/commands.py | 14 ++++++++++++++ qutebrowser/completion/models/instances.py | 6 +----- qutebrowser/utils/usertypes.py | 2 +- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index dd0fb3439..d92ad2bb2 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -30,8 +30,8 @@ import collections from PyQt5.QtCore import pyqtSignal, QUrl, QObject -from qutebrowser.utils import message, usertypes, urlutils, standarddir, objreg -from qutebrowser.commands import cmdexc, cmdutils +from qutebrowser.utils import message, urlutils, standarddir, objreg +from qutebrowser.commands import cmdexc from qutebrowser.misc import lineparser diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 6238e549c..9f5d5e210 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -996,6 +996,20 @@ class CommandDispatcher: bookmark_manager.bookmark_add(self._win_id, self._current_url(), self._current_title()) + @cmdutils.register(instance='command-dispatcher', scope='window', + maxsplit=0, + completion=[usertypes.Completion.bookmark_by_url]) + def bookmarks(self, url, tab=False, bg=False, window=False): + """Load a bookmark. + + Args: + url: The url of the bookmark to load. + tab: Load the bookmark in a new tab. + bg: Load the bookmark in a new background tab. + window: Load the bookmark in a new window. + """ + self._open(QUrl(url), tab, bg, window) + @cmdutils.register(instance='command-dispatcher', name='inspector', scope='window') def toggle_inspector(self): diff --git a/qutebrowser/completion/models/instances.py b/qutebrowser/completion/models/instances.py index 2277cf5b9..31654c295 100644 --- a/qutebrowser/completion/models/instances.py +++ b/qutebrowser/completion/models/instances.py @@ -113,13 +113,11 @@ def init_bookmark_completions(): log.completion.debug("Initializing bookmark completion.") try: _instances[usertypes.Completion.bookmark_by_url].deleteLater() - _instances[usertypes.Completion.bookmark_by_title].deleteLater() except KeyError: pass model = _init_model(miscmodels.BookmarkCompletionModel, 'url') _instances[usertypes.Completion.bookmark_by_url] = model model = _init_model(miscmodels.BookmarkCompletionModel, 'title') - _instances[usertypes.Completion.bookmark_by_title] = model @pyqtSlot() @@ -144,7 +142,6 @@ INITIALIZERS = { usertypes.Completion.quickmark_by_url: init_quickmark_completions, usertypes.Completion.quickmark_by_name: init_quickmark_completions, usertypes.Completion.bookmark_by_url: init_bookmark_completions, - usertypes.Completion.bookmark_by_title: init_bookmark_completions, usertypes.Completion.sessions: init_session_completion, } @@ -184,8 +181,7 @@ def init(): usertypes.Completion.quickmark_by_name])) bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.changed.connect( - functools.partial(update, [usertypes.Completion.bookmark_by_url, - usertypes.Completion.bookmark_by_title])) + functools.partial(update, [usertypes.Completion.bookmark_by_url])) session_manager = objreg.get('session-manager') session_manager.update_completion.connect( functools.partial(update, [usertypes.Completion.sessions])) diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index 2ee55e96f..cabfdc979 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -238,7 +238,7 @@ KeyMode = enum('KeyMode', ['normal', 'hint', 'command', 'yesno', 'prompt', Completion = enum('Completion', ['command', 'section', 'option', 'value', 'helptopic', 'quickmark_by_url', 'quickmark_by_name', 'bookmark_by_url', - 'bookmark_by_title', 'url', 'sessions']) + 'url', 'sessions']) # Exit statuses for errors. Needs to be an int for sys.exit. From ad763685e56fdf72b2e0b0903eb1ad1e02140633 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 24 May 2015 19:26:23 -0400 Subject: [PATCH 06/47] Added bookmark command default key binding. --- qutebrowser/config/configdata.py | 1 + 1 file changed, 1 insertion(+) diff --git a/qutebrowser/config/configdata.py b/qutebrowser/config/configdata.py index cb3a47be7..f6f038ee1 100644 --- a/qutebrowser/config/configdata.py +++ b/qutebrowser/config/configdata.py @@ -1195,6 +1195,7 @@ KEY_DATA = collections.OrderedDict([ ('set-cmd-text -s :quickmark-load', ['b']), ('set-cmd-text -s :quickmark-load -t', ['B']), ('set-cmd-text -s :quickmark-load -w', ['wb']), + ('bookmark', ['M']), ('save', ['sf']), ('set-cmd-text -s :set', ['ss']), ('set-cmd-text -s :set -t', ['sl']), From cbc4ec6531f648201a8240e917d3929ad7e9ed37 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 28 May 2015 19:50:36 -0400 Subject: [PATCH 07/47] Added filter bookmarks by name as well as url. --- qutebrowser/completion/models/base.py | 10 ++++++++++ qutebrowser/completion/models/sortfilter.py | 12 ++++++++---- qutebrowser/completion/models/urlmodel.py | 9 +++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/qutebrowser/completion/models/base.py b/qutebrowser/completion/models/base.py index b56444013..8c79910db 100644 --- a/qutebrowser/completion/models/base.py +++ b/qutebrowser/completion/models/base.py @@ -121,3 +121,13 @@ class BaseCompletionModel(QStandardItemModel): Override QAbstractItemModel::sort. """ raise NotImplementedError + + def custom_filter(self, pattern, row, parent): + """Custom filter. + + Args: + pattern: The current filter pattern. + row: The row to accept or reject in the filter. + parent: The parent item QModelIndex. + """ + raise NotImplementedError diff --git a/qutebrowser/completion/models/sortfilter.py b/qutebrowser/completion/models/sortfilter.py index 19802fa96..2310d73d1 100644 --- a/qutebrowser/completion/models/sortfilter.py +++ b/qutebrowser/completion/models/sortfilter.py @@ -137,12 +137,16 @@ class CompletionFilterModel(QSortFilterProxyModel): # No entries in parent model return False data = self.srcmodel.data(idx) - # TODO more sophisticated filtering if not self.pattern: return True - if not data: - return False - return self.pattern.casefold() in data.casefold() + + pattern = self.pattern.casefold() + try: + return self.srcmodel.custom_filter(pattern, row, parent) + except NotImplementedError: + if not data: + return False + return pattern in data.casefold() def intelligentLessThan(self, lindex, rindex): """Custom sorting implementation. diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 55b7c4ddb..27ff67e39 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -98,6 +98,15 @@ class UrlCompletionModel(base.BaseCompletionModel): """ self.new_item(self._bookmark_cat, url, title) + def custom_filter(self, pattern, row, parent): + """Filter by url and title. + """ + index0 = self.index(row, 0, parent) + index1 = self.index(row, 1, parent) + url = self.data(index0) + title = self.data(index1) + return pattern in url.casefold() or pattern in title.casefold() + @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): """Reformat the timestamps if the config option was changed.""" From e92c493b07cabbdb0db4b0f5162cc87d74f9008b Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 30 May 2015 12:37:21 -0400 Subject: [PATCH 08/47] Fixed bug making the application crash. --- qutebrowser/completion/models/urlmodel.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 27ff67e39..10d4fb9fd 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -103,8 +103,8 @@ class UrlCompletionModel(base.BaseCompletionModel): """ index0 = self.index(row, 0, parent) index1 = self.index(row, 1, parent) - url = self.data(index0) - title = self.data(index1) + url = self.data(index0) or '' + title = self.data(index1) or '' return pattern in url.casefold() or pattern in title.casefold() @config.change_filter('completion', 'timestamp-format') From 958216292717a60ff3d659a162ee1d8501b66155 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 1 Jun 2015 17:52:23 -0400 Subject: [PATCH 09/47] Fixed bookmarks command names. --- qutebrowser/browser/commands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 239307560..170ab5127 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -1014,7 +1014,7 @@ class CommandDispatcher: self._open(url, tab, bg, window) @cmdutils.register(instance='command-dispatcher', scope='window') - def bookmark(self): + def bookmark_add(self): """Save the current page as a bookmark.""" bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.bookmark_add(self._win_id, self._current_url(), @@ -1023,7 +1023,7 @@ class CommandDispatcher: @cmdutils.register(instance='command-dispatcher', scope='window', maxsplit=0, completion=[usertypes.Completion.bookmark_by_url]) - def bookmarks(self, url, tab=False, bg=False, window=False): + def bookmark_load(self, url, tab=False, bg=False, window=False): """Load a bookmark. Args: From 508584455004bcb4e72e529206315a3bb0796541 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 1 Jun 2015 17:55:09 -0400 Subject: [PATCH 10/47] Added highlighting for completion in name column. --- qutebrowser/completion/completiondelegate.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/qutebrowser/completion/completiondelegate.py b/qutebrowser/completion/completiondelegate.py index 03caa5158..56bf18d34 100644 --- a/qutebrowser/completion/completiondelegate.py +++ b/qutebrowser/completion/completiondelegate.py @@ -196,13 +196,10 @@ class CompletionItemDelegate(QStyledItemDelegate): if index.parent().isValid(): pattern = index.model().pattern - if index.column() == 0 and pattern: - repl = r'\g<0>' - text = re.sub(re.escape(pattern), repl, self._opt.text, - flags=re.IGNORECASE) - self._doc.setHtml(text) - else: - self._doc.setPlainText(self._opt.text) + repl = r'\g<0>' + text = re.sub(re.escape(pattern), repl, self._opt.text, + flags=re.IGNORECASE) + self._doc.setHtml(text) else: self._doc.setHtml('{}'.format(html.escape(self._opt.text))) From c8bbef0ab0c039359065537f05feb992cfee2521 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 1 Jun 2015 19:49:32 -0400 Subject: [PATCH 11/47] Fixed bookmark command name in config. --- qutebrowser/config/configdata.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qutebrowser/config/configdata.py b/qutebrowser/config/configdata.py index dbad5c66a..6afbdf5e9 100644 --- a/qutebrowser/config/configdata.py +++ b/qutebrowser/config/configdata.py @@ -1203,7 +1203,7 @@ KEY_DATA = collections.OrderedDict([ ('set-cmd-text -s :quickmark-load', ['b']), ('set-cmd-text -s :quickmark-load -t', ['B']), ('set-cmd-text -s :quickmark-load -w', ['wb']), - ('bookmark', ['M']), + ('bookmark-add', ['M']), ('save', ['sf']), ('set-cmd-text -s :set', ['ss']), ('set-cmd-text -s :set -t', ['sl']), From f1874ff44f0d7d96153690f4c22c9557a7a6dea3 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Mon, 1 Jun 2015 20:00:21 -0400 Subject: [PATCH 12/47] Added possibility to remove bookmarks and quickmarks. --- qutebrowser/completion/models/urlmodel.py | 2 +- qutebrowser/mainwindow/statusbar/command.py | 27 +++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 10d4fb9fd..80cae22e9 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -171,7 +171,7 @@ class UrlCompletionModel(base.BaseCompletionModel): url: The url of the bookmark which has been removed. """ for i in range(self._bookmark_cat.rowCount()): - url_item = self._bookmark_cat.child(i, 1) + url_item = self._bookmark_cat.child(i, 0) if url_item.data(Qt.DisplayRole) == url: self._bookmark_cat.removeRow(i) break diff --git a/qutebrowser/mainwindow/statusbar/command.py b/qutebrowser/mainwindow/statusbar/command.py index 1d8105c2f..93035d36f 100644 --- a/qutebrowser/mainwindow/statusbar/command.py +++ b/qutebrowser/mainwindow/statusbar/command.py @@ -26,7 +26,7 @@ from qutebrowser.keyinput import modeman, modeparsers from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.misc import cmdhistory from qutebrowser.misc import miscwidgets as misc -from qutebrowser.utils import usertypes, log, objreg, qtutils +from qutebrowser.utils import message, usertypes, log, objreg, qtutils class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): @@ -211,7 +211,30 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): e.ignore() return else: - super().keyPressEvent(e) + if e.key() == Qt.Key_D and e.modifiers() & Qt.ControlModifier == Qt.ControlModifier: + self.delete_current_item() + else: + super().keyPressEvent(e) + + def delete_current_item(self): + completer_obj = objreg.get('completer', scope='window', + window=self._win_id) + completion = objreg.get('completion', scope='window', + window=self._win_id) + index = completion.currentIndex() + model = completion.model() + url = model.data(index) + category = index.parent() + if category.isValid(): + if category.data() == 'Bookmarks': + bookmark_manager = objreg.get('bookmark-manager') + bookmark_manager.bookmark_del(url) + message.info(self._win_id, "Bookmarks deleted") + elif category.data() == 'Quickmarks': + quickmark_manager = objreg.get('quickmark-manager') + name = model.data(index.sibling(index.row(), index.column() + 1)) + quickmark_manager.quickmark_del(name) + message.info(self._win_id, "Quickmarks deleted") def sizeHint(self): """Dynamically calculate the needed size.""" From 8b14145a4d63699ce10a80154642102d6d531d6a Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Wed, 3 Jun 2015 19:31:31 -0400 Subject: [PATCH 13/47] Fixed style. --- qutebrowser/completion/models/urlmodel.py | 3 +-- qutebrowser/mainwindow/statusbar/command.py | 11 ++++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 80cae22e9..d0d603c19 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -99,8 +99,7 @@ class UrlCompletionModel(base.BaseCompletionModel): self.new_item(self._bookmark_cat, url, title) def custom_filter(self, pattern, row, parent): - """Filter by url and title. - """ + """Filter by url and title.""" index0 = self.index(row, 0, parent) index1 = self.index(row, 1, parent) url = self.data(index0) or '' diff --git a/qutebrowser/mainwindow/statusbar/command.py b/qutebrowser/mainwindow/statusbar/command.py index 93035d36f..86b761fdc 100644 --- a/qutebrowser/mainwindow/statusbar/command.py +++ b/qutebrowser/mainwindow/statusbar/command.py @@ -211,16 +211,16 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): e.ignore() return else: - if e.key() == Qt.Key_D and e.modifiers() & Qt.ControlModifier == Qt.ControlModifier: + if e.key() == Qt.Key_D and (e.modifiers() & Qt.ControlModifier == + Qt.ControlModifier): self.delete_current_item() else: super().keyPressEvent(e) def delete_current_item(self): - completer_obj = objreg.get('completer', scope='window', - window=self._win_id) + """Delete the selected bookmark/quickmark.""" completion = objreg.get('completion', scope='window', - window=self._win_id) + window=self._win_id) index = completion.currentIndex() model = completion.model() url = model.data(index) @@ -232,7 +232,8 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): message.info(self._win_id, "Bookmarks deleted") elif category.data() == 'Quickmarks': quickmark_manager = objreg.get('quickmark-manager') - name = model.data(index.sibling(index.row(), index.column() + 1)) + name = model.data(index.sibling(index.row(), + index.column() + 1)) quickmark_manager.quickmark_del(name) message.info(self._win_id, "Quickmarks deleted") From 57a72a7120da8542135f871d5b7e77f927c47abc Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 7 Jun 2015 19:36:19 -0400 Subject: [PATCH 14/47] Refactored bookmark removal to use a command. --- qutebrowser/completion/completionwidget.py | 11 +++++++- qutebrowser/completion/models/base.py | 4 +++ qutebrowser/completion/models/urlmodel.py | 26 ++++++++++++++++++- qutebrowser/config/configdata.py | 1 + qutebrowser/mainwindow/statusbar/command.py | 28 ++------------------- 5 files changed, 42 insertions(+), 28 deletions(-) diff --git a/qutebrowser/completion/completionwidget.py b/qutebrowser/completion/completionwidget.py index 0bd6b04c9..0ad17fa7e 100644 --- a/qutebrowser/completion/completionwidget.py +++ b/qutebrowser/completion/completionwidget.py @@ -26,7 +26,7 @@ subclasses to provide completions. from PyQt5.QtWidgets import QStyle, QTreeView, QSizePolicy from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QItemSelectionModel -from qutebrowser.commands import cmdutils +from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.config import config, style from qutebrowser.completion import completiondelegate, completer from qutebrowser.utils import usertypes, qtutils, objreg, utils @@ -245,6 +245,15 @@ class CompletionView(QTreeView): """Select the next completion item.""" self._next_prev_item(prev=False) + @cmdutils.register(instance='completion', hide=True, + modes=[usertypes.KeyMode.command], scope='window') + def completion_item_del(self): + """Delete the current completion item.""" + try: + self.model().srcmodel.delete_cur_item(self._win_id) + except NotImplementedError: + raise cmdexc.CommandError("Cannot delete this item.") + def selectionChanged(self, selected, deselected): """Extend selectionChanged to call completers selection_changed.""" super().selectionChanged(selected, deselected) diff --git a/qutebrowser/completion/models/base.py b/qutebrowser/completion/models/base.py index 8c79910db..7f1e0c7d6 100644 --- a/qutebrowser/completion/models/base.py +++ b/qutebrowser/completion/models/base.py @@ -95,6 +95,10 @@ class BaseCompletionModel(QStandardItemModel): nameitem.setData(userdata, Role.userdata) return nameitem, descitem, miscitem + def delete_cur_item(self, win_id): + """Delete the selected item.""" + raise NotImplementedError + def flags(self, index): """Return the item flags for index. diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index d0d603c19..46db1d54c 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -23,7 +23,7 @@ import datetime from PyQt5.QtCore import pyqtSlot, Qt -from qutebrowser.utils import objreg, utils +from qutebrowser.utils import message, objreg, utils from qutebrowser.completion.models import base from qutebrowser.config import config @@ -174,3 +174,27 @@ class UrlCompletionModel(base.BaseCompletionModel): if url_item.data(Qt.DisplayRole) == url: self._bookmark_cat.removeRow(i) break + + def delete_cur_item(self, win_id): + """Delete the selected item. + + Args: + win_id: The current windows id. + """ + completion = objreg.get('completion', scope='window', + window=win_id) + index = completion.currentIndex() + model = completion.model() + url = model.data(index) + category = index.parent() + if category.isValid(): + if category.data() == 'Bookmarks': + bookmark_manager = objreg.get('bookmark-manager') + bookmark_manager.bookmark_del(url) + message.info(win_id, "Bookmarks deleted") + elif category.data() == 'Quickmarks': + quickmark_manager = objreg.get('quickmark-manager') + name = model.data(index.sibling(index.row(), + index.column() + 1)) + quickmark_manager.quickmark_del(name) + message.info(win_id, "Quickmarks deleted") diff --git a/qutebrowser/config/configdata.py b/qutebrowser/config/configdata.py index 6149ba577..3f4fdb690 100644 --- a/qutebrowser/config/configdata.py +++ b/qutebrowser/config/configdata.py @@ -1280,6 +1280,7 @@ KEY_DATA = collections.OrderedDict([ ('command-history-next', ['']), ('completion-item-prev', ['', '']), ('completion-item-next', ['', '']), + ('completion-item-del', ['']), ('command-accept', RETURN_KEYS), ])), diff --git a/qutebrowser/mainwindow/statusbar/command.py b/qutebrowser/mainwindow/statusbar/command.py index 86b761fdc..1d8105c2f 100644 --- a/qutebrowser/mainwindow/statusbar/command.py +++ b/qutebrowser/mainwindow/statusbar/command.py @@ -26,7 +26,7 @@ from qutebrowser.keyinput import modeman, modeparsers from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.misc import cmdhistory from qutebrowser.misc import miscwidgets as misc -from qutebrowser.utils import message, usertypes, log, objreg, qtutils +from qutebrowser.utils import usertypes, log, objreg, qtutils class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): @@ -211,31 +211,7 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): e.ignore() return else: - if e.key() == Qt.Key_D and (e.modifiers() & Qt.ControlModifier == - Qt.ControlModifier): - self.delete_current_item() - else: - super().keyPressEvent(e) - - def delete_current_item(self): - """Delete the selected bookmark/quickmark.""" - completion = objreg.get('completion', scope='window', - window=self._win_id) - index = completion.currentIndex() - model = completion.model() - url = model.data(index) - category = index.parent() - if category.isValid(): - if category.data() == 'Bookmarks': - bookmark_manager = objreg.get('bookmark-manager') - bookmark_manager.bookmark_del(url) - message.info(self._win_id, "Bookmarks deleted") - elif category.data() == 'Quickmarks': - quickmark_manager = objreg.get('quickmark-manager') - name = model.data(index.sibling(index.row(), - index.column() + 1)) - quickmark_manager.quickmark_del(name) - message.info(self._win_id, "Quickmarks deleted") + super().keyPressEvent(e) def sizeHint(self): """Dynamically calculate the needed size.""" From c4fc5c0c43dca026accebcb8a8203fa7404283af Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 7 Jun 2015 19:51:46 -0400 Subject: [PATCH 15/47] Fixed to use the title "(null)" when the page does not have any title. --- qutebrowser/browser/commands.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index c0f19c0b2..fb539ab10 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -103,7 +103,8 @@ class CommandDispatcher: def _current_title(self): """Convenience method to get the current title.""" - return self._tabbed_browser.page_title(self._current_index()) + title = self._current_widget().title() + return title if title else "(null)" def _current_widget(self): """Get the currently active widget from a command.""" From d93732a6b37546474883abaf868da71ca8e32653 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 7 Jun 2015 20:04:42 -0400 Subject: [PATCH 16/47] Fixed to use 'bookmarks/urls' file instead of bookmarks. --- qutebrowser/browser/bookmarks.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index d92ad2bb2..5d7cd7530 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -25,6 +25,7 @@ OrderedDict. This is because we read them from a file at start and write them to a file on shutdown, so it makes sense to keep them as strings here. """ +import os import os.path import collections @@ -66,8 +67,11 @@ class BookmarkManager(QObject): if standarddir.config() is None: self._lineparser = None else: + bookmarks_directory = os.path.join(standarddir.config(), 'bookmarks') + if not os.path.isdir(bookmarks_directory): + os.makedirs(bookmarks_directory) self._lineparser = lineparser.LineParser( - standarddir.config(), 'bookmarks', parent=self) + standarddir.config(), 'bookmarks/urls', parent=self) for line in self._lineparser: if not line.strip(): # Ignore empty or whitespace-only lines. @@ -78,7 +82,7 @@ class BookmarkManager(QObject): message.error(0, "Invalid bookmark '{}'".format(line)) else: self.bookmarks[url] = title - filename = os.path.join(standarddir.config(), 'bookmarks') + filename = os.path.join(standarddir.config(), 'bookmarks/urls') objreg.get('save-manager').add_saveable( 'bookmark-manager', self.save, self.changed, filename=filename) From 31eed6c9a6a90c8d302ca5abcd1da2000bd084d1 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 7 Jun 2015 20:16:45 -0400 Subject: [PATCH 17/47] Fixed to avoid having duplicate bookmarks. --- qutebrowser/browser/bookmarks.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index 5d7cd7530..c982160f4 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -116,10 +116,13 @@ class BookmarkManager(QObject): message.error(win_id, "Can't set mark with empty URL!") return - self.bookmarks[urlstr] = title - self.changed.emit() - self.added.emit(title, urlstr) - message.info(win_id, "Bookmarks added") + if urlstr in self.bookmarks: + message.error(win_id, "Bookmark already exists!") + else: + self.bookmarks[urlstr] = title + self.changed.emit() + self.added.emit(title, urlstr) + message.info(win_id, "Bookmark added") def bookmark_del(self, url): """Delete a bookmark. From c2eabb13b031058f32d4769b9d4c4e04a2e2a68d Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 7 Jun 2015 20:25:04 -0400 Subject: [PATCH 18/47] Fixed style. --- qutebrowser/browser/bookmarks.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index c982160f4..1634f4f2e 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -67,7 +67,8 @@ class BookmarkManager(QObject): if standarddir.config() is None: self._lineparser = None else: - bookmarks_directory = os.path.join(standarddir.config(), 'bookmarks') + bookmarks_directory = os.path.join(standarddir.config(), + 'bookmarks') if not os.path.isdir(bookmarks_directory): os.makedirs(bookmarks_directory) self._lineparser = lineparser.LineParser( From 8159c5f56703b8f0fc6323763f0109131c604566 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 11 Jul 2015 18:56:19 -0400 Subject: [PATCH 19/47] Fixed last merge. --- qutebrowser/completion/completer.py | 11 ++++++++++- qutebrowser/completion/completionwidget.py | 22 ---------------------- 2 files changed, 10 insertions(+), 23 deletions(-) diff --git a/qutebrowser/completion/completer.py b/qutebrowser/completion/completer.py index 2d4165bbf..d1bc962f6 100644 --- a/qutebrowser/completion/completer.py +++ b/qutebrowser/completion/completer.py @@ -22,7 +22,7 @@ from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QTimer from qutebrowser.config import config -from qutebrowser.commands import cmdutils, runners +from qutebrowser.commands import cmdexc, cmdutils, runners from qutebrowser.utils import usertypes, log, objreg, utils from qutebrowser.completion.models import instances @@ -481,3 +481,12 @@ class Completer(QObject): """Select the next completion item.""" self._open_completion_if_needed() self.next_prev_item.emit(False) + + @cmdutils.register(instance='completion', hide=True, + modes=[usertypes.KeyMode.command], scope='window') + def completion_item_del(self): + """Delete the current completion item.""" + try: + self.model().srcmodel.delete_cur_item(self._win_id) + except NotImplementedError: + raise cmdexc.CommandError("Cannot delete this item.") diff --git a/qutebrowser/completion/completionwidget.py b/qutebrowser/completion/completionwidget.py index 5db383a64..a3bea931a 100644 --- a/qutebrowser/completion/completionwidget.py +++ b/qutebrowser/completion/completionwidget.py @@ -26,7 +26,6 @@ subclasses to provide completions. from PyQt5.QtWidgets import QStyle, QTreeView, QSizePolicy from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QItemSelectionModel -from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.config import config, style from qutebrowser.completion import completiondelegate, completer from qutebrowser.utils import qtutils, objreg, utils @@ -237,27 +236,6 @@ class CompletionView(QTreeView): selmod.clearSelection() selmod.clearCurrentIndex() - @cmdutils.register(instance='completion', hide=True, - modes=[usertypes.KeyMode.command], scope='window') - def completion_item_prev(self): - """Select the previous completion item.""" - self._next_prev_item(prev=True) - - @cmdutils.register(instance='completion', hide=True, - modes=[usertypes.KeyMode.command], scope='window') - def completion_item_next(self): - """Select the next completion item.""" - self._next_prev_item(prev=False) - - @cmdutils.register(instance='completion', hide=True, - modes=[usertypes.KeyMode.command], scope='window') - def completion_item_del(self): - """Delete the current completion item.""" - try: - self.model().srcmodel.delete_cur_item(self._win_id) - except NotImplementedError: - raise cmdexc.CommandError("Cannot delete this item.") - def selectionChanged(self, selected, deselected): """Extend selectionChanged to call completers selection_changed.""" super().selectionChanged(selected, deselected) From 4bc2f63608afc314d30c3bc4ef50ad0e977e6d25 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 11 Jul 2015 19:12:18 -0400 Subject: [PATCH 20/47] Renamed bookmark_add to add in bookmark manager. --- .gitignore | 1 + qutebrowser/browser/bookmarks.py | 2 +- qutebrowser/browser/commands.py | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 696cdc775..6d95e92f4 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ __pycache__ /.tox /testresults.html /.cache +TODO diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index 1634f4f2e..0343af924 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -95,7 +95,7 @@ class BookmarkManager(QObject): for tpl in self.bookmarks.items()] self._lineparser.save() - def bookmark_add(self, win_id, url, title): + def add(self, win_id, url, title): """Add a new bookmark. Args: diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 4335dd1de..a15ad79dd 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -1062,8 +1062,8 @@ class CommandDispatcher: def bookmark_add(self): """Save the current page as a bookmark.""" bookmark_manager = objreg.get('bookmark-manager') - bookmark_manager.bookmark_add(self._win_id, self._current_url(), - self._current_title()) + bookmark_manager.add(self._win_id, self._current_url(), + self._current_title()) @cmdutils.register(instance='command-dispatcher', scope='window', maxsplit=0, From 96a2178a25a95bb222459fc6b5cb6d58efa5c548 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 11 Jul 2015 19:23:21 -0400 Subject: [PATCH 21/47] Renamed bookmark_del to delete in bookmark manager. --- qutebrowser/browser/bookmarks.py | 2 +- qutebrowser/completion/models/urlmodel.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index 0343af924..35a1b9bf4 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -125,7 +125,7 @@ class BookmarkManager(QObject): self.added.emit(title, urlstr) message.info(win_id, "Bookmark added") - def bookmark_del(self, url): + def delete(self, url): """Delete a bookmark. Args: diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index ef2b548d6..bf66abb0d 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -190,7 +190,7 @@ class UrlCompletionModel(base.BaseCompletionModel): if category.isValid(): if category.data() == 'Bookmarks': bookmark_manager = objreg.get('bookmark-manager') - bookmark_manager.bookmark_del(url) + bookmark_manager.delete(url) message.info(win_id, "Bookmarks deleted") elif category.data() == 'Quickmarks': quickmark_manager = objreg.get('quickmark-manager') From 5e8129788a05f473ef7fe5fb2a2be4d98280011b Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 11 Jul 2015 19:44:01 -0400 Subject: [PATCH 22/47] Removed try/except. --- qutebrowser/browser/bookmarks.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index 35a1b9bf4..2c1558f84 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -32,7 +32,6 @@ import collections from PyQt5.QtCore import pyqtSignal, QUrl, QObject from qutebrowser.utils import message, urlutils, standarddir, objreg -from qutebrowser.commands import cmdexc from qutebrowser.misc import lineparser @@ -131,10 +130,6 @@ class BookmarkManager(QObject): Args: url: The url of the bookmark to delete. """ - try: - del self.bookmarks[url] - except KeyError: - raise cmdexc.CommandError("Bookmark '{}' not found!".format(url)) - else: - self.changed.emit() - self.removed.emit(url) + del self.bookmarks[url] + self.changed.emit() + self.removed.emit(url) From 1e354a797e8edf5530e1880925997617a00db1ac Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 11 Jul 2015 19:52:48 -0400 Subject: [PATCH 23/47] Removed useless checks. --- qutebrowser/browser/bookmarks.py | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index 2c1558f84..c57d0c23e 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -31,7 +31,7 @@ import collections from PyQt5.QtCore import pyqtSignal, QUrl, QObject -from qutebrowser.utils import message, urlutils, standarddir, objreg +from qutebrowser.utils import message, standarddir, objreg from qutebrowser.misc import lineparser @@ -102,20 +102,8 @@ class BookmarkManager(QObject): url: The url to add as bookmark. title: The title for the new bookmark. """ - if not url.isValid(): - urlutils.invalid_url_error(win_id, url, "save quickmark") - return urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) - # We don't raise cmdexc.CommandError here as this can be called async - # via prompt_save. - if not title: - message.error(win_id, "Can't set mark with empty title!") - return - if not urlstr: - message.error(win_id, "Can't set mark with empty URL!") - return - if urlstr in self.bookmarks: message.error(win_id, "Bookmark already exists!") else: From 5dbaea7a83e6a92a49dbf668c7bc5c39b16ed70e Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sat, 11 Jul 2015 20:28:31 -0400 Subject: [PATCH 24/47] Fixed empty title. --- qutebrowser/browser/bookmarks.py | 13 +++++++------ qutebrowser/browser/commands.py | 3 +-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py index c57d0c23e..966584c04 100644 --- a/qutebrowser/browser/bookmarks.py +++ b/qutebrowser/browser/bookmarks.py @@ -76,12 +76,13 @@ class BookmarkManager(QObject): if not line.strip(): # Ignore empty or whitespace-only lines. continue - try: - url, title = line.split(maxsplit=1) - except ValueError: - message.error(0, "Invalid bookmark '{}'".format(line)) - else: - self.bookmarks[url] = title + + parts = line.split(maxsplit=1) + if len(parts) == 2: + self.bookmarks[parts[0]] = parts[1] + elif len(parts) == 1: + self.bookmarks[parts[0]] = '' + filename = os.path.join(standarddir.config(), 'bookmarks/urls') objreg.get('save-manager').add_saveable( 'bookmark-manager', self.save, self.changed, diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index a15ad79dd..4ccab7e24 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -102,8 +102,7 @@ class CommandDispatcher: def _current_title(self): """Convenience method to get the current title.""" - title = self._current_widget().title() - return title if title else "(null)" + return self._current_widget().title() def _current_widget(self): """Get the currently active widget from a command.""" From d4c91f7b0ca1d58f5eb950eda36413d0b2e60a7b Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 12 Jul 2015 20:18:32 -0400 Subject: [PATCH 25/47] Fixed completion highlighting. --- qutebrowser/completion/completiondelegate.py | 12 ++++++++---- qutebrowser/completion/models/base.py | 1 + qutebrowser/completion/models/configmodel.py | 3 +++ qutebrowser/completion/models/miscmodels.py | 5 +++++ qutebrowser/completion/models/urlmodel.py | 3 +++ 5 files changed, 20 insertions(+), 4 deletions(-) diff --git a/qutebrowser/completion/completiondelegate.py b/qutebrowser/completion/completiondelegate.py index aae84992e..130454229 100644 --- a/qutebrowser/completion/completiondelegate.py +++ b/qutebrowser/completion/completiondelegate.py @@ -195,10 +195,14 @@ class CompletionItemDelegate(QStyledItemDelegate): if index.parent().isValid(): pattern = index.model().pattern - repl = r'\g<0>' - text = re.sub(re.escape(pattern), repl, self._opt.text, - flags=re.IGNORECASE) - self._doc.setHtml(text) + if(index.column() in index.model().srcmodel.columns_to_highlight + and pattern): + repl = r'\g<0>' + text = re.sub(re.escape(pattern), repl, self._opt.text, + flags=re.IGNORECASE) + self._doc.setHtml(text) + else: + self._doc.setPlainText(self._opt.text) else: self._doc.setHtml('{}'.format(html.escape(self._opt.text))) diff --git a/qutebrowser/completion/models/base.py b/qutebrowser/completion/models/base.py index 7f1e0c7d6..b7c5223d7 100644 --- a/qutebrowser/completion/models/base.py +++ b/qutebrowser/completion/models/base.py @@ -44,6 +44,7 @@ class BaseCompletionModel(QStandardItemModel): def __init__(self, parent=None): super().__init__(parent) self.setColumnCount(3) + self.columns_to_highlight = [] def new_category(self, name, sort=None): """Add a new category to the model. diff --git a/qutebrowser/completion/models/configmodel.py b/qutebrowser/completion/models/configmodel.py index 6d39fed7b..a44387a17 100644 --- a/qutebrowser/completion/models/configmodel.py +++ b/qutebrowser/completion/models/configmodel.py @@ -34,6 +34,7 @@ class SettingSectionCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) cat = self.new_category("Sections") for name in configdata.DATA.keys(): desc = configdata.SECTION_DESC[name].splitlines()[0].strip() @@ -53,6 +54,7 @@ class SettingOptionCompletionModel(base.BaseCompletionModel): def __init__(self, section, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) cat = self.new_category(section) sectdata = configdata.DATA[section] self._misc_items = {} @@ -106,6 +108,7 @@ class SettingValueCompletionModel(base.BaseCompletionModel): def __init__(self, section, option, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) self._section = section self._option = option objreg.get('config').changed.connect(self.update_current_value) diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index faea69269..2ce9cd147 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -33,6 +33,7 @@ class CommandCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) assert cmdutils.cmd_dict cmdlist = [] for obj in set(cmdutils.cmd_dict.values()): @@ -56,6 +57,7 @@ class HelpCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) self._init_commands() self._init_settings() @@ -98,6 +100,7 @@ class QuickmarkCompletionModel(base.BaseCompletionModel): def __init__(self, match_field='url', parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) cat = self.new_category("Quickmarks") quickmarks = objreg.get('quickmark-manager').marks.items() if match_field == 'url': @@ -119,6 +122,7 @@ class BookmarkCompletionModel(base.BaseCompletionModel): def __init__(self, match_field='url', parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) cat = self.new_category("Bookmarks") bookmarks = objreg.get('bookmark-manager').bookmarks.items() if match_field == 'url': @@ -140,6 +144,7 @@ class SessionCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) cat = self.new_category("Sessions") try: for name in objreg.get('session-manager').list_sessions(): diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index bf66abb0d..f89b2cf48 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -39,6 +39,9 @@ class UrlCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) + self.columns_to_highlight.append(0) + self.columns_to_highlight.append(1) + self._quickmark_cat = self.new_category("Quickmarks") self._bookmark_cat = self.new_category("Bookmarks") self._history_cat = self.new_category("History") From 1b24cfd618d7d9e1d0cc6fc1ba52f39ead538f8e Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 12 Jul 2015 20:21:49 -0400 Subject: [PATCH 26/47] Removed useless bookmark by title model. --- qutebrowser/completion/models/instances.py | 1 - 1 file changed, 1 deletion(-) diff --git a/qutebrowser/completion/models/instances.py b/qutebrowser/completion/models/instances.py index 7fa53d6d9..f8e89137c 100644 --- a/qutebrowser/completion/models/instances.py +++ b/qutebrowser/completion/models/instances.py @@ -117,7 +117,6 @@ def init_bookmark_completions(): pass model = _init_model(miscmodels.BookmarkCompletionModel, 'url') _instances[usertypes.Completion.bookmark_by_url] = model - model = _init_model(miscmodels.BookmarkCompletionModel, 'title') @pyqtSlot() From 5bca951c21db7dab8c8e2e21c0545d2f82224afa Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 12 Jul 2015 20:29:40 -0400 Subject: [PATCH 27/47] Removed casefold() function call when using a custom filter. --- qutebrowser/completion/models/sortfilter.py | 5 ++--- qutebrowser/completion/models/urlmodel.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/qutebrowser/completion/models/sortfilter.py b/qutebrowser/completion/models/sortfilter.py index 2310d73d1..be9199153 100644 --- a/qutebrowser/completion/models/sortfilter.py +++ b/qutebrowser/completion/models/sortfilter.py @@ -140,13 +140,12 @@ class CompletionFilterModel(QSortFilterProxyModel): if not self.pattern: return True - pattern = self.pattern.casefold() try: - return self.srcmodel.custom_filter(pattern, row, parent) + return self.srcmodel.custom_filter(self.pattern, row, parent) except NotImplementedError: if not data: return False - return pattern in data.casefold() + return self.pattern.casefold() in data.casefold() def intelligentLessThan(self, lindex, rindex): """Custom sorting implementation. diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index f89b2cf48..4500d66cc 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -107,7 +107,7 @@ class UrlCompletionModel(base.BaseCompletionModel): index1 = self.index(row, 1, parent) url = self.data(index0) or '' title = self.data(index1) or '' - return pattern in url.casefold() or pattern in title.casefold() + return pattern.casefold() in url.casefold() or pattern.casefold() in title.casefold() @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): From 91561e2c5b50de23b140e2b19843687ea853f536 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Sun, 12 Jul 2015 20:46:40 -0400 Subject: [PATCH 28/47] Fixed style. --- qutebrowser/completion/models/urlmodel.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 4500d66cc..14d8b5252 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -107,7 +107,8 @@ class UrlCompletionModel(base.BaseCompletionModel): index1 = self.index(row, 1, parent) url = self.data(index0) or '' title = self.data(index1) or '' - return pattern.casefold() in url.casefold() or pattern.casefold() in title.casefold() + return (pattern.casefold() in url.casefold() or pattern.casefold() in + title.casefold()) @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): From 2f11b41ae65d583f5f411cdd5696817f876d0269 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 16:37:10 +0200 Subject: [PATCH 29/47] Merge bookmarks and quickmarks into urlmarks. --- qutebrowser/app.py | 7 +- qutebrowser/browser/bookmarks.py | 124 -------------- .../browser/{quickmarks.py => urlmarks.py} | 155 ++++++++++++++---- qutebrowser/completion/models/miscmodels.py | 2 +- qutebrowser/completion/models/urlmodel.py | 2 +- 5 files changed, 126 insertions(+), 164 deletions(-) delete mode 100644 qutebrowser/browser/bookmarks.py rename qutebrowser/browser/{quickmarks.py => urlmarks.py} (54%) diff --git a/qutebrowser/app.py b/qutebrowser/app.py index c0946d154..da0a4ef6d 100644 --- a/qutebrowser/app.py +++ b/qutebrowser/app.py @@ -44,8 +44,7 @@ import qutebrowser.resources # pylint: disable=unused-import from qutebrowser.completion.models import instances as completionmodels from qutebrowser.commands import cmdutils, runners, cmdexc from qutebrowser.config import style, config, websettings, configexc -from qutebrowser.browser import (bookmarks, quickmarks, cookies, cache, - adblock, history) +from qutebrowser.browser import urlmarks, cookies, cache, adblock, history from qutebrowser.browser.network import qutescheme, proxy, networkmanager from qutebrowser.mainwindow import mainwindow from qutebrowser.misc import readline, ipc, savemanager, sessions, crashsignal @@ -414,10 +413,10 @@ def _init_modules(args, crash_handler): host_blocker.read_hosts() objreg.register('host-blocker', host_blocker) log.init.debug("Initializing quickmarks...") - quickmark_manager = quickmarks.QuickmarkManager(qApp) + quickmark_manager = urlmarks.QuickmarkManager(qApp) objreg.register('quickmark-manager', quickmark_manager) log.init.debug("Initializing bookmarks...") - bookmark_manager = bookmarks.BookmarkManager(qApp) + bookmark_manager = urlmarks.BookmarkManager(qApp) objreg.register('bookmark-manager', bookmark_manager) log.init.debug("Initializing proxy...") proxy.init() diff --git a/qutebrowser/browser/bookmarks.py b/qutebrowser/browser/bookmarks.py deleted file mode 100644 index 966584c04..000000000 --- a/qutebrowser/browser/bookmarks.py +++ /dev/null @@ -1,124 +0,0 @@ -# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: - -# Copyright 2014-2015 Florian Bruhin (The Compiler) -# Copyright 2015 Antoni Boucher -# -# This file is part of qutebrowser. -# -# qutebrowser is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# qutebrowser is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with qutebrowser. If not, see . - -"""Manager for bookmarks. - -Note we violate our general QUrl rule by storing url strings in the bookmarks -OrderedDict. This is because we read them from a file at start and write them -to a file on shutdown, so it makes sense to keep them as strings here. -""" - -import os -import os.path -import collections - -from PyQt5.QtCore import pyqtSignal, QUrl, QObject - -from qutebrowser.utils import message, standarddir, objreg -from qutebrowser.misc import lineparser - - -class BookmarkManager(QObject): - - """Manager for bookmarks. - - Attributes: - bookmarks: An OrderedDict of all bookmarks. - _lineparser: The LineParser used for the bookmarks, or None - (when qutebrowser is started with -c ''). - - Signals: - changed: Emitted when anything changed. - added: Emitted when a new bookmark was added. - arg 0: The title of the bookmark. - arg 1: The URL of the bookmark, as string. - removed: Emitted when an existing bookmark was removed. - arg 0: The title of the bookmark. - """ - - changed = pyqtSignal() - added = pyqtSignal(str, str) - removed = pyqtSignal(str) - - def __init__(self, parent=None): - """Initialize and read bookmarks.""" - super().__init__(parent) - - self.bookmarks = collections.OrderedDict() - - if standarddir.config() is None: - self._lineparser = None - else: - bookmarks_directory = os.path.join(standarddir.config(), - 'bookmarks') - if not os.path.isdir(bookmarks_directory): - os.makedirs(bookmarks_directory) - self._lineparser = lineparser.LineParser( - standarddir.config(), 'bookmarks/urls', parent=self) - for line in self._lineparser: - if not line.strip(): - # Ignore empty or whitespace-only lines. - continue - - parts = line.split(maxsplit=1) - if len(parts) == 2: - self.bookmarks[parts[0]] = parts[1] - elif len(parts) == 1: - self.bookmarks[parts[0]] = '' - - filename = os.path.join(standarddir.config(), 'bookmarks/urls') - objreg.get('save-manager').add_saveable( - 'bookmark-manager', self.save, self.changed, - filename=filename) - - def save(self): - """Save the bookmarks to disk.""" - if self._lineparser is not None: - self._lineparser.data = [' '.join(tpl) - for tpl in self.bookmarks.items()] - self._lineparser.save() - - def add(self, win_id, url, title): - """Add a new bookmark. - - Args: - win_id: The window ID to display the errors in. - url: The url to add as bookmark. - title: The title for the new bookmark. - """ - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) - - if urlstr in self.bookmarks: - message.error(win_id, "Bookmark already exists!") - else: - self.bookmarks[urlstr] = title - self.changed.emit() - self.added.emit(title, urlstr) - message.info(win_id, "Bookmark added") - - def delete(self, url): - """Delete a bookmark. - - Args: - url: The url of the bookmark to delete. - """ - del self.bookmarks[url] - self.changed.emit() - self.removed.emit(url) diff --git a/qutebrowser/browser/quickmarks.py b/qutebrowser/browser/urlmarks.py similarity index 54% rename from qutebrowser/browser/quickmarks.py rename to qutebrowser/browser/urlmarks.py index cf2a36b89..c36f6bed8 100644 --- a/qutebrowser/browser/quickmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -1,6 +1,7 @@ # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2015 Florian Bruhin (The Compiler) +# Copyright 2015 Antoni Boucher # # This file is part of qutebrowser. # @@ -17,13 +18,14 @@ # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see . -"""Manager for quickmarks. +"""Managers for bookmarks and quickmarks. Note we violate our general QUrl rule by storing url strings in the marks OrderedDict. This is because we read them from a file at start and write them to a file on shutdown, so it makes sense to keep them as strings here. """ +import os import os.path import functools import collections @@ -35,22 +37,19 @@ from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.misc import lineparser -class QuickmarkManager(QObject): +class UrlMarkManager(QObject): - """Manager for quickmarks. + """Base class for BookmarkManager and QuickmarkManager. Attributes: - marks: An OrderedDict of all quickmarks. - _lineparser: The LineParser used for the quickmarks, or None + marks: An OrderedDict of all quickmarks/bookmarks. + _lineparser: The LineParser used for the marks, or None (when qutebrowser is started with -c ''). Signals: changed: Emitted when anything changed. - added: Emitted when a new quickmark was added. - arg 0: The name of the quickmark. - arg 1: The URL of the quickmark, as string. - removed: Emitted when an existing quickmark was removed. - arg 0: The name of the quickmark. + added: Emitted when a new quickmark/bookmark was added. + removed: Emitted when an existing quickmark/bookmark was removed. """ changed = pyqtSignal() @@ -62,35 +61,76 @@ class QuickmarkManager(QObject): super().__init__(parent) self.marks = collections.OrderedDict() + self._lineparser = None if standarddir.config() is None: - self._lineparser = None - else: - self._lineparser = lineparser.LineParser( - standarddir.config(), 'quickmarks', parent=self) - for line in self._lineparser: - if not line.strip(): - # Ignore empty or whitespace-only lines. - continue - try: - key, url = line.rsplit(maxsplit=1) - except ValueError: - message.error('current', "Invalid quickmark '{}'".format( - line)) - else: - self.marks[key] = url - filename = os.path.join(standarddir.config(), 'quickmarks') - objreg.get('save-manager').add_saveable( - 'quickmark-manager', self.save, self.changed, - filename=filename) + return + + self._init_lineparser() + for line in self._lineparser: + if not line.strip(): + # Ignore empty or whitespace-only lines. + continue + self._parse_line(line) + self._init_savemanager(objreg.get('save-manager')) + + def _init_lineparser(self): + raise NotImplementedError + + def _parse_line(self, line): + raise NotImplementedError + + def _init_savemanager(self, _save_manager): + raise NotImplementedError def save(self): - """Save the quickmarks to disk.""" + """Save the marks to disk.""" if self._lineparser is not None: self._lineparser.data = [' '.join(tpl) for tpl in self.marks.items()] self._lineparser.save() + def delete(self, key): + """Delete a quickmark/bookmark. + + Args: + key: The key to delete (name for quickmarks, URL for bookmarks.) + """ + del self.marks[key] + self.changed.emit() + self.removed.emit(key) + + +class QuickmarkManager(UrlMarkManager): + + """Manager for quickmarks. + + The primary key for quickmarks is their *name*, this means: + + - self.marks maps names to URLs. + - changed gets emitted with the name as first argument and the URL as + second argument. + - removed gets emitted with the name as argument. + """ + + def _init_lineparser(self): + self._lineparser = lineparser.LineParser( + standarddir.config(), 'quickmarks', parent=self) + + def _init_savemanager(self, save_manager): + filename = os.path.join(standarddir.config(), 'quickmarks') + save_manager.add_saveable('quickmark-manager', self.save, self.changed, + filename=filename) + + def _parse_line(self, line): + try: + key, url = line.rsplit(maxsplit=1) + except ValueError: + message.error('current', "Invalid quickmark '{}'".format( + line)) + else: + self.marks[key] = url + def prompt_save(self, win_id, url): """Prompt for a new quickmark name to be added and add it. @@ -145,12 +185,9 @@ class QuickmarkManager(QObject): name: The name of the quickmark to delete. """ try: - del self.marks[name] + self.delete(name) except KeyError: raise cmdexc.CommandError("Quickmark '{}' not found!".format(name)) - else: - self.changed.emit() - self.removed.emit(name) def get(self, name): """Get the URL of the quickmark named name as a QUrl.""" @@ -168,3 +205,53 @@ class QuickmarkManager(QObject): raise cmdexc.CommandError("Invalid URL for quickmark {}: " "{}{}".format(name, urlstr, errstr)) return url + + +class BookmarkManager(UrlMarkManager): + + """Manager for bookmarks. + + The primary key for bookmarks is their *url*, this means: + + - self.marks maps URLs to titles. + - changed gets emitted with the URL as first argument and the title as + second argument. + - removed gets emitted with the URL as argument. + """ + + def _init_lineparser(self): + bookmarks_directory = os.path.join(standarddir.config(), 'bookmarks') + if not os.path.isdir(bookmarks_directory): + os.makedirs(bookmarks_directory) + self._lineparser = lineparser.LineParser( + standarddir.config(), 'bookmarks/urls', parent=self) + + def _init_savemanager(self, save_manager): + filename = os.path.join(standarddir.config(), 'bookmarks/urls') + save_manager.add_saveable('bookmark-manager', self.save, self.changed, + filename=filename) + + def _parse_line(self, line): + parts = line.split(maxsplit=1) + if len(parts) == 2: + self.marks[parts[0]] = parts[1] + elif len(parts) == 1: + self.marks[parts[0]] = '' + + def add(self, win_id, url, title): + """Add a new bookmark. + + Args: + win_id: The window ID to display the errors in. + url: The url to add as bookmark. + title: The title for the new bookmark. + """ + urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + + if urlstr in self.marks: + message.error(win_id, "Bookmark already exists!") + else: + self.marks[urlstr] = title + self.changed.emit() + self.added.emit(title, urlstr) + message.info(win_id, "Bookmark added") diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index 2ce9cd147..d098185f7 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -124,7 +124,7 @@ class BookmarkCompletionModel(base.BaseCompletionModel): super().__init__(parent) self.columns_to_highlight.append(0) cat = self.new_category("Bookmarks") - bookmarks = objreg.get('bookmark-manager').bookmarks.items() + bookmarks = objreg.get('bookmark-manager').marks.items() if match_field == 'url': for bm_url, bm_title in bookmarks: self.new_item(cat, bm_url, bm_title) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 14d8b5252..4dc650396 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -54,7 +54,7 @@ class UrlCompletionModel(base.BaseCompletionModel): quickmark_manager.removed.connect(self.on_quickmark_removed) bookmark_manager = objreg.get('bookmark-manager') - bookmarks = bookmark_manager.bookmarks.items() + bookmarks = bookmark_manager.marks.items() for bm_url, bm_title in bookmarks: self._add_bookmark_entry(bm_title, bm_url) bookmark_manager.added.connect(self.on_bookmark_added) From 16ac877227554777c6d4c892e201c3294ada6762 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 16:42:47 +0200 Subject: [PATCH 30/47] Add default keybindings for loading bookmarks. See #13, #681. --- qutebrowser/config/configdata.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/qutebrowser/config/configdata.py b/qutebrowser/config/configdata.py index c740b89b6..06ddad079 100644 --- a/qutebrowser/config/configdata.py +++ b/qutebrowser/config/configdata.py @@ -1275,6 +1275,9 @@ KEY_DATA = collections.OrderedDict([ ('set-cmd-text -s :quickmark-load -t', ['B']), ('set-cmd-text -s :quickmark-load -w', ['wb']), ('bookmark-add', ['M']), + ('set-cmd-text -s :bookmark-load', ['gb']), + ('set-cmd-text -s :bookmark-load -t', ['gB']), + ('set-cmd-text -s :bookmark-load -w', ['wB']), ('save', ['sf']), ('set-cmd-text -s :set', ['ss']), ('set-cmd-text -s :set -t', ['sl']), From c7f88c93b24ffee3a09ddd74b891ff0822eccd9f Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 17:11:34 +0200 Subject: [PATCH 31/47] Style fix. --- qutebrowser/completion/completiondelegate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qutebrowser/completion/completiondelegate.py b/qutebrowser/completion/completiondelegate.py index 130454229..a857df3c2 100644 --- a/qutebrowser/completion/completiondelegate.py +++ b/qutebrowser/completion/completiondelegate.py @@ -195,7 +195,7 @@ class CompletionItemDelegate(QStyledItemDelegate): if index.parent().isValid(): pattern = index.model().pattern - if(index.column() in index.model().srcmodel.columns_to_highlight + if (index.column() in index.model().srcmodel.columns_to_highlight and pattern): repl = r'\g<0>' text = re.sub(re.escape(pattern), repl, self._opt.text, From 3b0125e8cdfbe236cd699e52fa663c1c838135e4 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 17:22:45 +0200 Subject: [PATCH 32/47] Rename cols_to_highlight to _filter and simplify. --- qutebrowser/completion/completiondelegate.py | 4 ++-- qutebrowser/completion/models/base.py | 2 +- qutebrowser/completion/models/configmodel.py | 3 --- qutebrowser/completion/models/miscmodels.py | 5 ----- qutebrowser/completion/models/urlmodel.py | 3 +-- 5 files changed, 4 insertions(+), 13 deletions(-) diff --git a/qutebrowser/completion/completiondelegate.py b/qutebrowser/completion/completiondelegate.py index a857df3c2..f2f256a40 100644 --- a/qutebrowser/completion/completiondelegate.py +++ b/qutebrowser/completion/completiondelegate.py @@ -195,8 +195,8 @@ class CompletionItemDelegate(QStyledItemDelegate): if index.parent().isValid(): pattern = index.model().pattern - if (index.column() in index.model().srcmodel.columns_to_highlight - and pattern): + columns_to_filter = index.model().srcmodel.columns_to_filter + if index.column() in columns_to_filter and pattern: repl = r'\g<0>' text = re.sub(re.escape(pattern), repl, self._opt.text, flags=re.IGNORECASE) diff --git a/qutebrowser/completion/models/base.py b/qutebrowser/completion/models/base.py index b7c5223d7..0d4bf7fca 100644 --- a/qutebrowser/completion/models/base.py +++ b/qutebrowser/completion/models/base.py @@ -44,7 +44,7 @@ class BaseCompletionModel(QStandardItemModel): def __init__(self, parent=None): super().__init__(parent) self.setColumnCount(3) - self.columns_to_highlight = [] + self.columns_to_filter = [0] def new_category(self, name, sort=None): """Add a new category to the model. diff --git a/qutebrowser/completion/models/configmodel.py b/qutebrowser/completion/models/configmodel.py index a44387a17..6d39fed7b 100644 --- a/qutebrowser/completion/models/configmodel.py +++ b/qutebrowser/completion/models/configmodel.py @@ -34,7 +34,6 @@ class SettingSectionCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) cat = self.new_category("Sections") for name in configdata.DATA.keys(): desc = configdata.SECTION_DESC[name].splitlines()[0].strip() @@ -54,7 +53,6 @@ class SettingOptionCompletionModel(base.BaseCompletionModel): def __init__(self, section, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) cat = self.new_category(section) sectdata = configdata.DATA[section] self._misc_items = {} @@ -108,7 +106,6 @@ class SettingValueCompletionModel(base.BaseCompletionModel): def __init__(self, section, option, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) self._section = section self._option = option objreg.get('config').changed.connect(self.update_current_value) diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index d098185f7..8fe3a71be 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -33,7 +33,6 @@ class CommandCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) assert cmdutils.cmd_dict cmdlist = [] for obj in set(cmdutils.cmd_dict.values()): @@ -57,7 +56,6 @@ class HelpCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) self._init_commands() self._init_settings() @@ -100,7 +98,6 @@ class QuickmarkCompletionModel(base.BaseCompletionModel): def __init__(self, match_field='url', parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) cat = self.new_category("Quickmarks") quickmarks = objreg.get('quickmark-manager').marks.items() if match_field == 'url': @@ -122,7 +119,6 @@ class BookmarkCompletionModel(base.BaseCompletionModel): def __init__(self, match_field='url', parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) cat = self.new_category("Bookmarks") bookmarks = objreg.get('bookmark-manager').marks.items() if match_field == 'url': @@ -144,7 +140,6 @@ class SessionCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) cat = self.new_category("Sessions") try: for name in objreg.get('session-manager').list_sessions(): diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 4dc650396..f0889630d 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -39,8 +39,7 @@ class UrlCompletionModel(base.BaseCompletionModel): def __init__(self, parent=None): super().__init__(parent) - self.columns_to_highlight.append(0) - self.columns_to_highlight.append(1) + self.columns_to_filter = [0, 1] self._quickmark_cat = self.new_category("Quickmarks") self._bookmark_cat = self.new_category("Bookmarks") From aaa523ce7cce9993c52f53567e2c5a55120b4d74 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 17:41:32 +0200 Subject: [PATCH 33/47] Filter by cols_to_filter in CompletionFilterModel. --- qutebrowser/completion/models/sortfilter.py | 23 +++++++++++---------- qutebrowser/completion/models/urlmodel.py | 9 -------- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/qutebrowser/completion/models/sortfilter.py b/qutebrowser/completion/models/sortfilter.py index be9199153..3c247a0a2 100644 --- a/qutebrowser/completion/models/sortfilter.py +++ b/qutebrowser/completion/models/sortfilter.py @@ -130,22 +130,23 @@ class CompletionFilterModel(QSortFilterProxyModel): True if self.pattern is contained in item, or if it's a root item (category). False in all other cases """ - if parent == QModelIndex(): - return True - idx = self.srcmodel.index(row, 0, parent) - if not idx.isValid(): - # No entries in parent model - return False - data = self.srcmodel.data(idx) - if not self.pattern: + if parent == QModelIndex() or not self.pattern: return True try: return self.srcmodel.custom_filter(self.pattern, row, parent) except NotImplementedError: - if not data: - return False - return self.pattern.casefold() in data.casefold() + for col in self.srcmodel.columns_to_filter: + idx = self.srcmodel.index(row, col, parent) + if not idx.isValid(): + # No entries in parent model + continue + data = self.srcmodel.data(idx) + if not data: + continue + elif self.pattern.casefold() in data.casefold(): + return True + return False def intelligentLessThan(self, lindex, rindex): """Custom sorting implementation. diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index f0889630d..4ea640946 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -100,15 +100,6 @@ class UrlCompletionModel(base.BaseCompletionModel): """ self.new_item(self._bookmark_cat, url, title) - def custom_filter(self, pattern, row, parent): - """Filter by url and title.""" - index0 = self.index(row, 0, parent) - index1 = self.index(row, 1, parent) - url = self.data(index0) or '' - title = self.data(index1) or '' - return (pattern.casefold() in url.casefold() or pattern.casefold() in - title.casefold()) - @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): """Reformat the timestamps if the config option was changed.""" From 2d2779d6f3cbdbea31d6093e64efa3ef17b1763b Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 18:23:12 +0200 Subject: [PATCH 34/47] Clean up column handling in urlmodel. --- qutebrowser/completion/models/urlmodel.py | 31 +++++++++++++---------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 4ea640946..cb7640b1f 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -23,7 +23,7 @@ import datetime from PyQt5.QtCore import pyqtSlot, Qt -from qutebrowser.utils import message, objreg, utils +from qutebrowser.utils import message, objreg, utils, qtutils from qutebrowser.completion.models import base from qutebrowser.config import config @@ -36,10 +36,14 @@ class UrlCompletionModel(base.BaseCompletionModel): # pylint: disable=abstract-method + URL_COLUMN = 0 + TEXT_COLUMN = 1 + TIME_COLUMN = 2 + def __init__(self, parent=None): super().__init__(parent) - self.columns_to_filter = [0, 1] + self.columns_to_filter = [self.URL_COLUMN, self.TEXT_COLUMN] self._quickmark_cat = self.new_category("Quickmarks") self._bookmark_cat = self.new_category("Bookmarks") @@ -104,21 +108,21 @@ class UrlCompletionModel(base.BaseCompletionModel): def reformat_timestamps(self): """Reformat the timestamps if the config option was changed.""" for i in range(self._history_cat.rowCount()): - name_item = self._history_cat.child(i, 0) - atime_item = self._history_cat.child(i, 2) - atime = name_item.data(base.Role.sort) + url_item = self._history_cat.child(i, self.URL_COLUMN) + atime_item = self._history_cat.child(i, self.TIME_COLUMN) + atime = url_item.data(base.Role.sort) atime_item.setText(self._fmt_atime(atime)) @pyqtSlot(object) def on_history_item_added(self, entry): """Slot called when a new history item was added.""" for i in range(self._history_cat.rowCount()): - name_item = self._history_cat.child(i, 0) - atime_item = self._history_cat.child(i, 2) - url = name_item.data(base.Role.userdata) + url_item = self._history_cat.child(i, self.URL_COLUMN) + atime_item = self._history_cat.child(i, self.TIME_COLUMN) + url = url_item.data(base.Role.userdata) if url == entry.url: atime_item.setText(self._fmt_atime(entry.atime)) - name_item.setData(int(entry.atime), base.Role.sort) + url_item.setData(int(entry.atime), base.Role.sort) break else: self._add_history_entry(entry) @@ -141,7 +145,7 @@ class UrlCompletionModel(base.BaseCompletionModel): name: The name of the quickmark which has been removed. """ for i in range(self._quickmark_cat.rowCount()): - name_item = self._quickmark_cat.child(i, 1) + name_item = self._quickmark_cat.child(i, self.TEXT_COLUMN) if name_item.data(Qt.DisplayRole) == name: self._quickmark_cat.removeRow(i) break @@ -164,7 +168,7 @@ class UrlCompletionModel(base.BaseCompletionModel): url: The url of the bookmark which has been removed. """ for i in range(self._bookmark_cat.rowCount()): - url_item = self._bookmark_cat.child(i, 0) + url_item = self._bookmark_cat.child(i, self.URL_COLUMN) if url_item.data(Qt.DisplayRole) == url: self._bookmark_cat.removeRow(i) break @@ -188,7 +192,8 @@ class UrlCompletionModel(base.BaseCompletionModel): message.info(win_id, "Bookmarks deleted") elif category.data() == 'Quickmarks': quickmark_manager = objreg.get('quickmark-manager') - name = model.data(index.sibling(index.row(), - index.column() + 1)) + sibling = index.sibling(index.row(), self.NAME_COLUMN) + qtutils.ensure_valid(sibling) + name = model.data(sibling) quickmark_manager.quickmark_del(name) message.info(win_id, "Quickmarks deleted") From b5a9467b5c1cf239584611a91233d3aaa48e1529 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 18:35:49 +0200 Subject: [PATCH 35/47] Get rid of _add_*mark_entry in urlmodel. --- qutebrowser/completion/models/urlmodel.py | 48 +++-------------------- 1 file changed, 6 insertions(+), 42 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index cb7640b1f..cdc0c151c 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -52,15 +52,17 @@ class UrlCompletionModel(base.BaseCompletionModel): quickmark_manager = objreg.get('quickmark-manager') quickmarks = quickmark_manager.marks.items() for qm_name, qm_url in quickmarks: - self._add_quickmark_entry(qm_name, qm_url) - quickmark_manager.added.connect(self.on_quickmark_added) + self.new_item(self._quickmark_cat, qm_url, qm_name) + quickmark_manager.added.connect( + lambda name, url: self.new_item(self._quickmark_cat, url, name)) quickmark_manager.removed.connect(self.on_quickmark_removed) bookmark_manager = objreg.get('bookmark-manager') bookmarks = bookmark_manager.marks.items() for bm_url, bm_title in bookmarks: - self._add_bookmark_entry(bm_title, bm_url) - bookmark_manager.added.connect(self.on_bookmark_added) + self.new_item(self._bookmark_cat, bm_url, bm_title) + bookmark_manager.added.connect( + lambda name, url: self.new_item(self._bookmark_cat, url, name)) bookmark_manager.removed.connect(self.on_bookmark_removed) self._history = objreg.get('web-history') @@ -86,24 +88,6 @@ class UrlCompletionModel(base.BaseCompletionModel): self._fmt_atime(entry.atime), sort=int(entry.atime), userdata=entry.url) - def _add_quickmark_entry(self, name, url): - """Add a new quickmark entry to the completion. - - Args: - name: The name of the new quickmark. - url: The URL of the new quickmark. - """ - self.new_item(self._quickmark_cat, url, name) - - def _add_bookmark_entry(self, title, url): - """Add a new bookmark entry to the completion. - - Args: - title: The title of the new bookmark. - url: The URL of the new bookmark. - """ - self.new_item(self._bookmark_cat, url, title) - @config.change_filter('completion', 'timestamp-format') def reformat_timestamps(self): """Reformat the timestamps if the config option was changed.""" @@ -127,16 +111,6 @@ class UrlCompletionModel(base.BaseCompletionModel): else: self._add_history_entry(entry) - @pyqtSlot(str, str) - def on_quickmark_added(self, name, url): - """Called when a quickmark has been added by the user. - - Args: - name: The name of the new quickmark. - url: The url of the new quickmark, as string. - """ - self._add_quickmark_entry(name, url) - @pyqtSlot(str) def on_quickmark_removed(self, name): """Called when a quickmark has been removed by the user. @@ -150,16 +124,6 @@ class UrlCompletionModel(base.BaseCompletionModel): self._quickmark_cat.removeRow(i) break - @pyqtSlot(str, str) - def on_bookmark_added(self, title, url): - """Called when a bookmark has been added by the user. - - Args: - title: The title of the new bookmark. - url: The url of the new bookmark, as string. - """ - self._add_bookmark_entry(title, url) - @pyqtSlot(str) def on_bookmark_removed(self, url): """Called when a bookmark has been removed by the user. From 660b5531e5a125d28b0057d71a5f31bed47a22ec Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 18:43:01 +0200 Subject: [PATCH 36/47] Share code between on_{quick,book}mark_removed. --- qutebrowser/completion/models/urlmodel.py | 26 ++++++++++++++--------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index cdc0c151c..424584e6f 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -111,6 +111,20 @@ class UrlCompletionModel(base.BaseCompletionModel): else: self._add_history_entry(entry) + def _remove_item(self, data, category, column): + """Helper function for on_quickmark_removed and on_bookmark_removed. + + Args: + data: The item to search for. + category: The category to search in. + column: The column to use for matching. + """ + for i in range(category.rowCount()): + item = category.child(i, column) + if item.data(Qt.DisplayRole) == data: + category.removeRow(i) + break + @pyqtSlot(str) def on_quickmark_removed(self, name): """Called when a quickmark has been removed by the user. @@ -118,11 +132,7 @@ class UrlCompletionModel(base.BaseCompletionModel): Args: name: The name of the quickmark which has been removed. """ - for i in range(self._quickmark_cat.rowCount()): - name_item = self._quickmark_cat.child(i, self.TEXT_COLUMN) - if name_item.data(Qt.DisplayRole) == name: - self._quickmark_cat.removeRow(i) - break + self._remove_item(name, self._quickmark_cat, self.TEXT_COLUMN) @pyqtSlot(str) def on_bookmark_removed(self, url): @@ -131,11 +141,7 @@ class UrlCompletionModel(base.BaseCompletionModel): Args: url: The url of the bookmark which has been removed. """ - for i in range(self._bookmark_cat.rowCount()): - url_item = self._bookmark_cat.child(i, self.URL_COLUMN) - if url_item.data(Qt.DisplayRole) == url: - self._bookmark_cat.removeRow(i) - break + self._remove_item(url, self._bookmark_cat, self.URL_COLUMN) def delete_cur_item(self, win_id): """Delete the selected item. From ecf3e166ffec01f6300cd1aba2beafda9e553225 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 18:47:02 +0200 Subject: [PATCH 37/47] Fix wrong column attribute. --- qutebrowser/completion/models/urlmodel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 424584e6f..32bd810fd 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -162,7 +162,7 @@ class UrlCompletionModel(base.BaseCompletionModel): message.info(win_id, "Bookmarks deleted") elif category.data() == 'Quickmarks': quickmark_manager = objreg.get('quickmark-manager') - sibling = index.sibling(index.row(), self.NAME_COLUMN) + sibling = index.sibling(index.row(), self.TEXT_COLUMN) qtutils.ensure_valid(sibling) name = model.data(sibling) quickmark_manager.quickmark_del(name) From b962fff7f12ba98d4f93bf4d23760c70a5de4953 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 18:48:00 +0200 Subject: [PATCH 38/47] Don't show message when deleting items. --- qutebrowser/completion/completer.py | 4 +++- qutebrowser/completion/models/urlmodel.py | 10 +++------- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/qutebrowser/completion/completer.py b/qutebrowser/completion/completer.py index d1bc962f6..bc1a9daa0 100644 --- a/qutebrowser/completion/completer.py +++ b/qutebrowser/completion/completer.py @@ -486,7 +486,9 @@ class Completer(QObject): modes=[usertypes.KeyMode.command], scope='window') def completion_item_del(self): """Delete the current completion item.""" + completion = objreg.get('completion', scope='window', + window=self._win_id) try: - self.model().srcmodel.delete_cur_item(self._win_id) + self.model().srcmodel.delete_cur_item(completion) except NotImplementedError: raise cmdexc.CommandError("Cannot delete this item.") diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 32bd810fd..cf89d5d93 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -23,7 +23,7 @@ import datetime from PyQt5.QtCore import pyqtSlot, Qt -from qutebrowser.utils import message, objreg, utils, qtutils +from qutebrowser.utils import objreg, utils, qtutils from qutebrowser.completion.models import base from qutebrowser.config import config @@ -143,14 +143,12 @@ class UrlCompletionModel(base.BaseCompletionModel): """ self._remove_item(url, self._bookmark_cat, self.URL_COLUMN) - def delete_cur_item(self, win_id): + def delete_cur_item(self, completion): """Delete the selected item. Args: - win_id: The current windows id. + completion: The Completion object to use. """ - completion = objreg.get('completion', scope='window', - window=win_id) index = completion.currentIndex() model = completion.model() url = model.data(index) @@ -159,11 +157,9 @@ class UrlCompletionModel(base.BaseCompletionModel): if category.data() == 'Bookmarks': bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.delete(url) - message.info(win_id, "Bookmarks deleted") elif category.data() == 'Quickmarks': quickmark_manager = objreg.get('quickmark-manager') sibling = index.sibling(index.row(), self.TEXT_COLUMN) qtutils.ensure_valid(sibling) name = model.data(sibling) quickmark_manager.quickmark_del(name) - message.info(win_id, "Quickmarks deleted") From 0acd1b8dc8aa0203776fe26312d0ce0e1ed2962b Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 18:52:15 +0200 Subject: [PATCH 39/47] Use urlutils.fuzzy_url for loading bookmarks. --- qutebrowser/browser/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index a14dd6d90..8b863743d 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -1076,7 +1076,7 @@ class CommandDispatcher: bg: Load the bookmark in a new background tab. window: Load the bookmark in a new window. """ - self._open(QUrl(url), tab, bg, window) + self._open(urlutils.fuzzy_url(url), tab, bg, window) @cmdutils.register(instance='command-dispatcher', hide=True, scope='window') From 093b3cba254cac46066fc2577796689af3b7c1e9 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 26 Jul 2015 21:05:32 +0200 Subject: [PATCH 40/47] Add a bookmark-del command. --- qutebrowser/browser/urlmarks.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/qutebrowser/browser/urlmarks.py b/qutebrowser/browser/urlmarks.py index c36f6bed8..e83732c6b 100644 --- a/qutebrowser/browser/urlmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -255,3 +255,16 @@ class BookmarkManager(UrlMarkManager): self.changed.emit() self.added.emit(title, urlstr) message.info(win_id, "Bookmark added") + + @cmdutils.register(instance='bookmark-manager', maxsplit=0, + completion=[usertypes.Completion.bookmark_by_url]) + def bookmark_del(self, url): + """Delete a bookmark. + + Args: + url: The URL of the bookmark to delete. + """ + try: + self.delete(url) + except KeyError: + raise cmdexc.CommandError("Bookmark '{}' not found!".format(url)) From c016e8a4cf293df17fc6ca3ed7e6a046bf86ba1f Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 12:34:53 +0200 Subject: [PATCH 41/47] Improve error handling for quick-/bookmarks. --- qutebrowser/browser/commands.py | 19 +++++++++---- qutebrowser/browser/urlmarks.py | 48 +++++++++++++++++++++++++-------- 2 files changed, 51 insertions(+), 16 deletions(-) diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 8b863743d..dfbb0592b 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -38,7 +38,7 @@ import pygments.formatters from qutebrowser.commands import userscripts, cmdexc, cmdutils, runners from qutebrowser.config import config, configexc -from qutebrowser.browser import webelem, inspector +from qutebrowser.browser import webelem, inspector, urlmarks from qutebrowser.keyinput import modeman from qutebrowser.utils import (message, usertypes, log, qtutils, urlutils, objreg, utils) @@ -1054,15 +1054,20 @@ class CommandDispatcher: bg: Load the quickmark in a new background tab. window: Load the quickmark in a new window. """ - url = objreg.get('quickmark-manager').get(name) + try: + url = objreg.get('quickmark-manager').get(name) + except urlmarks.Error as e: + raise cmdexc.CommandError(str(e)) self._open(url, tab, bg, window) @cmdutils.register(instance='command-dispatcher', scope='window') def bookmark_add(self): """Save the current page as a bookmark.""" bookmark_manager = objreg.get('bookmark-manager') - bookmark_manager.add(self._win_id, self._current_url(), - self._current_title()) + try: + bookmark_manager.add(self._current_url(), self._current_title()) + except urlmarks.Error as e: + raise cmdexc.CommandError(str(e)) @cmdutils.register(instance='command-dispatcher', scope='window', maxsplit=0, @@ -1076,7 +1081,11 @@ class CommandDispatcher: bg: Load the bookmark in a new background tab. window: Load the bookmark in a new window. """ - self._open(urlutils.fuzzy_url(url), tab, bg, window) + try: + url = urlutils.fuzzy_url(url) + except urlutils.FuzzyUrlError as e: + raise cmdexc.CommandError(e) + self._open(url, tab, bg, window) @cmdutils.register(instance='command-dispatcher', hide=True, scope='window') diff --git a/qutebrowser/browser/urlmarks.py b/qutebrowser/browser/urlmarks.py index e83732c6b..735f05e13 100644 --- a/qutebrowser/browser/urlmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -37,6 +37,34 @@ from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.misc import lineparser +class Error(Exception): + + """Base class for all errors in this module.""" + + pass + + +class InvalidUrlError(Error): + + """Exception emitted when a URL is invalid.""" + + pass + + +class DoesNotExistError(Error): + + """Exception emitted when a given URL does not exist.""" + + pass + + +class AlreadyExistsError(Error): + + """Exception emitted when a given URL does already exist.""" + + pass + + class UrlMarkManager(QObject): """Base class for BookmarkManager and QuickmarkManager. @@ -192,18 +220,14 @@ class QuickmarkManager(UrlMarkManager): def get(self, name): """Get the URL of the quickmark named name as a QUrl.""" if name not in self.marks: - raise cmdexc.CommandError( + raise DoesNotExistError( "Quickmark '{}' does not exist!".format(name)) urlstr = self.marks[name] try: url = urlutils.fuzzy_url(urlstr, do_search=False) except urlutils.FuzzyUrlError as e: - if e.url is None or not e.url.errorString(): - errstr = '' - else: - errstr = ' ({})'.format(e.url.errorString()) - raise cmdexc.CommandError("Invalid URL for quickmark {}: " - "{}{}".format(name, urlstr, errstr)) + raise InvalidUrlError( + "Invalid URL for quickmark {}: {}".format(name, str(e))) return url @@ -238,23 +262,25 @@ class BookmarkManager(UrlMarkManager): elif len(parts) == 1: self.marks[parts[0]] = '' - def add(self, win_id, url, title): + def add(self, url, title): """Add a new bookmark. Args: - win_id: The window ID to display the errors in. url: The url to add as bookmark. title: The title for the new bookmark. """ + if not url.isValid(): + errstr = urlutils.get_errstring(url) + raise InvalidUrlError(errstr) + urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) if urlstr in self.marks: - message.error(win_id, "Bookmark already exists!") + raise AlreadyExistsError("Bookmark already exists!") else: self.marks[urlstr] = title self.changed.emit() self.added.emit(title, urlstr) - message.info(win_id, "Bookmark added") @cmdutils.register(instance='bookmark-manager', maxsplit=0, completion=[usertypes.Completion.bookmark_by_url]) From 69ade32cb956d490cbcbc0a61d26059d272288d2 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 12:35:43 +0200 Subject: [PATCH 42/47] Get rid of quickmark_by_name completion. --- qutebrowser/completion/models/instances.py | 9 ++------- qutebrowser/completion/models/miscmodels.py | 13 +++---------- qutebrowser/utils/usertypes.py | 5 ++--- 3 files changed, 7 insertions(+), 20 deletions(-) diff --git a/qutebrowser/completion/models/instances.py b/qutebrowser/completion/models/instances.py index f8e89137c..ad2ae4ff6 100644 --- a/qutebrowser/completion/models/instances.py +++ b/qutebrowser/completion/models/instances.py @@ -97,13 +97,10 @@ def init_quickmark_completions(): """Initialize quickmark completion models.""" log.completion.debug("Initializing quickmark completion.") try: - _instances[usertypes.Completion.quickmark_by_url].deleteLater() _instances[usertypes.Completion.quickmark_by_name].deleteLater() except KeyError: pass - model = _init_model(miscmodels.QuickmarkCompletionModel, 'url') - _instances[usertypes.Completion.quickmark_by_url] = model - model = _init_model(miscmodels.QuickmarkCompletionModel, 'name') + model = _init_model(miscmodels.QuickmarkCompletionModel) _instances[usertypes.Completion.quickmark_by_name] = model @@ -138,7 +135,6 @@ INITIALIZERS = { usertypes.Completion.section: _init_setting_completions, usertypes.Completion.option: _init_setting_completions, usertypes.Completion.value: _init_setting_completions, - usertypes.Completion.quickmark_by_url: init_quickmark_completions, usertypes.Completion.quickmark_by_name: init_quickmark_completions, usertypes.Completion.bookmark_by_url: init_bookmark_completions, usertypes.Completion.sessions: init_session_completion, @@ -176,8 +172,7 @@ def init(): """Initialize completions. Note this only connects signals.""" quickmark_manager = objreg.get('quickmark-manager') quickmark_manager.changed.connect( - functools.partial(update, [usertypes.Completion.quickmark_by_url, - usertypes.Completion.quickmark_by_name])) + functools.partial(update, [usertypes.Completion.quickmark_by_name])) bookmark_manager = objreg.get('bookmark-manager') bookmark_manager.changed.connect( diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index 8fe3a71be..004254152 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -96,19 +96,12 @@ class QuickmarkCompletionModel(base.BaseCompletionModel): # pylint: disable=abstract-method - def __init__(self, match_field='url', parent=None): + def __init__(self, parent=None): super().__init__(parent) cat = self.new_category("Quickmarks") quickmarks = objreg.get('quickmark-manager').marks.items() - if match_field == 'url': - for qm_name, qm_url in quickmarks: - self.new_item(cat, qm_url, qm_name) - elif match_field == 'name': - for qm_name, qm_url in quickmarks: - self.new_item(cat, qm_name, qm_url) - else: - raise ValueError("Invalid value '{}' for match_field!".format( - match_field)) + for qm_name, qm_url in quickmarks: + self.new_item(cat, qm_name, qm_url) class BookmarkCompletionModel(base.BaseCompletionModel): diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index 467e82633..42ce0b93a 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -236,9 +236,8 @@ KeyMode = enum('KeyMode', ['normal', 'hint', 'command', 'yesno', 'prompt', # Available command completions Completion = enum('Completion', ['command', 'section', 'option', 'value', - 'helptopic', 'quickmark_by_url', - 'quickmark_by_name', 'bookmark_by_url', - 'url', 'sessions']) + 'helptopic', 'quickmark_by_name', + 'bookmark_by_url', 'url', 'sessions']) # Exit statuses for errors. Needs to be an int for sys.exit. From 08fe1d59e61f7137ff139472938396c2da18d242 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 12:36:45 +0200 Subject: [PATCH 43/47] Get rid of bookmark_by_title completion. --- qutebrowser/completion/models/instances.py | 2 +- qutebrowser/completion/models/miscmodels.py | 13 +++---------- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/qutebrowser/completion/models/instances.py b/qutebrowser/completion/models/instances.py index ad2ae4ff6..0fc683488 100644 --- a/qutebrowser/completion/models/instances.py +++ b/qutebrowser/completion/models/instances.py @@ -112,7 +112,7 @@ def init_bookmark_completions(): _instances[usertypes.Completion.bookmark_by_url].deleteLater() except KeyError: pass - model = _init_model(miscmodels.BookmarkCompletionModel, 'url') + model = _init_model(miscmodels.BookmarkCompletionModel) _instances[usertypes.Completion.bookmark_by_url] = model diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index 004254152..2a1d9cfef 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -110,19 +110,12 @@ class BookmarkCompletionModel(base.BaseCompletionModel): # pylint: disable=abstract-method - def __init__(self, match_field='url', parent=None): + def __init__(self, parent=None): super().__init__(parent) cat = self.new_category("Bookmarks") bookmarks = objreg.get('bookmark-manager').marks.items() - if match_field == 'url': - for bm_url, bm_title in bookmarks: - self.new_item(cat, bm_url, bm_title) - elif match_field == 'title': - for bm_url, bm_title in bookmarks: - self.new_item(cat, bm_title, bm_url) - else: - raise ValueError("Invalid value '{}' for match_field!".format( - match_field)) + for bm_url, bm_title in bookmarks: + self.new_item(cat, bm_url, bm_title) class SessionCompletionModel(base.BaseCompletionModel): From d9d68db5dfd0329864d1296e93dd444c503d3501 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 12:44:38 +0200 Subject: [PATCH 44/47] Simplify delete_cur_item for UrlCompletionModel. --- qutebrowser/completion/models/urlmodel.py | 25 ++++++++++++----------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index cf89d5d93..702f9458e 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -150,16 +150,17 @@ class UrlCompletionModel(base.BaseCompletionModel): completion: The Completion object to use. """ index = completion.currentIndex() - model = completion.model() - url = model.data(index) + qtutils.ensure_valid(index) + url = index.data() category = index.parent() - if category.isValid(): - if category.data() == 'Bookmarks': - bookmark_manager = objreg.get('bookmark-manager') - bookmark_manager.delete(url) - elif category.data() == 'Quickmarks': - quickmark_manager = objreg.get('quickmark-manager') - sibling = index.sibling(index.row(), self.TEXT_COLUMN) - qtutils.ensure_valid(sibling) - name = model.data(sibling) - quickmark_manager.quickmark_del(name) + qtutils.ensure_valid(category) + + if category.data() == 'Bookmarks': + bookmark_manager = objreg.get('bookmark-manager') + bookmark_manager.delete(url) + elif category.data() == 'Quickmarks': + quickmark_manager = objreg.get('quickmark-manager') + sibling = index.sibling(index.row(), self.TEXT_COLUMN) + qtutils.ensure_valid(sibling) + name = model.data(sibling) + quickmark_manager.quickmark_del(name) From 6c5d1c96d2964c1164980d2037a1e3dcf20d3615 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 12:46:33 +0200 Subject: [PATCH 45/47] Regenerate docs. --- README.asciidoc | 2 +- doc/help/commands.asciidoc | 43 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index 2c11d315c..fc8eeb196 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -135,6 +135,7 @@ Contributors, sorted by the number of commits in descending order: // QUTE_AUTHORS_START * Florian Bruhin * Bruno Oliveira +* Antoni Boucher * Raphael Pierzina * Joel Torstensson * Martin Tournoij @@ -142,7 +143,6 @@ Contributors, sorted by the number of commits in descending order: * Lamar Pavel * Austin Anderson * Artur Shaik -* Antoni Boucher * ZDarian * Peter Vilim * John ShaggyTwoDope Jenkins diff --git a/doc/help/commands.asciidoc b/doc/help/commands.asciidoc index f12b3ba99..a898b9698 100644 --- a/doc/help/commands.asciidoc +++ b/doc/help/commands.asciidoc @@ -8,6 +8,9 @@ |<>|Update the adblock block lists. |<>|Go back in the history of the current tab. |<>|Bind a key to a command. +|<>|Save the current page as a bookmark. +|<>|Delete a bookmark. +|<>|Load a bookmark. |<>|Close the current window. |<>|Download a given URL, or current page if no URL given. |<>|Cancel the last/[count]th download. @@ -99,6 +102,41 @@ Bind a key to a command. * This command does not split arguments after the last argument and handles quotes literally. * With this command, +;;+ is interpreted literally instead of splitting off a second command. +[[bookmark-add]] +=== bookmark-add +Save the current page as a bookmark. + +[[bookmark-del]] +=== bookmark-del +Syntax: +:bookmark-del 'url'+ + +Delete a bookmark. + +==== positional arguments +* +'url'+: The URL of the bookmark to delete. + +==== note +* This command does not split arguments after the last argument and handles quotes literally. +* With this command, +;;+ is interpreted literally instead of splitting off a second command. + +[[bookmark-load]] +=== bookmark-load +Syntax: +:bookmark-load [*--tab*] [*--bg*] [*--window*] 'url'+ + +Load a bookmark. + +==== positional arguments +* +'url'+: The url of the bookmark to load. + +==== optional arguments +* +*-t*+, +*--tab*+: Load the bookmark in a new tab. +* +*-b*+, +*--bg*+: Load the bookmark in a new background tab. +* +*-w*+, +*--window*+: Load the bookmark in a new window. + +==== note +* This command does not split arguments after the last argument and handles quotes literally. +* With this command, +;;+ is interpreted literally instead of splitting off a second command. + [[close]] === close Close the current window. @@ -724,6 +762,7 @@ How many steps to zoom out. |<>|Execute the command currently in the commandline. |<>|Go forward in the commandline history. |<>|Go back in the commandline history. +|<>|Delete the current completion item. |<>|Select the next completion item. |<>|Select the previous completion item. |<>|Drop selection and keep selection mode enabled. @@ -790,6 +829,10 @@ Go forward in the commandline history. === command-history-prev Go back in the commandline history. +[[completion-item-del]] +=== completion-item-del +Delete the current completion item. + [[completion-item-next]] === completion-item-next Select the next completion item. From 8f2a4fc0c47436b170a07d64b648139438acbb2b Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 12:49:30 +0200 Subject: [PATCH 46/47] Update changelog. --- CHANGELOG.asciidoc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.asciidoc b/CHANGELOG.asciidoc index d1c7dc291..006241695 100644 --- a/CHANGELOG.asciidoc +++ b/CHANGELOG.asciidoc @@ -25,6 +25,12 @@ Changed this might cause qutebrowser to hang. - The `:yank-selected` command now works in all modes instead of just caret mode and is not hidden anymore. +- New bookmark functionality (similar to quickmarks without a name). + * New command `:bookmark-add` to bookmark the current page (bound to `M`). + * New command `:bookmark-load` to load a bookmark (bound to `gb`/`gB`/`wB`). +- New (hidden) command `:completion-item-del` (bound to ``) to delete + the current item in the completion (for quickmarks/bookmarks). + v0.3.0 ------ From 57e79db136ec68bbfd32db449d47425f32a1ff5d Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 29 Jul 2015 15:04:07 +0200 Subject: [PATCH 47/47] Fix undefined name error. --- qutebrowser/completion/models/urlmodel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 702f9458e..03f55e3ac 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -162,5 +162,5 @@ class UrlCompletionModel(base.BaseCompletionModel): quickmark_manager = objreg.get('quickmark-manager') sibling = index.sibling(index.row(), self.TEXT_COLUMN) qtutils.ensure_valid(sibling) - name = model.data(sibling) + name = sibling.data() quickmark_manager.quickmark_del(name)