Debian Codegraph @

shiny/materialdesign/icons/gen.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build ignore
6
7 package main
8
9 import (
10 "bytes"
11 "encoding/xml"
12 "errors"
13 "flag"
14 "fmt"
15 "go/format"
16 "io"
17 "log"
18 "os"
19 "path"
20 "path/filepath"
21 "sort"
22 "strconv"
23 "strings"
24
25 "golang.org/x/exp/shiny/iconvg"
26 "golang.org/x/image/math/f32"
27 )
28
29 var mdicons = flag.String("mdicons", "", "The directory on the local file system where "+
30 "https://github.com/google/material-design-icons was checked out",
31 )
32
33 // outSize is the width and height (in ideal vector space) of the generated
34 // IconVG graphic, regardless of the size of the input SVG.
35 const outSize = 48
36
37 // errSkip deliberately skips generating an icon.
38 //
39 // When manually debugging one particular icon, it can be useful to add
40 // something like:
41 //
42 // if baseName != "check_box" { return errSkip }
43 //
44 // at the top of func genFile.
45 var errSkip = errors.New("skipping SVG to IconVG conversion")
46
47 var (
48 out = new(bytes.Buffer)
49 failures = []string{}
50 varNames = []string{}
51
52 totalFiles int
53 totalIVGBytes int
54 totalPNG24Bytes int
55 totalPNG48Bytes int
56 totalSVGBytes int
57 )
58
59 var acronyms = map[string]string{
60 "3d": "3D",
61 "ac": "AC",
62 "adb": "ADB",
63 "airplanemode": "AirplaneMode",
64 "atm": "ATM",
65 "av": "AV",
66 "ccw": "CCW",
67 "cw": "CW",
68 "din": "DIN",
69 "dns": "DNS",
70 "dvr": "DVR",
71 "eta": "ETA",
72 "ev": "EV",
73 "gif": "GIF",
74 "gps": "GPS",
75 "hd": "HD",
76 "hdmi": "HDMI",
77 "hdr": "HDR",
78 "http": "HTTP",
79 "https": "HTTPS",
80 "iphone": "IPhone",
81 "iso": "ISO",
82 "jpeg": "JPEG",
83 "markunread": "MarkUnread",
84 "mms": "MMS",
85 "nfc": "NFC",
86 "ondemand": "OnDemand",
87 "pdf": "PDF",
88 "phonelink": "PhoneLink",
89 "png": "PNG",
90 "rss": "RSS",
91 "rv": "RV",
92 "sd": "SD",
93 "sim": "SIM",
94 "sip": "SIP",
95 "sms": "SMS",
96 "streetview": "StreetView",
97 "svideo": "SVideo",
98 "textdirection": "TextDirection",
99 "textsms": "TextSMS",
100 "timelapse": "TimeLapse",
101 "toc": "TOC",
102 "tv": "TV",
103 "usb": "USB",
104 "vpn": "VPN",
105 "wb": "WB",
106 "wc": "WC",
107 "whatshot": "WhatsHot",
108 "wifi": "WiFi",
109 }
110
111 func upperCase(s string) string {
112 if a, ok := acronyms[s]; ok {
113 return a
114 }
115 if c := s[0]; 'a' <= c && c <= 'z' {
116 return string(c-0x20) + s[1:]
117 }
118 return s
119 }
120
121 func main() {
122 flag.Parse()
123
124 out.WriteString("// generated by go run gen.go; DO NOT EDIT\n\npackage icons\n\n")
125
126 f, err := os.Open(*mdicons)
127 if err != nil {
128 log.Fatalf("%v\n\nDid you override the -mdicons flag in icons.go?\n\n", err)
129 }
130 defer f.Close()
131 infos, err := f.Readdir(-1)
132 if err != nil {
133 log.Fatal(err)
134 }
135 names := []string{}
136 for _, info := range infos {
137 if !info.IsDir() {
138 continue
139 }
140 name := info.Name()
141 if name[0] == '.' {
142 continue
143 }
144 names = append(names, name)
145 }
146 sort.Strings(names)
147 for _, name := range names {
148 genDir(name)
149 }
150
151 fmt.Fprintf(out,
152 "// In total, %d SVG bytes in %d files (%d PNG bytes at 24px * 24px,\n"+
153 "// %d PNG bytes at 48px * 48px) converted to %d IconVG bytes.\n",
154 totalSVGBytes, totalFiles, totalPNG24Bytes, totalPNG48Bytes, totalIVGBytes)
155
156 if len(failures) != 0 {
157 out.WriteString("\n/*\nFAILURES:\n\n")
158 for _, failure := range failures {
159 out.WriteString(failure)
160 out.WriteByte('\n')
161 }
162 out.WriteString("\n*/")
163 }
164
165 raw := out.Bytes()
166 formatted, err := format.Source(raw)
167 if err != nil {
168 log.Fatalf("gofmt failed: %v\n\nGenerated code:\n%s", err, raw)
169 }
170 if err := os.WriteFile("data.go", formatted, 0644); err != nil {
171 log.Fatalf("WriteFile failed: %s\n", err)
172 }
173
174 // Generate data_test.go. The code immediately above generates data.go.
175 {
176 b := new(bytes.Buffer)
177 b.WriteString("// generated by go run gen.go; DO NOT EDIT\n\npackage icons\n\n")
178 b.WriteString("var list = []struct{ name string; data []byte } {\n")
179 for _, v := range varNames {
180 fmt.Fprintf(b, "{%q, %s},\n", v, v)
181 }
182 b.WriteString("}\n\n")
183 raw := b.Bytes()
184 formatted, err := format.Source(raw)
185 if err != nil {
186 log.Fatalf("gofmt failed: %v\n\nGenerated code:\n%s", err, raw)
187 }
188 if err := os.WriteFile("data_test.go", formatted, 0644); err != nil {
189 log.Fatalf("WriteFile failed: %s\n", err)
190 }
191 }
192 }
193
194 func genDir(dirName string) {
195 fqPNGDirName := filepath.FromSlash(path.Join(*mdicons, dirName, "1x_web"))
196 fqSVGDirName := filepath.FromSlash(path.Join(*mdicons, dirName, "svg/production"))
197 f, err := os.Open(fqSVGDirName)
198 if err != nil {
199 return
200 }
201 defer f.Close()
202
203 infos, err := f.Readdir(-1)
204 if err != nil {
205 log.Fatal(err)
206 }
207 baseNames, fileNames, sizes := []string{}, map[string]string{}, map[string]int{}
208 for _, info := range infos {
209 name := info.Name()
210
211 if !strings.HasPrefix(name, "ic_") || skippedFiles[[2]string{dirName, name}] {
212 continue
213 }
214 size := 0
215 switch {
216 case strings.HasSuffix(name, "_12px.svg"):
217 size = 12
218 case strings.HasSuffix(name, "_18px.svg"):
219 size = 18
220 case strings.HasSuffix(name, "_24px.svg"):
221 size = 24
222 case strings.HasSuffix(name, "_36px.svg"):
223 size = 36
224 case strings.HasSuffix(name, "_48px.svg"):
225 size = 48
226 default:
227 continue
228 }
229
230 baseName := name[3 : len(name)-9]
231 if prevSize, ok := sizes[baseName]; ok {
232 if size > prevSize {
233 fileNames[baseName] = name
234 sizes[baseName] = size
235 }
236 } else {
237 fileNames[baseName] = name
238 sizes[baseName] = size
239 baseNames = append(baseNames, baseName)
240 }
241 }
242
243 sort.Strings(baseNames)
244 for _, baseName := range baseNames {
245 fileName := fileNames[baseName]
246 err := genFile(fqSVGDirName, dirName, baseName, fileName, float32(sizes[baseName]))
247 if err == errSkip {
248 continue
249 }
250 if err != nil {
251 failures = append(failures, fmt.Sprintf("%v/svg/production/%v: %v", dirName, fileName, err))
252 continue
253 }
254 totalPNG24Bytes += pngSize(fqPNGDirName, dirName, baseName, 24)
255 totalPNG48Bytes += pngSize(fqPNGDirName, dirName, baseName, 48)
256 }
257 }
258
259 func pngSize(fqPNGDirName, dirName, baseName string, targetSize int) int {
260 for _, size := range [...]int{48, 24, 18} {
261 if size > targetSize {
262 continue
263 }
264 fInfo, err := os.Stat(filepath.Join(fqPNGDirName,
265 fmt.Sprintf("ic_%s_black_%ddp.png", baseName, size)))
266 if err != nil {
267 continue
268 }
269 return int(fInfo.Size())
270 }
271 failures = append(failures,
272 fmt.Sprintf("no PNG found for %s/1x_web/ic_%s_black_{48,24,18}dp.png", dirName, baseName))
273 return 0
274 }
275
276 type SVG struct {
277 Width float32 `xml:"where,attr"`
278 Height float32 `xml:"height,attr"`
279 ViewBox string `xml:"viewBox,attr"`
280 Paths []Path `xml:"path"`
281 // Some of the SVG files contain <circle> elements, not just <path>
282 // elements. IconVG doesn't have circles per se. Instead, we convert such
283 // circles to be paired arcTo commands, tacked on to the first path.
284 //
285 // In general, this isn't correct if the circles and the path overlap, but
286 // that doesn't happen in the specific case of the Material Design icons.
287 Circles []Circle `xml:"circle"`
288 }
289
290 type Path struct {
291 D string `xml:"d,attr"`
292 Fill string `xml:"fill,attr"`
293 FillOpacity *float32 `xml:"fill-opacity,attr"`
294 Opacity *float32 `xml:"opacity,attr"`
295 }
296
297 type Circle struct {
298 Cx float32 `xml:"cx,attr"`
299 Cy float32 `xml:"cy,attr"`
300 R float32 `xml:"r,attr"`
301 }
302
303 var skippedPaths = map[string]string{
304 // hardware/svg/production/ic_scanner_48px.svg contains a filled white
305 // rectangle that is overwritten by the subsequent path.
306 //
307 // See https://github.com/google/material-design-icons/issues/490
308 //
309 // Matches <path fill="#fff" d="M16 34h22v4H16z"/>
310 "M16 34h22v4H16z": "#fff",
311
312 // device/svg/production/ic_airplanemode_active_48px.svg and
313 // maps/svg/production/ic_flight_48px.svg contain a degenerate path that
314 // contains only one moveTo op.
315 //
316 // See https://github.com/google/material-design-icons/issues/491
317 //
318 // Matches <path d="M20.36 18"/>
319 "M20.36 18": "",
320 }
321
322 var skippedFiles = map[[2]string]bool{
323 // ic_play_circle_filled_white_48px.svg is just the same as
324 // ic_play_circle_filled_48px.svg with an explicit fill="#fff".
325 {"av", "ic_play_circle_filled_white_48px.svg"}: true,
326 }
327
328 func genFile(fqSVGDirName, dirName, baseName, fileName string, size float32) error {
329 fqFileName := filepath.Join(fqSVGDirName, fileName)
330 svgData, err := os.ReadFile(fqFileName)
331 if err != nil {
332 return err
333 }
334
335 varName := upperCase(dirName)
336 for _, s := range strings.Split(baseName, "_") {
337 varName += upperCase(s)
338 }
339 fmt.Fprintf(out, "var %s = []byte{", varName)
340 defer fmt.Fprintf(out, "\n}\n\n")
341 varNames = append(varNames, varName)
342
343 var enc iconvg.Encoder
344 enc.Reset(iconvg.Metadata{
345 ViewBox: iconvg.Rectangle{
346 Min: f32.Vec2{-24, -24},
347 Max: f32.Vec2{+24, +24},
348 },
349 Palette: iconvg.DefaultPalette,
350 })
351
352 g := &SVG{}
353 if err := xml.Unmarshal(svgData, g); err != nil {
354 return err
355 }
356
357 var vbx, vby float32
358 for i, v := range strings.Split(g.ViewBox, " ") {
359 f, err := strconv.ParseFloat(v, 32)
360 if err != nil {
361 return err
362 }
363 switch i {
364 case 0:
365 vbx = float32(f)
366 case 1:
367 vby = float32(f)
368 }
369 }
370 offset := f32.Vec2{
371 vbx * outSize / size,
372 vby * outSize / size,
373 }
374
375 // adjs maps from opacity to a cReg adj value.
376 adjs := map[float32]uint8{}
377
378 for _, p := range g.Paths {
379 if fill, ok := skippedPaths[p.D]; ok && fill == p.Fill {
380 continue
381 }
382 if err := genPath(&enc, &p, adjs, size, offset, g.Circles); err != nil {
383 return err
384 }
385 g.Circles = nil
386 }
387
388 if len(g.Circles) != 0 {
389 if err := genPath(&enc, &Path{}, adjs, size, offset, g.Circles); err != nil {
390 return err
391 }
392 g.Circles = nil
393 }
394
395 ivgData, err := enc.Bytes()
396 if err != nil {
397 return err
398 }
399 for i, x := range ivgData {
400 if i&0x0f == 0x00 {
401 out.WriteByte('\n')
402 }
403 fmt.Fprintf(out, "%#02x, ", x)
404 }
405
406 totalFiles++
407 totalSVGBytes += len(svgData)
408 totalIVGBytes += len(ivgData)
409 return nil
410 }
411
412 func genPath(enc *iconvg.Encoder, p *Path, adjs map[float32]uint8, size float32, offset f32.Vec2, circles []Circle) error {
413 adj := uint8(0)
414 opacity := float32(1)
415 if p.Opacity != nil {
416 opacity = *p.Opacity
417 } else if p.FillOpacity != nil {
418 opacity = *p.FillOpacity
419 }
420 if opacity != 1 {
421 var ok bool
422 if adj, ok = adjs[opacity]; !ok {
423 adj = uint8(len(adjs) + 1)
424 adjs[opacity] = adj
425 // Set CREG[0-adj] to be a blend of transparent (0x7f) and the
426 // first custom palette color (0x80).
427 enc.SetCReg(adj, false, iconvg.BlendColor(uint8(opacity*0xff), 0x7f, 0x80))
428 }
429 }
430
431 needStartPath := true
432 if p.D != "" {
433 needStartPath = false
434 if err := genPathData(enc, adj, p.D, size, offset); err != nil {
435 return err
436 }
437 }
438
439 for _, c := range circles {
440 // Normalize.
441 cx := c.Cx * outSize / size
442 cx -= outSize/2 + offset[0]
443 cy := c.Cy * outSize / size
444 cy -= outSize/2 + offset[1]
445 r := c.R * outSize / size
446
447 if needStartPath {
448 needStartPath = false
449 enc.StartPath(adj, cx-r, cy)
450 } else {
451 enc.ClosePathAbsMoveTo(cx-r, cy)
452 }
453
454 // Convert a circle to two relative arcTo ops, each of 180 degrees.
455 // We can't use one 360 degree arcTo as the start and end point
456 // would be coincident and the computation is degenerate.
457 enc.RelArcTo(r, r, 0, false, true, +2*r, 0)
458 enc.RelArcTo(r, r, 0, false, true, -2*r, 0)
459 }
460
461 enc.ClosePathEndPath()
462 return nil
463 }
464
465 func genPathData(enc *iconvg.Encoder, adj uint8, pathData string, size float32, offset f32.Vec2) error {
466 if strings.HasSuffix(pathData, "z") {
467 pathData = pathData[:len(pathData)-1]
468 }
469 r := strings.NewReader(pathData)
470
471 var args [6]float32
472 op, relative, started := byte(0), false, false
473 for {
474 b, err := r.ReadByte()
475 if err == io.EOF {
476 break
477 }
478 if err != nil {
479 return err
480 }
481
482 switch {
483 case b == ' ':
484 continue
485 case 'A' <= b && b <= 'Z':
486 op, relative = b, false
487 case 'a' <= b && b <= 'z':
488 op, relative = b, true
489 default:
490 r.UnreadByte()
491 }
492
493 n := 0
494 switch op {
495 case 'L', 'l', 'T', 't':
496 n = 2
497 case 'Q', 'q', 'S', 's':
498 n = 4
499 case 'C', 'c':
500 n = 6
501 case 'H', 'h', 'V', 'v':
502 n = 1
503 case 'M', 'm':
504 n = 2
505 case 'Z', 'z':
506 default:
507 return fmt.Errorf("unknown opcode %c\n", b)
508 }
509
510 scan(&args, r, n)
511 normalize(&args, n, op, size, offset, relative)
512
513 switch op {
514 case 'L':
515 enc.AbsLineTo(args[0], args[1])
516 case 'l':
517 enc.RelLineTo(args[0], args[1])
518 case 'T':
519 enc.AbsSmoothQuadTo(args[0], args[1])
520 case 't':
521 enc.RelSmoothQuadTo(args[0], args[1])
522 case 'Q':
523 enc.AbsQuadTo(args[0], args[1], args[2], args[3])
524 case 'q':
525 enc.RelQuadTo(args[0], args[1], args[2], args[3])
526 case 'S':
527 enc.AbsSmoothCubeTo(args[0], args[1], args[2], args[3])
528 case 's':
529 enc.RelSmoothCubeTo(args[0], args[1], args[2], args[3])
530 case 'C':
531 enc.AbsCubeTo(args[0], args[1], args[2], args[3], args[4], args[5])
532 case 'c':
533 enc.RelCubeTo(args[0], args[1], args[2], args[3], args[4], args[5])
534 case 'H':
535 enc.AbsHLineTo(args[0])
536 case 'h':
537 enc.RelHLineTo(args[0])
538 case 'V':
539 enc.AbsVLineTo(args[0])
540 case 'v':
541 enc.RelVLineTo(args[0])
542 case 'M':
543 if !started {
544 started = true
545 enc.StartPath(adj, args[0], args[1])
546 } else {
547 enc.ClosePathAbsMoveTo(args[0], args[1])
548 }
549 case 'm':
550 enc.ClosePathRelMoveTo(args[0], args[1])
551 }
552 }
553 return nil
554 }
555
556 func scan(args *[6]float32, r *strings.Reader, n int) {
557 for i := 0; i < n; i++ {
558 for {
559 if b, _ := r.ReadByte(); b != ' ' {
560 r.UnreadByte()
561 break
562 }
563 }
564 fmt.Fscanf(r, "%f", &args[i])
565 }
566 }
567
568 func atof(s []byte) (float32, error) {
569 f, err := strconv.ParseFloat(string(s), 32)
570 if err != nil {
571 return 0, fmt.Errorf("could not parse %q as a float32: %v", s, err)
572 }
573 return float32(f), nil
574 }
575
576 func normalize(args *[6]float32, n int, op byte, size float32, offset f32.Vec2, relative bool) {
577 for i := 0; i < n; i++ {
578 args[i] *= outSize / size
579 if relative {
580 continue
581 }
582 args[i] -= outSize / 2
583 switch {
584 case n != 1:
585 args[i] -= offset[i&0x01]
586 case op == 'H':
587 args[i] -= offset[0]
588 case op == 'V':
589 args[i] -= offset[1]
590 }
591 }
592 }