vcom/internal/imgview/imgview_test.go
vrubelroman 6c13b19ad1 feat(imgview): image actor with kitty/ueberzugpp, SyncTTY and off-UI decoding (5C.1)
Adds golang.org/x/image v0.39.0 (draw, webp; vendored; x/sys and x/text
unchanged). SyncTTY serialises renderer frames and image blocks under one
mutex. The actor keeps only the latest Desired state (100 Apply → ≤ 2
decodes), refuses images above 50 Mpx from the header alone, scales with
ApproxBiLinear and writes kitty graphics as one ESC7/CUP/APC/ESC8 block
(raw RGBA, chunked or via a temp file, tmux passthrough). ueberzugpp gets
JSON lines through a pipe with a 200 ms write deadline; a helper that stops
reading is killed with its process group and the backend falls back to
none with an event. Stop removes the placement, temp files and processes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:01:26 +03:00

342 lines
10 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package imgview
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"vcom/internal/preview"
)
// slowWriter writes byte by byte, yielding in between, so unsynchronised
// writers would interleave.
type slowWriter struct {
mu sync.Mutex
buf bytes.Buffer
}
func (w *slowWriter) Write(p []byte) (int, error) {
for _, b := range p {
w.mu.Lock()
w.buf.WriteByte(b)
w.mu.Unlock()
runtime.Gosched()
}
return len(p), nil
}
func TestSyncTTYNoInterleave(t *testing.T) {
w := &slowWriter{}
tty := NewSyncWriter(w)
var wg sync.WaitGroup
for i := range 8 {
wg.Add(2)
go func() { // renderer frames
defer wg.Done()
for j := range 20 {
_, _ = tty.Write([]byte(fmt.Sprintf("<frame %d.%d|%s>", i, j, strings.Repeat("x", 50))))
}
}()
go func() { // kitty blocks in several parts
defer wg.Done()
for j := range 20 {
_ = tty.WriteBlock([]byte(fmt.Sprintf("<kitty %d.%d|", i, j)), []byte(strings.Repeat("k", 50)), []byte(">"))
}
}()
}
wg.Wait()
out := w.buf.String()
// Every '<' must be followed by a whole unit up to its '>' with no '<' inside.
n := 0
for len(out) > 0 {
if out[0] != '<' {
t.Fatalf("garbage at %q", out[:min(40, len(out))])
}
end := strings.IndexByte(out, '>')
if end < 0 || strings.Contains(out[1:end], "<") {
t.Fatalf("interleaved output near %q", out[:min(80, len(out))])
}
out = out[end+1:]
n++
}
if n != 8*20*2 {
t.Fatalf("%d units", n)
}
}
func writePNG(t testing.TB, dir, name string, w, h int) string {
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i := range img.Pix {
img.Pix[i] = byte(i)
}
p := filepath.Join(dir, name)
f, err := os.Create(p)
if err != nil {
t.Fatal(err)
}
if err := png.Encode(f, img); err != nil {
t.Fatal(err)
}
f.Close()
return p
}
func TestActorLatestWins(t *testing.T) {
dir := t.TempDir()
var decodes atomic.Int32
decodeHook = func() { decodes.Add(1); time.Sleep(20 * time.Millisecond) }
t.Cleanup(func() { decodeHook = nil })
var out bytes.Buffer
var mu sync.Mutex
tty := NewSyncWriter(writerFunc(func(p []byte) (int, error) { mu.Lock(); defer mu.Unlock(); return out.Write(p) }))
a := Start(Options{Backend: Kitty, TTY: tty, CellW: 8, CellH: 16})
defer a.Stop()
var paths []string
for i := range 5 {
paths = append(paths, writePNG(t, dir, fmt.Sprintf("%d.png", i), 64+i, 32))
}
t0 := time.Now()
for i := range 100 {
a.Apply(Desired{Visible: true, Rect: Rect{X: 1, Y: 1, W: 10, H: 5}, Gen: uint64(i),
Image: preview.ImageRef{Local: paths[i%5], Size: int64(i)}})
}
if el := time.Since(t0); el > 50*time.Millisecond {
t.Fatalf("100 Apply took %v: Apply must not block", el)
}
deadline := time.Now().Add(2 * time.Second)
for {
mu.Lock()
got := strings.Count(out.String(), "a=T")
mu.Unlock()
if got > 0 && !a.stale() {
break
}
if time.Now().After(deadline) {
t.Fatal("nothing drawn")
}
time.Sleep(10 * time.Millisecond)
}
time.Sleep(60 * time.Millisecond)
if n := decodes.Load(); n > 2 {
t.Fatalf("%d decodes for 100 Apply calls, want ≤ 2", n)
}
}
type writerFunc func([]byte) (int, error)
func (f writerFunc) Write(p []byte) (int, error) { return f(p) }
// hugePNG writes a valid PNG whose IHDR claims w×h (the pixel data is tiny
// and wrong: a full decode would fail or take ages; DecodeConfig must stop
// first).
func hugePNG(t *testing.T, w, h uint32) string {
var b bytes.Buffer
_ = png.Encode(&b, image.NewGray(image.Rect(0, 0, 1, 1)))
data := b.Bytes()
ihdr := data[8+8 : 8+8+13] // after signature, length and type
binary.BigEndian.PutUint32(ihdr[0:4], w)
binary.BigEndian.PutUint32(ihdr[4:8], h)
crc := crc32.ChecksumIEEE(data[8+4 : 8+8+13])
binary.BigEndian.PutUint32(data[8+8+13:], crc)
p := filepath.Join(t.TempDir(), "huge.png")
_ = os.WriteFile(p, data, 0o644)
return p
}
func TestRejectHugeImage(t *testing.T) {
p := hugePNG(t, 10000, 10000) // 100 Mpx
var decodes atomic.Int32
decodeHook = func() { decodes.Add(1) }
t.Cleanup(func() { decodeHook = nil })
t0 := time.Now()
_, err := loadScaled(t.Context(), p, 800, 600)
if !errors.Is(err, ErrTooLarge) || decodes.Load() != 0 {
t.Fatalf("err=%v decodes=%d", err, decodes.Load())
}
if el := time.Since(t0); el > 50*time.Millisecond {
t.Fatalf("took %v", el)
}
// Through the actor the error becomes an event, nothing is drawn.
events := make(chan Event, 4)
var out bytes.Buffer
a := Start(Options{Backend: Kitty, TTY: NewSyncWriter(&out), CellW: 8, CellH: 16, OnEvent: func(e Event) { events <- e }})
a.Apply(Desired{Visible: true, Rect: Rect{W: 10, H: 5}, Image: preview.ImageRef{Local: p}})
select {
case e := <-events:
if !errors.Is(e.Err, ErrTooLarge) {
t.Fatalf("event %+v", e)
}
case <-time.After(2 * time.Second):
t.Fatal("no event")
}
a.Stop()
if strings.Contains(out.String(), "a=T") {
t.Fatal("drawn anyway")
}
}
func TestUeberzugStuckIsKilled(t *testing.T) {
stuck := filepath.Join(t.TempDir(), "ueberzug")
pidFile := stuck + ".pid"
// Never reads stdin; records its pid.
_ = os.WriteFile(stuck, []byte("#!/bin/sh\necho $$ > "+pidFile+"\nexec sleep 60\n"), 0o755)
events := make(chan Event, 8)
a := Start(Options{Backend: Ueberzug, Ueberzug: []string{stuck}, OnEvent: func(e Event) { events <- e }})
defer a.Stop()
if a.Backend() != Ueberzug {
t.Fatal("did not start")
}
img := writePNG(t, t.TempDir(), "a.png", 4, 4)
// Long paths fill the 64 KiB pipe after a few commands.
longDir := filepath.Join(t.TempDir(), strings.Repeat("d", 200), strings.Repeat("e", 200))
_ = os.MkdirAll(longDir, 0o755)
long := filepath.Join(longDir, "a.png")
_ = os.Link(img, long)
start := time.Now()
var disabledAt time.Time
for i := 0; disabledAt.IsZero() && time.Since(start) < 3*time.Second; i++ {
t0 := time.Now()
a.Apply(Desired{Visible: true, Rect: Rect{X: i % 7, W: 10 + i%5, H: 5}, Image: preview.ImageRef{Local: long + strings.Repeat("/.", 0)}})
if el := time.Since(t0); el > 5*time.Millisecond {
t.Fatalf("Apply blocked for %v", el)
}
select {
case e := <-events:
if e.Disabled && errors.Is(e.Err, ErrStuck) {
disabledAt = time.Now()
}
case <-time.After(2 * time.Millisecond):
}
}
if disabledAt.IsZero() {
t.Fatal("stuck helper never detected")
}
if a.Backend() != None {
t.Fatal("backend not switched off")
}
// The helper is gone.
pid, _ := os.ReadFile(pidFile)
time.Sleep(50 * time.Millisecond)
if _, err := os.Stat("/proc/" + strings.TrimSpace(string(pid))); err == nil {
t.Fatalf("helper %s still running", pid)
}
}
func TestUeberzugCommands(t *testing.T) {
log := filepath.Join(t.TempDir(), "log")
helper := filepath.Join(t.TempDir(), "uz")
_ = os.WriteFile(helper, []byte("#!/bin/sh\ncat > "+log+"\n"), 0o755)
a := Start(Options{Backend: Ueberzug, Ueberzug: []string{helper}})
img := writePNG(t, t.TempDir(), "a.png", 4, 4)
a.Apply(Desired{Visible: true, Rect: Rect{X: 3, Y: 2, W: 10, H: 5}, Image: preview.ImageRef{Local: img}})
time.Sleep(100 * time.Millisecond)
a.Apply(Desired{Visible: false})
time.Sleep(100 * time.Millisecond)
a.Stop()
b, _ := os.ReadFile(log)
s := string(b)
if !strings.Contains(s, `"action":"add"`) || !strings.Contains(s, `"x":3`) || !strings.Contains(s, `"action":"remove"`) {
t.Fatalf("commands:\n%s", s)
}
}
func TestKittyBlock(t *testing.T) {
var out bytes.Buffer
k := &kitty{tty: NewSyncWriter(&out)}
img := scaleToFit(image.NewRGBA(image.Rect(0, 0, 100, 100)), 40, 20)
if img.Rect.Dx() != 20 || img.Rect.Dy() != 20 {
t.Fatalf("scaled %v", img.Rect)
}
if err := k.show(img, Rect{X: 4, Y: 2, W: 5, H: 3}); err != nil {
t.Fatal(err)
}
s := out.String()
if !strings.Contains(s, "\x1b7\x1b[3;5H\x1b_Ga=T,f=32,s=20,v=20,") || !strings.HasSuffix(s, "\x1b8") || !strings.Contains(s, "C=1") {
t.Fatalf("block %q", s[:min(120, len(s))])
}
// Chunked: every APC but the last says m=1.
if strings.Count(s, "m=1") != strings.Count(s, "\x1b_G")-2 { // minus the delete and the last chunk
t.Fatalf("chunks: %d m=1, %d APC", strings.Count(s, "m=1"), strings.Count(s, "\x1b_G"))
}
// File transmission and tmux passthrough.
out.Reset()
tmp := t.TempDir()
k = &kitty{tty: NewSyncWriter(&out), tmpDir: tmp, tmux: true}
if err := k.show(img, Rect{W: 5, H: 3}); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "t=t") || !strings.HasPrefix(out.String(), "\x1bPtmux;\x1b\x1b_G") {
t.Fatalf("tmux/file %q", out.String()[:min(80, out.Len())])
}
k.stop()
if files, _ := filepath.Glob(filepath.Join(tmp, "*")); len(files) != 0 {
t.Fatalf("temp files after stop: %v", files)
}
}
func TestDetect(t *testing.T) {
env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
if Detect("auto", env(map[string]string{"TERM": "xterm-kitty"})) != Kitty {
t.Error("kitty")
}
if Detect("auto", env(map[string]string{"TERM_PROGRAM": "WezTerm"})) != Kitty {
t.Error("wezterm")
}
if Detect("auto", env(map[string]string{"KITTY_WINDOW_ID": "1", "TMUX": "x"})) == Kitty {
t.Error("kitty auto in tmux")
}
if Detect("kitty", env(map[string]string{"TMUX": "x"})) != Kitty || Detect("none", env(nil)) != None {
t.Error("explicit")
}
}
func BenchmarkKittyPayload6000x4000(b *testing.B) {
dir := b.TempDir()
img := image.NewYCbCr(image.Rect(0, 0, 6000, 4000), image.YCbCrSubsampleRatio420)
for i := range img.Y {
img.Y[i] = byte(i * 7)
}
p := filepath.Join(dir, "photo.jpg")
f, _ := os.Create(p)
_ = jpeg.Encode(f, img, &jpeg.Options{Quality: 85})
f.Close()
k := &kitty{tty: NewSyncWriter(writerFunc(func(p []byte) (int, error) { return len(p), nil }))}
b.ResetTimer()
for range b.N {
scaled, err := loadScaled(b.Context(), p, 100*8, 40*16)
if err != nil {
b.Fatal(err)
}
if _, err := k.kittyBlock(scaled, Rect{W: 100, H: 40}); err != nil {
b.Fatal(err)
}
}
}
// Scale + payload only (the stdlib JPEG decoder dominates the benchmark
// above: ~180 of ~200 ms for 24 Mpx).
func BenchmarkKittyPayloadDecoded6000x4000(b *testing.B) {
img := image.NewYCbCr(image.Rect(0, 0, 6000, 4000), image.YCbCrSubsampleRatio420)
k := &kitty{tty: NewSyncWriter(writerFunc(func(p []byte) (int, error) { return len(p), nil }))}
b.ResetTimer()
for range b.N {
if _, err := k.kittyBlock(scaleToFit(img, 800, 640), Rect{W: 100, H: 40}); err != nil {
b.Fatal(err)
}
}
}