1#!/usr/local/bin/python3.8
2# vim:fileencoding=utf-8
3# License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
4
5
6from qt.core import Qt
7
8from calibre.gui2 import error_dialog
9from calibre.gui2.actions import InterfaceAction
10
11
12class BrowseAnnotationsAction(InterfaceAction):
13
14    name = 'Browse Annotations'
15    action_spec = (_('Browse annotations'), 'highlight.png',
16                   _('Browse highlights and bookmarks from all books in the library'), _('B'))
17    dont_add_to = frozenset(('context-menu-device',))
18    action_type = 'current'
19
20    def genesis(self):
21        self.qaction.triggered.connect(self.show_browser)
22        self._browser = None
23
24    @property
25    def browser(self):
26        if self._browser is None:
27            from calibre.gui2.library.annotations import AnnotationsBrowser
28            self.gui.library_view.selection_changed.connect(self.selection_changed)
29            self._browser = AnnotationsBrowser(self.gui)
30            self._browser.show_book.connect(self.open_book, type=Qt.ConnectionType.QueuedConnection)
31            self._browser.open_annotation.connect(self.open_annotation, type=Qt.ConnectionType.QueuedConnection)
32        return self._browser
33
34    def show_browser(self):
35        self.browser.show_dialog(self.gui.library_view.get_selected_ids(as_set=True))
36
37    def library_changed(self, db):
38        if self._browser is not None:
39            self._browser.reinitialize()
40
41    def selection_changed(self):
42        if self._browser is not None:
43            self._browser.selection_changed()
44
45    def open_book(self, book_id, fmt):
46        if not self.gui.library_view.select_rows({book_id}):
47            db = self.gui.current_db.new_api
48            title = db.field_for('title', book_id)
49            return error_dialog(self._browser or self.gui, _('Not visible'), _(
50                'The book "{}" is not currently visible in the calibre library.'
51                ' If you have a search or a Virtual library applied, first clear'
52                ' it.').format(title), show=True)
53
54    def open_annotation(self, book_id, fmt, cfi):
55        self.gui.iactions['View'].view_format_by_id(book_id, fmt, open_at=cfi)
56