1package xturbo_test
2
3import (
4 "errors"
5 "log"
6
7 "golang.org/x/sys/unix"
8
9 "bnema.dev/xturbo"
10 "bnema.dev/xturbo/xproto"
11)
12
13// Replies registered with Expect carry this kind (16 and above are free).
14const kindGeometry uint16 = 16
15
16func Example() {
17 c, err := xturbo.Dial("") // "" means $DISPLAY
18 if err != nil {
19 log.Fatal(err)
20 }
21 defer c.Close()
22
23 // Startup: blocking calls, bounded by a 5 s deadline.
24 var atoms [1]uint32
25 if err := c.InternAtoms([]string{"WM_DELETE_WINDOW"}, false, atoms[:]); err != nil {
26 log.Fatal(err)
27 }
28
29 // Queue requests; they return a Seq (0 on failure, see c.Buf().Err()).
30 b := c.Buf()
31 win, err := c.NewXID()
32 if err != nil {
33 log.Fatal(err)
34 }
35 var v xproto.CreateWindowValues
36 v.SetEventMask(xproto.EventMaskExposure | xproto.EventMaskStructureNotify)
37 xproto.CreateWindow(b, 0, xproto.Window(win), xproto.Window(c.Root()),
38 0, 0, 640, 480, 0, xproto.WindowClassInputOutput, 0, &v)
39 xproto.MapWindow(b, xproto.Window(win))
40 if seq := xproto.GetGeometry(b, xproto.Drawable(win)); seq != 0 {
41 if err := c.Expect(seq, kindGeometry, win, 0, 0, 0); err != nil {
42 log.Fatal(err)
43 }
44 }
45
46 // Callbacks run inside Dispatch. Events, replies and errors are borrowed:
47 // copy what you keep.
48 h := &xturbo.Handler{
49 OnEvent: func(ev *xturbo.Event) {
50 switch ev.Kind {
51 case xproto.KindExpose:
52 e := xproto.ExposeOf(ev)
53 log.Printf("expose %dx%d", e.Width(), e.Height())
54 }
55 },
56 OnReply: func(r *xturbo.Reply) {
57 if r.Kind == kindGeometry {
58 if g, ok := xproto.ParseGetGeometryReply(r.Raw); ok {
59 log.Printf("window %#x is %dx%d", r.Args[0], g.Width(), g.Height())
60 }
61 }
62 },
63 OnError: func(e *xturbo.XError) { log.Print(e) },
64 }
65
66 for {
67 // Flush never blocks. On ErrWouldBlock, also wait for POLLOUT.
68 events := int16(unix.POLLIN)
69 if err := c.Flush(); errors.Is(err, xturbo.ErrWouldBlock) {
70 events |= unix.POLLOUT
71 } else if err != nil {
72 log.Fatal(err)
73 }
74 fds := []unix.PollFd{{Fd: int32(c.Fd()), Events: events}}
75 if _, err := unix.Poll(fds, -1); err != nil && err != unix.EINTR {
76 log.Fatal(err)
77 }
78 if err := c.Dispatch(h); err != nil { // io.EOF: server closed
79 log.Fatal(err)
80 }
81 // Keep the XID pool topped up without blocking later.
82 if c.XIDsLow() {
83 _ = c.PrefetchXIDs()
84 }
85 }
86}