Debian Codegraph @

image.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package vaxis
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "fmt"
7 "image"
8 "image/color"
9 "image/png"
10 "io"
11
12 "git.sr.ht/~rockorager/vaxis/log"
13 "git.sr.ht/~rockorager/vaxis/octreequant"
14
15 "github.com/mattn/go-sixel"
16 "golang.org/x/image/draw"
17 )
18
19 // Alpha value that we consider to be transparent enough to use default
20 // background color
21 const transparentEnough = 50
22
23 const (
24 noGraphics = iota
25 fullBlock
26 halfBlock
27 sixelGraphics
28 kitty
29 )
30
31 // Image is a static image on the screen
32 type Image interface {
33 // Draw draws the [Image] to the [Window]. The image will not be drawn
34 // if it is larger than the window
35 Draw(Window)
36 // Destroy removes an image from memory. Call when done with this image
37 Destroy()
38 // Resizes the image to fit within the provided area. The image will not
39 // be upscaled, nor will it's aspect ratio be changed
40 Resize(w int, h int)
41 // CellSize is the current cell size of the encoded image
42 CellSize() (w int, h int)
43 }
44
45 // NewImage creates a new image using the highest quality renderer the terminal
46 // is capable of
47 func (vx *Vaxis) NewImage(img image.Image) (Image, error) {
48 switch vx.graphicsProtocol {
49 case fullBlock:
50 return vx.NewFullBlockImage(img), nil
51 case halfBlock:
52 return vx.NewHalfBlockImage(img), nil
53 case sixelGraphics:
54 return vx.NewSixel(img), nil
55 case kitty:
56 return vx.NewKittyGraphic(img), nil
57 default:
58 return nil, fmt.Errorf("no supported image protocol")
59 }
60 }
61
62 type KittyImage struct {
63 vx *Vaxis
64 img image.Image
65 id uint64
66 w int
67 h int
68 uploaded int32
69 encoding int32
70 buf *bytes.Buffer
71 }
72
73 func (vx *Vaxis) NewKittyGraphic(img image.Image) *KittyImage {
74 log.Trace("new kitty image")
75 k := &KittyImage{
76 vx: vx,
77 img: img,
78 id: vx.nextGraphicID(),
79 buf: bytes.NewBuffer(nil),
80 }
81 return k
82 }
83
84 // Draw draws the [Image] to the [Window].
85 func (k *KittyImage) Draw(win Window) {
86 if atomicLoad(&k.encoding) {
87 return
88 }
89 col, row := win.Origin()
90 log.Trace("placing kitty image at cell %d,%d", col, row)
91 // the pid is a 32 bit number where the high 16bits are the width and
92 // the low 16 are the height
93 pid := uint(col)<<16 | uint(row)
94 writeFunc := func(w io.Writer) {
95 if !atomicLoad(&k.uploaded) {
96 w.Write(k.buf.Bytes())
97 atomicStore(&k.uploaded, true)
98 k.buf.Reset()
99 }
100 fmt.Fprintf(w, "\x1B_Ga=p,i=%d,p=%d,C=1\x1B\\", k.id, pid)
101 }
102 deleteFunc := func(w io.Writer) {
103 fmt.Fprintf(w, "\x1B_Ga=d,d=i,i=%d,p=%d\x1B\\", k.id, pid)
104 }
105 placement := &placement{
106 col: col,
107 row: row,
108 id: k.id,
109 w: k.w,
110 h: k.h,
111 writeTo: writeFunc,
112 deleteFn: deleteFunc,
113 }
114 k.vx.graphicsNext = append(k.vx.graphicsNext, placement)
115 }
116
117 // Destroy deletes this image from memory
118 func (k *KittyImage) Destroy() {
119 fmt.Fprintf(k.vx.console, "\x1B_Ga=d,d=I,i=%d\x1B\\", k.id)
120 }
121
122 func (k *KittyImage) CellSize() (w int, h int) {
123 return k.w, k.h
124 }
125
126 // Resizes the image to fit within the wxh area. The image will not be
127 // upscaled, nor will it's aspect ratio be changed. Resizing will be done in a
128 // separate goroutine. A [Redraw] event will be posted when complete
129 func (k *KittyImage) Resize(w int, h int) {
130 // Resize the image
131 cellPixW := k.vx.winSize.XPixel / k.vx.winSize.Cols
132 cellPixH := k.vx.winSize.YPixel / k.vx.winSize.Rows
133 img := resizeImage(k.img, w, h, cellPixW, cellPixH)
134
135 // Reupload the image
136 max := img.Bounds().Max
137 k.w = max.X / cellPixW
138 if max.X%cellPixW != 0 {
139 k.w += 1
140 }
141 k.h = max.Y / cellPixH
142 if max.Y%cellPixH != 0 {
143 k.h += 1
144 }
145
146 atomicStore(&k.encoding, true)
147 go func() {
148 defer atomicStore(&k.encoding, false)
149 // Encode it to base64
150 buf := bytes.NewBuffer(nil)
151 wc := base64.NewEncoder(base64.StdEncoding, buf)
152 err := png.Encode(wc, img)
153 if err != nil {
154 log.Error("couldn't encode kitty image: %v", err)
155 return
156 }
157 wc.Close()
158 b := make([]byte, 4096)
159 atomicStore(&k.uploaded, false)
160 for buf.Len() > 0 {
161 n, err := buf.Read(b)
162 if err == io.EOF {
163 break
164 }
165 m := 1
166 if buf.Len() == 0 {
167 m = 0
168 }
169 fmt.Fprintf(k.buf, "\x1B_Gf=100,i=%d,m=%d;%s\x1B\\", k.id, m, string(b[:n]))
170 }
171 k.vx.PostEventBlocking(Redraw{})
172 }()
173 }
174
175 type Sixel struct {
176 vx *Vaxis
177 img image.Image
178 buf *bytes.Buffer
179 id uint64
180 w int
181 h int
182 encoding int32
183 }
184
185 // Draw draws the [Image] to the [Window]. The image will not be drawn
186 // if it is larger than the window
187 func (s *Sixel) Draw(win Window) {
188 if s.buf.Len() == 0 {
189 return
190 }
191 if atomicLoad(&s.encoding) {
192 return
193 }
194 w, h := win.Size()
195 if s.w > w || s.h > h {
196 return
197 }
198 for y := 0; y < s.h; y += 1 {
199 for x := 0; x < s.w; x += 1 {
200 win.SetCell(x, y, Cell{
201 sixel: true,
202 })
203 }
204 }
205 writeFunc := func(w io.Writer) {
206 // Also need to set sixel value in here for Refresh cycles
207 for y := 0; y < s.h; y += 1 {
208 for x := 0; x < s.w; x += 1 {
209 win.SetCell(x, y, Cell{
210 sixel: true,
211 })
212 }
213 }
214 w.Write(s.buf.Bytes())
215 }
216 deleteFunc := func(_ io.Writer) {
217 // no-op. we expect users to Clear the screen or just print
218 // cells, which will have the effect of clearing the sixel
219 }
220 col, row := win.Origin()
221 log.Trace("placing sixel image at cell %d,%d", col, row)
222 placement := &placement{
223 col: col,
224 row: row,
225 writeTo: writeFunc,
226 deleteFn: deleteFunc,
227 id: s.id,
228 w: s.w,
229 h: s.h,
230 }
231 s.vx.graphicsNext = append(s.vx.graphicsNext, placement)
232 }
233
234 // Destroy removes an image from memory. Call when done with this image
235 func (s *Sixel) Destroy() {
236 s.buf.Reset()
237 }
238
239 // Resizes the image to fit within the wxh area. The image will not be
240 // upscaled, nor will it's aspect ratio be changed. Resize will be done in a
241 // separate gorotuine. A Redraw event will be posted when complete
242 func (s *Sixel) Resize(w int, h int) {
243 atomicStore(&s.encoding, true)
244 go func() {
245 defer atomicStore(&s.encoding, false)
246 // Resize the image
247 cellPixW := s.vx.winSize.XPixel / s.vx.winSize.Cols
248 cellPixH := s.vx.winSize.YPixel / s.vx.winSize.Rows
249 img := resizeImage(s.img, w, h, cellPixW, cellPixH)
250 max := img.Bounds().Max
251 s.w = max.X / cellPixW
252 if max.X%cellPixW != 0 {
253 s.w += 1
254 }
255 s.h = max.Y / cellPixH
256 if max.Y%cellPixH != 0 {
257 s.h += 1
258 }
259 // Re-encode the image
260 s.buf.Reset()
261 var paletted image.Image
262 if p, ok := img.(*image.Paletted); ok && len(p.Palette) < 255 {
263 // fast-path for paletted images: pass through to sixel
264 paletted = p
265 } else {
266 paletted = octreequant.Paletted(img, 254)
267 }
268 err := sixel.NewEncoder(s.buf).Encode(paletted)
269 if err != nil {
270 log.Error("couldn't encode sixel: %v", err)
271 return
272 }
273
274 // Foot requires that we set the P2 parameter = 1 in order to
275 // enable transparency. This doesn't seem to affect other sixel
276 // based terminals
277 b := s.buf.Bytes()
278 b[4] = 0x31
279
280 s.vx.PostEventBlocking(Redraw{})
281 }()
282 }
283
284 // CellSize is the current cell size of the encoded image
285 func (s *Sixel) CellSize() (w int, h int) {
286 if atomicLoad(&s.encoding) {
287 return
288 }
289 return s.w, s.h
290 }
291
292 func (vx *Vaxis) NewSixel(img image.Image) *Sixel {
293 log.Trace("new sixel image")
294 s := &Sixel{
295 vx: vx,
296 img: img,
297 id: vx.nextGraphicID(),
298 buf: bytes.NewBuffer(nil),
299 }
300 return s
301 }
302
303 // placement is an image placement. If two placements are identical, the
304 // image will not be redrawn
305 type placement struct {
306 writeTo func(w io.Writer)
307 deleteFn func(w io.Writer)
308 col int
309 row int
310 id uint64
311 w int
312 h int
313 }
314
315 // samePlacement compares two placements for equality. Two placements are
316 // considered equal if it is the same image, with the same size, at the same
317 // location
318 func samePlacement(p1, p2 *placement) bool {
319 if p1.id != p2.id {
320 return false
321 }
322 if p1.col != p2.col {
323 return false
324 }
325 if p1.row != p2.row {
326 return false
327 }
328 if p1.w != p2.w {
329 return false
330 }
331 if p1.h != p2.h {
332 return false
333 }
334 return true
335 }
336
337 // Resizes an image to fit within the provided rectangle (as cells). If the
338 // image already fits, it won't be resized
339 func resizeImage(img image.Image, w int, h int, cellPixW int, cellPixH int) image.Image {
340 wPix := img.Bounds().Max.X
341 hPix := img.Bounds().Max.Y
342 // Looks complicated but we're just calculating the size of the
343 // image in cells, and rounding up since we will always take
344 // over any cell we bleed into.
345 columns := wPix / cellPixW
346 if wPix%cellPixW != 0 {
347 columns += 1
348 }
349 lines := hPix / cellPixH
350 if hPix%cellPixH != 0 {
351 lines += 1
352 }
353 log.Debug("resizing image from (%d x %d) to (%d x %d)", columns, lines, w, h)
354 if columns <= w && lines <= h {
355 return img
356 }
357 // calculate scale factors
358 sfX := float64(w) / float64(columns)
359 sfY := float64(h) / float64(lines)
360 newPixelWidth := wPix
361 newPixelHeight := hPix
362 switch {
363 case sfX == sfY:
364 // no-op
365 case sfX < sfY:
366 // Width is farther off, so set our new width to w and scale h
367 // appropriately
368 newPixelWidth = int(sfX * float64(wPix))
369 newPixelHeight = int(sfX * float64(hPix))
370 case sfX > sfY:
371 newPixelWidth = int(sfY * float64(wPix))
372 newPixelHeight = int(sfY * float64(hPix))
373 }
374 dst := image.NewRGBA(image.Rect(0, 0, newPixelWidth, newPixelHeight))
375 draw.NearestNeighbor.Scale(dst, dst.Rect, img, img.Bounds(), draw.Over, nil)
376 return dst
377 }
378
379 // FullBlockImage is an image composed of 0x20 characters. This is the most
380 // primitive graphics protocol
381 type FullBlockImage struct {
382 vx *Vaxis
383 img image.Image
384 cells []Color
385 width int
386 height int
387 }
388
389 func (vx *Vaxis) NewFullBlockImage(img image.Image) *FullBlockImage {
390 log.Trace("new full block image")
391 fb := &FullBlockImage{
392 vx: vx,
393 img: img,
394 }
395 return fb
396 }
397
398 func (fb *FullBlockImage) Draw(win Window) {
399 col, row := win.Origin()
400 log.Trace("placing full block image at cell %d,%d", col, row)
401 for i, cell := range fb.cells {
402 y := i / fb.width
403 x := i - (y * fb.width)
404 win.SetCell(x, y, Cell{
405 Character: Character{
406 Grapheme: " ",
407 Width: 1,
408 },
409 Style: Style{
410 Background: cell,
411 },
412 })
413 }
414 }
415
416 // Resize resizes and re-encodes an image
417 func (fb *FullBlockImage) Resize(w int, h int) {
418 // FullBlockImage gets resized with a cell geometry of 1x2 pixels. We
419 // will then average the vertical two pixels to make a single color ' '
420 // character
421 img := resizeImage(fb.img, w, h, 1, 2)
422
423 // Store the actual width and height of the resized image
424 fb.width = img.Bounds().Max.X
425 h = img.Bounds().Max.Y
426 if h%2 != 0 {
427 h += 1
428 }
429 fb.height = h / 2
430 // The image will be made into an array of cells, each cell will capture
431 // 1x2 pixels
432 fb.cells = make([]Color, (fb.height * fb.width))
433 for i := range fb.cells {
434 y := i / fb.width
435 x := i - (y * fb.width)
436 y *= 2
437
438 top := img.At(x, y)
439 bot := img.At(x, y+1)
440 r, g, b, a := averageColor(top, bot)
441 switch {
442 // TODO: What is the right value for alpha that we should set
443 // the background color = 0??
444 case a < 50:
445 fb.cells[i] = 0
446 default:
447 fb.cells[i] = RGBColor(r, g, b)
448 }
449 }
450 }
451
452 func (fb *FullBlockImage) Destroy() {
453 fb.cells = []Color{}
454 }
455
456 func (fb *FullBlockImage) CellSize() (int, int) {
457 return fb.width, fb.height
458 }
459
460 func toRGB(c color.Color) (uint8, uint8, uint8, uint8) {
461 pr, pg, pb, pa := c.RGBA()
462 var r, g, b, a uint8
463 switch pa {
464 case 0:
465 r = uint8(pr)
466 g = uint8(pg)
467 b = uint8(pb)
468 default:
469 r = uint8((pr * 255) / pa)
470 g = uint8((pg * 255) / pa)
471 b = uint8((pb * 255) / pa)
472 a = uint8(pa >> 8)
473 }
474 return r, g, b, a
475 }
476
477 // averageColor computes the average color from all inputs and returns it's rgb
478 // value
479 func averageColor(c color.Color, colors ...color.Color) (uint8, uint8, uint8, uint8) {
480 var r, g, b, a int
481 colors = append(colors, c)
482 for _, col := range colors {
483 rA, gA, bA, aA := toRGB(col)
484 r += int(rA)
485 g += int(gA)
486 b += int(bA)
487 a += int(aA)
488 }
489 n := len(colors)
490 return uint8(r / n), uint8(g / n), uint8(b / n), uint8(a / n)
491 }
492
493 // HalfBlockImage is an image composed of half block characters.
494 type HalfBlockImage struct {
495 vx *Vaxis
496 img image.Image
497 cells []Cell
498 width int
499 height int
500 }
501
502 func (vx *Vaxis) NewHalfBlockImage(img image.Image) *HalfBlockImage {
503 log.Trace("new half block image")
504 hb := &HalfBlockImage{
505 vx: vx,
506 img: img,
507 }
508 return hb
509 }
510
511 func (hb *HalfBlockImage) Draw(win Window) {
512 col, row := win.Origin()
513 log.Trace("placing half block image at cell %d,%d", col, row)
514 for i, cell := range hb.cells {
515 y := i / hb.width
516 x := i - (y * hb.width)
517 win.SetCell(x, y, cell)
518 }
519 }
520
521 // Resize resizes and re-encodes an image
522 func (hb *HalfBlockImage) Resize(w int, h int) {
523 // HalfBlockImage gets resized with a cell geometry of 1x2 pixels.
524 img := resizeImage(hb.img, w, h, 1, 2)
525
526 // Store the actual width and height of the resized image
527 hb.width = img.Bounds().Max.X
528 h = img.Bounds().Max.Y
529 if h%2 != 0 {
530 h += 1
531 }
532 hb.height = h / 2
533 // The image will be made into an array of cells, each cell will capture
534 // 1x2 pixels
535 hb.cells = make([]Cell, (hb.height * hb.width))
536 for i := range hb.cells {
537 y := i / hb.width
538 x := i - (y * hb.width)
539 y *= 2
540
541 tr, tg, tb, ta := toRGB(img.At(x, y))
542 br, bg, bb, ba := toRGB(img.At(x, y+1))
543 // Figure out if one of the alpha channels is transparent
544 // "enough"
545 switch {
546 case ta < transparentEnough && ba < transparentEnough:
547 // Use a transparent space
548 hb.cells[i] = Cell{
549 Character: Character{
550 Grapheme: " ",
551 Width: 1,
552 },
553 }
554 case ta < transparentEnough:
555 // Top is transparent. Use a lower block
556 hb.cells[i] = Cell{
557 Character: Character{
558 Grapheme: "▄",
559 Width: 1,
560 },
561 Style: Style{
562 Foreground: RGBColor(br, bg, bb),
563 },
564 }
565 case ba < transparentEnough:
566 // Bottom is transparent. Use an upper block
567 hb.cells[i] = Cell{
568 Character: Character{
569 Grapheme: "▀",
570 Width: 1,
571 },
572 Style: Style{
573 Foreground: RGBColor(tr, tg, tb),
574 },
575 }
576 default:
577 // Neither is transparent. Use an upper block
578 hb.cells[i] = Cell{
579 Character: Character{
580 Grapheme: "▀",
581 Width: 1,
582 },
583 Style: Style{
584 Foreground: RGBColor(tr, tg, tb),
585 Background: RGBColor(br, bg, bb),
586 },
587 }
588 }
589 }
590 }
591
592 func (hb *HalfBlockImage) Destroy() {
593 hb.cells = []Cell{}
594 }
595
596 func (hb *HalfBlockImage) CellSize() (int, int) {
597 return hb.width, hb.height
598 }