/
gotoimage.go
175 lines (140 loc) · 3.85 KB
/
gotoimage.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
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
package gotoimage
import (
"context"
"fmt"
"errors"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
)
func Render(sourcefile string) ([]byte,error){
//it will return if source file is not exist
if ! Existfile(sourcefile){
return nil,errors.New("source file is not exist")
}
// Disable chrome headless
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
// create chrome instance
ctx1, cancel1 := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel1()
// create a timeout ctx for chrome ctx
ctx, cancel2 := context.WithTimeout(ctx1, time.Minute)
defer cancel2()
//imgbuf is used for store the screenshot of "https://play.golang.org/" execution page
var imgbuf []byte
selcode:=`//*[@id="code"]`
golangplayurl:=`https://play.golang.org/`
err := chromedp.Run(ctx,
chromedp.Navigate(golangplayurl),
chromedp.WaitVisible("div.linedtextarea"),
//Clear the default code area
chromedp.Clear(selcode,chromedp.BySearch),
chromedp.SendKeys(selcode,generategocode(sourcefile),chromedp.BySearch),
chromedp.Click("fmt",chromedp.ByID),
chromedp.Click("run",chromedp.ByID),
chromedp.WaitVisible("span.system"),
screenshot("body",&imgbuf,chromedp.BySearch),
//wait 2 seconds
chromedp.Sleep(2*time.Second),
)
if err != nil {
log.Println(err)
return nil,err
}
if err:=Saveimage(filepath.Base(sourcefile)+".png",imgbuf);err!=nil{
log.Println(err)
}
return imgbuf,err
}
//read source code from file
func generategocode(filename string) string {
buffile, err := ioutil.ReadFile(filename)
if err != nil {
log.Println(err)
}
return string(buffile)
}
func Existfile(filename string) bool {
_,err:=os.Stat(filename)
if err!=nil{
return false
}
return true
}
//save the result image as png
func Saveimage(name string,buf []byte) error {
if buf==nil{
panic("buf cannot be nil")
}
err:=ioutil.WriteFile(name,buf,644)
if err!=nil{
log.Println("write file err ",err)
}
return err
}
//screenshot for play.golang.org executing result
func screenshot(sel interface{}, picbuf *[]byte, opts ...chromedp.QueryOption) chromedp.QueryAction {
if picbuf == nil {
panic("picbuf cannot be nil")
}
return chromedp.QueryAfter(sel, func(ctx context.Context,id runtime.ExecutionContextID, nodes ...*cdp.Node) error {
if len(nodes) < 1 {
return fmt.Errorf("selector %q did not return any nodes", sel)
}
// get layout metrics
_, _, contentSize, _,_,_,err := page.GetLayoutMetrics().Do(ctx)
if err != nil {
return err
}
width, height := int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height))
// force viewport emulation
err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
WithScreenOrientation(&emulation.ScreenOrientation{
Type: emulation.OrientationTypePortraitPrimary,
Angle: 0,
}).
Do(ctx)
if err != nil {
return err
}
// get box model
box, err := dom.GetBoxModel().WithNodeID(nodes[0].NodeID).Do(ctx)
if err != nil {
return err
}
if len(box.Margin) != 8 {
return chromedp.ErrInvalidBoxModel
}
// take screenshot of the box
buf, err := page.CaptureScreenshot().
WithFormat(page.CaptureScreenshotFormatPng).
WithClip(&page.Viewport{
X: math.Round(box.Margin[0]),
Y: math.Round(box.Margin[1]),
Width: math.Round(box.Margin[4] - box.Margin[0]),
Height: math.Round(box.Margin[5] - box.Margin[1]),
Scale: 1.0,
}).Do(ctx)
if err != nil {
return err
}
*picbuf = buf
return nil
}, append(opts, chromedp.NodeVisible)...)
}