~eliasnaur/gio-experiments

ref: 2ff064cc0cd9dc9835219a978fd7b2d661793786 gio-experiments/layout/format.go -rw-r--r-- 10.7 KiB
2ff064ccElias Naur layout: bump gio version 1 year, 11 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
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
// SPDX-License-Identifier: Unlicense OR MIT

package layout

import (
	"fmt"
	"image"
	"strconv"

	"gioui.org/layout"
	"gioui.org/unit"
)

type formatter struct {
	current int
	orig    string
	expr    string
	skip    int
}

type formatError string

// Format lays out widgets according to a format string, similar to
// how fmt.Printf interpolates a string.
//
// The format string is an epxression where layouts are similar to
// function calls, and the underscore denotes a widget from the
// arguments. The ith _ invokes the ith widget from the arguments.
//
// If the layout format is invalid, Format panics with an error where
// a cross, ✗, marks the error position.
//
// For example,
//
//   Format(gtx, "inset(8dp, _)", w)
//
// is equivalent to
//
//   layout.UniformInset(unit.Dp(8)).Layout(gtx, w)
//
// Available layouts:
//
// inset(insets, widget) applies inset to widget. Insets are either:
// one value for uniform insets; two values for top/bottom and
// right/left insets; three values for top, bottom and right/left
// insets; or four values for top, right, bottom, left insets.
//
// direction(widget) aligns a widget. Direction is one of north, northeast,
// east, southeast, south, southwest, west, northwest, center.
//
// hmax/vmax/max(widget) forces the horizontal, vertical or both
// constraints to their maximum before laying out widget.
//
// hmin/vmin/min(widget) forces the horizontal, vertical or both
// constraints to their minimum before laying out widget.
//
// hcap/vcap(size, widget) caps the maximum horizontal or vertical
// constraints to size.
//
// hflex/vflex(alignment, children...) lays out children with a
// horizontal or vertical layout.Flex. Each rigid child must be on the form
// r(widget), and each flex child on the form f(<weight>, widget).
// If alignment is specified, it must be one of: start, middle, end,
// baseline. The default alignment is start.
//
// stack(alignment, children) lays out children with a layout.Stack. Each
// Rigid child must be on the form r(widget), and each expand child
// on the form e(widget).
// If alignment is specified it must be one of the directions listed
// above.
func Format(gtx layout.Context, format string, widgets ...layout.Widget) layout.Dimensions {
	if format == "" {
		return layout.Dimensions{}
	}
	f := formatter{
		orig: format,
		expr: format,
	}
	defer func() {
		if err := recover(); err != nil {
			if _, ok := err.(formatError); !ok {
				panic(err)
			}
			pos := len(f.orig) - len(f.expr)
			msg := f.orig[:pos] + "✗" + f.orig[pos:]
			panic(fmt.Errorf("Format: %s:%d: %s", msg, pos, err))
		}
	}()
	return formatExpr(gtx, &f, widgets)
}

func formatExpr(gtx layout.Context, f *formatter, widgets []layout.Widget) layout.Dimensions {
	switch peek(f) {
	case '_':
		return formatWidget(gtx, f, widgets)
	default:
		return formatLayout(gtx, f, widgets)
	}
}

func formatLayout(gtx layout.Context, f *formatter, widgets []layout.Widget) layout.Dimensions {
	name := parseName(f)
	if name == "" {
		errorf("missing layout name")
	}
	expect(f, "(")
	fexpr := func(gtx layout.Context) layout.Dimensions {
		return formatExpr(gtx, f, widgets)
	}
	align, ok := dirFor(name)
	var dims layout.Dimensions
	if ok {
		dims = align.Layout(gtx, fexpr)
		expect(f, ")")
		return dims
	}
	switch name {
	case "inset":
		in := parseInset(gtx, f, widgets)
		dims = in.Layout(gtx, fexpr)
	case "hflex":
		dims = formatFlex(gtx, layout.Horizontal, f, widgets)
	case "vflex":
		dims = formatFlex(gtx, layout.Vertical, f, widgets)
	case "stack":
		dims = formatStack(gtx, f, widgets)
	case "hmax":
		gtx.Constraints.Min.X = gtx.Constraints.Max.X
		dims = formatExpr(gtx, f, widgets)
	case "vmax":
		gtx.Constraints.Min.Y = gtx.Constraints.Max.Y
		dims = formatExpr(gtx, f, widgets)
	case "max":
		gtx.Constraints.Min = gtx.Constraints.Max
		dims = formatExpr(gtx, f, widgets)
	case "hmin":
		gtx.Constraints.Max.X = gtx.Constraints.Min.X
		dims = formatExpr(gtx, f, widgets)
	case "vmin":
		gtx.Constraints.Max.Y = gtx.Constraints.Min.Y
		dims = formatExpr(gtx, f, widgets)
	case "min":
		gtx.Constraints.Max = gtx.Constraints.Min
		dims = formatExpr(gtx, f, widgets)
	case "hcap":
		w := gtx.Px(parseValue(f))
		expect(f, ",")
		cs := gtx.Constraints
		cs.Max = cs.Constrain(image.Pt(w, cs.Max.X))
		dims = formatExpr(gtx, f, widgets)
	case "vcap":
		h := gtx.Px(parseValue(f))
		expect(f, ",")
		cs := gtx.Constraints
		cs.Max = cs.Constrain(image.Pt(cs.Max.X, h))
		dims = formatExpr(gtx, f, widgets)
	default:
		errorf("invalid layout %q", name)
	}
	expect(f, ")")
	return dims
}

func formatWidget(gtx layout.Context, f *formatter, widgets []layout.Widget) layout.Dimensions {
	expect(f, "_")
	if i, max := f.current, len(widgets)-1; i > max {
		errorf("widget index %d out of bounds [0;%d]", i, max)
	}
	if f.skip == 0 {
		return widgets[f.current](gtx)
	}
	f.current++
	return layout.Dimensions{}
}

func formatStack(gtx layout.Context, f *formatter, widgets []layout.Widget) layout.Dimensions {
	st := layout.Stack{}
	backup := *f
	// Parse alignment, if present.
	name := parseName(f)
	align, ok := dirFor(name)
	if ok {
		st.Alignment = align
		expect(f, ",")
	} else {
		*f = backup
	}
	var children []layout.StackChild
loop:
	for {
		switch peek(f) {
		case ')':
			break loop
		case 'r':
			w := func(gtx layout.Context) layout.Dimensions {
				expect(f, "r(")
				dims := formatExpr(gtx, f, widgets)
				expect(f, ")")
				if peek(f) == ',' {
					expect(f, ",")
				}
				return dims
			}
			backup := *f
			f.skip++
			w(gtx)
			f.skip--
			children = append(children, layout.Stacked(func(gtx layout.Context) layout.Dimensions {
				*f = backup
				return w(gtx)
			}))
		case 'e':
			w := func(gtx layout.Context) layout.Dimensions {
				expect(f, "e(")
				dims := formatExpr(gtx, f, widgets)
				expect(f, ")")
				if peek(f) == ',' {
					expect(f, ",")
				}
				return dims
			}
			backup := *f
			f.skip++
			w(gtx)
			f.skip--
			children = append(children, layout.Expanded(func(gtx layout.Context) layout.Dimensions {
				*f = backup
				return w(gtx)
			}))
		default:
			errorf("invalid stack child")
		}
	}
	if f.skip == 0 {
		backup := *f
		dims := st.Layout(gtx, children...)
		*f = backup
		return dims
	}
	return layout.Dimensions{}
}

func formatFlex(gtx layout.Context, axis layout.Axis, f *formatter, widgets []layout.Widget) layout.Dimensions {
	fl := layout.Flex{Axis: axis}
	backup := *f
	// Parse alignment, if present.
	name := parseName(f)
	al, ok := alignmentFor(name)
	if ok {
		fl.Alignment = al
		expect(f, ",")
	} else {
		*f = backup
	}
	var children []layout.FlexChild
loop:
	for {
		switch peek(f) {
		case ')':
			break loop
		case 'r':
			w := func(gtx layout.Context) layout.Dimensions {
				expect(f, "r(")
				dims := formatExpr(gtx, f, widgets)
				expect(f, ")")
				if peek(f) == ',' {
					expect(f, ",")
				}
				return dims
			}
			backup := *f
			f.skip++
			w(gtx)
			f.skip--
			children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions {
				*f = backup
				return w(gtx)
			}))
		case 'f':
			var weight float32
			w := func(gtx layout.Context) layout.Dimensions {
				expect(f, "f(")
				weight = parseFloat(f)
				expect(f, ",")
				dims := formatExpr(gtx, f, widgets)
				expect(f, ")")
				if peek(f) == ',' {
					expect(f, ",")
				}
				return dims
			}
			backup := *f
			f.skip++
			w(gtx)
			f.skip--
			children = append(children, layout.Flexed(weight, func(gtx layout.Context) layout.Dimensions {
				*f = backup
				return w(gtx)
			}))
		default:
			errorf("invalid flex child")
		}
	}
	if f.skip == 0 {
		backup := *f
		dims := fl.Layout(gtx, children...)
		*f = backup
		return dims
	}
	return layout.Dimensions{}
}

