toast

package module
v2.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2024 License: MIT, Unlicense Imports: 4 Imported by: 0

README

go-toast

This package implements Windows toast notifications using the Windows Runtime COM API.

The XML schema used to describe such notifications is here:

https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/adaptive-interactive-toasts

Package wintoast offers a lower-level api. Package toast offers a higher-level wrapper.

wintoast uses build tags to guard Windows only code. It will still compile on non-Windows platforms, however the functions are stubbed out and will do nothing when invoked.

Usage

Basic
noti := toast.Notification{
    AppID: "My cool app",
    Title: "Title",
    Body: "Body",
}

err := noti.Push()
Actions / Inputs with Callback

Additionally, we can respond to notification activation with a callback.

// Set the callback that receives the data from the notification.
// Any data from actions or inputs will be accessible here. 
toast.SetActivationCallback(func(args string, data []UserData) {
    fmt.Printf("args: %q, data: %v\n", args, data)
})

n := toast.Notification{
    AppID: "My cool app",
    Title: "Title",
    Body: "Body", 
}

n.Inputs = append(n.Inputs, toast.Input{
	ID:          "reply-to:john-doe",
	Title:       "Reply",
	Placeholder: "Reply to John Doe",
})

n.Inputs = append(n.Inputs, toast.Input{
	ID:          "select-action",
	Title:       "Selection Action",
	Placeholder: "Pick an action to perform",
	Selections: []toast.InputSelection{
		{
			ID:      "1",
			Content: "do thing one",
		},
		{
			ID:      "2",
			Content: "do thing two",
		},
		{
			ID:      "3",
			Content: "do thing three",
		},
	},
})

n.Actions = append(n.Actions, toast.Action{
	Type:      toast.Foreground,
	Content:   "Send",
	Arguments: "send",
})

n.Actions = append(n.Actions, toast.Action{
	Type:      toast.Foreground,
	Content:   "Close",
	Arguments: "close",
})

err := n.Push()

Documentation

Overview

Package toast wraps the lower-level wintoast api and provides an easy way to send and respond to toast notifications on Windows.

First, setup your AppData vis SetAppData function. This will install your application metadata into the Windows Registry.

Then, if you want in-process callback to be invoked upon user interaction, invoke SetActivationCallback.

Finally, generate your notification by instantiation a toast.Notification and pushing it with Push method.

Index

Constants

View Source
const (
	Default        toastAudio = "ms-winsoundevent:Notification.Default"
	IM             toastAudio = "ms-winsoundevent:Notification.IM"
	Mail           toastAudio = "ms-winsoundevent:Notification.Mail"
	Reminder       toastAudio = "ms-winsoundevent:Notification.Reminder"
	SMS            toastAudio = "ms-winsoundevent:Notification.SMS"
	LoopingAlarm   toastAudio = "ms-winsoundevent:Notification.Looping.Alarm"
	LoopingAlarm2  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm2"
	LoopingAlarm3  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm3"
	LoopingAlarm4  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm4"
	LoopingAlarm5  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm5"
	LoopingAlarm6  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm6"
	LoopingAlarm7  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm7"
	LoopingAlarm8  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm8"
	LoopingAlarm9  toastAudio = "ms-winsoundevent:Notification.Looping.Alarm9"
	LoopingAlarm10 toastAudio = "ms-winsoundevent:Notification.Looping.Alarm10"
	LoopingCall    toastAudio = "ms-winsoundevent:Notification.Looping.Call"
	LoopingCall2   toastAudio = "ms-winsoundevent:Notification.Looping.Call2"
	LoopingCall3   toastAudio = "ms-winsoundevent:Notification.Looping.Call3"
	LoopingCall4   toastAudio = "ms-winsoundevent:Notification.Looping.Call4"
	LoopingCall5   toastAudio = "ms-winsoundevent:Notification.Looping.Call5"
	LoopingCall6   toastAudio = "ms-winsoundevent:Notification.Looping.Call6"
	LoopingCall7   toastAudio = "ms-winsoundevent:Notification.Looping.Call7"
	LoopingCall8   toastAudio = "ms-winsoundevent:Notification.Looping.Call8"
	LoopingCall9   toastAudio = "ms-winsoundevent:Notification.Looping.Call9"
	LoopingCall10  toastAudio = "ms-winsoundevent:Notification.Looping.Call10"
	Silent         toastAudio = "silent"
)
View Source
const (
	Short toastDuration = "short"
	Long  toastDuration = "long"
)

Variables

View Source
var (
	ErrorInvalidAudio    error = errors.New("toast: invalid audio")
	ErrorInvalidDuration       = errors.New("toast: invalid duration")
)

Functions

func SetActivationCallback

func SetActivationCallback(cb func(args string, data []UserData))

SetActivationCallback sets the global activation callback.

The first argument contains application defined data (embedded within the xml), which is how the callback knows which part of the toast was activated. Argument data is defined by `toast.Action.Arguments` on the notification.

The second argument contains user defined data (input/selected by user). All elements of user input will be supplied here, even if the value is empty. User inputs correspond to all `toast.Input`s defined on the notification.

This function will be invoked when a toast notification is interacted with.

This will do nothing if the the powershell fallback is in-effect.

func SetAppData

func SetAppData(data AppData) error

SetAppData sets application metadata in the Windows Registry. This is required to display the application name, as well as any branding. Registry is global state, hence it makes sense to set it global.

