-
Notifications
You must be signed in to change notification settings - Fork 8
/
generator.go
87 lines (81 loc) · 1.57 KB
/
generator.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
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
package main
import (
"bytes"
"image"
"image/gif"
"io/ioutil"
"github.com/james4k/terminal"
"os"
)
// GifGenerator type
type GifGenerator struct {
Speed float64
Col int
Row int
NoLoop bool
ScreenInfo *ScreenInfo
}
// NewGifGenerator returns GifGenerator instance
func NewGifGenerator() *GifGenerator {
return &GifGenerator{
Speed: 1.0,
Col: 80,
Row: 24,
NoLoop: false,
ScreenInfo: NewScreenInfo(),
}
}
// Generate writes to outFile an animated GIF
func (g *GifGenerator) Generate(input string, output string) (err error) {
// virtual terminal
var state = terminal.State{}
vt, err := terminal.Create(&state, ioutil.NopCloser(bytes.NewBuffer([]byte{})))
if err != nil {
return
}
defer vt.Close()
vt.Resize(g.Col, g.Row)
// play and capture
var (
images []*image.Paletted
delays []int
ttyTime int64
gifTime int64
)
err = g.TtyPlay(input, vt, func(diff int32) (err error) {
ttyTime += int64(float64(diff) / g.Speed)
delay := int((ttyTime-gifTime)/10000/10) * 10
gifTime += int64(delay) * 10000
if delay > 0 {
var img *image.Paletted
img, err = g.Capture(&state)
if err != nil {
return
}
images = append(images, img)
delays = append(delays, delay)
}
return nil
})
if err != nil {
return
}
// generate gif file
outFile, err := os.Create(output)
if err != nil {
return
}
defer outFile.Close()
opts := gif.GIF{
Image: images,
Delay: delays,
}
if g.NoLoop {
opts.LoopCount = 1
}
err = gif.EncodeAll(outFile, &opts)
if err != nil {
return
}
return nil
}