提交 9a58761b 编写于 作者: yanghye's avatar yanghye

v2.3.60 notice

上级 c9fb84f2
......@@ -10,6 +10,7 @@ package main
import (
"embed"
"energye/notice"
"fmt"
"github.com/energye/energy/cef"
"github.com/energye/energy/common/assetserve"
......@@ -72,7 +73,6 @@ func main() {
})
cef.BrowserWindow.SetBrowserInitAfter(func(window cef.IBrowserWindow) {
sysTray(window)
//tray(browserWindow)
//sys_tray.TrayMain()
return
})
......@@ -99,6 +99,10 @@ func sysTray(browserWindow cef.IBrowserWindow) {
tray := sysTray.AsSysTray()
check := tray.AddMenuItem("check")
check.Check()
not := tray.AddMenuItem("通知")
not.Click(func() {
notice.SendNotification(notice.NewNotification("标题", "内容"))
})
enable := tray.AddMenuItem("启用/禁用")
enable.Click(func() {
fmt.Println("启用/禁用 点击")
......@@ -120,6 +124,7 @@ func sysTray(browserWindow cef.IBrowserWindow) {
})
sysTray.Show()
return
//测试图标切换
go func() {
var b bool
......
package notice
import (
"strconv"
"time"
)
var uniqueID string
// Notification 表示可发送到操作系统的用户通知
type Notification struct {
Title, Content string
Icon string
Timeout int32
}
// NewNotification 创建一个通知,可以传递给SendNotification
func NewNotification(title, content string) *Notification {
return &Notification{Title: title, Content: content}
}
func UniqueID() string {
if uniqueID != "" {
return uniqueID
}
uniqueID = "missing-id-" + strconv.FormatInt(time.Now().Unix(), 10) // This is a fake unique - it just has to not be reused...
return uniqueID
}
package app
/*
#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"
)
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)
}
}
#import <Foundation/Foundation.h>
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400
#import <UserNotifications/UserNotifications.h>
#endif
static int notifyNum = 0;
extern void fallbackSend(char *cTitle, char *cBody);
bool isBundled() {
return [[NSBundle mainBundle] bundleIdentifier] != nil;
}
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400
void doSendNotification(UNUserNotificationCenter *center, NSString *title, NSString *body) {
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
[content autorelease];
content.title = title;
content.body = body;
notifyNum++;
NSString *identifier = [NSString stringWithFormat:@"fyne-notify-%d", notifyNum];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:nil];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Could not send notification: %@", error);
}
}];
}
void sendNotification(char *cTitle, char *cBody) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
NSString *title = [NSString stringWithUTF8String:cTitle];
NSString *body = [NSString stringWithUTF8String:cBody];
UNAuthorizationOptions options = UNAuthorizationOptionAlert;
[center requestAuthorizationWithOptions:options
completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!granted) {
if (error != NULL) {
NSLog(@"Error asking for permission to send notifications %@", error);
// this happens if our app was not signed, so do it the old way
fallbackSend((char *)[title UTF8String], (char *)[body UTF8String]);
} else {
NSLog(@"Unable to get permission to send notifications");
}
} else {
doSendNotification(center, title, body);
}
}];
}
#else
void sendNotification(char *cTitle, char *cBody) {
fallbackSend(cTitle, cBody);
}
#endif
//go:build linux
// +build linux
package app
import (
"sync"
"github.com/godbus/dbus/v5"
)
var once sync.Once
func SendNotification(n *Notification) {
conn, err := dbus.SessionBus() // shared connection, don't close
if err != nil {
println("Failed to send message to bus", err)
return
}
appName := UniqueID()
appIcon := a.cachedIconPath()
timeout := int32(0)
obj := conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
call := obj.Call("org.freedesktop.Notifications.Notify", 0, appName, uint32(0), appIcon, n.Title, n.Content, []string{}, map[string]dbus.Variant{}, timeout)
if call.Err != nil {
println("Failed to send message to bus", call.Err)
}
}
//go:build windows
// +build windows
package notice
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"syscall"
"golang.org/x/sys/execabs"
)
const notificationTemplate = `$title = "%s"
$content = "%s"
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
$template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
$toastXml = [xml] $template.GetXml()
$toastXml.GetElementsByTagName("text")[0].AppendChild($toastXml.CreateTextNode($title)) > $null
$toastXml.GetElementsByTagName("text")[1].AppendChild($toastXml.CreateTextNode($content)) > $null
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($toastXml.OuterXml)
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("%s").Show($toast);`
var scriptNum = 0
func SendNotification(n *Notification) {
title := escapeNotificationString(n.Title)
content := escapeNotificationString(n.Content)
appID := UniqueID()
script := fmt.Sprintf(notificationTemplate, title, content, appID)
go runScript("notify", script)
}
func escapeNotificationString(in string) string {
noSlash := strings.ReplaceAll(in, "`", "``")
return strings.ReplaceAll(noSlash, "\"", "`\"")
}
func runScript(name, script string) {
scriptNum++
appID := UniqueID()
fileName := fmt.Sprintf("notice-%s-%s-%d.ps1", appID, name, scriptNum)
tmpFilePath := filepath.Join(os.TempDir(), fileName)
err := ioutil.WriteFile(tmpFilePath, []byte(script), 0600)
if err != nil {
return
}
defer os.Remove(tmpFilePath)
launch := "(Get-Content -Encoding UTF8 -Path " + tmpFilePath + " -Raw) | Invoke-Expression"
cmd := execabs.Command("PowerShell", "-ExecutionPolicy", "Bypass", launch)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
err = cmd.Run()
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册