Debian Codegraph @

ansi/kitty/decoder.go

raw
1 // Package kitty provides Kitty terminal graphics protocol functionality.
2 package kitty
3
4 import (
5 "compress/zlib"
6 "fmt"
7 "image"
8 "image/color"
9 "image/png"
10 "io"
11 )
12
13 // Decoder is a decoder for the Kitty graphics protocol. It supports decoding
14 // images in the 24-bit [RGB], 32-bit [RGBA], and [PNG] formats. It can also
15 // decompress data using zlib.
16 // The default format is 32-bit [RGBA].
17 type Decoder struct {
18 // Uses zlib decompression.
19 Decompress bool
20
21 // Can be one of [RGB], [RGBA], or [PNG].
22 Format int
23
24 // Width of the image in pixels. This can be omitted if the image is [PNG]
25 // formatted.
26 Width int
27
28 // Height of the image in pixels. This can be omitted if the image is [PNG]
29 // formatted.
30 Height int
31 }
32
33 // Decode decodes the image data from r in the specified format.
34 func (d *Decoder) Decode(r io.Reader) (image.Image, error) {
35 if d.Decompress {
36 zr, err := zlib.NewReader(r)
37 if err != nil {
38 return nil, fmt.Errorf("failed to create zlib reader: %w", err)
39 }
40
41 defer zr.Close() //nolint:errcheck
42 r = zr
43 }
44
45 if d.Format == 0 {
46 d.Format = RGBA
47 }
48
49 switch d.Format {
50 case RGBA, RGB:
51 return d.decodeRGBA(r, d.Format == RGBA)
52
53 case PNG:
54 return png.Decode(r) //nolint:wrapcheck
55
56 default:
57 return nil, fmt.Errorf("unsupported format: %d", d.Format)
58 }
59 }
60
61 // decodeRGBA decodes the image data in 32-bit RGBA or 24-bit RGB formats.
62 func (d *Decoder) decodeRGBA(r io.Reader, alpha bool) (image.Image, error) {
63 m := image.NewRGBA(image.Rect(0, 0, d.Width, d.Height))
64
65 var buf []byte
66 if alpha {
67 buf = make([]byte, 4)
68 } else {
69 buf = make([]byte, 3)
70 }
71
72 for y := range d.Height {
73 for x := range d.Width {
74 if _, err := io.ReadFull(r, buf[:]); err != nil {
75 return nil, fmt.Errorf("failed to read pixel data: %w", err)
76 }
77 if alpha {
78 m.SetRGBA(x, y, color.RGBA{buf[0], buf[1], buf[2], buf[3]})
79 } else {
80 m.SetRGBA(x, y, color.RGBA{buf[0], buf[1], buf[2], 0xff})
81 }
82 }
83 }
84
85 return m, nil
86 }