Skip to content
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

feat: support launching applications using protocols #80

Merged
merged 4 commits into from
Aug 13, 2023
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Minor
- InvalidImageException is thrown when trying to add online images or images that do not exist
- Body is now the first argument for toasts
- Added support for inline images (#77)
- Added support for launching applications using their protocols (#80)

0.4.1 (2023-04-20)
===========
Expand Down
8 changes: 2 additions & 6 deletions docs/advanced_usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ Lets try out displaying an image
Open a website on click
-----------------------

We use :meth:`windows_toasts.toast_types.Toast.on_activated` along with the built-in
`webbrowser <https://docs.python.org/3/library/webbrowser.html>`_ module to open a website
when the notification is pressed.
We use :meth:`windows_toasts.toast_types.Toast.SetLaunchAction` to open a website when the notification is pressed.

.. code-block:: python

Expand All @@ -42,13 +40,11 @@ when the notification is pressed.
newToast = ToastText1()
newToast.SetBody('Hello there! You just won a thousand dollars! Click me to claim it!')
# Inline lambda function. This could also be an actual function
newToast.on_activated = lambda _: webbrowser.open('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
newToast.SetLaunchAction('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

# Send it
toaster.show_toast(newToast)

.. warning::
Make sure your lambda/function takes an argument! The on_x fields pass data back to the callable. on_activated for instance returns :class:`~windows_toasts.events.ToastActivatedEventArgs`.

Play different audio
--------------------
Expand Down
7 changes: 5 additions & 2 deletions src/windows_toasts/toast_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,11 @@ def AddAction(self, action: ToastButton) -> None:

actionNode = self.xmlDocument.create_element("action")
self.SetAttribute(actionNode, "content", action.content)
self.SetAttribute(actionNode, "arguments", action.arguments)
self.SetAttribute(actionNode, "activationType", "background")
if action.launch is None:
self.SetAttribute(actionNode, "arguments", action.arguments)
else:
self.SetAttribute(actionNode, "activationType", "protocol")
self.SetAttribute(actionNode, "arguments", action.launch)

if action.image is not None:
self.SetAttribute(actionNode, "imageUri", action.image.path)
Expand Down
16 changes: 16 additions & 0 deletions src/windows_toasts/toast_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import copy
import datetime
import urllib.parse
import uuid
import warnings
from typing import Callable, ClassVar, Iterable, List, Literal, Optional, TypeVar
Expand Down Expand Up @@ -56,6 +57,8 @@ class Toast:
"""Expiration time of the toast"""
suppress_popup: bool = False
"""Whether to suppress the toast popup and relegate it immediately to the action center"""
launch_action: Optional[str] = None
"""Protocol to launch when the toast is clicked"""
on_activated: Optional[Callable[[ToastActivatedEventArgs], None]]
"""Callable to execute when the toast is clicked if basic, or a button is clicked if interactable"""
on_dismissed: Optional[Callable[[ToastDismissedEventArgs], None]]
Expand Down Expand Up @@ -84,6 +87,7 @@ def __init__(
group: Optional[str] = None,
expiration_time: Optional[datetime.datetime] = None,
suppress_popup: bool = False,
launch_action: Optional[str] = None,
on_activated: Optional[Callable[[ToastActivatedEventArgs], None]] = None,
on_dismissed: Optional[Callable[[ToastDismissedEventArgs], None]] = None,
on_failed: Optional[Callable[[ToastFailedEventArgs], None]] = None,
Expand Down Expand Up @@ -121,6 +125,8 @@ def __init__(
:type expiration_time: Optional[datetime.datetime]
:param suppress_popup: See :meth:`SetSuppressPopup`
:type suppress_popup: bool
:param launch_action: See :meth:`SetLaunchAction`
:type launch_action: Optional[str]
:param on_activated: Callable to execute when the toast is clicked if basic, or a button is clicked if \
interactable
:type on_activated: Optional[Callable[[ToastActivatedEventArgs], None]]
Expand All @@ -141,6 +147,7 @@ def __init__(
self.SetProgressBar(progress_bar)
self.SetExpirationTime(expiration_time)
self.SetSuppressPopup(suppress_popup)
self.SetLaunchAction(launch_action)

if headline is not None:
self.SetHeadline(headline)
Expand Down Expand Up @@ -302,6 +309,15 @@ def SetSuppressPopup(self, suppressPopup: bool) -> None:
"""
self.suppress_popup = suppressPopup

def SetLaunchAction(self, launchAction: str) -> None:
"""
Sets the protocol to launch when the toast is clicked
"""
if not urllib.parse.urlparse(launchAction).scheme:
warnings.warn(f"Ensure your launch action of {launchAction} is a proper protocol")

self.launch_action = launchAction

def clone(self) -> Toast:
"""
Clone the current toast and return the new one
Expand Down
7 changes: 6 additions & 1 deletion src/windows_toasts/toasters.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,12 @@ def _setup_toast(self, toast: Toast, dynamic: bool) -> ToastDocument:
if toast.scenario != ToastScenario.Default:
toastContent.SetScenario(toast.scenario)

toastContent.SetAttribute(toastContent.GetElementByTagName("toast"), "launch", toast.tag)
if toast.launch_action is not None:
toastContent.SetAttribute(toastContent.GetElementByTagName("toast"), "launch", toast.launch_action)
toastContent.SetAttribute(toastContent.GetElementByTagName("toast"), "activationType", "protocol")
else:
toastContent.SetAttribute(toastContent.GetElementByTagName("toast"), "launch", toast.tag)

return toastContent

def show_toast(self, toast: Toast) -> None:
Expand Down
2 changes: 2 additions & 0 deletions src/windows_toasts/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,5 +235,7 @@ class ToastButton:
"""Whether to place the button in the context menu rather than the actual toast"""
tooltip: Optional[str] = None
"""The tooltip for a button, if the button has an empty content string"""
launch: Optional[str] = None
"""An optional protocol to launch when the button is pressed"""
colour: ToastButtonColour = ToastButtonColour.Default
""":class:`ToastButtonColour` for the button"""
11 changes: 11 additions & 0 deletions tests/test_toasts.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ def test_errors_toast(example_image_path):
with warns(UserWarning, match="Toast of type ToastText1 does not support images"):
textToast.AddImage(displayImage)

with warns(UserWarning, match="is a proper protocol"):
textToast.SetLaunchAction("notanactualprotocol")

assert len(textToast.textFields) == 1
assert textToast.textFields[0] == "Hello, World!"

Expand Down Expand Up @@ -293,3 +296,11 @@ def test_expiration_toasts():
expirationTime = datetime.now() + timedelta(minutes=1)
newToast = ToastText1(body="Hello, World!", group="Test Toasts", expiration_time=expirationTime)
WindowsToaster("Python").show_toast(newToast)


def test_protocol_launch():
from src.windows_toasts import ToastButton, ToastText1

newToast = ToastText1(body="Click on me to open google.com", launch_action="https://google.com")
newToast.AddAction(ToastButton("Launch calculator", launch="calculator://"))
InteractableWindowsToaster("Python").show_toast(newToast)