This repository has been archived by the owner on Nov 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
wl-scanner.go
584 lines (495 loc) · 15.4 KB
/
wl-scanner.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
package main
import (
"bytes"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
)
type (
Protocol struct {
XMLName xml.Name `xml:"protocol"`
Name string `xml:"name,attr"`
Copyright string `xml:"copyright"`
Interfaces []Interface `xml:"interface"`
}
Description struct {
XMLName xml.Name `xml:"description"`
Summary string `xml:"summary,attr"`
Description string `xml:"description"`
}
Interface struct {
XMLName xml.Name `xml:"interface"`
Name string `xml:"name,attr"`
Version int `xml:"version,attr"`
Since int `xml:"since,attr"` // maybe in future versions
Description Description `xml:"description"`
Requests []Request `xml:"request"`
Events []Event `xml:"event"`
Enums []Enum `xml:"enum"`
}
Request struct {
XMLName xml.Name `xml:"request"`
Name string `xml:"name,attr"`
Type string `xml:"type,attr"`
Since int `xml:"since,attr"`
Description Description `xml:"description"`
Args []Arg `xml:"arg"`
}
Arg struct {
XMLName xml.Name `xml:"arg"`
Name string `xml:"name,attr"`
Type string `xml:"type,attr"`
Interface string `xml:"interface,attr"`
Enum string `xml:"enum,attr"`
AllowNull bool `xml:"allow-null,attr"`
Summary string `xml:"summary,attr"`
}
Event struct {
XMLName xml.Name `xml:"event"`
Name string `xml:"name,attr"`
Since int `xml:"since,attr"`
Description Description `xml:"description"`
Args []Arg `xml:"arg"`
}
Enum struct {
XMLName xml.Name `xml:"enum"`
Name string `xml:"name,attr"`
BitField bool `xml:"bitfield,attr"`
Description Description `xml:"description"`
Entries []Entry `xml:"entry"`
}
Entry struct {
XMLName xml.Name `xml:"entry"`
Name string `xml:"name,attr"`
Value string `xml:"value,attr"`
Summary string `xml:"summary,attr"`
}
)
var (
wlTypes map[string]string = map[string]string{
"int": "int32",
"uint": "uint32",
"string": "string",
"fd": "uintptr",
"fixed": "float32",
"array": "[]int32",
}
bufTypesMap map[string]string = map[string]string{
"int32": "Int32()",
"uint32": "Uint32()",
"string": "String()",
"float32": "Float32()",
"[]int32": "Array()",
"uintptr": "FD()",
}
wlNames map[string]string
constBuffer bytes.Buffer
ifaceBuffer bytes.Buffer
reqCodesBuffer bytes.Buffer
overwrite = flag.Bool("overwrite", false, "Overwrite existing client.go file")
develXml = flag.Bool("devel", false, "Get development version of wayland.xml from repository")
)
func init() {
flag.Parse()
log.SetFlags(0)
}
func main() {
var xmlFile *os.File
if *develXml {
file, err := getDevelXml()
if err != nil {
file.Close()
log.Fatalf("Error while reading xml file: %s", err)
}
xmlFile = file
xmlFile.Seek(0, 0)
} else {
xmlFilePath, err := filepath.Abs("wayland.xml")
if err != nil {
log.Fatalf("Cannot find wayland.xml: %s", err)
}
file, err := os.Open(xmlFilePath)
if err != nil {
log.Fatalf("Cannot open wayland.xml: %s", err)
}
xmlFile = file
}
defer xmlFile.Close()
var protocol Protocol
if err := xml.NewDecoder(xmlFile).Decode(&protocol); err != nil {
log.Fatalf("Cannot decode wayland.xml: %s", err)
}
wlNames = make(map[string]string)
fmt.Fprintln(&constBuffer, "//generated by wl-scanner\n//https://github.com/sternix/wl-scanner")
fmt.Fprintln(&constBuffer, "package wl")
for _, iface := range protocol.Interfaces {
//required for arg type's determine
caseAndRegister(iface.Name)
}
//TODO is \n required
fmt.Fprintln(&reqCodesBuffer, "\n//Interface Request Codes") // request codes
fmt.Fprintln(&reqCodesBuffer, "const (") // request codes
for _, iface := range protocol.Interfaces {
eventBuffer, eventNames := interfaceEvents(iface)
eventBuffer.WriteTo(&ifaceBuffer)
interfaceTypes(iface, eventNames)
interfaceConstructor(iface, eventNames)
if len(eventNames) > 0 {
interfaceHandleEvents(iface, eventNames)
interfaceDispose(iface)
interfaceDispatch(iface)
}
interfaceRequests(iface)
interfaceEnums(iface)
}
fmt.Fprint(&reqCodesBuffer, ")") // request codes end
// if file exists
if _, err := os.Stat("client.go"); err == nil {
if !*overwrite {
log.Print("client.go exists if you want to overwrite try -overwrite flag")
return
}
}
file, err := os.Create("client.go")
if err != nil {
log.Fatalf("Cannot create file: %s", err)
}
constBuffer.WriteTo(file)
reqCodesBuffer.WriteTo(file)
ifaceBuffer.WriteTo(file)
file.Close()
// go fmt file
fmtFile()
}
// register names to map
func caseAndRegister(wlName string) string {
var orj string = wlName
wlName = CamelCase(wlName)
wlNames[orj] = wlName
return wlName
}
func enumArgName(ifaceName, enumName string) string {
if strings.Index(enumName, ".") == -1 {
return ifaceName + CamelCase(enumName)
}
parts := strings.Split(enumName, ".")
if len(parts) != 2 {
log.Fatal("enum args must be \"interface.enum\" format")
}
return CamelCase(parts[0]) + CamelCase(parts[1])
}
func CamelCase(wlName string) string {
if strings.HasPrefix(wlName, "wl_") {
wlName = strings.TrimPrefix(wlName, "wl_")
}
// replace all "_" chars to " " chars
wlName = strings.Replace(wlName, "_", " ", -1)
// Capitalize first chars
wlName = strings.Title(wlName)
// remove all spaces
wlName = strings.Replace(wlName, " ", "", -1)
return wlName
}
func interfaceConstructor(iface Interface, eventNames []string) {
ifaceName := wlNames[iface.Name]
// interface constructor
fmt.Fprintf(&ifaceBuffer, "\nfunc New%s(conn *Connection) *%s {\n", ifaceName, ifaceName)
fmt.Fprintf(&ifaceBuffer, "ret := new(%s)\n", ifaceName)
for _, evName := range eventNames {
fmt.Fprintf(&ifaceBuffer, "ret.%sChan = make(chan *%s%sEvent)\n", evName, ifaceName, evName)
}
if len(eventNames) > 0 {
fmt.Fprintln(&ifaceBuffer, "ret.disposeChan = make(chan struct{})")
fmt.Fprintln(&ifaceBuffer, "go ret.handleEvents()")
}
fmt.Fprintln(&ifaceBuffer, "conn.Register(ret)")
fmt.Fprintln(&ifaceBuffer, "return ret")
fmt.Fprintln(&ifaceBuffer, "}")
}
func interfaceHandleEvents(iface Interface, eventNames []string) {
ifaceName := wlNames[iface.Name]
fmt.Fprintf(&ifaceBuffer, "\nfunc (p *%s) handleEvents() {\n", ifaceName)
fmt.Fprintln(&ifaceBuffer, "loop:")
fmt.Fprintln(&ifaceBuffer, "for {")
fmt.Fprintln(&ifaceBuffer, "select {")
for _, evName := range eventNames {
fmt.Fprintf(&ifaceBuffer, "case ev := <-p.%sChan:\n", evName)
fmt.Fprintf(&ifaceBuffer, "if p.On%s != nil {\n", evName)
fmt.Fprintf(&ifaceBuffer, "p.On%s(ev)\n", evName)
fmt.Fprintln(&ifaceBuffer, "}")
}
fmt.Fprintln(&ifaceBuffer, "case <-p.disposeChan:")
fmt.Fprintln(&ifaceBuffer, "break loop")
fmt.Fprintln(&ifaceBuffer, "}") // select
fmt.Fprintln(&ifaceBuffer, "}") // for
fmt.Fprintln(&ifaceBuffer, "}") // func
}
func interfaceDispose(iface Interface) {
ifaceName := wlNames[iface.Name]
fmt.Fprintf(&ifaceBuffer, "\nfunc (p *%s) Dispose() {\n", ifaceName)
fmt.Fprintln(&ifaceBuffer, "p.disposeChan <- struct{}{}")
fmt.Fprintln(&ifaceBuffer, "}")
}
/*
switch opcode {
case 0:
//ret := new(DisplayErrorEvent) TODO
ret := DisplayErrorEvent{
ObjectId: buf.Proxy(),
Code: buf.Uint32(),
Message: buf.String(),
}
p.errorChan<-ret
case 1:
ret := DisplayDeleteIdEvent {
Id : buf.Uint32(),
}
p.deleteIdChan<-ret
default: // for debug
log.Print("Unhandled event %d",opcode)
}
*/
// if events > 0
func interfaceDispatch(iface Interface) {
ifaceName := wlNames[iface.Name]
fmt.Fprintf(&ifaceBuffer, "\nfunc (p *%s) Dispatch(event *Event) {\n", ifaceName)
fmt.Fprintln(&ifaceBuffer, "switch event.opcode {")
for i, event := range iface.Events {
eventName := caseAndRegister(event.Name)
fmt.Fprintf(&ifaceBuffer, "case %d:\n", i)
fmt.Fprintf(&ifaceBuffer, "ev := new(%s%sEvent)\n", ifaceName, eventName)
for _, arg := range event.Args {
if t, ok := wlTypes[arg.Type]; ok { // if basic type
/*
if arg.Type == "uint" && arg.Enum != "" { // enum type
enumTypeName := ifaceName + CamelCase(arg.Enum)
fmt.Fprintf(&eventBuffer, "%s %s\n", CamelCase(arg.Name), enumTypeName)
} else {
fmt.Fprintf(&eventBuffer, "%s %s\n", CamelCase(arg.Name), t)
}*/
bufMethod, ok := bufTypesMap[t]
if !ok {
log.Printf("%s not registered", t)
} else {
fmt.Fprintf(&ifaceBuffer, "ev.%s = event.%s\n", CamelCase(arg.Name), bufMethod)
}
} else { // interface type
if (arg.Type == "object" || arg.Type == "new_id") && arg.Interface != "" {
t = "*" + wlNames[arg.Interface] // type assertion
fmt.Fprintf(&ifaceBuffer, "ev.%s = event.Proxy(p.Connection()).(%s)\n", CamelCase(arg.Name), t)
} else {
fmt.Fprintf(&ifaceBuffer, "ev.%s = event.Proxy(p.Connection())\n", CamelCase(arg.Name))
}
}
}
fmt.Fprintf(&ifaceBuffer, "p.%sChan<-ev\n", eventName)
}
/*
fmt.Fprintln(&ifaceBuffer,"default:")
defStr := fmt.Sprintf("%s Dispatch: Unhandled event:",ifaceName)
fmt.Fprintf(&ifaceBuffer, defStr + "opcode %d",
*/
fmt.Fprintln(&ifaceBuffer, "}") // switch
fmt.Fprintln(&ifaceBuffer, "}") // func
}
func interfaceTypes(iface Interface, eventNames []string) {
ifaceName := wlNames[iface.Name]
// interface type definition
fmt.Fprintf(&ifaceBuffer, "\ntype %s struct {\n", ifaceName)
fmt.Fprintln(&ifaceBuffer, "BaseProxy")
for _, evName := range eventNames {
fmt.Fprintf(&ifaceBuffer, "%sChan chan *%s%sEvent\n", evName, ifaceName, evName)
}
//TODO some work above
if len(eventNames) > 0 {
fmt.Fprintln(&ifaceBuffer, "disposeChan chan struct{}")
for _, evName := range eventNames {
fmt.Fprintf(&ifaceBuffer, "On%s func(*%s%sEvent)\n", evName, ifaceName, evName)
}
}
fmt.Fprintln(&ifaceBuffer, "}")
}
func interfaceRequests(iface Interface) {
ifaceName := wlNames[iface.Name]
// interface method definitions (requests)
// order used for request identification
for order, req := range iface.Requests {
reqName := CamelCase(req.Name)
reqCodeName := strings.ToTitle(fmt.Sprintf("_%s_%s", ifaceName, reqName)) // first _ for not export constant
fmt.Fprintf(&reqCodesBuffer, "%s = %d\n", reqCodeName, order)
fmt.Fprintf(&ifaceBuffer, "\nfunc (p *%s) %s(", ifaceName, reqName)
// get args buffer
requestArgs(ifaceName, req).WriteTo(&ifaceBuffer)
fmt.Fprint(&ifaceBuffer, ")") // close the args
// get returns buffer
requestRets(req).WriteTo(&ifaceBuffer)
fmt.Fprintln(&ifaceBuffer, "{")
// get method body
requestBody(req, reqCodeName).WriteTo(&ifaceBuffer)
fmt.Fprintln(&ifaceBuffer, "\n}")
}
}
func interfaceEnums(iface Interface) {
ifaceName := wlNames[iface.Name]
// Enums - Constants
for _, enum := range iface.Enums {
enumName := caseAndRegister(enum.Name)
//constTypeName := ifaceName + enumName
//fmt.Fprintf(&constBuffer, "\ntype %s uint32\n", constTypeName) // enums are uint
fmt.Fprintln(&constBuffer, "\nconst (")
for _, entry := range enum.Entries {
entryName := caseAndRegister(entry.Name)
constName := ifaceName + enumName + entryName
fmt.Fprintf(&constBuffer, "%s = %s\n", constName, entry.Value)
}
fmt.Fprintln(&constBuffer, ")")
}
}
func interfaceEvents(iface Interface) (bytes.Buffer, []string) {
var (
eventBuffer bytes.Buffer
eventNames []string
ifaceName = wlNames[iface.Name]
)
// Event struct types
for _, event := range iface.Events {
eventName := caseAndRegister(event.Name)
fmt.Fprintf(&eventBuffer, "\ntype %s%sEvent struct {\n", ifaceName, eventName)
for _, arg := range event.Args {
if t, ok := wlTypes[arg.Type]; ok { // if basic type
/*
if arg.Type == "uint" && arg.Enum != "" { // enum type
enumTypeName := ifaceName + CamelCase(arg.Enum)
fmt.Fprintf(&eventBuffer, "%s %s\n", CamelCase(arg.Name), enumTypeName)
} else {
fmt.Fprintf(&eventBuffer, "%s %s\n", CamelCase(arg.Name), t)
}*/
fmt.Fprintf(&eventBuffer, "%s %s\n", CamelCase(arg.Name), t)
} else { // interface type
if (arg.Type == "object" || arg.Type == "new_id") && arg.Interface != "" {
t = "*" + wlNames[arg.Interface]
} else {
t = "Proxy"
}
fmt.Fprintf(&eventBuffer, "%s %s\n", CamelCase(arg.Name), t)
}
}
eventNames = append(eventNames, eventName)
fmt.Fprintln(&eventBuffer, "}")
}
return eventBuffer, eventNames
}
func requestArgs(ifaceName string, req Request) *bytes.Buffer {
var (
args []string
argsBuffer bytes.Buffer
)
for _, arg := range req.Args {
// special type, for example registry.bind
if arg.Type == "new_id" {
if arg.Interface == "" {
args = append(args, "iface string")
args = append(args, "version uint32")
args = append(args, fmt.Sprintf("%s Proxy", arg.Name))
} else {
continue
}
} else if arg.Type == "object" && arg.Interface != "" {
argTypeName := wlNames[arg.Interface]
args = append(args, fmt.Sprintf("%s *%s", arg.Name, argTypeName))
/*} else if arg.Type == "uint" && arg.Enum != "" {
args = append(args, fmt.Sprintf("%s %s", arg.Name, enumArgName(ifaceName, arg.Enum)))
*/
} else {
args = append(args, fmt.Sprintf("%s %s", arg.Name, wlTypes[arg.Type]))
}
}
fmt.Fprint(&argsBuffer, strings.Join(args, ","))
return &argsBuffer
}
func requestRets(req Request) *bytes.Buffer {
var (
rets []string
retsBuffer bytes.Buffer
)
for _, arg := range req.Args {
if arg.Type == "new_id" && arg.Interface != "" {
retTypeName := wlNames[arg.Interface]
rets = append(rets, fmt.Sprintf("*%s", retTypeName))
}
}
// all request have an error return
rets = append(rets, "error")
retstr := strings.Join(rets, ",")
if len(rets) > 1 {
fmt.Fprintf(&retsBuffer, "( %s )", retstr)
} else {
fmt.Fprint(&retsBuffer, retstr)
}
return &retsBuffer
}
func requestBody(req Request, reqCodeName string) *bytes.Buffer {
var (
params []string
bodyBuffer bytes.Buffer
hasRet string
)
for _, arg := range req.Args {
if arg.Type == "new_id" {
if arg.Interface != "" {
retTypeName := wlNames[arg.Interface]
fmt.Fprintf(&bodyBuffer, "ret := New%s(p.Connection())\n", retTypeName)
params = append(params, "Proxy(ret)")
hasRet = "ret,"
} else {
params = append(params, "iface")
params = append(params, "version")
params = append(params, arg.Name)
}
} else {
params = append(params, arg.Name)
}
}
fmt.Fprintf(&bodyBuffer, "return %s p.Connection().SendRequest(p,%s,%s)", hasRet, reqCodeName, strings.Join(params, ","))
return &bodyBuffer
}
func getDevelXml() (*os.File, error) {
url := "https://cgit.freedesktop.org/wayland/wayland/plain/protocol/wayland.xml"
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("HTTP Get error: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Cannot get wayland.xml StatusCode != StatusOK")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Cannot read response body: %s", err)
}
file, err := ioutil.TempFile("", "devel_wayland_xml")
if err != nil {
return nil, fmt.Errorf("Cannot create temp file: %s", err)
}
file.Write(body)
return file, nil
}
func fmtFile() {
goex, err := exec.LookPath("go")
if err != nil {
log.Printf("go executable cannot found run \"go fmt client.go\" yourself: %s", err)
return
}
cmd := exec.Command(goex, "fmt", "client.go")
errr := cmd.Run()
if errr != nil {
log.Fatalf("Cannot run cmd: %s", errr)
}
}