desktop-notifier 3.5.7.dev0__tar.gz → 4.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {desktop_notifier-3.5.7.dev0/src/desktop_notifier.egg-info → desktop_notifier-4.0.0}/PKG-INFO +2 -1
  2. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/pyproject.toml +5 -1
  3. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/__init__.py +1 -1
  4. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/base.py +7 -14
  5. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/dbus.py +44 -26
  6. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/macos.py +4 -7
  7. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/macos_support.py +0 -13
  8. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/main.py +6 -23
  9. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/winrt.py +3 -3
  10. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0/src/desktop_notifier.egg-info}/PKG-INFO +2 -1
  11. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier.egg-info/SOURCES.txt +2 -2
  12. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier.egg-info/requires.txt +1 -0
  13. desktop_notifier-4.0.0/tests/test_api.py +94 -0
  14. desktop_notifier-3.5.7.dev0/src/desktop_notifier/macos_legacy.py +0 -166
  15. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/LICENSE +0 -0
  16. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/README.md +0 -0
  17. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/setup.cfg +0 -0
  18. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/dummy.py +0 -0
  19. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/py.typed +0 -0
  20. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/resources/__init__.py +0 -0
  21. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier/resources/python.png +0 -0
  22. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier.egg-info/dependency_links.txt +0 -0
  23. {desktop_notifier-3.5.7.dev0 → desktop_notifier-4.0.0}/src/desktop_notifier.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: desktop-notifier
3
- Version: 3.5.7.dev0
3
+ Version: 4.0.0
4
4
  Summary: Python library for cross-platform desktop notifications
5
5
  Author-email: Sam Schott <sam.schott@outlook.com>
6
6
  License: MIT
@@ -36,6 +36,7 @@ Requires-Dist: flake8; extra == "dev"
36
36
  Requires-Dist: flake8-pyproject; extra == "dev"
37
37
  Requires-Dist: mypy; extra == "dev"
38
38
  Requires-Dist: pytest; extra == "dev"
39
+ Requires-Dist: pytest-asyncio; extra == "dev"
39
40
  Requires-Dist: pytest-cov; extra == "dev"
40
41
  Provides-Extra: docs
41
42
  Requires-Dist: furo==2024.4.27; extra == "docs"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "desktop-notifier"
7
- version = "3.5.7.dev0"
7
+ version = "4.0.0"
8
8
  authors = [{name = "Sam Schott", email = "sam.schott@outlook.com"}]
9
9
  license = {text = "MIT"}
10
10
  description = "Python library for cross-platform desktop notifications"
@@ -50,6 +50,7 @@ dev = [
50
50
  "flake8-pyproject",
51
51
  "mypy",
52
52
  "pytest",
53
+ "pytest-asyncio",
53
54
  "pytest-cov",
54
55
  ]
