github.com/robotn/xgb@v0.0.0-20190912153532-2cb92d044934/examples/get-active-window/main.go (about)

     1  // Example get-active-window reads the _NET_ACTIVE_WINDOW property of the root
     2  // window and uses the result (a window id) to get the name of the window.
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"log"
     8  
     9  	"github.com/robotn/xgb"
    10  	"github.com/robotn/xgb/xproto"
    11  )
    12  
    13  func main() {
    14  	X, err := xgb.NewConn()
    15  	if err != nil {
    16  		log.Fatal(err)
    17  	}
    18  
    19  	// Get the window id of the root window.
    20  	setup := xproto.Setup(X)
    21  	root := setup.DefaultScreen(X).Root
    22  
    23  	// Get the atom id (i.e., intern an atom) of "_NET_ACTIVE_WINDOW".
    24  	aname := "_NET_ACTIVE_WINDOW"
    25  	activeAtom, err := xproto.InternAtom(X, true, uint16(len(aname)),
    26  		aname).Reply()
    27  	if err != nil {
    28  		log.Fatal(err)
    29  	}
    30  
    31  	// Get the atom id (i.e., intern an atom) of "_NET_WM_NAME".
    32  	aname = "_NET_WM_NAME"
    33  	nameAtom, err := xproto.InternAtom(X, true, uint16(len(aname)),
    34  		aname).Reply()
    35  	if err != nil {
    36  		log.Fatal(err)
    37  	}
    38  
    39  	// Get the actual value of _NET_ACTIVE_WINDOW.
    40  	// Note that 'reply.Value' is just a slice of bytes, so we use an
    41  	// XGB helper function, 'Get32', to pull an unsigned 32-bit integer out
    42  	// of the byte slice. We then convert it to an X resource id so it can
    43  	// be used to get the name of the window in the next GetProperty request.
    44  	reply, err := xproto.GetProperty(X, false, root, activeAtom.Atom,
    45  		xproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()
    46  	if err != nil {
    47  		log.Fatal(err)
    48  	}
    49  	windowId := xproto.Window(xgb.Get32(reply.Value))
    50  	fmt.Printf("Active window id: %X\n", windowId)
    51  
    52  	// Now get the value of _NET_WM_NAME for the active window.
    53  	// Note that this time, we simply convert the resulting byte slice,
    54  	// reply.Value, to a string.
    55  	reply, err = xproto.GetProperty(X, false, windowId, nameAtom.Atom,
    56  		xproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()
    57  	if err != nil {
    58  		log.Fatal(err)
    59  	}
    60  	fmt.Printf("Active window name: %s\n", string(reply.Value))
    61  }