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-dev.go
528 lines (457 loc) · 11.9 KB
/
wl-scanner-dev.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
package main
import (
"bytes"
"encoding/xml"
"fmt"
"log"
"os"
"os/exec"
"strings"
"text/template"
)
// xml types
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"`
}
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"`
}
)
// go types
type (
GoInterface struct {
Name string
WlInterface Interface
Requests []GoRequest
Events []GoEvent
Enums []GoEnum
}
GoRequest struct {
Name string
IfaceName string
Params string
Returns string
Args string
HasNewId bool
NewIdInterface string
Order int
}
GoEvent struct {
Name string
IfaceName string
PName string
Args []GoArg
}
GoArg struct {
Name string
Type string
PName string
BufMethod string
}
GoEnum struct {
Name string
IfaceName string
Entries []GoEntry
}
GoEntry struct {
Name string
Value string
}
)
var (
wlTypes map[string]string = map[string]string{
"int": "int32",
"uint": "uint32",
"string": "string",
"fd": "uintptr",
"fixed": "float32",
"array": "[]int32",
}
// sync with event.go
bufTypesMap map[string]string = map[string]string{
"int32": "Int32()",
"uint32": "Uint32()",
"string": "String()",
"float32": "Float32()",
"[]int32": "Array()",
"uintptr": "FD()",
}
wlNames map[string]string
fileBuffer = &bytes.Buffer{}
)
func init() {
log.SetFlags(0)
}
func main() {
var protocol Protocol
file, err := os.Open("wayland.xml")
if err != nil {
log.Fatal(err)
}
err = decodeWlXML(file, &protocol)
if err != nil {
log.Fatal(err)
}
wlNames = make(map[string]string)
// required for request and event parameters
for _, iface := range protocol.Interfaces {
caseAndRegister(iface.Name)
}
fmt.Fprintln(fileBuffer, "//generated by wl-scanner\n//https://github.com/sternix/wl-scanner")
fmt.Fprintln(fileBuffer, "package wl")
fmt.Fprintln(fileBuffer, "import \"sync\"")
for _, iface := range protocol.Interfaces {
goIface := GoInterface{
Name: wlNames[iface.Name],
WlInterface: iface,
}
goIface.ProcessEvents()
goIface.Constructor()
goIface.ProcessRequests()
goIface.ProcessEnums()
}
out, err := os.Create("client.go")
if err != nil {
log.Fatal(err)
}
defer out.Close()
fileBuffer.WriteTo(out)
fmtFile()
}
func decodeWlXML(file *os.File, prot *Protocol) error {
err := xml.NewDecoder(file).Decode(&prot)
if err != nil {
return fmt.Errorf("Cannot decode wayland.xml: %s", err)
}
return nil
}
// register names to map
func caseAndRegister(wlName string) string {
var orj string = wlName
wlName = CamelCase(wlName)
wlNames[orj] = wlName
return wlName
}
func executeTemplate(name string, tpl string, data interface{}) {
tmpl := template.Must(template.New(name).Parse(tpl))
err := tmpl.Execute(fileBuffer, data)
if err != nil {
log.Fatal(err)
}
}
func (i *GoInterface) Constructor() {
executeTemplate("InterfaceTypeTemplate", ifaceTypeTemplate, i)
executeTemplate("InterfaceConstructorTemplate", ifaceConstructorTemplate, i)
}
func (i *GoInterface) ProcessRequests() {
for order, wlReq := range i.WlInterface.Requests {
var (
returns []string
params []string
sendRequestArgs []string // for sendRequest
)
req := GoRequest{
Name: CamelCase(wlReq.Name),
IfaceName: i.Name,
Order: order,
}
/* TODO request kodlarını sabit olarak tanımla
reqCodeName := strings.ToTitle(fmt.Sprintf("_%s_%s", i.Name , req.Name)) // first _ for not export constant
"%s = %d", reqCodeName, order)
*/
for _, arg := range wlReq.Args {
if arg.Type == "new_id" {
if arg.Interface != "" {
newIdIface := wlNames[arg.Interface]
req.NewIdInterface = newIdIface
sendRequestArgs = append(params, "Proxy(ret)")
req.HasNewId = true
returns = append(returns, "*"+newIdIface)
} else { //special for registry.Bind
sendRequestArgs = append(sendRequestArgs, "iface")
sendRequestArgs = append(sendRequestArgs, "version")
sendRequestArgs = append(sendRequestArgs, arg.Name)
params = append(params, "iface string")
params = append(params, "version uint32")
params = append(params, fmt.Sprintf("%s Proxy", arg.Name))
}
} else if arg.Type == "object" && arg.Interface != "" {
paramTypeName := wlNames[arg.Interface]
params = append(params, fmt.Sprintf("%s *%s", arg.Name, paramTypeName))
sendRequestArgs = append(sendRequestArgs, arg.Name)
/*} else if arg.Type == "uint" && arg.Enum != "" {
params = append(params, fmt.Sprintf("%s %s", arg.Name, enumArgName(ifaceName, arg.Enum)))
}*/
} else {
sendRequestArgs = append(sendRequestArgs, arg.Name)
params = append(params, fmt.Sprintf("%s %s", arg.Name, wlTypes[arg.Type]))
}
}
req.Params = strings.Join(params, ",")
if len(sendRequestArgs) > 0 {
req.Args = "," + strings.Join(sendRequestArgs, ",")
}
if len(returns) > 0 { // ( ret , error )
req.Returns = fmt.Sprintf("(%s , error)", strings.Join(returns, ","))
} else { // returns only error
req.Returns = "error"
}
executeTemplate("RequestTemplate", requestTemplate, req)
i.Requests = append(i.Requests, req)
}
}
func (i *GoInterface) ProcessEvents() {
// Event struct types
for _, wlEv := range i.WlInterface.Events {
ev := GoEvent{
Name: CamelCase(wlEv.Name),
PName: snakeCase(wlEv.Name),
IfaceName: i.Name,
}
for _, arg := range wlEv.Args {
goarg := GoArg{
Name: CamelCase(arg.Name),
PName: snakeCase(arg.Name),
}
if t, ok := wlTypes[arg.Type]; ok { // if basic type
bufMethod, ok := bufTypesMap[t]
if !ok {
log.Printf("%s not registered", t)
} else {
goarg.BufMethod = bufMethod
}
/*
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)
}*/
goarg.Type = t
} else { // interface type
if (arg.Type == "object" || arg.Type == "new_id") && arg.Interface != "" {
t = "*" + wlNames[arg.Interface]
goarg.BufMethod = fmt.Sprintf("Proxy(p.Context()).(%s)", t)
} else {
t = "Proxy"
goarg.BufMethod = "Proxy(p.Context())"
}
goarg.Type = t
}
ev.Args = append(ev.Args, goarg)
}
executeTemplate("EventTemplate", eventTemplate, ev)
executeTemplate("AddRemoveHandlerTemplate", ifaceAddRemoveHandlerTemplate, ev)
i.Events = append(i.Events, ev)
}
if len(i.Events) > 0 {
executeTemplate("InterfaceDispatchTemplate", ifaceDispatchTemplate, i)
}
}
func (i *GoInterface) ProcessEnums() {
// Enums - Constants
for _, wlEnum := range i.WlInterface.Enums {
goEnum := GoEnum{
Name: CamelCase(wlEnum.Name),
IfaceName: i.Name,
}
for _, wlEntry := range wlEnum.Entries {
goEntry := GoEntry{
Name: CamelCase(wlEntry.Name),
Value: wlEntry.Value,
}
goEnum.Entries = append(goEnum.Entries, goEntry)
}
executeTemplate("InterfaceEnumsTemplate", ifaceEnums, goEnum)
}
}
/*
func enumArgName(ifaceName, enumName string) string {
if strings.Index(enumName, ".") == -1 {
return ifaceName + CamelCase(enumName)
}
parts := strings.Split(enumName, ".")
if len(parts) != 2 {
log.Fatalf("enum args must be \"interface.enum\" format: we get %s",enumName)
}
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 snakeCase(wlName string) string {
if strings.HasPrefix(wlName, "wl_") {
wlName = strings.TrimPrefix(wlName, "wl_")
}
// replace all "_" chars to " " chars
wlName = strings.Replace(wlName, "_", " ", -1)
parts := strings.Split(wlName, " ")
for i, p := range parts {
if i == 0 {
continue
}
parts[i] = strings.Title(p)
}
return strings.Join(parts, "")
}
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")
er2 := cmd.Run()
if er2 != nil {
log.Fatalf("Cannot run cmd: %s", er2)
}
}
// templates
var (
ifaceTypeTemplate = `
type {{.Name}} struct {
BaseProxy
{{- if gt (len .Events) 0 }}
mu sync.RWMutex
{{- end}}
{{- range .Events}}
{{.PName}}Handlers []Handler
{{- end}}
}
`
ifaceConstructorTemplate = `
func New{{.Name}}(ctx *Context) *{{.Name}} {
ret := new({{.Name}})
ctx.register(ret)
return ret
}
`
ifaceAddRemoveHandlerTemplate = `
func (p *{{.IfaceName}}) Add{{.Name}}Handler(h Handler) {
if h != nil {
p.mu.Lock()
p.{{.PName}}Handlers = append(p.{{.PName}}Handlers , h)
p.mu.Unlock()
}
}
func (p *{{.IfaceName}}) Remove{{.Name}}Handler(h Handler) {
p.mu.Lock()
defer p.mu.Unlock()
for i , e := range p.{{.PName}}Handlers {
if e == h {
p.{{.PName}}Handlers = append(p.{{.PName}}Handlers[:i] , p.{{.PName}}Handlers[i+1:]...)
break
}
}
}
`
requestTemplate = `
func (p *{{.IfaceName}}) {{.Name}}({{.Params}}) {{.Returns}} {
{{- if .HasNewId}}
ret := New{{.NewIdInterface}}(p.Context())
return ret , p.Context().sendRequest(p,{{.Order}}{{.Args}})
{{- else}}
return p.Context().sendRequest(p,{{.Order}}{{.Args}})
{{- end}}
}
`
eventTemplate = `
type {{.IfaceName}}{{.Name}}Event struct {
{{- range .Args }}
{{.Name}} {{.Type}}
{{- end }}
}
`
ifaceDispatchTemplate = `
func (p *{{.Name}}) Dispatch(event *Event) {
{{- $ifaceName := .Name }}
switch event.opcode {
{{- range $i , $event := .Events }}
case {{$i}}:
if len(p.{{.PName}}Handlers) > 0 {
ev := {{$ifaceName}}{{.Name}}Event{}
{{- range $event.Args}}
ev.{{.Name}} = event.{{.BufMethod}}
{{- end}}
p.mu.RLock()
for _, h := range p.{{.PName}}Handlers {
h.Handle(ev)
}
p.mu.RUnlock()
}
{{- end}}
}
}
`
ifaceEnums = `
const (
{{- $ifaceName := .IfaceName }}
{{- $enumName := .Name }}
{{- range .Entries}}
{{$ifaceName}}{{$enumName}}{{.Name}} = {{.Value}}
{{- end}}
)
`
)