Types

type Action

type Action struct {
	Type      ActivationType
	Content   string
	Arguments string
	InputID   string // optional ID of any related input, affects styling.
}

Action

Defines an actionable button. See https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts for more info.

toast.Action{toast.Protocol, "Open Maps", "bingmaps:?q=sushi"}

TODO(jfm): we can likely support an activation callback directly in the Action.

type ActivationType

type ActivationType = string

ActivationType identifies the method that Windows Runtime will use to handle notification interactions.

See https://learn.microsoft.com/en-us/dotnet/api/microsoft.toolkit.uwp.notifications.toastactivationtype

const (
	// Protocol is for launching third-party applications using a protocol uri, like https or mailto.
	Protocol ActivationType = "protocol"
	// Foreground is for launching your foreground application. This is required to enable the activation
	// callback. There is a third option: Background, however for Desktop applications Foreground and
	// Background behave identically.
	//
	// See https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/send-local-toast-desktop-cpp-wrl#foreground-vs-background-activation
	Foreground ActivationType = "foreground"
)

type AppData

type AppData = wintoast.AppData

type CropStyle

type CropStyle = string

CropStyle specifies the hint-crop attribute for an image.

const (
	CropStyleEmpty  CropStyle = ""
	CropStyleSquare CropStyle = "square"
	CropStyleCircle CropStyle = "circle"
)

type Input

type Input struct {
	ID          string
	Title       string
	Placeholder string
	Selections  []InputSelection
}

Input

Defines an input element, generally a text input. See https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-input for more info.

Inputs are by default textual, however if selections are supplied the input will be rendered as a select input.

type InputSelection

type InputSelection struct {
	ID      string
	Content string
}

InputSelection

Defines an input selection for use with select inputs. See https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-selection for more info.

type Notification

type Notification struct {
	// The name of your app. This value shows up in Windows Action Centre, so make it
	// something readable for your users.
	AppID string

	// The main title/heading for the toast notification.
	Title string

	// The single/multi line message to display for the toast notification.
	Body string

	// An optional path to an image on the OS to display to the left of the title & message.
	Icon string

	// An optional crop style for the Icon.
	IconCrop CropStyle

	// An optional path to an image to display as a bold hero image.
	HeroIcon string

	// A color to show as the icon background.
	IconBackgroundColor string

	// Action to take when the notification is as a whole activated.
	ActivationType ActivationType

	// The activation/action arguments (invoked when the user clicks the notification).
	// This is returned to the callback when activated.
	ActivationArguments string

	// Optional text input to display before the actions.
	Inputs []Input

	// Optional action buttons to display below the notification title & message.
	Actions []Action

	// The audio to play when displaying the toast
	Audio toastAudio

	// Whether to loop the audio (default false).
	Loop bool

	// How long the toast should show up for (short/long).
	Duration toastDuration

	// This is an absolute path to an executable that will launched by the
	// Windows Runtime when the COM server is not running. This executable must be able
	// to handle the -Embedding flag that Windows invokes it with.
	ActivationExe string
}

Notification

The toast notification data. The following fields are strongly recommended;

  • AppID
  • Title

If no toastAudio is provided, then the toast notification will be silent.

The AppID is shown beneath the toast message (in certain cases), and above the notification within the Action Center - and is used to group your notifications together. It is recommended that you provide a "pretty" name for your app, and not something like "com.example.MyApp". It can be ellided if the value has already been set via SetAppData.

If no Title is provided, but a Body is, the body will display as the toast notification's title - which is a slightly different font style (heavier).

The Icon should be an absolute path to the icon (as the toast is invoked from a temporary path on the user's system, not the working directory).

If you would like the toast to call an external process/open a webpage, then you can set ActivationArguments to the uri you would like to trigger when the toast is clicked. For example: "https://google.com" would open the Google homepage when the user clicks the toast notification. By default, clicking the toast just hides/dismisses it.

The following would show a notification to the user letting them know they received an email, and opens gmail.com when they click the notification. It also makes the Windows 10 "mail" sound effect.

toast := toast.Notification{
    AppID:               "Google Mail",
    Title:               email.Subject,
    Message:             email.Preview,
    Icon:                "C:/Program Files/Google Mail/icons/logo.png",
    ActivationArguments: "https://gmail.com",
    Audio:               toast.Mail,
}

err := toast.Push()

func (*Notification) Push

func (n *Notification) Push() error

Push the notification to the Windows Runtime via the COM API. Ensure SetAppData has been called prior to pushing notifications.

notification := toast.Notification{
    AppID: "Example App",
    Title: "My notification",
    Message: "Some message about how important something is...",
    Icon: "go.png",
    Actions: []toast.Action{
        {"protocol", "I'm a button", ""},
        {"protocol", "Me too!", ""},
    },
}
err := notification.Push()
if err != nil {
    log.Fatalln(err)
}

type UserData

type UserData = wintoast.UserData

UserData contains user supplied data from the notification, such as text input or a selection.

Directories

Path Synopsis
examples
internal
Package tmpl wraps several templates that are used to generate notifications.
Package tmpl wraps several templates that are used to generate notifications.
Package wintoast provides a pure-Go implementation of toast notifications on Windows.
Package wintoast provides a pure-Go implementation of toast notifications on Windows.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL