aboutsummaryrefslogtreecommitdiffstats
path: root/layout/grid.go
blob: 183179481a81f66d672f2e77019571bcc7877268 (plain) (blame)
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
package layout

import (
	"image"
	"image/color"
	"image/draw"

	"github.com/faiface/gui"
)

// Grid represents a simple grid layout.
// Do not edit properties directly, use the constructor instead.
type Grid struct {
	Contents   [][]*gui.Env
	Background color.Color
	Gap        int
	SplitX     func(int, int) []int
	SplitY     func(int, int) []int
}

func NewGrid(env gui.Env, contents [][]*gui.Env, options ...func(*Grid)) gui.Env {
	ret := &Grid{
		Background: image.Black,
		Gap:        0,
		Contents:   contents,
		SplitX:     evenSplit,
		SplitY:     evenSplit,
	}
	for _, f := range options {
		f(ret)
	}

	mux, env := NewMux(env, ret)
	for _, row := range contents {
		for _, item := range row {
			*item = mux.MakeEnv()
		}
	}

	return env
}

func GridBackground(c color.Color) func(*Grid) {
	return func(grid *Grid) {
		grid.Background = c
	}
}

func GridGap(g int) func(*Grid) {
	return func(grid *Grid) {
		grid.Gap = g
	}
}

func GridSplitX(split func(int, int) []int) func(*Grid) {
	return func(grid *Grid) {
		grid.SplitX = split
	}
}

func GridSplitY(split func(int, int) []int) func(*Grid) {
	return func(grid *Grid) {
		grid.SplitY = split
	}
}

func (g *Grid) Redraw(drw draw.Image, bounds image.Rectangle) {
	draw.Draw(drw, bounds, image.NewUniform(g.Background), image.ZP, draw.Src)
}

func (g *Grid) Lay(bounds image.Rectangle) []image.Rectangle {
	gap := g.Gap
	ret := make([]image.Rectangle, 0)
	rows := len(g.Contents)

	rowsH := g.SplitY(rows, bounds.Dy()-(g.Gap*(rows+1)))

	X := gap + bounds.Min.X
	Y := gap + bounds.Min.Y
	for y, row := range g.Contents {
		cols := len(row)
		h := rowsH[y]
		colsW := g.SplitX(cols, bounds.Dx()-(g.Gap*(cols+1)))
		X = gap + bounds.Min.X
		for x := range row {
			w := colsW[x]
			ret = append(ret, image.Rect(X, Y, X+w, Y+h))
			X += gap + w
		}
		Y += gap + h
	}

	return ret
}