Debian Codegraph @

ansi/kitty/writer.go

raw
1 package kitty
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "image"
9 "io"
10 "os"
11
12 "github.com/charmbracelet/x/ansi"
13 )
14
15 var (
16 // GraphicsTempDir is the directory where temporary files are stored.
17 // This is used in [WriteKittyGraphics] along with [os.CreateTemp].
18 GraphicsTempDir = ""
19
20 // GraphicsTempPattern is the pattern used to create temporary files.
21 // This is used in [WriteKittyGraphics] along with [os.CreateTemp].
22 // The Kitty Graphics protocol requires the file path to contain the
23 // substring "tty-graphics-protocol".
24 GraphicsTempPattern = "tty-graphics-protocol-*"
25 )
26
27 // EncodeGraphics writes an image using the Kitty Graphics protocol with the
28 // given options to w. It chunks the written data if o.Chunk is true.
29 //
30 // You can omit m and use nil when rendering an image from a file. In this
31 // case, you must provide a file path in o.File and use o.Transmission =
32 // [File]. You can also use o.Transmission = [TempFile] to write
33 // the image to a temporary file. In that case, the file path is ignored, and
34 // the image is written to a temporary file that is automatically deleted by
35 // the terminal.
36 //
37 // See https://sw.kovidgoyal.net/kitty/graphics-protocol/
38 func EncodeGraphics(w io.Writer, m image.Image, o *Options) error {
39 if o == nil {
40 o = &Options{}
41 }
42
43 if o.Transmission == 0 && len(o.File) != 0 {
44 o.Transmission = File
45 }
46
47 var data bytes.Buffer // the data to be encoded into base64
48 e := &Encoder{
49 Compress: o.Compression == Zlib,
50 Format: o.Format,
51 }
52
53 switch o.Transmission {
54 case Direct:
55 if err := e.Encode(&data, m); err != nil {
56 return fmt.Errorf("failed to encode direct image: %w", err)
57 }
58
59 case SharedMemory:
60 //nolint:godox
61 // TODO: Implement shared memory
62 return fmt.Errorf("shared memory transmission is not yet implemented")
63
64 case File:
65 if len(o.File) == 0 {
66 return ErrMissingFile
67 }
68
69 f, err := os.Open(o.File)
70 if err != nil {
71 return fmt.Errorf("failed to open file: %w", err)
72 }
73
74 defer f.Close() //nolint:errcheck
75
76 stat, err := f.Stat()
77 if err != nil {
78 return fmt.Errorf("failed to get file info: %w", err)
79 }
80
81 mode := stat.Mode()
82 if !mode.IsRegular() {
83 return fmt.Errorf("file is not a regular file")
84 }
85
86 // Write the file path to the buffer
87 if _, err := data.WriteString(f.Name()); err != nil {
88 return fmt.Errorf("failed to write file path to buffer: %w", err)
89 }
90
91 case TempFile:
92 f, err := os.CreateTemp(GraphicsTempDir, GraphicsTempPattern)
93 if err != nil {
94 return fmt.Errorf("failed to create file: %w", err)
95 }
96
97 defer f.Close() //nolint:errcheck
98
99 if err := e.Encode(f, m); err != nil {
100 return fmt.Errorf("failed to encode image to file: %w", err)
101 }
102
103 // Write the file path to the buffer
104 if _, err := data.WriteString(f.Name()); err != nil {
105 return fmt.Errorf("failed to write file path to buffer: %w", err)
106 }
107 }
108
109 // Encode image to base64
110 var payload bytes.Buffer // the base64 encoded image to be written to w
111 b64 := base64.NewEncoder(base64.StdEncoding, &payload)
112 if _, err := data.WriteTo(b64); err != nil {
113 return fmt.Errorf("failed to write base64 encoded image to payload: %w", err)
114 }
115 if err := b64.Close(); err != nil {
116 return err //nolint:wrapcheck
117 }
118
119 // If not chunking, write all at once
120 if !o.Chunk {
121 _, err := io.WriteString(w, ansi.KittyGraphics(payload.Bytes(), o.Options()...))
122 return err //nolint:wrapcheck
123 }
124
125 // Write in chunks
126 var (
127 err error
128 n int
129 )
130 chunk := make([]byte, MaxChunkSize)
131 isFirstChunk := true
132
133 for {
134 // Stop if we read less than the chunk size [MaxChunkSize].
135 n, err = io.ReadFull(&payload, chunk)
136 if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) {
137 break
138 }
139 if err != nil {
140 return fmt.Errorf("failed to read chunk: %w", err)
141 }
142
143 opts := buildChunkOptions(o, isFirstChunk, false)
144 if _, err := io.WriteString(w, ansi.KittyGraphics(chunk[:n], opts...)); err != nil {
145 return err //nolint:wrapcheck
146 }
147
148 isFirstChunk = false
149 }
150
151 // Write the last chunk
152 opts := buildChunkOptions(o, isFirstChunk, true)
153 _, err = io.WriteString(w, ansi.KittyGraphics(chunk[:n], opts...))
154 return err //nolint:wrapcheck
155 }
156
157 // buildChunkOptions creates the options slice for a chunk.
158 func buildChunkOptions(o *Options, isFirstChunk, isLastChunk bool) []string {
159 var opts []string
160 if isFirstChunk {
161 opts = o.Options()
162 } else {
163 // These options are allowed in subsequent chunks
164 if o.Quite > 0 {
165 opts = append(opts, fmt.Sprintf("q=%d", o.Quite))
166 }
167 if o.Action == Frame {
168 opts = append(opts, "a=f")
169 }
170 }
171
172 if !isFirstChunk || !isLastChunk {
173 // We don't need to encode the (m=) option when we only have one chunk.
174 if isLastChunk {
175 opts = append(opts, "m=0")
176 } else {
177 opts = append(opts, "m=1")
178 }
179 }
180 return opts
181 }