Debian Codegraph @

examples/image/main.go

raw symbols SCIP
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "flag"
8 "fmt"
9 "image"
10 "image/color"
11 "io"
12 "log"
13 "os"
14 "slices"
15 "strings"
16 "time"
17
18 _ "image/jpeg" // Register JPEG format
19
20 uv "github.com/charmbracelet/ultraviolet"
21 "github.com/charmbracelet/x/ansi"
22 "github.com/charmbracelet/x/ansi/iterm2"
23 "github.com/charmbracelet/x/ansi/kitty"
24 "github.com/charmbracelet/x/ansi/sixel"
25 "github.com/charmbracelet/x/mosaic"
26 )
27
28 type imageEncoding uint8
29
30 const (
31 blocksEncoding imageEncoding = iota + 1
32 sixelEncoding
33 itermEncoding
34 kittyEncoding
35
36 unknownEncoding = 0
37 )
38
39 func (e imageEncoding) String() string {
40 switch e {
41 case blocksEncoding:
42 return "blocks"
43 case sixelEncoding:
44 return "sixel"
45 case itermEncoding:
46 return "iterm"
47 case kittyEncoding:
48 return "kitty"
49 default:
50 return "unknown"
51 }
52 }
53
54 var desiredEnc int
55
56 func init() {
57 flag.IntVar(&desiredEnc, "encoding", int(unknownEncoding), "image encoding")
58
59 f, err := os.OpenFile("image.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
60 if err != nil {
61 log.Fatalf("failed to open log file: %v", err)
62 }
63 log.SetFlags(log.LstdFlags | log.Lshortfile)
64 log.SetOutput(f)
65 }
66
67 func main() {
68 flag.Parse()
69
70 t := uv.DefaultTerminal()
71
72 // Use altscreen buffer.
73 t.EnterAltScreen() //nolint:errcheck
74
75 // Enable mouse support.
76 t.EnableMouse() //nolint:errcheck
77
78 if err := t.Start(); err != nil {
79 log.Fatalf("failed to start program: %v", err)
80 }
81
82 // Get image info.
83 charmImgFile, err := os.Open("./charm.jpg")
84 if err != nil {
85 log.Fatalf("failed to open image file: %v", err)
86 }
87
88 defer charmImgFile.Close() //nolint:errcheck
89 charmImgStat, err := charmImgFile.Stat()
90 if err != nil {
91 log.Fatalf("failed to stat image file: %v", err)
92 }
93
94 charmImgFileSize := charmImgStat.Size()
95
96 var charmImgBuf bytes.Buffer
97 var charmImgB64 []byte
98 imgTee := io.TeeReader(charmImgFile, &charmImgBuf)
99 charmImg, _, err := image.Decode(imgTee)
100 if err != nil {
101 log.Fatalf("failed to decode image: %v", err)
102 }
103
104 charmImgArea := charmImg.Bounds()
105
106 // Image related variables.
107 var (
108 winSize uv.WindowSizeEvent
109 pixSize uv.WindowPixelSizeEvent
110 imgEnc = blocksEncoding
111 )
112 if desiredEnc > 0 {
113 imgEnc = imageEncoding(desiredEnc)
114 }
115
116 winSize.Width, winSize.Height, err = t.GetSize()
117 if err != nil {
118 log.Fatalf("failed to get terminal size: %v", err)
119 }
120
121 t.Resize(winSize.Width, winSize.Height) //nolint:errcheck
122
123 upgradeEnc := func(enc imageEncoding) {
124 if desiredEnc == unknownEncoding {
125 if enc > imgEnc {
126 imgEnc = enc
127 }
128 }
129 }
130
131 // Check environment variables for supported encodings.
132 var (
133 termType = os.Getenv("TERM")
134 termProg string
135 lcTerm string
136 termVersion string
137 ok bool
138 )
139 if termProg, ok = os.LookupEnv("TERM_PROGRAM"); ok {
140 if strings.Contains(termProg, "iTerm") ||
141 strings.Contains(termProg, "WezTerm") ||
142 strings.Contains(termProg, "mintty") ||
143 strings.Contains(termProg, "vscode") ||
144 strings.Contains(termProg, "Tabby") ||
145 strings.Contains(termProg, "Hyper") ||
146 strings.Contains(termProg, "rio") {
147 upgradeEnc(itermEncoding)
148 }
149 if lcTerm, ok = os.LookupEnv("LC_TERMINAL"); ok {
150 if strings.Contains(lcTerm, "iTerm") {
151 upgradeEnc(itermEncoding)
152 }
153 }
154 }
155
156 // Display image methods.
157 imgCellSize := func() (int, int) {
158 if winSize.Width == 0 || winSize.Height == 0 || pixSize.Width == 0 || pixSize.Height == 0 {
159 return 0, 0
160 }
161
162 cellW, cellH := pixSize.Width/winSize.Width, pixSize.Height/winSize.Height
163 imgW, imgH := charmImgArea.Dx(), charmImgArea.Dy()
164 return imgW / cellW, imgH / cellH
165 }
166
167 var transmitKitty bool
168 var imgCellW, imgCellH int
169 var imgOffsetX, imgOffsetY int
170 imgCellW, imgCellH = imgCellSize()
171 imgOffsetX = winSize.Width/2 - imgCellW/2
172 imgOffsetY = winSize.Height/2 - imgCellH/2
173
174 fillStyle := uv.Style{Fg: ansi.IndexedColor(240)}
175 displayImg := func() {
176 img := charmImg
177 imgArea := uv.Rect(
178 imgOffsetX,
179 imgOffsetY,
180 imgCellW,
181 imgCellH,
182 )
183 if !imgArea.In(winSize.Bounds()) {
184 imgArea = imgArea.Intersect(winSize.Bounds())
185 // TODO: Crop image.
186 }
187
188 log.Printf("image area: %v", imgArea)
189
190 // Clear the screen.
191 t.Clear()
192 fill := uv.Cell{Content: "/", Width: 1, Style: fillStyle}
193 t.Fill(&fill)
194
195 // Draw the image on the screen.
196 switch imgEnc {
197 case blocksEncoding:
198 blocks := mosaic.New().Width(imgCellW).Height(imgCellH).Scale(2)
199 ss := uv.NewStyledString(blocks.Render(img))
200 ss.Draw(t, imgArea)
201
202 case itermEncoding, sixelEncoding:
203 t.FillArea(&uv.EmptyCell, imgArea)
204
205 case kittyEncoding:
206 const imgId = 31 // random id for kitty graphics
207 if !transmitKitty {
208 var buf bytes.Buffer
209 if err := kitty.EncodeGraphics(&buf, img, &kitty.Options{
210 ID: imgId,
211 Action: kitty.TransmitAndPut,
212 Transmission: kitty.Direct,
213 Format: kitty.RGBA,
214 Size: int(charmImgFileSize),
215 ImageWidth: charmImgArea.Dx(),
216 ImageHeight: charmImgArea.Dy(),
217 Columns: imgArea.Dx(),
218 Rows: imgArea.Dy(),
219 VirtualPlacement: true,
220 Quite: 2,
221 }); err != nil {
222 log.Fatalf("failed to encode image for Kitty Graphics: %v", err)
223 }
224
225 t.WriteString(buf.String()) //nolint:errcheck
226 transmitKitty = true
227 t.Flush()
228 }
229
230 // Build Kitty graphics unicode place holders
231 var fg color.Color
232 var extra int
233 var r, g, b int
234 extra, r, g, b = imgId>>24&0xff, imgId>>16&0xff, imgId>>8&0xff, imgId&0xff
235
236 if r == 0 && g == 0 {
237 fg = ansi.IndexedColor(b)
238 } else {
239 fg = color.RGBA{
240 R: uint8(r), //nolint:gosec
241 G: uint8(g), //nolint:gosec
242 B: uint8(b), //nolint:gosec
243 A: 0xff,
244 }
245 }
246
247 for y := 0; y < imgArea.Dy(); y++ {
248 // As an optimization, we only write the fg color sequence id, and
249 // column-row data once on the first cell. The terminal will handle
250 // the rest.
251 content := []rune{kitty.Placeholder, kitty.Diacritic(y), kitty.Diacritic(0)}
252 if extra > 0 {
253 content = append(content, kitty.Diacritic(extra))
254 }
255 t.SetCell(imgArea.Min.X, imgArea.Min.Y+y, &uv.Cell{
256 Style: uv.Style{Fg: fg},
257 Content: string(content),
258 Width: 1,
259 })
260 for x := 1; x < imgArea.Dx(); x++ {
261 t.SetCell(imgArea.Min.X+x, imgArea.Min.Y+y, &uv.Cell{
262 Style: uv.Style{Fg: fg},
263 Content: string(kitty.Placeholder),
264 Width: 1,
265 })
266 }
267 }
268
269 }
270
271 t.Display() //nolint:errcheck
272
273 switch imgEnc {
274 case sixelEncoding:
275 var senc sixel.Encoder
276 var buf bytes.Buffer
277 senc.Encode(&buf, img)
278 six := ansi.SixelGraphics(0, 1, 0, buf.Bytes())
279 // Note: Sixel starts drawing from the current cursor position
280 // and the cursor ends up at the bottom of the image
281 // Add a small offset to prevent top cutoff
282 if imgArea.Min.Y > 0 {
283 t.MoveTo(imgArea.Min.X, imgArea.Min.Y+1)
284 } else {
285 t.MoveTo(imgArea.Min.X, imgArea.Min.Y)
286 }
287
288 t.WriteString(six) //nolint:errcheck
289 t.WriteString(ansi.CursorPosition(imgArea.Min.X+1, imgArea.Min.Y+1))
290
291 case itermEncoding:
292 // Now, we need to encode the image and place it in the first
293 // cell before moving the cursor to the correct position.
294 if charmImgB64 == nil {
295 // Encode the image to base64 for the first time.
296 charmImgB64 = []byte(base64.StdEncoding.EncodeToString(charmImgBuf.Bytes()))
297 }
298
299 data := ansi.ITerm2(iterm2.File{
300 Name: "charm.jpg",
301 Width: iterm2.Cells(imgArea.Dx()),
302 Height: iterm2.Cells(imgArea.Dy()),
303 Inline: true,
304 Content: charmImgB64,
305 IgnoreAspectRatio: true,
306 })
307
308 cup := ansi.CursorPosition(imgArea.Min.X+1, imgArea.Min.Y+1)
309 t.MoveTo(imgArea.Min.X, imgArea.Min.Y)
310 t.WriteString(data) //nolint:errcheck
311 t.WriteString(cup) //nolint:errcheck
312 }
313
314 if t.Buffered() > 0 {
315 t.Flush() //nolint:errcheck
316 }
317 }
318
319 // Query image encoding support.
320 t.WriteString(ansi.RequestPrimaryDeviceAttributes) // Query Sixel support.
321 t.WriteString(ansi.RequestNameVersion) // Query terminal version and name.
322 t.WriteString(ansi.WindowOp(ansi.RequestWindowSizeWinOp)) // Request window size.
323 // Query Kitty Graphics support using random id=31.
324 t.WriteString(ansi.KittyGraphics([]byte("AAAA"), "i=31", "s=1", "v=1", "a=q", "t=d", "f=24"))
325
326 ctx, cancel := context.WithCancel(context.Background())
327 defer cancel()
328
329 evch := make(chan uv.Event)
330 go func() {
331 defer close(evch)
332 _ = t.StreamEvents(ctx, evch)
333 }()
334
335 // Listen for input events.
336 for ev := range evch {
337 switch ev := ev.(type) {
338 case uv.WindowPixelSizeEvent:
339 // XXX: This is only emitted with traditional Unix systems. On
340 // Windows, we would need to use [ansi.RequestWindowSizeWinOp] to
341 // get the pixel size.
342 pixSize = ev
343 imgCellW, imgCellH = imgCellSize()
344 imgOffsetX = winSize.Width/2 - imgCellW/2
345 imgOffsetY = winSize.Height/2 - imgCellH/2
346 displayImg()
347 case uv.WindowSizeEvent:
348 winSize = ev
349 imgCellW, imgCellH = imgCellSize()
350 imgOffsetX = winSize.Width/2 - imgCellW/2
351 imgOffsetY = winSize.Height/2 - imgCellH/2
352 t.Erase()
353 log.Printf("image cell size: %d x %d", imgCellW, imgCellH)
354 if err := t.Resize(ev.Width, ev.Height); err != nil {
355 log.Fatalf("failed to resize program: %v", err)
356 }
357
358 displayImg()
359 case uv.KeyPressEvent:
360 switch {
361 case ev.MatchStrings("q", "ctrl+c"):
362 cancel() // This will stop the loop
363 case ev.MatchStrings("up", "k"):
364 imgOffsetY--
365 case ev.MatchStrings("down", "j"):
366 imgOffsetY++
367 case ev.MatchStrings("left", "h"):
368 imgOffsetX--
369 case ev.MatchStrings("right", "l"):
370 imgOffsetX++
371 }
372
373 displayImg()
374 case uv.MouseClickEvent:
375 imgOffsetX = ev.X - (imgCellW / 2)
376 imgOffsetY = ev.Y - (imgCellH / 2)
377
378 displayImg()
379 case uv.PrimaryDeviceAttributesEvent:
380 if slices.Contains(ev, 4) {
381 upgradeEnc(sixelEncoding)
382 displayImg()
383 }
384
385 case uv.TerminalVersionEvent:
386 if strings.Contains(string(ev), "iTerm") || strings.Contains(string(ev), "WezTerm") {
387 upgradeEnc(itermEncoding)
388 displayImg()
389 }
390
391 case uv.WindowOpEvent:
392 // The [ansi.RequestWindowSizeWinOp] request responds with a "4" or
393 // [ansi.ResizeWindowWinOp] first parameter.
394 if ev.Op == ansi.ResizeWindowWinOp && len(ev.Args) >= 2 {
395 pixSize.Height = ev.Args[0]
396 pixSize.Width = ev.Args[1]
397 }
398 case uv.KittyGraphicsEvent:
399 if strings.Contains(termType, "wezterm") ||
400 strings.Contains(termVersion, "WezTerm") ||
401 strings.Contains(termProg, "WezTerm") {
402 // WezTerm doesn't support Kitty Unicode Graphics
403 break
404 }
405 if ev.Options.ID == 31 {
406 upgradeEnc(kittyEncoding)
407 }
408
409 displayImg()
410 }
411 }
412
413 ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
414 defer cancel()
415
416 if err := t.Shutdown(ctx); err != nil {
417 log.Fatalf("failed to shutdown program: %v", err)
418 }
419
420 fmt.Println("image encoding:", imgEnc)
421 }
422
423 func init() {
424 f, err := os.OpenFile("uv_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
425 if err != nil {
426 log.Fatalf("failed to open log file: %v", err)
427 }
428
429 log.SetOutput(f)
430 }