/
foreground_linux.go
90 lines (73 loc) · 1.93 KB
/
foreground_linux.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//go:build linux
package foreground
import (
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
)
// getActiveWindowID returns the X11 window ID of the active window.
func getActiveWindowID() (xproto.Window, error) {
conn, err := xgb.NewConn()
if err != nil {
return 0, err
}
defer conn.Close()
setup := xproto.Setup(conn)
root := setup.DefaultScreen(conn).Root
aname := "_NET_ACTIVE_WINDOW"
activeAtom, err := xproto.InternAtom(conn, true, uint16(len(aname)), aname).Reply()
if err != nil {
return 0, err
}
reply, err := xproto.GetProperty(conn, false, root, activeAtom.Atom,
xproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()
if err != nil {
return 0, err
}
return xproto.Window(xgb.Get32(reply.Value)), nil
}
// GetForegroundPID returns the PID of the foreground window.
func GetForegroundPID() (uint32, error) {
windowID, err := getActiveWindowID()
if err != nil {
return 0, err
}
conn, err := xgb.NewConn()
if err != nil {
return 0, err
}
defer conn.Close()
aname := "_NET_WM_PID"
pidAtom, err := xproto.InternAtom(conn, true, uint16(len(aname)), aname).Reply()
if err != nil {
return 0, err
}
reply, err := xproto.GetProperty(conn, false, windowID, pidAtom.Atom,
xproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()
if err != nil {
return 0, err
}
return xgb.Get32(reply.Value), nil
}
// GetForegroundTitle returns the title of the foreground window.
func GetForegroundTitle() (string, error) {
windowID, err := getActiveWindowID()
if err != nil {
return "", err
}
conn, err := xgb.NewConn()
if err != nil {
return "", err
}
defer conn.Close()
aname := "_NET_WM_NAME"
nameAtom, err := xproto.InternAtom(conn, true, uint16(len(aname)), aname).Reply()
if err != nil {
return "", err
}
reply, err := xproto.GetProperty(conn, false, windowID, nameAtom.Atom,
xproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()
if err != nil {
return "", err
}
return string(reply.Value), nil
}