Skip to content

Add cross-platform notification timeouts #206

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

Closed
Closed
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
2 changes: 1 addition & 1 deletion docs/background/platform_support.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Please refer to the platform documentation for more detailed information:
"sound", "Play a sound with the notification", "✓ [#f2]_", "✓ [#f5]_", "✓"
"thread", "An identifier to group notifications together", "--", "✓", "✓"
"attachment", "File attachment, e.g., an image", "✓ [#f2]_ [#f6]_", "✓ [#f6]_", "✓ [#f6]_"
"timeout", "Duration in seconds until notification auto-dismissal", "✓", "--", "--"
"timeout", "Duration in seconds until notification auto-dismissal", "✓", "", ""

.. [#f1] App name and icon on macOS and Windows are automatically determined by the
calling application.
Expand Down
19 changes: 19 additions & 0 deletions src/desktop_notifier/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
"""
from __future__ import annotations

import asyncio
import logging
from abc import ABC, abstractmethod
from asyncio import Task
from typing import Any, Callable

from ..common import Capability, Notification
Expand All @@ -27,6 +29,7 @@ class DesktopNotifierBackend(ABC):
def __init__(self, app_name: str) -> None:
self.app_name = app_name
self._notification_cache: dict[str, Notification] = dict()
self._timeout_tasks: dict[str, Task[Any]] = dict()

self.on_clicked: Callable[[str], Any] | None = None
self.on_dismissed: Callable[[str], Any] | None = None
Expand Down Expand Up @@ -67,11 +70,27 @@ async def send(self, notification: Notification) -> None:
logger.debug("Notification sent: %s", notification)
self._notification_cache[notification.identifier] = notification

if notification.timeout > 0:
self._timeout_tasks[notification.identifier] = asyncio.create_task(
self._timeout_task(notification.identifier, notification.timeout)
)

async def _timeout_task(self, identifier: str, timeout: float) -> None:
"""
Waits until a notification's timeout delay is reached and clears the notification.
This asyncio task might be cancelled by :meth:`_clear_notification_from_cache`.
"""
await asyncio.sleep(timeout)
await self._clear(identifier)

def _clear_notification_from_cache(self, identifier: str) -> Notification | None:
"""
Removes the notification from our cache. Should be called by backends when the
notification is closed.
"""
if identifier in self._timeout_tasks:
self._timeout_tasks[identifier].cancel()
del self._timeout_tasks[identifier]
return self._notification_cache.pop(identifier, None)

@abstractmethod
Expand Down
6 changes: 4 additions & 2 deletions src/desktop_notifier/backends/dbus.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ async def _send(self, notification: Notification) -> None:
else:
hints = {}

timeout = notification.timeout * 1000 if notification.timeout != -1 else -1
# few notifications servers implement timeouts, thus we use our own implementation
timeout = -1

if notification.icon:
if notification.icon.is_named():
icon = notification.icon.name
Expand Down Expand Up @@ -258,8 +260,8 @@ async def get_capabilities(self) -> frozenset[Capability]:
Capability.APP_NAME,
Capability.ICON,
Capability.TITLE,
Capability.TIMEOUT,
Capability.URGENCY,
Capability.TIMEOUT,
}

# Capabilities supported by some notification servers.
Expand Down
1 change: 1 addition & 0 deletions src/desktop_notifier/backends/macos.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ async def get_capabilities(self) -> frozenset[Capability]:
Capability.SOUND_NAME,
Capability.THREAD,
Capability.ATTACHMENT,
Capability.TIMEOUT,
}
if macos_version >= Version("12.0"):
capabilities.add(Capability.URGENCY)
Expand Down
1 change: 1 addition & 0 deletions src/desktop_notifier/backends/winrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ async def get_capabilities(self) -> frozenset[Capability]:
Capability.ATTACHMENT,
Capability.SOUND,
Capability.SOUND_NAME,
Capability.TIMEOUT,
}
# Custom audio is support only starting with the Windows 10 Anniversary update.
# See https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/custom-audio-on-toasts#add-the-custom-audio.
Expand Down
2 changes: 1 addition & 1 deletion src/desktop_notifier/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ class Notification:
thread: str | None = None
"""An identifier to group related notifications together, e.g., from a chat space"""

timeout: int = -1
timeout: float = -1
"""Duration in seconds for which the notification is shown"""

identifier: str = field(default_factory=uuid_str)
Expand Down
Loading