55
56
  docs = [
@@ -69,7 +70,10 @@ __init__.py: F401"""
69
70
  statistics = "True"
70
71
 
71
72
  [tool.mypy]
73
+ # Imports are not available on all platforms.
72
74
  ignore_missing_imports = true
75
+ # On platforms where imports are not available, ignores may be unused.
76
+ warn_unused_ignores = false
73
77
  strict = true
74
78
  files = ["src"]
75
79
 
@@ -2,7 +2,7 @@
2
2
  from .main import DesktopNotifier, Button, ReplyField, Notification, Urgency
3
3
 
4
4
 
5
- __version__ = "3.5.7.dev0"
5
+ __version__ = "4.0.0"
6
6
  __author__ = "Sam Schott"
7
7
  __url__ = "https://github.com/samschott/desktop-notifier"
8
8
 
@@ -8,7 +8,6 @@ from __future__ import annotations
8
8
 
9
9
  # system imports
10
10
  import logging
11
- import platform
12
11
  from enum import Enum
13
12
  from collections import deque
14
13
  from pathlib import Path
@@ -137,6 +136,7 @@ class Notification:
137
136
  thread: str | None = None,
138
137
  timeout: int = -1,
139
138
  ) -> None:
139
+ self._identifier = ""
140
140
  self._winrt_identifier = ""
141
141
  self._macos_identifier = ""
142
142
  self._dbus_identifier = 0
@@ -156,17 +156,11 @@ class Notification:
156
156
 
157
157
  @property
158
158
  def identifier(self) -> str:
159
- if platform.system() == "Darwin":
160
- return self._macos_identifier
161
- elif platform.system() == "Linux":
162
- if self._dbus_identifier == 0:
163
- return ""
164
- else:
165
- return str(self._dbus_identifier)
166
- elif platform.system() == "Windows":
167
- return self._winrt_identifier
168
- else:
169
- raise RuntimeError(f"Unsupported platform {platform.system()}")
159
+ return self._identifier
160
+
161
+ @identifier.setter
162
+ def identifier(self, nid: str) -> None:
163
+ self._identifier = nid
170
164
 
171
165
  def __repr__(self) -> str:
172
166
  return f"<{self.__class__.__name__}(title='{self.title}', message='{self.message}')>"
@@ -188,7 +182,7 @@ class DesktopNotifierBase:
188
182
  self.app_name = app_name
189
183
  self.notification_limit = notification_limit
190
184
  self._current_notifications: Deque[Notification] = deque([], notification_limit)
191
- self._notification_for_nid: Dict[str | int, Notification] = {}
185
+ self._notification_for_nid: Dict[str, Notification] = {}
192
186
 
193
187
  async def request_authorisation(self) -> bool:
194
188
  """
@@ -213,7 +207,6 @@ class DesktopNotifierBase:
213
207
 
214
208
  :param notification: Notification to send.
215
209
  """
216
-
217
210
  notification_to_replace: Notification | None
218
211
 
219
212
  if len(self._current_notifications) == self.notification_limit:
@@ -32,6 +32,18 @@ NOTIFICATION_CLOSED_PROGRAMMATICALLY = 3
32
32
  NOTIFICATION_CLOSED_UNDEFINED = 4
33
33
 
34
34
 
35
+ def identifier_from_dbus(nid: int) -> str:
36
+ if nid == 0:
37
+ return ""
38
+ return str(nid)
39
+
40
+
41
+ def identifier_to_dbus(nid: str) -> int:
42
+ if nid == "":
43
+ return 0
44
+ return int(nid)
45
+
46
+
35
47
  class DBusDesktopNotifier(DesktopNotifierBase):
36
48
  """DBus notification backend for Linux
37
49
 
@@ -89,9 +101,13 @@ class DBusDesktopNotifier(DesktopNotifierBase):
89
101
  # Some older interfaces may not support notification actions.
90
102
  if hasattr(self.interface, "on_notification_closed"):
91
103
  self.interface.on_notification_closed(self._on_closed)
104
+ else:
105
+ logger.warning("on_closed callbacks not supported")
92
106
 
93
107
  if hasattr(self.interface, "on_action_invoked"):
94
108
  self.interface.on_action_invoked(self._on_action)
109
+ else:
110
+ logger.warning("on_action_invoked callbacks not supported")
95
111
 
96
112
  return self.interface
97
113
 
@@ -110,7 +126,7 @@ class DBusDesktopNotifier(DesktopNotifierBase):
110
126
  self.interface = await self._init_dbus()
111
127
 
112
128
  if notification_to_replace:
113
- replaces_nid = notification_to_replace._dbus_identifier
129
+ replaces_nid = identifier_to_dbus(notification_to_replace.identifier)
114
130
  else:
115
131
  replaces_nid = 0
116
132
 
@@ -138,20 +154,20 @@ class DBusDesktopNotifier(DesktopNotifierBase):
138
154
 
139
155
  timeout = notification.timeout * 1000 if notification.timeout != -1 else -1
140
156
 
141
- # dbus_next proxy APIs are generated at runtime.
142
- if hasattr(self.interface, "call_notify"):
143
- platform_nid = await self.interface.call_notify(
144
- self.app_name,
145
- replaces_nid,
146
- notification.icon or "",
147
- notification.title,
148
- notification.message,
149
- actions,
150
- hints,
151
- timeout,
152
- )
157
+ # dbus_next proxy APIs are generated at runtime. Silence the type checker but
158
+ # raise an AttributeError if required.
159
+ platform_nid = await self.interface.call_notify( # type:ignore[attr-defined]
160
+ self.app_name,
161
+ replaces_nid,
162
+ notification.icon or "",
163
+ notification.title,
164
+ notification.message,
165
+ actions,
166
+ hints,
167
+ timeout,
168
+ )
153
169
 
154
- notification._dbus_identifier = platform_nid
170
+ notification.identifier = identifier_from_dbus(platform_nid)
155
171
 
156
172
  async def _clear(self, notification: Notification) -> None:
157
173
  """
@@ -160,9 +176,11 @@ class DBusDesktopNotifier(DesktopNotifierBase):
160
176
  if not self.interface:
161
177
  return
162
178
 
163
- # dbus_next proxy APIs are generated at runtime.
164
- if hasattr(self.interface, "call_close_notification"):
165
- await self.interface.call_close_notification(notification._dbus_identifier)
179
+ # dbus_next proxy APIs are generated at runtime. Silence the type checker but
180
+ # raise an AttributeError if required.
181
+ await self.interface.call_close_notification( # type:ignore[attr-defined]
182
+ identifier_to_dbus(notification.identifier)
183
+ )
166
184
 
167
185
  async def _clear_all(self) -> None:
168
186
  """
@@ -171,17 +189,17 @@ class DBusDesktopNotifier(DesktopNotifierBase):
171
189
  if not self.interface:
172
190
  return
173
191
 
174
- # dbus_next proxy APIs are generated at runtime.
175
- if hasattr(self.interface, "call_close_notification"):
176
- for notification in self.current_notifications:
177
- await self.interface.call_close_notification(
178
- notification._dbus_identifier
179
- )
192
+ for notification in self.current_notifications:
193
+ # dbus_next proxy APIs are generated at runtime. Silence the type checker
194
+ # but raise an AttributeError if required.
195
+ await self.interface.call_close_notification( # type:ignore[attr-defined]
196
+ identifier_to_dbus(notification.identifier)
197
+ )
180
198
 
181
199
  # Note that _on_action and _on_closed might be called for the same notification
182
200
  # with some notification servers. This is not a problem because the _on_action
183
201
  # call will come first, in which case we are no longer interested in calling the
184
- # on_dismissed callback.
202
+ # _on_closed callback.
185
203
 
186
204
  def _on_action(self, nid: int, action_key: str) -> None:
187
205
  """
@@ -194,7 +212,7 @@ class DBusDesktopNotifier(DesktopNotifierBase):
194
212
  """
195
213
 
196
214
  # Get the notification instance from the platform ID.
197
- notification = self._notification_for_nid.get(nid)
215
+ notification = self._notification_for_nid.get(identifier_from_dbus(nid))
198
216
 
199
217
  # Execute any callbacks for button clicks.
200
218
  if notification:
@@ -226,7 +244,7 @@ class DBusDesktopNotifier(DesktopNotifierBase):
226
244
  """
227
245
 
228
246
  # Get the notification instance from the platform ID.
229
- notification = self._notification_for_nid.get(nid)
247
+ notification = self._notification_for_nid.get(identifier_from_dbus(nid))
230
248
 
231
249
  # Execute callback for user dismissal.
232
250
  if notification:
@@ -104,7 +104,7 @@ class NotificationCenterDelegate(NSObject): # type: ignore
104
104
  self, center, response, completion_handler: objc_block
105
105
  ) -> None:
106
106
  # Get the notification which was clicked from the platform ID.
107
- platform_nid = py_from_ns(response.notification.request._macos_identifier)
107
+ platform_nid = py_from_ns(response.notification.request.identifier)
108
108
  py_notification = self.interface._notification_for_nid[platform_nid]
109
109
  py_notification = cast(Notification, py_notification)
110
110
 
@@ -234,9 +234,8 @@ class CocoaNotificationCenter(DesktopNotifierBase):
234
234
  :param notification: Notification to send.
235
235
  :param notification_to_replace: Notification to replace, if any.
236
236
  """
237
-
238
237
  if notification_to_replace:
239
- platform_nid = notification_to_replace._macos_identifier
238
+ platform_nid = notification_to_replace.identifier
240
239
  else:
241
240
  platform_nid = str(uuid.uuid4())
242
241
 
@@ -307,7 +306,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
307
306
  else:
308
307
  raise RuntimeError(error.localizedDescription) # type:ignore
309
308
 
310
- notification._macos_identifier = platform_nid
309
+ notification.identifier = platform_nid
311
310
 
312
311
  async def _create_category_for_notification(
313
312
  self, notification: Notification
@@ -396,9 +395,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
396
395
 
397
396
  :param notification: Notification to clear.
398
397
  """
399
- self.nc.removeDeliveredNotificationsWithIdentifiers(
400
- [notification._macos_identifier]
401
- )
398
+ self.nc.removeDeliveredNotificationsWithIdentifiers([notification.identifier])
402
399
 
403
400
  async def _clear_all(self) -> None:
404
401
  """
@@ -18,7 +18,6 @@ macos_version = Version(platform.mac_ver()[0])
18
18
 
19
19
 
20
20
  __all__ = [
21
- "is_bundle",
22
21
  "is_signed_bundle",
23
22
  "macos_version",
24
23
  ]
@@ -39,18 +38,6 @@ kSecCSCheckNestedCode = 1 << 3
39
38
  kSecCSStrictValidate = 1 << 4
40
39
 
41
40
 
42
- def is_bundle() -> bool:
43
- """
44
- Detect if we are in an app bundle / framework.
45
-
46
- :returns: Whether we are inside a valid app bundle or framework.
47
- """
48
-
49
- main_bundle = NSBundle.mainBundle
50
-
51
- return main_bundle.bundleIdentifier is not None
52
-
53
-
54
41
  def is_signed_bundle() -> bool:
55
42
  """
56
43
  Detect if we are in a signed app bundle / framework.
@@ -59,10 +59,9 @@ def get_implementation() -> Type[DesktopNotifierBase]:
59
59
  :raises RuntimeError: when passing ``macos_legacy = True`` on macOS 12.0 and later.
60
60
  """
61
61
  if platform.system() == "Darwin":
62
- from .macos_support import is_bundle, is_signed_bundle, macos_version
62
+ from .macos_support import is_signed_bundle, macos_version
63
63
 
64
64
  has_unusernotificationcenter = macos_version >= Version("10.14")
65
- has_nsusernotificationcenter = macos_version < Version("12.0")
66
65
  is_signed = is_signed_bundle()
67
66
 
68
67
  if has_unusernotificationcenter and is_signed:
@@ -70,30 +69,14 @@ def get_implementation() -> Type[DesktopNotifierBase]:
70
69
  from .macos import CocoaNotificationCenter
71
70
 
72
71
  return CocoaNotificationCenter
73
-
74
- elif has_nsusernotificationcenter and is_bundle():
75
- if has_unusernotificationcenter and not is_signed:
72
+ else:
73
+ if has_unusernotificationcenter:
76
74
  logger.warning(
77
- "Running outside of a signed Framework or bundle: "
78
- "falling back to NSUserNotificationCenter"
75
+ "Notification Center can only be used "
76
+ "from a signed Framework or app bundle"
79
77
  )
80
78
  else:
81
- logger.warning(
82
- "Running on macOS 10.13 or earlier: "
83
- "falling back to NSUserNotificationCenter"
84
- )
85
-
86
- # Use deprecated NSUserNotificationCenter.
87
- from .macos_legacy import CocoaNotificationCenterLegacy
88
-
89
- return CocoaNotificationCenterLegacy
90
-
91
- else:
92
- # Use dummy backend.
93
- logger.warning(
94
- "Notification Center can only be used "
95
- "from a signed Framework or app bundle"
96
- )
79
+ logger.warning("Only macOS 10.14 and later are supported")
97
80
 
98
81
  from .dummy import DummyNotificationCenter
99
82
 
@@ -134,7 +134,7 @@ class WinRTDesktopNotifier(DesktopNotifierBase):
134
134
  :param notification_to_replace: Notification to replace, if any.
135
135
  """
136
136
  if notification_to_replace:
137
- platform_nid = notification_to_replace._winrt_identifier
137
+ platform_nid = notification_to_replace.identifier
138
138
  else:
139
139
  platform_nid = str(uuid.uuid4())
140
140
 
@@ -288,14 +288,14 @@ class WinRTDesktopNotifier(DesktopNotifierBase):
288
288
 
289
289
  self.notifier.show(native)
290
290
 
291
- notification._winrt_identifier = platform_nid
291
+ notification.identifier = platform_nid
292
292
 
293
293
  async def _clear(self, notification: Notification) -> None:
294
294
  """
295
295
  Asynchronously removes a notification from the notification center.
296
296
  """
297
297
  if self.manager.history:
298
- self.manager.history.remove(notification._winrt_identifier)
298
+ self.manager.history.remove(notification.identifier)
299
299
 
300
300
  async def _clear_all(self) -> None:
301
301
  """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: desktop-notifier
3
- Version: 3.5.7.dev0
3
+ Version: 4.0.0
4
4
  Summary: Python library for cross-platform desktop notifications
5
5
  Author-email: Sam Schott <sam.schott@outlook.com>
6
6
  License: MIT
@@ -36,6 +36,7 @@ Requires-Dist: flake8; extra == "dev"
36
36
  Requires-Dist: flake8-pyproject; extra == "dev"
37
37
  Requires-Dist: mypy; extra == "dev"
38
38
  Requires-Dist: pytest; extra == "dev"
39
+ Requires-Dist: pytest-asyncio; extra == "dev"
39
40
  Requires-Dist: pytest-cov; extra == "dev"
40
41
  Provides-Extra: docs
41
42
  Requires-Dist: furo==2024.4.27; extra == "docs"
@@ -6,7 +6,6 @@ src/desktop_notifier/base.py
6
6
  src/desktop_notifier/dbus.py
7
7
  src/desktop_notifier/dummy.py
8
8
  src/desktop_notifier/macos.py
9
- src/desktop_notifier/macos_legacy.py
10
9
  src/desktop_notifier/macos_support.py
11
10
  src/desktop_notifier/main.py
12
11
  src/desktop_notifier/py.typed
@@ -17,4 +16,5 @@ src/desktop_notifier.egg-info/dependency_links.txt
17
16
  src/desktop_notifier.egg-info/requires.txt
18
17
  src/desktop_notifier.egg-info/top_level.txt
19
18
  src/desktop_notifier/resources/__init__.py
20
- src/desktop_notifier/resources/python.png
19
+ src/desktop_notifier/resources/python.png
20
+ tests/test_api.py
@@ -21,6 +21,7 @@ flake8
21
21
  flake8-pyproject
22
22
  mypy
23
23
  pytest
24
+ pytest-asyncio
24
25
  pytest-cov
25
26
 
26
27
  [docs]
@@ -0,0 +1,94 @@
1
+ import sys
2
+ import pytest
3
+
4
+ from desktop_notifier import Urgency, Button, ReplyField
5
+
6
+
7
+ @pytest.mark.asyncio
8
+ async def test_send(notifier):
9
+ notification = await notifier.send(
10
+ title="Julius Caesar",
11
+ message="Et tu, Brute?",
12
+ urgency=Urgency.Critical,
13
+ buttons=[
14
+ Button(
15
+ title="Mark as read",
16
+ on_pressed=lambda: print("Marked as read"),
17
+ )
18
+ ],
19
+ reply_field=ReplyField(
20
+ title="Reply",
21
+ button_title="Send",
22
+ on_replied=lambda text: print("Brutus replied:", text),
23
+ ),
24
+ on_clicked=lambda: print("Notification clicked"),
25
+ on_dismissed=lambda: print("Notification dismissed"),
26
+ sound=True,
27
+ thread="test_notifications",
28
+ timeout=5,
29
+ )
30
+ assert notification in notifier.current_notifications
31
+ assert notification.identifier != ""
32
+
33
+
34
+ def test_send_sync(notifier):
35
+ notification = notifier.send_sync(
36
+ title="Julius Caesar",
37
+ message="Et tu, Brute?",
38
+ urgency=Urgency.Critical,
39
+ buttons=[
40
+ Button(
41
+ title="Mark as read",
42
+ on_pressed=lambda: print("Marked as read"),
43
+ )
44
+ ],
45
+ reply_field=ReplyField(
46
+ title="Reply",
47
+ button_title="Send",
48
+ on_replied=lambda text: print("Brutus replied:", text),
49
+ ),
50
+ on_clicked=lambda: print("Notification clicked"),
51
+ on_dismissed=lambda: print("Notification dismissed"),
52
+ sound=True,
53
+ thread="test_notifications",
54
+ timeout=5,
55
+ )
56
+ assert notification in notifier.current_notifications
57
+ assert notification.identifier != ""
58
+
59
+
60
+ @pytest.mark.asyncio
61
+ @pytest.mark.skipif(
62
+ sys.platform.startswith("win"),
63
+ reason="Clearing individual notifications is broken on Windows",
64
+ )
65
+ async def test_clear(notifier):
66
+ n0 = await notifier.send(
67
+ title="Julius Caesar",
68
+ message="Et tu, Brute?",
69
+ )
70
+ n1 = await notifier.send(
71
+ title="Julius Caesar",
72
+ message="Et tu, Brute?",
73
+ )
74
+ assert n0 in notifier.current_notifications
75
+ assert n1 in notifier.current_notifications
76
+
77
+ await notifier.clear(n0)
78
+ assert n0 not in notifier.current_notifications
79
+
80
+
81
+ async def test_clear_all(notifier):
82
+ n0 = await notifier.send(
83
+ title="Julius Caesar",
84
+ message="Et tu, Brute?",
85
+ )
86
+ n1 = await notifier.send(
87
+ title="Julius Caesar",
88
+ message="Et tu, Brute?",
89
+ )
90
+ assert n0 in notifier.current_notifications
91
+ assert n1 in notifier.current_notifications
92
+
93
+ await notifier.clear_all()
94
+ assert len(notifier.current_notifications) == 0
@@ -1,166 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- NSUserNotificationCenter backend for macOS.
4
-
5
- * Should be used for macOS 10.13 and earlier.
6
- * Deprecated but still available in macOS 11.0.
7
- * Requires a running CFRunLoop to invoke callbacks.
8
-
9
- """
10
-
11
- # system imports
12
- import uuid
13
- import platform
14
- import logging
15
- from typing import cast, Optional
16
-
17
- # external imports
18
- from rubicon.objc import NSObject, ObjCClass, objc_method, py_from_ns
19
- from rubicon.objc.runtime import load_library
20
-
21
- # local imports
22
- from .base import Notification, DesktopNotifierBase
23
-
24
-
25
- __all__ = ["CocoaNotificationCenterLegacy"]
26
-
27
- logger = logging.getLogger(__name__)
28
- macos_version, *_ = platform.mac_ver()
29
-
30
- foundation = load_library("Foundation")
31
-
32
- NSUserNotification = ObjCClass("NSUserNotification")
33
- NSUserNotificationCenter = ObjCClass("NSUserNotificationCenter")
34
- NSDate = ObjCClass("NSDate")
35
-
36
- NSUserNotificationActivationTypeContentsClicked = 1
37
- NSUserNotificationActivationTypeActionButtonClicked = 2
38
- NSUserNotificationActivationTypeAdditionalActionClicked = 4
39
-
40
- NSUserNotificationDefaultSoundName = "DefaultSoundName"
41
-
42
-
43
- class NotificationCenterDelegate(NSObject): # type: ignore
44
- """Delegate to handle user interactions with notifications"""
45
-
46
- @objc_method # type:ignore
47
- def userNotificationCenter_didActivateNotification_(
48
- self, center, notification
49
- ) -> None:
50
- platform_nid = py_from_ns(notification._macos_identifier)
51
- py_notification = self.interface._notification_for_nid[platform_nid]
52
- py_notification = cast(Notification, py_notification)
53
-
54
- self.interface._clear_notification_from_cache(py_notification)
55
-
56
- if (
57
- notification.activationType
58
- == NSUserNotificationActivationTypeContentsClicked
59
- ):
60
- if py_notification.on_clicked:
61
- py_notification.on_clicked()
62
-
63
- elif (
64
- notification.activationType
65
- == NSUserNotificationActivationTypeActionButtonClicked
66
- ):
67
- callback = py_notification.buttons[0].on_pressed
68
-
69
- if callback:
70
- callback()
71
-
72
-
73
- class CocoaNotificationCenterLegacy(DesktopNotifierBase):
74
- """NSUserNotificationCenter backend for macOS
75
-
76
- Should be used for macOS High Sierra and earlier. Supports only a single button per
77
- notification. Both app name and bundle identifier will be ignored. The notification
78
- center automatically uses the values provided by the app bundle or the Python
79
- framework.
80
-
81
- :param app_name: The name of the app. Does not have any effect because the app
82
- name is automatically determined from the bundle or framework.
83
- :param notification_limit: Maximum number of notifications to keep in the system's
84
- notification center.
85
- """
86
-
87
- def __init__(
88
- self,
89
- app_name: str = "Python",
90
- notification_limit: Optional[int] = None,
91
- ) -> None:
92
- super().__init__(app_name, notification_limit)
93
-
94
- self.nc = NSUserNotificationCenter.defaultUserNotificationCenter
95
- self.nc_delegate = NotificationCenterDelegate.alloc().init()
96
- self.nc_delegate.interface = self
97
- self.nc.delegate = self.nc_delegate
98
-
99
- async def request_authorisation(self) -> bool:
100
- """
101
- Request authorisation to send notifications.
102
-
103
- :returns: Whether authorisation has been granted.
104
- """
105
- return True
106
-
107
- async def has_authorisation(self) -> bool:
108
- """
109
- Whether we have authorisation to send notifications.
110
- """
111
- return True
112
-
113
- async def _send(
114
- self,
115
- notification: Notification,
116
- notification_to_replace: Optional[Notification],
117
- ) -> None:
118
- """
119
- Uses NSUserNotificationCenter to schedule a notification.
120
-
121
- :param notification: Notification to send.
122
- :param notification_to_replace: Notification to replace, if any.
123
- """
124
- if notification_to_replace:
125
- platform_nid = notification_to_replace._macos_identifier
126
- else:
127
- platform_nid = str(uuid.uuid4())
128
-
129
- n = NSUserNotification.alloc().init()
130
- n.title = notification.title
131
- n.informativeText = notification.message
132
- n.identifier = platform_nid
133
- n.deliveryDate = NSDate.dateWithTimeInterval(0, sinceDate=NSDate.date())
134
-
135
- # store the notification instance for clearing
136
- notification._native = n # type: ignore
137
-
138
- if notification.sound:
139
- n.soundName = NSUserNotificationDefaultSoundName
140
-
141
- if notification.buttons:
142
- if len(notification.buttons) > 1:
143
- logger.debug(
144
- "NSUserNotificationCenter: only a single button is supported"
145
- )
146
- n.hasActionButton = True
147
- n.actionButtonTitle = notification.buttons[0].title
148
-
149
- self.nc.scheduleNotification(n)
150
-
151
- notification._macos_identifier = platform_nid
152
-
153
- async def _clear(self, notification: Notification) -> None:
154
- """
155
- Removes a notifications from the notification center
156
-
157
- :param notification: Notification to clear.
158
- """
159
- if hasattr(notification, "_native"):
160
- self.nc.removeDeliveredNotification(notification._native)
161
-
162
- async def _clear_all(self) -> None:
163
- """
164
- Clears all notifications from notification center
165
- """
166
- self.nc.removeAllDeliveredNotifications()