Skip to content

Add on_cleared event #208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,22 @@ async def main() -> None:
buttons=[
Button(
title="Mark as read",
on_pressed=lambda: print("Marked as read"),
)
on_pressed=lambda: print("Button 'Mark as read' was clicked"),
),
Button(
title="Click me!!",
on_pressed=lambda: print("Button 'Click me!!' was clicked"),
),
],
reply_field=ReplyField(
on_replied=lambda text: print("Brutus replied:", text),
title="Reply",
button_title="Send",
on_replied=lambda text: print(f"Received reply '{text}'"),
),
on_dispatched=lambda: print("Notification showing"),
on_clicked=lambda: print("Notification clicked"),
on_dismissed=lambda: print("Notification dismissed"),
on_dispatched=lambda: print("Notification is showing now"),
on_cleared=lambda: print("Notification was closed w/o user interaction"),
on_clicked=lambda: print("Notification was clicked"),
on_dismissed=lambda: print("Notification was dismissed by the user"),
sound=DEFAULT_SOUND,
)

Expand Down
3 changes: 2 additions & 1 deletion examples/eventloop.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ async def main() -> None:
on_replied=lambda text: print(f"Received reply '{text}'"),
),
on_dispatched=lambda: print("Notification is showing now"),
on_cleared=lambda: print("Notification was closed w/o user interaction"),
on_clicked=lambda: print("Notification was clicked"),
on_dismissed=lambda: print("Notification was dismissed"),
on_dismissed=lambda: print("Notification was dismissed by the user"),
sound=DEFAULT_SOUND,
)

Expand Down
7 changes: 6 additions & 1 deletion examples/eventloop_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ def on_dispatched(identifier: str) -> None:
print(f"Notification '{identifier}' is showing now")


def on_cleared(identifier: str) -> None:
print(f"Notification '{identifier}' was closed w/o user interaction")


def on_clicked(identifier: str) -> None:
print(f"Notification '{identifier}' was clicked")


def on_dismissed(identifier: str) -> None:
print(f"Notification '{identifier}' was dismissed")
print(f"Notification '{identifier}' was dismissed by the user")


def on_button_pressed(identifier: str, button_identifier: str) -> None:
Expand All @@ -34,6 +38,7 @@ def on_replied(identifier: str, reply: str) -> None:
async def main() -> None:
notifier = DesktopNotifier(app_name="Sample App")
notifier.on_dispatched = on_dispatched
notifier.on_cleared = on_cleared
notifier.on_clicked = on_clicked
notifier.on_dismissed = on_dismissed
notifier.on_button_pressed = on_button_pressed
Expand Down
17 changes: 11 additions & 6 deletions examples/synchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,21 @@
buttons=[
Button(
title="Mark as read",
on_pressed=lambda: print("Marked as read"),
)
on_pressed=lambda: print("Button 'Mark as read' was clicked"),
),
Button(
title="Click me!!",
on_pressed=lambda: print("Button 'Click me!!' was clicked"),
),
],
reply_field=ReplyField(
title="Reply",
button_title="Send",
on_replied=lambda text: print("Brutus replied:", text),
on_replied=lambda text: print(f"Received reply '{text}'"),
),
on_dispatched=lambda: print("Notification showing"),
on_clicked=lambda: print("Notification clicked"),
on_dismissed=lambda: print("Notification dismissed"),
on_dispatched=lambda: print("Notification is showing now"),
on_cleared=lambda: print("Notification was closed w/o user interaction"),
on_clicked=lambda: print("Notification was clicked"),
on_dismissed=lambda: print("Notification was dismissed by the user"),
sound=DEFAULT_SOUND,
)
9 changes: 9 additions & 0 deletions src/desktop_notifier/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def __init__(self, app_name: str, app_icon: Icon | None = None) -> None:
self._notification_cache: dict[str, Notification] = dict()

