-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
57 lines (45 loc) · 1.09 KB
/
context.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
package doodlekit
import (
"context"
"github.com/lucasepe/doodlekit/internal/canvas"
"github.com/lucasepe/doodlekit/internal/rng"
)
// Canvas return the drawing context pointer from the context.
func Canvas(ctx context.Context) *canvas.Canvas {
v := ctx.Value(contextKeyCanvas)
if val, ok := v.(*canvas.Canvas); ok {
return val
}
return nil
}
// Rng return the pseudo random numbers generator from the context.
func Rng(ctx context.Context) rng.RNG {
v := ctx.Value(contextKeyRng)
if val, ok := v.(rng.RNG); ok {
return val
}
return nil
}
type contextKey string
func (c contextKey) String() string {
return "doodlekit." + string(c)
}
var (
contextKeyCanvas = contextKey("canvas")
contextKeyRng = contextKey("rng")
)
type option func(*canvas.Canvas)
func resize(sf int) option {
return func(gc *canvas.Canvas) {
gc.Resize(sf)
}
}
func newContext(opts ...option) context.Context {
gc := canvas.New(nil)
for _, fn := range opts {
fn(gc)
}
ctx := context.WithValue(context.Background(), contextKeyCanvas, gc)
ctx = context.WithValue(ctx, contextKeyRng, rng.New())
return ctx
}