func parseInset(gtx layout.Context, f *formatter, widgets []layout.Widget) layout.Inset {
	v1 := parseValue(f)
	if peek(f) == ',' {
		expect(f, ",")
		return layout.UniformInset(v1)
	}
	v2 := parseValue(f)
	if peek(f) == ',' {
		expect(f, ",")
		return layout.Inset{
			Top:    v1,
			Right:  v2,
			Bottom: v1,
			Left:   v2,
		}
	}
	v3 := parseValue(f)
	if peek(f) == ',' {
		expect(f, ",")
		return layout.Inset{
			Top:    v1,
			Right:  v2,
			Bottom: v3,
			Left:   v2,
		}
	}
	v4 := parseValue(f)
	expect(f, ",")
	return layout.Inset{
		Top:    v1,
		Right:  v2,
		Bottom: v3,
		Left:   v4,
	}
}

func parseValue(f *formatter) unit.Value {
	i := parseFloat(f)
	if len(f.expr) < 2 {
		errorf("missing unit")
	}
	u := f.expr[:2]
	var v unit.Value
	switch u {
	case "dp":
		v = unit.Dp(i)
	case "sp":
		v = unit.Sp(i)
	case "px":
		v = unit.Px(i)
	default:
		errorf("unknown unit")
	}
	f.expr = f.expr[len(u):]
	return v
}

func parseName(f *formatter) string {
	skipWhitespace(f)
	i := 0
loop:
	for ; i < len(f.expr); i++ {
		c := f.expr[i]
		switch {
		case c == '(' || c == ',' || c == ')':
			break loop
		case c < 'a' || 'z' < c:
			errorf("invalid character '%c' in layout name", c)
		}
	}
	fname := f.expr[:i]
	f.expr = f.expr[i:]
	return fname
}

func parseFloat(f *formatter) float32 {
	skipWhitespace(f)
	i := 0
	for ; i < len(f.expr); i++ {
		c := f.expr[i]
		if (c < '0' || c > '9') && c != '.' {
			break
		}
	}
	expr := f.expr[:i]
	v, err := strconv.ParseFloat(expr, 32)
	if err != nil {
		errorf("invalid number %q", expr)
	}
	f.expr = f.expr[i:]
	return float32(v)
}

func parseInt(f *formatter) int {
	skipWhitespace(f)
	i := 0
	for ; i < len(f.expr); i++ {
		c := f.expr[i]
		if c < '0' || c > '9' {
			break
		}
	}
	expr := f.expr[:i]
	v, err := strconv.Atoi(expr)
	if err != nil {
		errorf("invalid number %q", expr)
	}
	f.expr = f.expr[i:]
	return v
}

func peek(f *formatter) rune {
	skipWhitespace(f)
	if len(f.expr) == 0 {
		errorf("unexpected end")
	}
	return rune(f.expr[0])
}

func expect(f *formatter, str string) {
	skipWhitespace(f)
	n := len(str)
	if len(f.expr) < n || f.expr[:n] != str {
		errorf("expected %q", str)
	}
	f.expr = f.expr[n:]
}

func skipWhitespace(f *formatter) {
	for len(f.expr) > 0 {
		switch f.expr[0] {
		case '\t', '\n', '\v', '\f', '\r', ' ':
			f.expr = f.expr[1:]
		default:
			return
		}
	}
}

func alignmentFor(name string) (layout.Alignment, bool) {
	var a layout.Alignment
	switch name {
	case "start":
		a = layout.Start
	case "middle":
		a = layout.Middle
	case "end":
		a = layout.End
	case "baseline":
		a = layout.Baseline
	default:
		return 0, false
	}
	return a, true
}

func dirFor(name string) (layout.Direction, bool) {
	var d layout.Direction
	switch name {
	case "center":
		d = layout.Center
	case "northwest":
		d = layout.NW
	case "north":
		d = layout.N
	case "northeast":
		d = layout.NE
	case "east":
		d = layout.E
	case "southeast":
		d = layout.SE
	case "south":
		d = layout.S
	case "southwest":
		d = layout.SW
	case "west":
		d = layout.W
	default:
		return 0, false
	}
	return d, true
}

func errorf(f string, args ...interface{}) {
	panic(formatError(fmt.Sprintf(f, args...)))
}

func (e formatError) Error() string {
	return string(e)
}