aboutsummaryrefslogtreecommitdiffstats
path: root/thumbnailer.go
blob: 6c69fc1c03d3fa25ce5c15cceee07157f545ce9c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"image"
	"image/color"
	"image/color/palette"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"

	runewidth "github.com/mattn/go-runewidth"
	_ "golang.org/x/image/bmp"
	"golang.org/x/image/draw"
	_ "golang.org/x/image/tiff"
	_ "golang.org/x/image/webp"
	"golang.org/x/sys/unix"
)

var (
	x = flag.Int("x", 15, "set image width in columns")
	m = flagPrintMode(flag.CommandLine, "m", modeSixel, "one of 'block', 'block24', or 'sixel'")
)

type printMode int

const (
	modeInvalid printMode = iota
	modeBlock
	modeBlock24
	modeSixel
)

type printModeValue printMode

func (m *printModeValue) String() string {
	switch printMode(*m) {
	case modeBlock:
		return "block"
	case modeBlock24:
		return "block24"
	case modeSixel:
		return "sixel"
	default:
		return "invalid"
	}
}

func (m *printModeValue) Set(s string) error {
	var mode printMode
	switch s {
	case "block":
		mode = modeBlock
	case "block24":
		mode = modeBlock24
	case "sixel":
		mode = modeSixel
	default:
		return fmt.Errorf("bad mode type %q, should be one of 'block', 'block24', or 'sixel'", s)
	}
	*m = printModeValue(mode)
	return nil
}

func flagPrintMode(fs *flag.FlagSet, name string, value printMode, usage string) *printMode {
	fs.Var((*printModeValue)(&value), name, usage)
	return &value
}

func isDir(filename string) (bool, error) {
	stat, err := os.Stat(filename)
	if err != nil {
		return false, err
	}
	return stat.IsDir(), nil
}

func isLink(filename string) (bool, error) {
	stat, err := os.Lstat(filename)
	if err != nil {
		return false, err
	}
	return stat.Mode().Type() == fs.ModeSymlink, nil
}

var errNotAnImage = errors.New("not an image")

type notAnImageError struct {
	error
}

func (e *notAnImageError) Is(err error) bool {
	return err == errNotAnImage
}

func load(filename string) (image.Image, error) {
	file := os.Stdin
	if filename != "-" {
		var err error
		file, err = os.Open(filename)
		if err != nil {
			if errors.Is(err, fs.ErrNotExist) {
				if isLink, _ := isLink(filename); isLink {
					return nil, &notAnImageError{err}
				}
			}
			return nil, err
		}
		defer file.Close()
	}

	img, _, err := image.Decode(file)
	if err != nil {
		return nil, &notAnImageError{fmt.Errorf("decode %q: %s", filename, err)}
	}

	return img, nil
}

type xtermColor int8

func (c xtermColor) RGBA() (r, g, b, a uint32) {
	var col color.RGBA
	switch c {
	case 0:
		col = color.RGBA{R: 0x00, G: 0x00, B: 0x00, A: 0xff}
	case 1:
		col = color.RGBA{R: 0xcd, G: 0x00, B: 0x00, A: 0xff}
	case 2:
		col = color.RGBA{R: 0x00, G: 0xcd, B: 0x00, A: 0xff}
	case 3:
		col = color.RGBA{R: 0xcd, G: 0xcd, B: 0x00, A: 0xff}
	case 4:
		col = color.RGBA{R: 0x00, G: 0x00, B: 0xee, A: 0xff}
	case 5:
		col = color.RGBA{R: 0xcd, G: 0x00, B: 0xcd, A: 0xff}
	case 6:
		col = color.RGBA{R: 0x00, G: 0xcd, B: 0xcd, A: 0xff}
	case 7:
		col = color.RGBA{R: 0xe5, G: 0xe5, B: 0xe5, A: 0xff}
	case 60:
		col = color.RGBA{R: 0x7f, G: 0x7f, B: 0x7f, A: 0xff}
	case 61:
		col = color.RGBA{R: 0xff, G: 0x00, B: 0x00, A: 0xff}
	case 62:
		col = color.RGBA{R: 0x00, G: 0xff, B: 0x00, A: 0xff}
	case 63:
		col = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff}
	case 64:
		col = color.RGBA{R: 0x5c, G: 0x5c, B: 0xff, A: 0xff}
	case 65:
		col = color.RGBA{R: 0xff, G: 0x00, B: 0xff, A: 0xff}
	case 66:
		col = color.RGBA{R: 0x00, G: 0xff, B: 0xff, A: 0xff}
	case 67:
		col = color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}
	default:
		panic("not an xterm color")
	}
	return col.RGBA()
}

