Debian Codegraph @

src/calibre/gui2/notify.py

raw
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2009, Kovid Goyal <[email protected]>
3
4 import sys
5 from contextlib import suppress
6 from functools import lru_cache
7
8 from calibre.constants import DEBUG, MAIN_APP_UID, __appname__, get_osx_version, islinux, ismacos, iswindows
9 from calibre.utils.resources import get_image_path as I
10
11
12 class Notifier:
13 DEFAULT_TIMEOUT = 5000
14
15 def get_msg_parms(self, timeout, body, summary):
16 if summary is None:
17 summary = 'calibre'
18 if timeout == 0:
19 timeout = self.DEFAULT_TIMEOUT
20 return timeout, body, summary
21
22 def __call__(self, body, summary=None, replaces_id=None, timeout=0):
23 raise NotImplementedError('implement in subclass')
24
25
26 @lru_cache(maxsize=2)
27 def icon(data=False):
28 return I('lt.png', data=data)
29
30
31 class DBUSNotifier(Notifier):
32 def __init__(self):
33 self.initialized = False
34
35 def initialize(self):
36 from jeepney.io.blocking import open_dbus_connection
37
38 if self.initialized:
39 return
40 self.initialized = True
41 self.ok = False
42 try:
43 self.connection = open_dbus_connection(bus='SESSION')
44 except Exception:
45 return
46 with suppress(Exception):
47 self.ok = self.initialize_fdo()
48 if self.ok:
49 self.notify = self.fdo_notify
50 return
51 if DEBUG:
52 print('Failed to connect to FDO Notifications service', file=sys.stderr)
53 with suppress(Exception):
54 self.ok = self.initialize_portal()
55 if self.ok:
56 self.notify = self.portal_notify
57 else:
58 print('Failed to connect to Portal Notifications service', file=sys.stderr)
59
60 def initialize_fdo(self):
61 from jeepney import DBusAddress, MessageType, new_method_call
62
63 self.address = DBusAddress(
64 '/org/freedesktop/Notifications',
65 bus_name='org.freedesktop.Notifications',
66 interface='org.freedesktop.Notifications',
67 )
68
69 msg = new_method_call(self.address, 'GetCapabilities')
70 reply = self.connection.send_and_get_reply(msg)
71 return bool(reply and reply.header.message_type is MessageType.method_return)
72
73 def initialize_portal(self):
74 from jeepney import DBusAddress, MessageType, Properties
75
76 self.address = DBusAddress(
77 '/org/freedesktop/portal/desktop',
78 bus_name='org.freedesktop.portal.Desktop',
79 interface='org.freedesktop.portal.Notification',
80 )
81 p = Properties(self.address)
82 msg = p.get('version')
83 reply = self.connection.send_and_get_reply(msg)
84 return bool(reply and reply.header.message_type is MessageType.method_return and reply.body[0][1] >= 1)
85
86 def fdo_notify(self, body, summary=None, replaces_id=None, timeout=0):
87 from jeepney import new_method_call
88
89 timeout, body, summary = self.get_msg_parms(timeout, body, summary)
90 msg = new_method_call(
91 self.address,
92 'Notify',
93 'susssasa{sv}i',
94 (
95 __appname__,
96 replaces_id or 0,
97 icon(),
98 summary,
99 body,
100 [],
101 {}, # Actions, hints
102 timeout,
103 ),
104 )
105 try:
106 self.connection.send(msg)
107 except Exception:
108 import traceback
109
110 traceback.print_exc()
111
112 def portal_notify(self, body, summary=None, replaces_id=None, timeout=0):
113 from jeepney import new_method_call
114
115 _, body, summary = self.get_msg_parms(timeout, body, summary)
116 # Note: This backend does not natively support the notion of timeouts
117 #
118 # While the effect may be emulated by manually withdrawing the notifi-
119 # cation from the Calibre side, this resulted in a less than optimal
120 # User Experience. Based on this, KG decided it to be better to not
121 # support timeouts at all for this backend.
122 #
123 # See discussion at https://github.com/kovidgoyal/calibre/pull/1268.
124
125 # For the icon: This should instead just send the themable icon name
126 #
127 # Doing that however, requires Calibre to first be converted to use
128 # its AppID everywhere and then we still need a fallback for portable
129 # installations.
130 msg = new_method_call(
131 self.address,
132 'AddNotification',
133 'sa{sv}',
134 (
135 str(replaces_id or 0),
136 {
137 'title': ('s', summary),
138 'body': ('s', body),
139 'icon': ('(sv)', ('bytes', ('ay', icon(data=True)))),
140 },
141 ),
142 )
143 try:
144 self.connection.send(msg)
145 except Exception:
146 import traceback
147
148 traceback.print_exc()
149
150 def __call__(self, body, summary=None, replaces_id=None, timeout=0):
151 self.initialize()
152 if not self.ok:
153 if DEBUG:
154 print('Failed to connect to any notification service', file=sys.stderr)
155 return
156 self.notify(body, summary, replaces_id, timeout)
157
158
159 class QtNotifier(Notifier):
160 def __init__(self, systray=None):
161 self.systray = systray
162 self.ok = self.systray is not None and self.systray.supportsMessages()
163
164 def __call__(self, body, summary=None, replaces_id=None, timeout=0):
165 timeout, body, summary = self.get_msg_parms(timeout, body, summary)
166 from qt.core import QSystemTrayIcon
167
168 if self.systray is not None:
169 try:
170 hide = False
171 try:
172 if not isinstance(body, str):
173 body = body.decode('utf-8')
174 if ismacos and not self.systray.isVisible():
175 self.systray.show()
176 hide = True
177 self.systray.showMessage(summary, body, QSystemTrayIcon.MessageIcon.Information, timeout)
178 finally:
179 if hide:
180 self.systray.hide()
181 except Exception:
182 pass
183
184
185 class WinToastNotifier(Notifier):
186 def __init__(self):
187 try:
188 from calibre_extensions.wintoast import initialize_toast
189 except ImportError:
190 self.ok = False
191 else:
192 from qt.core import QApplication
193
194 app = QApplication.instance()
195 auid = getattr(app, 'windows_app_uid', MAIN_APP_UID)
196 appname = __appname__
197 if app is not None:
198 appname = app.applicationName() or appname
199 try:
200 initialize_toast(appname, auid)
201 except Exception as err:
202 self.ok = False
203 print('Failed to initialize_toast with error:', err, file=sys.stderr)
204 else:
205 self.ok = True
206 from qt.core import QObject, Qt, pyqtSignal
207
208 class dispatcher(QObject):
209 dispatch = pyqtSignal(str, str)
210
211 self.dispatcher = dispatcher()
212 self.dispatcher.dispatch.connect(self.do_notify, type=Qt.ConnectionType.QueuedConnection)
213
214 def do_notify(self, title, message):
215 from calibre_extensions.wintoast import notify
216
217 try:
218 notify(title, message, icon())
219 except Exception as err:
220 print('Failed to send toast notification with error:', err, file=sys.stderr)
221
222 def __call__(self, body, summary=None, replaces_id=None, timeout=0):
223 timeout, body, summary = self.get_msg_parms(timeout, body, summary)
224 if summary:
225 title, message = summary, body
226 else:
227 title, message = '', body
228 self.dispatcher.dispatch.emit(title, message)
229
230
231 class DummyNotifier(Notifier):
232 ok = True
233
234 def __call__(self, body, summary=None, replaces_id=None, timeout=0):
235 pass
236
237
238 class AppleNotifier(Notifier):
239 def __init__(self):
240 from calibre_extensions import cocoa
241
242 self.cocoa = cocoa
243 self.ok = True
244
245 def notify(self, body, summary):
246 if summary:
247 title, informative_text = summary, body
248 else:
249 title, informative_text = body, None
250 self.cocoa.send_notification(None, title, informative_text)
251
252 def __call__(self, body, summary=None, replaces_id=None, timeout=0):
253 timeout, body, summary = self.get_msg_parms(timeout, body, summary)
254 if self.ok:
255 try:
256 self.notify(body, summary)
257 except Exception:
258 import traceback
259
260 traceback.print_exc()
261
262
263 def get_notifier(systray=None):
264 ans = None
265 if islinux:
266 ans = DBUSNotifier()
267 elif ismacos:
268 if get_osx_version() >= (10, 8, 0):
269 ans = AppleNotifier()
270 if not ans.ok:
271 ans = DummyNotifier()
272 else:
273 # We don't use Qt's systray based notifier as it uses Growl and is
274 # broken with different versions of Growl
275 ans = DummyNotifier()
276 elif iswindows:
277 ans = WinToastNotifier()
278 if not ans.ok:
279 ans = None
280 if ans is None:
281 ans = QtNotifier(systray)
282 if not ans.ok:
283 ans = None
284 return ans
285
286
287 def hello():
288 n = get_notifier()
289 n('hello')
290
291
292 def develop_win():
293 from calibre_extensions.wintoast import initialize_toast, notify
294
295 initialize_toast(__appname__, MAIN_APP_UID)
296 notify('calibre notification', 'hello world', icon())
297
298
299 if __name__ == '__main__':
300 hello()