github.com/jmigpin/editor@v1.6.0/driver/xdriver/xutil/atoms.go (about)

     1  package xutil
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  
     7  	"github.com/BurntSushi/xgb"
     8  	"github.com/BurntSushi/xgb/xproto"
     9  )
    10  
    11  // Tags can be used with: `loadAtoms:"atomname"`.
    12  // "st" should be a pointer to a struct with xproto.Atom fields.
    13  // "onlyIfExists" asks the x server to assign a value only if the atom exists.
    14  func LoadAtoms(conn *xgb.Conn, st interface{}, onlyIfExists bool) error {
    15  	// request atoms
    16  	// use reflection to get atoms names
    17  	typ := reflect.Indirect(reflect.ValueOf(st)).Type()
    18  	var cookies []xproto.InternAtomCookie
    19  	for i := 0; i < typ.NumField(); i++ {
    20  		sf := typ.Field(i)
    21  
    22  		name := sf.Name
    23  		tagStr := sf.Tag.Get("loadAtoms")
    24  		if tagStr != "" {
    25  			name = tagStr
    26  		}
    27  		// request value
    28  		cookie := xproto.InternAtom(conn, onlyIfExists, uint16(len(name)), name)
    29  		cookies = append(cookies, cookie)
    30  	}
    31  	// get atoms
    32  	val := reflect.Indirect(reflect.ValueOf(st))
    33  	for i := 0; i < val.NumField(); i++ {
    34  		reply, err := cookies[i].Reply() // get value
    35  		if err != nil {
    36  			return err
    37  		}
    38  		v := val.Field(i)
    39  		v.Set(reflect.ValueOf(reply.Atom))
    40  	}
    41  	return nil
    42  }
    43  
    44  //----------
    45  
    46  func GetAtomName(conn *xgb.Conn, atom xproto.Atom) (string, error) {
    47  	cookie := xproto.GetAtomName(conn, atom)
    48  	r, err := cookie.Reply()
    49  	if err != nil {
    50  		return "", err
    51  	}
    52  	return r.Name, nil
    53  }
    54  
    55  func PrintAtomsNames(conn *xgb.Conn, atoms ...xproto.Atom) {
    56  	for _, a := range atoms {
    57  		name, err := GetAtomName(conn, a)
    58  		if err != nil {
    59  			fmt.Println(err)
    60  			continue
    61  		}
    62  		fmt.Printf("%d: %s\n", a, name)
    63  	}
    64  }