var xtermPalette = color.Palette{xtermColor(0), xtermColor(1), xtermColor(2), xtermColor(3), xtermColor(4), xtermColor(5), xtermColor(6), xtermColor(7), xtermColor(60), xtermColor(61), xtermColor(62), xtermColor(63), xtermColor(64), xtermColor(65), xtermColor(66), xtermColor(67)}

func printImgXterm(w io.Writer, img image.Image) {
	for y := 0; y < img.Bounds().Dy(); y += 2 {
		if y > 0 {
			fmt.Fprintln(w)
		}
		for x := 0; x < img.Bounds().Dx(); x++ {
			hi := img.At(x, y)
			if hi == color.Transparent {
				if x > 0 && img.At(x-1, y) != color.Transparent {
					fmt.Fprint(w, "\033[49m")
				}
				fmt.Fprint(w, " ")
			} else {
				lo := 9
				if y+1 < img.Bounds().Dy() && img.At(x, y+1) != color.Transparent {
					lo = int(img.At(x, y+1).(xtermColor))
				}
				fmt.Fprintf(w, "\033[%dm\033[%dm▀", 30+hi.(xtermColor), 40+lo)
			}
		}
		fmt.Fprint(w, "\033[39m\033[49m")
	}
}

func printImgBlock24(w io.Writer, img image.Image) {
	for y := 0; y < img.Bounds().Dy(); y += 2 {
		if y > 0 {
			fmt.Fprintln(w)
		}
		for x := 0; x < img.Bounds().Dx(); x++ {
			hi := img.At(x, y)
			if hi == color.Transparent {
				if x > 0 && img.At(x-1, y) != color.Transparent {
					fmt.Fprint(w, "\033[49m")
				}
				fmt.Fprint(w, " ")
			} else {
				if y+1 < img.Bounds().Dy() && img.At(x, y+1) != color.Transparent {
					r, g, b, _ := img.At(x, y+1).RGBA()
					fmt.Fprintf(w, "\033[48;2;%d;%d;%dm", r>>8, g>>8, b>>8)
				} else {
					fmt.Fprint(w, "\033[49m")
				}
				r, g, b, _ := hi.RGBA()
				fmt.Fprintf(w, "\033[38;2;%d;%d;%dm▀", r>>8, g>>8, b>>8)
			}
		}
		fmt.Fprint(w, "\033[39m\033[49m")
	}
}

func scale100(c uint32) int {
	return int(c) * 100 / 0xffff
}

func printImgSixel(w io.Writer, img image.PalettedImage) {
	fmt.Fprint(w, "\033P7;1q")
	for i, c := range img.ColorModel().(color.Palette)[1:] {
		r, g, b, _ := c.RGBA()
		fmt.Fprintf(w, "#%d;2;%d;%d;%d", i, scale100(r), scale100(g), scale100(b))
	}
	for y := 0; y < img.Bounds().Dy(); y++ {
		if y > 0 {
			if y%6 == 0 {
				fmt.Fprint(w, "-")
			} else {
				fmt.Fprint(w, "$")
			}
		}
		for x := 0; x < img.Bounds().Dx(); x++ {
			if img.At(x, y) == color.Transparent {
				fmt.Fprint(w, "?")
			} else {
				char := '?' + 1<<(y%6)
				fmt.Fprintf(w, "#%d%c", img.ColorIndexAt(x, y)-1, char)
			}
		}
	}
	fmt.Fprint(w, "\033\\")
}

func printImg(w io.Writer, img image.Image) {
	switch *m {
	case modeBlock:
		printImgXterm(w, img)
	case modeBlock24:
		printImgBlock24(w, img)
	case modeSixel:
		printImgSixel(w, img.(image.PalettedImage))
	default:
		panic("invalid mode")
	}
}

type pixelAspectRatio struct {
	x, y int
}

func compositeImageRow(images []image.Image, width, padding int, aspectRatio pixelAspectRatio, palette color.Palette) image.Image {
	resultWidth := width*len(images) + padding*(len(images)-1)
	maxHeight := 0
	for _, img := range images {
		maxHeight = max(maxHeight, img.Bounds().Dy()*width/(img.Bounds().Dx()*aspectRatio.y/aspectRatio.x))
	}
	bounds := image.Rect(0, 0, resultWidth, maxHeight)
	var result draw.Image
	if len(palette) > 0 {
		result = image.NewPaletted(bounds, append([]color.Color{color.Transparent}, palette...))
	} else {
		result = image.NewRGBA(bounds)
	}
	offset := 0
	for _, img := range images {
		height := img.Bounds().Dy() * width / (img.Bounds().Dx() * aspectRatio.y / aspectRatio.x)
		dstBounds := image.Rect(offset, (maxHeight-height)/2, offset+width, (maxHeight-height)/2+height)
		if len(palette) > 0 {
			tmp := image.NewRGBA(image.Rect(0, 0, width, height))
			draw.BiLinear.Scale(tmp, tmp.Bounds(), img, img.Bounds(), draw.Src, nil)
			draw.FloydSteinberg.Draw(result, dstBounds, tmp, image.Point{})
		} else {
			draw.BiLinear.Scale(result, dstBounds, img, img.Bounds(), draw.Src, nil)
		}
		offset += width + padding
	}
	return result
}

