vendor/github.com/gen2brain/beeep/notify_unix.go
59 lines · 1452 bytes
1//go:build (linux && !nodbus) || (freebsd && !nodbus) || (netbsd && !nodbus) || (openbsd && !nodbus)
2// +build linux,!nodbus freebsd,!nodbus netbsd,!nodbus openbsd,!nodbus
3
4package beeep
5
6import (
7 "errors"
8 "os/exec"
9
10 "github.com/godbus/dbus/v5"
11)
12
13// Notify sends desktop notification.
14//
15// On Linux it tries to send notification via D-Bus and it will fallback to `notify-send` binary.
16func Notify(title, message, appIcon string) error {
17 appIcon = pathAbs(appIcon)
18
19 cmd := func() error {
20 send, err := exec.LookPath("sw-notify-send")
21 if err != nil {
22 send, err = exec.LookPath("notify-send")
23 if err != nil {
24 return err
25 }
26 }
27
28 c := exec.Command(send, title, message, "-i", appIcon)
29 return c.Run()
30 }
31
32 knotify := func() error {
33 send, err := exec.LookPath("kdialog")
34 if err != nil {
35 return err
36 }
37 c := exec.Command(send, "--title", title, "--passivepopup", message, "10", "--icon", appIcon)
38 return c.Run()
39 }
40
41 conn, err := dbus.SessionBus()
42 if err != nil {
43 return cmd()
44 }
45 obj := conn.Object("org.freedesktop.Notifications", dbus.ObjectPath("/org/freedesktop/Notifications"))
46
47 call := obj.Call("org.freedesktop.Notifications.Notify", 0, "", uint32(0), appIcon, title, message, []string{}, map[string]dbus.Variant{}, int32(-1))
48 if call.Err != nil {
49 e := cmd()
50 if e != nil {
51 e := knotify()
52 if e != nil {
53 return errors.New("beeep: " + call.Err.Error() + "; " + e.Error())
54 }
55 }
56 }
57
58 return nil
59}