self.on_dispatched: Callable[[str], Any] | None = None
self.on_cleared: Callable[[str], Any] | None = None
self.on_clicked: Callable[[str], Any] | None = None
self.on_dismissed: Callable[[str], Any] | None = None
self.on_button_pressed: Callable[[str, str], Any] | None = None
Expand Down Expand Up @@ -154,6 +155,14 @@ def handle_dispatched(
elif self.on_dispatched:
self.on_dispatched(identifier)

def handle_cleared(
self, identifier: str, notification: Notification | None = None
) -> None:
if notification and notification.on_cleared:
notification.on_cleared()
elif self.on_cleared:
self.on_cleared(identifier)

def handle_clicked(
self, identifier: str, notification: Notification | None = None
) -> None:
Expand Down
3 changes: 3 additions & 0 deletions src/desktop_notifier/backends/dbus.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ def _on_closed(self, nid: int, reason: int) -> None:

if reason == NOTIFICATION_CLOSED_DISMISSED:
self.handle_dismissed(identifier, notification)
else:
self.handle_cleared(identifier, notification)

async def get_capabilities(self) -> frozenset[Capability]:
if not self.interface:
Expand All @@ -265,6 +267,7 @@ async def get_capabilities(self) -> frozenset[Capability]:
Capability.TIMEOUT,
Capability.URGENCY,
Capability.ON_DISPATCHED,
Capability.ON_CLEARED,
}