type img struct {
	i        image.Image
	filename string
}

func compositeImages(w io.Writer, images []img, width, imagesPerRow, cellX, cellY int) {
	imageWidth := width
	padding := 1
	var colorPalette color.Palette
	aspectRatio := pixelAspectRatio{1, 1}
	switch *m {
	case modeBlock:
		colorPalette = xtermPalette
		aspectRatio = pixelAspectRatio{2 * cellX, cellY}
	case modeBlock24:
		aspectRatio = pixelAspectRatio{2 * cellX, cellY}
	case modeSixel:
		imageWidth = width * cellX
		padding = cellX
		colorPalette = palette.WebSafe
	}
	for row := range slices.Chunk(images, imagesPerRow) {
		images := make([]image.Image, len(row))
		for i, img := range row {
			images[i] = img.i
		}
		rowImage := compositeImageRow(images, imageWidth, padding, aspectRatio, colorPalette)
		printImg(w, rowImage)
		names := make([][]string, len(row))
		maxLen := 0
		for i, img := range row {
			names[i] = strings.Split(runewidth.Wrap(img.filename, width), "\n")
			maxLen = max(maxLen, len(names[i]))
		}
		for i := 0; i < maxLen; i++ {
			fmt.Fprintln(w)
			for imgIdx, name := range names {
				if imgIdx > 0 {
					fmt.Fprint(w, " ")
				}
				if i < len(name) {
					fmt.Fprintf(w, "%s", runewidth.FillRight(name[i], width))
				} else {
					fmt.Fprintf(w, "%*s", width, "")
				}
			}
		}
		fmt.Fprintln(w)
	}
}

func thumbnailFiles(w io.Writer, args []string, width, imagesPerRow, cellX, cellY int) error {
	images := make([]img, len(args))
	for i, arg := range args {
		image, err := load(arg)
		if err != nil {
			return err
		}
		images[i] = img{image, filepath.Base(arg)}
	}
	compositeImages(w, images, width, imagesPerRow, cellX, cellY)
	return nil
}

func readDir(d string) ([]string, error) {
	files, err := os.ReadDir(d)
	if err != nil {
		return nil, err
	}
	filenames := make([]string, len(files))
	for i, f := range files {
		filenames[i] = filepath.Join(d, f.Name())
	}
	return filenames, nil
}

func thumbnailDir(w io.Writer, dir string, width, imagesPerRow, cellX, cellY int) error {
	files, err := readDir(dir)
	if err != nil {
		return err
	}
	var images []img
	for _, file := range files {
		image, err := load(file)
		if err != nil {
			if errors.Is(err, errNotAnImage) {
				continue
			}
			return err
		}
		images = append(images, img{image, filepath.Base(file)})
	}
	compositeImages(w, images, width, imagesPerRow, cellX, cellY)
	return nil
}

func thumbnailer(args []string) error {
	cols := *x
	if *x <= 0 {
		return fmt.Errorf("-x must be greater than 0")
	}
	ws, err := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
	if err != nil {
		return fmt.Errorf("terminal size: %s", err)
	}
	termCols := int(ws.Col)
	cellX, cellY := int(ws.Xpixel)/int(ws.Col), int(ws.Ypixel)/int(ws.Row)

	cols = min(cols, termCols)
	imagesPerRow := (termCols + 1) / (cols + 1)

	var files, dirs []string
	if len(args) == 0 {
		dirs = []string{"."}
	} else {
		for _, arg := range args {
			isDir, err := isDir(arg)
			if err != nil {
				return err
			}
			if isDir {
				dirs = append(dirs, arg)
			} else {
				files = append(files, arg)
			}
		}
	}
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	if err := thumbnailFiles(w, files, cols, imagesPerRow, cellX, cellY); err != nil {
		return err
	}
	if len(files) > 0 && len(dirs) > 0 {
		fmt.Fprintln(w)
	}
	for i, d := range dirs {
		if i > 0 {
			fmt.Fprintln(w)
		}
		if len(dirs) > 1 {
			fmt.Fprintf(w, "%s:\n", d)
		}
		if err := thumbnailDir(w, d, cols, imagesPerRow, cellX, cellY); err != nil {
			return err
		}
	}

	return nil
}

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: thumbnailer [FILE]...\n")
	}
	flag.Parse()

	if err := thumbnailer(flag.Args()); err != nil {
		fmt.Fprintf(os.Stderr, "Failed: %s\n", err)
		os.Exit(1)
	}
}