Debian Codegraph @

request.go

raw symbols SCIP
1 package wl
2
3 import (
4 "errors"
5 "net"
6 "syscall"
7 )
8
9 type Request struct {
10 pid ProxyId
11 opcode uint32
12 data []byte
13 oob []byte
14 }
15
16 func (context *Context) SendRequest(proxy Proxy, opcode uint32, args ...interface{}) (err error) {
17 req := Request{
18 pid: proxy.Id(),
19 opcode: opcode,
20 }
21
22 for _, arg := range args {
23 req.Write(arg)
24 }
25
26 return writeRequest(context.conn, req)
27 }
28
29 func (r *Request) Write(arg interface{}) {
30 switch t := arg.(type) {
31 case Proxy:
32 r.PutProxy(t)
33 case uint32:
34 r.PutUint32(t)
35 case int32:
36 r.PutInt32(t)
37 case float32:
38 r.PutFloat32(t)
39 case string:
40 r.PutString(t)
41 case []int32:
42 r.PutArray(t)
43 case uintptr:
44 r.PutFd(t)
45 default:
46 panic("Invalid Wayland request parameter type.")
47 }
48 }
49
50 func (r *Request) PutUint32(u uint32) {
51 buf := bytePool.Take(4)
52 order.PutUint32(buf, u)
53 r.data = append(r.data, buf...)
54 }
55
56 func (r *Request) PutProxy(p Proxy) {
57 r.PutUint32(uint32(p.Id()))
58 }
59
60 func (r *Request) PutInt32(i int32) {
61 r.PutUint32(uint32(i))
62 }
63
64 func (r *Request) PutFloat32(f float32) {
65 fx := float64ToFixed(float64(f))
66 r.PutUint32(uint32(fx))
67 }
68
69 func (r *Request) PutString(s string) {
70 tail := 4 - (len(s) & 0x3)
71 r.PutUint32(uint32(len(s) + tail))
72 r.data = append(r.data, []byte(s)...)
73 // if padding required
74 if tail > 0 {
75 padding := make([]byte, tail)
76 r.data = append(r.data, padding...)
77 }
78 }
79
80 func (r *Request) PutArray(a []int32) {
81 r.PutUint32(uint32(len(a)))
82 for _, e := range a {
83 r.PutUint32(uint32(e))
84 }
85 }
86
87 func (r *Request) PutFd(fd uintptr) {
88 rights := syscall.UnixRights(int(fd))
89 r.oob = append(r.oob, rights...)
90 }
91
92 func writeRequest(conn *net.UnixConn, r Request) error {
93 var header []byte
94 // calculate message total size
95 size := uint32(len(r.data) + 8)
96 buf := make([]byte, 4)
97 order.PutUint32(buf, uint32(r.pid))
98 header = append(header, buf...)
99 order.PutUint32(buf, uint32(size<<16|r.opcode&0x0000ffff))
100 header = append(header, buf...)
101
102 d, c, err := conn.WriteMsgUnix(append(header, r.data...), r.oob, nil)
103 if err != nil {
104 return err
105 }
106 if c != len(r.oob) || d != (len(header)+len(r.data)) {
107 return errors.New("WriteMsgUnix failed")
108 }
109 bytePool.Give(r.data)
110
111 return nil
112 }