energy/ipc/ipc.go
2023-03-09 23:17:55 +08:00

94 lines
1.7 KiB
Go

//----------------------------------------
//
// Copyright © yanghy. All Rights Reserved.
//
// Licensed under Apache License Version 2.0, January 2004
//
// https://www.apache.org/licenses/LICENSE-2.0
//
//----------------------------------------
package ipc
import (
"github.com/energye/energy/common"
"sync"
)
var (
browser *browserIPC
)
// browserIPC 主进程 IPC
type browserIPC struct {
onEvent map[string]EmitCallback
lock sync.Mutex
}
type EmitCallback func(context IContext)
func init() {
if common.Args.IsMain() {
browser = &browserIPC{onEvent: make(map[string]EmitCallback)}
}
}
//On
// IPC GO 监听事件
func On(name string, fn EmitCallback) {
if browser != nil {
browser.addOnEvent(name, fn)
}
}
//RemoveOn
// IPC GO 移除监听事件
func RemoveOn(name string) {
if browser == nil || name == "" {
return
}
browser.lock.Lock()
defer browser.lock.Unlock()
delete(browser.onEvent, name)
}
//Emit
// IPC GO 中触发 JS 监听的事件
func Emit(name string) {
}
//CheckOnEvent
// IPC 检查 GO 中监听的事件是存在, 并返回回调函数
func CheckOnEvent(name string) EmitCallback {
if browser == nil || name == "" {
return nil
}
browser.lock.Lock()
defer browser.lock.Unlock()
if callback, ok := browser.onEvent[name]; ok {
return callback
}
return nil
}
// addOnEvent 添加监听事件
func (m *browserIPC) addOnEvent(name string, fn EmitCallback) {
if m == nil || name == "" || fn == nil {
return
}
m.lock.Lock()
defer m.lock.Unlock()
m.onEvent[name] = fn
}
// emitOnEvent 触发监听事件
func (m *browserIPC) emitOnEvent(name string, argumentList IArrayValue) {
if m == nil || name == "" || argumentList == nil {
return
}
m.lock.Lock()
defer m.lock.Unlock()
}