~pierrec/giox

ref: c164e218831e giox/cmd/iconx/reflect.go -rw-r--r-- 1.6 KiB
c164e218Pierre Curto cm/iconx: update the set of icons 6 months ago
                                                                                
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
package main

import (
	"go/ast"
	"go/token"
	"strconv"
	"strings"

	"gioui.org/widget"
	"golang.org/x/tools/go/packages"
)

type iconData struct {
	Name string
	Data []byte
	Icon *widget.Icon
}

func loadIcons() (map[string][]iconData, error) {
	cfg := &packages.Config{Mode: packages.NeedName |
		packages.NeedImports | packages.NeedDeps |
		packages.NeedTypes | packages.NeedTypesSizes |
		packages.NeedSyntax | packages.NeedTypesInfo,
	}
	pkgs, err := packages.Load(cfg, "golang.org/x/exp/shiny/materialdesign/icons")
	if err != nil {
		return nil, err
	}
	pkgIcons := pkgs[0]
	res := make(map[string][]iconData)
	for _, f := range pkgIcons.Syntax {
		for _, decl := range f.Decls {
			switch d := decl.(type) {
			case *ast.GenDecl:
				if d.Tok != token.VAR {
					continue
				}
				spec := d.Specs[0]
				v := spec.(*ast.ValueSpec)
				bytes := v.Values[0].(*ast.CompositeLit).Elts
				data := iconData{
					Name: v.Names[0].Name,
					Data: make([]byte, len(bytes)),
				}
				for i, elt := range bytes {
					e := elt.(*ast.BasicLit)
					b, err := strconv.ParseInt(e.Value, 0, 64)
					if err != nil {
						return nil, err
					}
					data.Data[i] = byte(b)
				}
				data.Icon, err = widget.NewIcon(data.Data)
				if err != nil {
					return nil, err
				}
				key, name := icName(data.Name)
				data.Name = name
				res[key] = append(res[key], data)
			}
		}
	}
	return res, nil
}

func icName(s string) (parent, name string) {
	switch {
	case strings.HasPrefix(s, "AV"):
		parent = "AV"
		name = s
	default:
		for i, c := range s[1:] {
			if '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' {
				i++
				parent = s[:i]
				name = s[i:]
				break
			}
		}
	}
	return
}