Add a signal plugins can connect to to be notified of db events

This commit is contained in:
Kovid Goyal 2021-08-10 12:30:26 +05:30
parent d3681ca528
commit 3f64519587
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 33 additions and 1 deletions

View File

@ -110,6 +110,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{
proceed_requested = pyqtSignal(object, object)
book_converted = pyqtSignal(object, object)
enter_key_pressed_in_book_list = pyqtSignal(object) # used by action chains plugin
event_in_db = pyqtSignal(object, object, object)
shutting_down = False
def __init__(self, opts, parent=None, gui_debug=None):
@ -200,6 +201,13 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{
else:
stmap[st.name] = st
def add_db_listener(self, callback):
self.library_broker.start_listening_for_db_events()
self.event_in_db.connect(callback)
def remove_db_listener(self, callback):
self.event_in_db.disconnect(callback)
def initialize(self, library_path, db, actions, show_gui=True):
opts = self.opts
self.preferences_action, self.quit_action = actions
@ -1103,6 +1111,10 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{
self.shutting_down = True
self.show_shutdown_message()
self.server_change_notification_timer.stop()
try:
self.event_in_db.disconnect()
except Exception:
pass
from calibre.customize.ui import has_library_closed_plugins
if has_library_closed_plugins():

View File

@ -201,12 +201,16 @@ class GuiLibraryBroker(LibraryBroker):
from calibre.gui2 import gprefs
self.last_used_times = defaultdict(lambda: -EXPIRED_AGE)
self.gui_library_id = None
self.listening_for_db_events = False
LibraryBroker.__init__(self, load_gui_libraries(gprefs))
self.gui_library_changed(db)
def init_library(self, library_path, is_default_library):
library_path = self.original_path_map.get(library_path, library_path)
return LibraryDatabase(library_path, is_second_db=True)
db = LibraryDatabase(library_path, is_second_db=True)
if self.listening_for_db_events:
db.add_listener(self.on_db_event)
return db
def get(self, library_id=None):
try:
@ -214,6 +218,22 @@ class GuiLibraryBroker(LibraryBroker):
finally:
self.last_used_times[library_id or self.default_library] = monotonic()
def start_listening_for_db_events(self):
with self:
self.listening_for_db_events = True
for db in self.loaded_dbs:
db.new_api.add_listener(self.on_db_event)
def on_db_event(self, event_type, library_id, event_data):
from calibre.gui2.ui import get_gui
gui = get_gui()
if gui is not None:
db = LibraryBroker.get(self, library_id)
with self:
db = self.loaded_dbs.get(library_id)
if db is not None:
gui.event_in_db.emit(db, event_type, event_data)
def get_library(self, original_library_path):
library_path = canonicalize_path(original_library_path)
with self: