energy/pkgs/notice/notice_darwin.go

66 lines
1.5 KiB
Go
Raw Normal View History

2023-01-26 12:42:54 +08:00
//----------------------------------------
//
// Copyright © yanghy. All Rights Reserved.
//
// Licensed under Apache License Version 2.0, January 2004
//
// https://www.apache.org/licenses/LICENSE-2.0
2023-01-26 12:42:54 +08:00
//
//----------------------------------------
2023-01-26 12:33:19 +08:00
//go:build darwin
// +build darwin
2023-01-25 22:26:08 +08:00
package notice
2023-01-25 21:02:18 +08:00
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation
#include <stdbool.h>
#include <stdlib.h>
bool isBundled();
void sendNotification(char *title, char *content);
*/
import "C"
import (
"fmt"
"golang.org/x/sys/execabs"
"strings"
2023-01-26 12:33:19 +08:00
"unsafe"
2023-01-25 21:02:18 +08:00
)
func SendNotification(n *Notification) {
if C.isBundled() {
titleStr := C.CString(n.Title)
defer C.free(unsafe.Pointer(titleStr))
contentStr := C.CString(n.Content)
defer C.free(unsafe.Pointer(contentStr))
C.sendNotification(titleStr, contentStr)
return
}
fallbackNotification(n.Title, n.Content)
}
func escapeNotificationString(in string) string {
noSlash := strings.ReplaceAll(in, "\\", "\\\\")
return strings.ReplaceAll(noSlash, "\"", "\\\"")
}
//export fallbackSend
func fallbackSend(cTitle, cContent *C.char) {
title := C.GoString(cTitle)
content := C.GoString(cContent)
fallbackNotification(title, content)
}
func fallbackNotification(title, content string) {
template := `display notification "%s" with title "%s"`
script := fmt.Sprintf(template, escapeNotificationString(content), escapeNotificationString(title))
err := execabs.Command("osascript", "-e", script).Start()
if err != nil {
println("Failed to launch darwin notify script", err)
}
}