-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathscreenshots.go
More file actions
433 lines (389 loc) · 15.7 KB
/
Copy pathscreenshots.go
File metadata and controls
433 lines (389 loc) · 15.7 KB
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
package biloba
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"image"
"image/color/palette"
"image/draw"
"image/png"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/BourgeoisBear/rasterm"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
// screenshotCaptureTimeout bounds a single tab's screenshot capture so a wedged tab can't hang the
// suite, while staying generous enough that a healthy full-page PNG capture doesn't spuriously time
// out under heavy parallel/CI load.
const screenshotCaptureTimeout = 5 * time.Second
// inlineImageProtocol identifies which terminal inline-image escape sequence a
// screenshot should be encoded with.
type inlineImageProtocol int
const (
inlineImageNone inlineImageProtocol = iota
inlineImageITerm
inlineImageKitty
inlineImageSixel
)
// detectInlineImageProtocol decides which (if any) terminal inline-image protocol
// to use. The decision order is:
//
// 1. BILOBA_INLINE_SCREENSHOTS=iterm|kitty|sixel → force that protocol; =none → force off.
// 2. Environment-variable terminal detection (iTerm2, VSCode, WezTerm, Ghostty, kitty, Konsole, …).
// 3. BILOBA_PROBE_TERMINAL=true → query the terminal directly (Primary DA) for Sixel support.
// 4. Otherwise → off.
//
// Kitty's graphics protocol is preferred where available (best quality), then the
// broadly-supported iTerm2 OSC 1337 protocol (works in iTerm2, VSCode, WezTerm, …),
// then Sixel as a last-resort fallback for older terminals.
func detectInlineImageProtocol() inlineImageProtocol {
switch strings.ToLower(os.Getenv("BILOBA_INLINE_SCREENSHOTS")) {
case "iterm", "iterm2":
return inlineImageITerm
case "kitty":
return inlineImageKitty
case "sixel":
return inlineImageSixel
case "none", "off", "false":
return inlineImageNone
}
// unset, "auto", or an unrecognized value falls through to terminal auto-detection.
if p := inlineImageProtocolFromEnv(); p != inlineImageNone {
return p
}
// Some Sixel-capable terminals (xterm, foot, mlterm, …) don't announce themselves
// through environment variables. Probing requires putting the controlling TTY into
// raw mode, so it is opt-in to avoid interfering with the test runner's terminal.
if os.Getenv("BILOBA_PROBE_TERMINAL") == "true" {
if ok, err := rasterm.IsSixelCapable(); err == nil && ok {
return inlineImageSixel
}
}
return inlineImageNone
}
// inlineImageProtocolFromEnv maps well-known terminal environment variables to the
// best inline-image protocol that terminal supports.
func inlineImageProtocolFromEnv() inlineImageProtocol {
termProgram := os.Getenv("TERM_PROGRAM")
term := os.Getenv("TERM")
// Kitty graphics protocol — best quality where supported.
if os.Getenv("KITTY_WINDOW_ID") != "" || term == "xterm-kitty" || termProgram == "ghostty" {
return inlineImageKitty
}
// VSCode's integrated terminal renders Sixel but NOT the iTerm2 OSC 1337
// protocol, so prefer Sixel there.
if termProgram == "vscode" {
return inlineImageSixel
}
// iTerm2 OSC 1337 inline-image protocol — broad reach (iTerm2, WezTerm, …).
switch termProgram {
case "iTerm.app", "WezTerm", "rio":
return inlineImageITerm
}
if os.Getenv("LC_TERMINAL") == "iTerm2" { // iTerm2 forwarded over ssh
return inlineImageITerm
}
if os.Getenv("KONSOLE_VERSION") != "" { // Konsole speaks OSC 1337
return inlineImageITerm
}
if term == "mintty" {
return inlineImageITerm
}
return inlineImageNone
}
// inlineImagesSupported reports whether the current terminal can render any inline
// image protocol. See detectInlineImageProtocol for the decision order.
func inlineImagesSupported() bool {
return detectInlineImageProtocol() != inlineImageNone
}
/*
CaptureScreenshot() returns a full screenshot of the current tab as a []byte array (you can decode it with the image package)
Like all the screenshot captures it is a waiting command bounded by its own ~5s default deadline; override that with [Biloba.WithTimeout] or abort it with [Biloba.WithContext] (WithPolling and Immediate are not supported).
*/
func (b *Biloba) CaptureScreenshot() []byte {
b.gt.Helper()
b.guardConfig("CaptureScreenshot", knobTimeout, knobContext)
return b.captureScreenshot()
}
// captureScreenshot is the unguarded substrate behind CaptureScreenshot and its imgcat/to-file
// wrappers. It runs under a bounded context (default screenshotCaptureTimeout) that honors the
// WithTimeout/WithContext knobs a waiting command is allowed.
func (b *Biloba) captureScreenshot() []byte {
b.gt.Helper()
ctx, cancel := b.waitingContext(screenshotCaptureTimeout)
defer cancel()
var img []byte
err := chromedp.Run(ctx, chromedp.FullScreenshot(&img, 100))
if err != nil {
b.gt.Fatalf("Failed to capture screenshot:\n%s", err.Error())
}
return img
}
/*
CaptureImgCatScreenshot() returns a full screenshot of the current tab as an iTerm2 imgcat-compatible string. Simply print it out to see images on your terminal.
It is a waiting command: see [Biloba.CaptureScreenshot] for the WithTimeout/WithContext knobs it honors.
*/
func (b *Biloba) CaptureImgcatScreenshot() string {
b.gt.Helper()
b.guardConfig("CaptureImgcatScreenshot", knobTimeout, knobContext)
return b.asImgCat(b.captureScreenshot())
}
/*
CaptureScreenshotToFile writes a full screenshot of the current tab as a PNG file to the given path and returns its absolute path.
The directory is created if it does not already exist.
The absolute path is printed to the test output so it appears in failure output and is readable by tools that can render PNG files.
It is a waiting command: see [Biloba.CaptureScreenshot] for the WithTimeout/WithContext knobs it honors.
Read https://onsi.github.io/biloba/#capturing-screenshots for details.
*/
func (b *Biloba) CaptureScreenshotToFile(path string) string {
b.gt.Helper()
b.guardConfig("CaptureScreenshotToFile", knobTimeout, knobContext)
return b.writeScreenshotToFile(b.captureScreenshot(), path)
}
// writeScreenshotToFile resolves path to an absolute path, creates any missing intermediate
// directories, writes img there as a PNG, prints the path to the test output (so it surfaces in
// failure output and is readable by tools that render PNGs), and returns the absolute path. It
// fails the spec on any error.
func (b *Biloba) writeScreenshotToFile(img []byte, path string) string {
b.gt.Helper()
absPath, err := filepath.Abs(path)
if err != nil {
b.gt.Fatalf("Failed to resolve screenshot path %q:\n%s", path, err.Error())
return ""
}
if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
b.gt.Fatalf("Failed to create screenshot directory %q:\n%s", filepath.Dir(absPath), err.Error())
return ""
}
if err := os.WriteFile(absPath, img, 0644); err != nil {
b.gt.Fatalf("Failed to write screenshot to %q:\n%s", absPath, err.Error())
return ""
}
b.gt.Printf("Screenshot written to: %s\n", absPath)
return absPath
}
/*
CaptureScreenshotOf(selector) returns a screenshot of the first element matching selector as a []byte array (you can decode it with the image package). The screenshot is clipped to the element's bounding box and can capture an element below the fold without scrolling. Same-origin >>>-pierced iframe elements are translated to top-level page coordinates.
It is a waiting command: see [Biloba.CaptureScreenshot] for the WithTimeout/WithContext knobs it honors.
Read https://onsi.github.io/biloba/#capturing-screenshots for details.
*/
func (b *Biloba) CaptureScreenshotOf(selector any) []byte {
b.gt.Helper()
b.guardConfig("CaptureScreenshotOf", knobTimeout, knobContext)
return b.captureScreenshotOf(selector)
}
// captureScreenshotOf is the unguarded substrate behind CaptureScreenshotOf and its imgcat/to-file
// wrappers. The element capture runs under a bounded context (default screenshotCaptureTimeout) that
// honors the WithTimeout/WithContext knobs a waiting command is allowed.
func (b *Biloba) captureScreenshotOf(selector any) []byte {
b.gt.Helper()
img, _, err := b.elementScreenshot(selector)
if err != nil {
b.gt.Fatalf("Failed to capture screenshot of element:\n%s", err.Error())
return nil
}
return img
}
// elementScreenshot captures the first element matching selector, clipped to its bounding box, and
// hands back the PNG along with the clip it used. The clip is what turns a mask rectangle measured in
// document coordinates into image coordinates, which is why the visual-regression path needs it back.
// Unlike captureScreenshotOf it returns errors rather than failing the spec: a matcher polls it, and
// an error there means "retry".
func (b *Biloba) elementScreenshot(selector any) ([]byte, *page.Viewport, error) {
r := b.runBilobaHandler("boundingBox", selector)
if r.Error() != nil {
return nil, nil, r.Error()
}
box, ok := r.Result.(map[string]any)
if !ok {
return nil, nil, fmt.Errorf("unexpected bounding box result: %v", r.Result)
}
clip := &page.Viewport{
X: toFloat64(box["x"]),
Y: toFloat64(box["y"]),
Width: toFloat64(box["width"]),
Height: toFloat64(box["height"]),
Scale: 1,
}
cctx, cancel := b.waitingContext(screenshotCaptureTimeout)
defer cancel()
var img []byte
err := chromedp.Run(cctx, chromedp.ActionFunc(func(ctx context.Context) error {
var captureErr error
img, captureErr = page.CaptureScreenshot().
WithClip(clip).
WithFromSurface(true).
WithCaptureBeyondViewport(true).
Do(ctx)
return captureErr
}))
if err != nil {
return nil, clip, err
}
return img, clip, nil
}
/*
CaptureImgcatScreenshotOf(selector) returns a screenshot of the first element matching selector as an iTerm2 imgcat-compatible string. Simply print it out to see the image on your terminal.
It is a waiting command: see [Biloba.CaptureScreenshot] for the WithTimeout/WithContext knobs it honors.
Read https://onsi.github.io/biloba/#capturing-screenshots for details.
*/
func (b *Biloba) CaptureImgcatScreenshotOf(selector any) string {
b.gt.Helper()
b.guardConfig("CaptureImgcatScreenshotOf", knobTimeout, knobContext)
return b.asImgCat(b.captureScreenshotOf(selector))
}
/*
CaptureScreenshotOfToFile writes a screenshot of the first element matching selector as a PNG file to the given path and returns its absolute path.
The directory is created if it does not already exist.
The absolute path is printed to the test output so it appears in failure output and is readable by tools that can render PNG files.
It is a waiting command: see [Biloba.CaptureScreenshot] for the WithTimeout/WithContext knobs it honors.
Read https://onsi.github.io/biloba/#capturing-screenshots for details.
*/
func (b *Biloba) CaptureScreenshotOfToFile(selector any, path string) string {
b.gt.Helper()
b.guardConfig("CaptureScreenshotOfToFile", knobTimeout, knobContext)
return b.writeScreenshotToFile(b.captureScreenshotOf(selector), path)
}
func (b *Biloba) asImgCat(img []byte) string {
return b.asInlineImage(img, inlineImageITerm)
}
// encodeInlineImage encodes a PNG into the escape sequence for the given terminal inline-image
// protocol, returning "" for inlineImageNone. It reports an encoding error instead of failing the
// test: asInlineImage is the caller that turns the error into a Fatalf, but a failure message being
// rendered (see visual.go) cannot do that - it runs while a spec is already failing, and during a
// progress report it runs on Ginkgo's goroutine.
func encodeInlineImage(img []byte, proto inlineImageProtocol) (string, error) {
buf := &bytes.Buffer{}
switch proto {
case inlineImageITerm:
buf.WriteString("\033]1337;File=;inline=1:")
encoder := base64.NewEncoder(base64.StdEncoding, buf)
if _, err := encoder.Write(img); err != nil {
return "", err
}
encoder.Close()
buf.WriteString("\033\\")
case inlineImageKitty:
if err := rasterm.KittyCopyPNGInline(buf, bytes.NewReader(img), rasterm.KittyImgOpts{}); err != nil {
return "", err
}
case inlineImageSixel:
paletted, err := pngToPaletted(img)
if err != nil {
return "", err
}
if err := rasterm.SixelWriteImage(buf, paletted); err != nil {
return "", err
}
default:
return "", nil
}
return buf.String(), nil
}
// asInlineImage encodes a PNG screenshot into the escape sequence for the given
// terminal inline-image protocol. Returns "" for inlineImageNone.
func (b *Biloba) asInlineImage(img []byte, proto inlineImageProtocol) string {
encoded, err := encodeInlineImage(img, proto)
if err != nil {
b.gt.Fatalf("Failed to encode inline screenshot:\n%s", err.Error())
}
return encoded
}
// pngToPaletted decodes a PNG and dithers it down to a 256-color paletted image,
// as required by the Sixel encoder (which is an inherently paletted format).
func pngToPaletted(img []byte) (*image.Paletted, error) {
src, err := png.Decode(bytes.NewReader(img))
if err != nil {
return nil, err
}
bounds := src.Bounds()
out := image.NewPaletted(bounds, palette.Plan9)
draw.FloydSteinberg.Draw(out, bounds, src, bounds.Min)
return out, nil
}
type tabScreenshot struct {
title string
imgcatScreenshot string
filePath string
failure string
}
// sanitizeForFilename replaces any characters that are not alphanumeric, hyphens, underscores, or dots with underscores,
// and collapses runs of underscores.
var nonFilenameRE = regexp.MustCompile(`[^a-zA-Z0-9\-_.]`)
var multiUnderscoreRE = regexp.MustCompile(`_+`)
func sanitizeForFilename(s string) string {
s = nonFilenameRE.ReplaceAllString(s, "_")
s = multiUnderscoreRE.ReplaceAllString(s, "_")
s = strings.Trim(s, "_")
if len(s) > 80 {
s = s[:80]
}
return s
}
func (b *Biloba) safeAllTabScreenshots(width int, height int) []tabScreenshot {
out := []tabScreenshot{}
for idx, tab := range b.AllTabs() {
// Bound the capture so a wedged tab can't hang screenshot collection, but keep it generous:
// FullScreenshot encodes a PNG of the whole page and, under heavy parallel/CI load, legitimately
// takes well over a second. A 1s bound here spuriously timed out healthy captures - surfacing as
// "Timed out attempting to fetch screenshot" noise and flaking the inline-encoding specs.
ctx, cancel := context.WithTimeout(tab.Context, screenshotCaptureTimeout)
defer cancel()
var originalWidth, originalHeight int
if width > 0 && height > 0 {
originalWidth, originalHeight = b.WindowSize()
err := chromedp.Run(ctx, chromedp.EmulateViewport(int64(width), int64(height)))
if err != nil {
out = append(out, tabScreenshot{failure: fmt.Sprintf("failed to set window size: %s", err.Error())})
continue
}
}
var img []byte
var title string
err := chromedp.Run(ctx,
chromedp.Title(&title),
chromedp.FullScreenshot(&img, 100),
)
if width > 0 && height > 0 {
err := chromedp.Run(ctx, chromedp.EmulateViewport(int64(originalWidth), int64(originalHeight), chromedp.EmulatePortrait))
if err != nil {
out = append(out, tabScreenshot{failure: fmt.Sprintf("failed to reset window size: %s", err.Error())})
continue
}
}
if ctx.Err() != nil {
out = append(out, tabScreenshot{failure: "Timed out attempting to fetch screenshot for tab"})
continue
} else if err != nil {
out = append(out, tabScreenshot{failure: fmt.Sprintf("Failed to fetch screenshot for tab: %s", err.Error())})
continue
}
ts := tabScreenshot{
title: title,
}
if b.root.inlineScreenshotsEnabled() {
ts.imgcatScreenshot = b.asInlineImage(img, detectInlineImageProtocol())
}
if b.root.screenshotsDir != "" {
specName := sanitizeForFilename(b.gt.Name())
tabLabel := sanitizeForFilename(title)
if tabLabel == "" {
tabLabel = fmt.Sprintf("tab%d", idx)
}
filename := fmt.Sprintf("screenshot-%s-%s.png", specName, tabLabel)
absPath := filepath.Join(b.root.screenshotsDir, filename)
if mkErr := os.MkdirAll(b.root.screenshotsDir, 0755); mkErr == nil {
if writeErr := os.WriteFile(absPath, img, 0644); writeErr == nil {
ts.filePath = absPath
}
}
}
out = append(out, ts)
}
return out
}