# Capabilities supported by some notification servers.
Expand Down
10 changes: 5 additions & 5 deletions src/desktop_notifier/backends/winrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,11 +263,11 @@ def _on_dismissed(

notification = self._clear_notification_from_cache(sender.tag)

if (
dismissed_args
and dismissed_args.reason == ToastDismissalReason.USER_CANCELED
):
self.handle_dismissed(sender.tag, notification)
if dismissed_args:
# ToastDismissalReason.APPLICATION_HIDDEN and ToastDismissalReason.TIMED_OUT
# both just indicate that the toast was sent to the notifications center
if dismissed_args.reason == ToastDismissalReason.USER_CANCELED:
self.handle_dismissed(sender.tag, notification)

def _on_failed(
self, sender: ToastNotification | None, failed_args: ToastFailedEventArgs | None
Expand Down
8 changes: 8 additions & 0 deletions src/desktop_notifier/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,9 @@ class Notification:
on_dispatched: Callable[[], Any] | None = None
"""Method to call when the notification was sent to the notifications server for display"""

on_cleared: Callable[[], Any] | None = None
"""Method to call when the notification is cleared without user interaction"""

on_clicked: Callable[[], Any] | None = None
"""Method to call when the notification is clicked"""

Expand Down Expand Up @@ -300,6 +303,11 @@ class Capability(Enum):
ON_DISPATCHED = auto()
"""Supports on-dispatched callbacks"""

ON_CLEARED = auto()
"""Supports on-cleared callbacks, which are called if a notification wasn't
cleared by user interaction, but programmatically; platforms not supporting
this distinction will call on-dismissed callbacks instead"""

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about "Supports callbacks on programmatic closing and notification timeouts"?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm… Reading through both my original suggestion five months later and yours now, I'd interpret both like "if this cap isn't set, the notification can't be closed programmatically". I made another attempt, WDYT?

ON_CLICKED = auto()
"""Supports on-clicked callbacks"""

Expand Down
19 changes: 19 additions & 0 deletions src/desktop_notifier/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ async def send(
buttons: Sequence[Button] = (),
reply_field: ReplyField | None = None,
on_dispatched: Callable[[], Any] | None = None,
on_cleared: Callable[[], Any] | None = None,
on_clicked: Callable[[], Any] | None = None,
on_dismissed: Callable[[], Any] | None = None,
attachment: Attachment | None = None,
Expand All @@ -242,6 +243,7 @@ async def send(
buttons=tuple(buttons),
reply_field=reply_field,
on_dispatched=on_dispatched,
on_cleared=on_cleared,
on_clicked=on_clicked,
on_dismissed=on_dismissed,
attachment=attachment,
Expand Down Expand Up @@ -294,6 +296,23 @@ def on_dispatched(self) -> Callable[[str], Any] | None:
def on_dispatched(self, handler: Callable[[str], Any] | None) -> None:
self._backend.on_dispatched = handler

@property
def on_cleared(self) -> Callable[[str], Any] | None:
"""
A method to call when a notification is cleared without user interaction
(e.g. if cleared by another process)

The method must take the notification identifier as a single argument.

If the notification itself already specifies an on_cleared handler, it will be
used instead of the class-level handler.
"""
return self._backend.on_cleared

@on_cleared.setter
def on_cleared(self, handler: Callable[[str], Any] | None) -> None:
self._backend.on_cleared = handler

@property
def on_clicked(self) -> Callable[[str], Any] | None:
"""
Expand Down
2 changes: 2 additions & 0 deletions src/desktop_notifier/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def send(
buttons: Sequence[Button] = (),
reply_field: ReplyField | None = None,
on_dispatched: Callable[[], Any] | None = None,
on_cleared: Callable[[], Any] | None = None,
on_clicked: Callable[[], Any] | None = None,
on_dismissed: Callable[[], Any] | None = None,
attachment: Attachment | None = None,
Expand All @@ -113,6 +114,7 @@ def send(
buttons=tuple(buttons),
reply_field=reply_field,
on_dispatched=on_dispatched,
on_cleared=on_cleared,
on_clicked=on_clicked,
on_dismissed=on_dismissed,
attachment=attachment,
Expand Down
54 changes: 54 additions & 0 deletions tests/test_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,46 @@ async def test_dispatched_callback_called(notifier: DesktopNotifier) -> None:
notification_handler.assert_called_once()


@pytest.mark.asyncio
async def test_cleared_callback_called(notifier: DesktopNotifier) -> None:
await check_supported(notifier, Capability.ON_CLEARED)

class_handler = Mock()
notification_handler = Mock()
notifier.on_cleared = class_handler
notification = Notification(
title="Julius Caesar",
message="Et tu, Brute?",
on_cleared=notification_handler,
)

identifier = await notifier.send_notification(notification)
await notifier.clear(identifier)

class_handler.assert_not_called()
notification_handler.assert_called_once()


@pytest.mark.asyncio
async def test_cleared_callback_not_dismissed(notifier: DesktopNotifier) -> None:
await check_supported(notifier, Capability.ON_CLEARED)

on_cleared = Mock()
on_dismissed = Mock()
notification = Notification(
title="Julius Caesar",
message="Et tu, Brute?",
on_cleared=on_cleared,
on_dismissed=on_dismissed,
)

identifier = await notifier.send_notification(notification)
await notifier.clear(identifier)

on_dismissed.assert_not_called()
on_cleared.assert_called_once()


@pytest.mark.asyncio
async def test_clicked_callback_called(notifier: DesktopNotifier) -> None:
await check_supported(notifier, Capability.ON_CLICKED)
Expand Down Expand Up @@ -163,6 +203,20 @@ async def test_dispatched_fallback_handler_called(notifier: DesktopNotifier) ->
class_handler.assert_called_with(identifier)


@pytest.mark.asyncio
async def test_cleared_fallback_handler_called(notifier: DesktopNotifier) -> None:
await check_supported(notifier, Capability.ON_CLEARED)

class_handler = Mock()
notifier.on_cleared = class_handler
notification = Notification(title="Julius Caesar", message="Et tu, Brute?")

identifier = await notifier.send_notification(notification)
await notifier.clear(identifier)

class_handler.assert_called_with(identifier)


@pytest.mark.asyncio
async def test_clicked_fallback_handler_called(notifier: DesktopNotifier) -> None:
await check_supported(notifier, Capability.ON_CLICKED)
Expand Down
Loading