forked from wailsapp/wails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_instance.go
69 lines (56 loc) · 1.6 KB
/
single_instance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//go:build linux
// +build linux
package linux
import (
"encoding/json"
"github.com/godbus/dbus/v5"
"github.com/secoba/wails/v2/pkg/options"
"os"
"strings"
)
type dbusHandler func(string)
func (f dbusHandler) SendMessage(message string) *dbus.Error {
f(message)
return nil
}
func SetupSingleInstance(uniqueID string) {
id := "wails_app_" + strings.ReplaceAll(strings.ReplaceAll(uniqueID, "-", "_"), ".", "_")
dbusName := "org." + id + ".SingleInstance"
dbusPath := "/org/" + id + "/SingleInstance"
conn, err := dbus.ConnectSessionBus()
// if we will reach any error during establishing connection or sending message we will just continue.
// It should not be the case that such thing will happen actually, but just in case.
if err != nil {
return
}
f := dbusHandler(func(message string) {
var secondInstanceData options.SecondInstanceData
err := json.Unmarshal([]byte(message), &secondInstanceData)
if err == nil {
secondInstanceBuffer <- secondInstanceData
}
})
err = conn.Export(f, dbus.ObjectPath(dbusPath), dbusName)
if err != nil {
return
}
reply, err := conn.RequestName(dbusName, dbus.NameFlagDoNotQueue)
if err != nil {
return
}
// if name already taken, try to send args to existing instance, if no success just launch new instance
if reply == dbus.RequestNameReplyExists {
data := options.SecondInstanceData{
Args: os.Args[1:],
}
serialized, err := json.Marshal(data)
if err != nil {
return
}
err = conn.Object(dbusName, dbus.ObjectPath(dbusPath)).Call(dbusName+".SendMessage", 0, string(serialized)).Store()
if err != nil {
return
}
os.Exit(1)
}
}