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
|
package main
import (
"bufio"
"flag"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"path/filepath"
"slices"
"strconv"
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"
"roseh.moe/pkg/sixel"
)
var (
x = flag.Int("x", 15, "set image width in columns")
l = flag.Bool("l", false, "print image attributes")
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 {
stat, err := os.Stat(filename)
return err == nil && stat.IsDir()
}
func isImage(filename string) bool {
f, err := os.Open(filename)
if err != nil {
return false
}
defer f.Close()
_, _, err = image.DecodeConfig(f)
return err == nil
}
func imageDimensions(filename string) (width, height int, err error) {
f, err := os.Open(filename)
if err != nil {
return 0, 0, err
}
defer f.Close()
config, _, err := image.DecodeConfig(f)
return config.Width, config.Height, err
}
func load(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, fmt.Errorf("decode %q: %s", filename, err)
}
return img, nil
}
func printImg(w io.Writer, img image.Image) {
switch *m {
case modeBlock:
sixel.PrintXTerm16(w, img)
case modeBlock24:
sixel.PrintBlock(w, img)
case modeSixel:
sixel.Print(w, img, nil)
default:
panic("invalid mode")
}
}
func escapeString(s string) string {
for _, r := range s {
if !strconv.IsGraphic(r) {
return strconv.QuoteToGraphic(s)
}
}
return s
}
func divRound(n, d int) int {
return (n + d/2) / d
}
type pixelAspectRatio struct {
x, y int
}
func layoutRow(imagePaths []string, width, rowWidth, cellX int) []int {
filenameWidths := make([]int, len(imagePaths))
for i, path := range imagePaths {
filenameWidths[i] = cellX * runewidth.StringWidth(escapeString(filepath.Base(path)))
}
var logicalWidth int
for i, filenameWidth := range filenameWidths {
if i > 0 {
logicalWidth += 2 * cellX
}
logicalWidth += max(width, filenameWidth)
}
layout := make([]int, len(imagePaths))
var offset int
for i, filenameWidth := range filenameWidths {
imageWidth := max(width, filenameWidth)
layout[i] = divRound(offset*rowWidth, logicalWidth)
offset += imageWidth + 2*cellX
}
return layout
}
func compositeImageRow(imagePaths []string, layout []int, width, rowWidth, cellX int, aspectRatio pixelAspectRatio) (image.Image, error) {
var maxHeight int
for _, filename := range imagePaths {
imageWidth, imageHeight, err := imageDimensions(filename)
if err != nil {
return nil, err
}
maxHeight = max(maxHeight, divRound(imageHeight*width*aspectRatio.x, imageWidth*aspectRatio.y))
}
bounds := image.Rect(0, 0, rowWidth, maxHeight)
result := image.NewRGBA(bounds)
for i, filename := range imagePaths {
img, err := load(filename)
if err != nil {
return nil, err
}
start := layout[i]
end := rowWidth
if i+1 < len(imagePaths) {
end = layout[i+1]
}
height := divRound(img.Bounds().Dy()*width*aspectRatio.x, img.Bounds().Dx()*aspectRatio.y)
offsetStart := start + (end-start-width)/2
dstBounds := image.Rect(offsetStart, (maxHeight-height)/2, offsetStart+width, (maxHeight-height)/2+height)
draw.BiLinear.Scale(result, dstBounds, img, img.Bounds(), draw.Src, nil)
}
return result, nil
}
func splitRows(imagePaths []string, width, rowWidth int) [][]string {
var rows [][]string
for len(imagePaths) > 0 {
row := imagePaths[:0]
thisRowWidth := 0
for ; len(row) < len(imagePaths); row = row[:len(row)+1] {
nextW := max(width, runewidth.StringWidth(escapeString(filepath.Base(imagePaths[len(row)]))))
if len(row) > 0 {
nextW += 2
}
if thisRowWidth > 0 && thisRowWidth+nextW > rowWidth {
break
}
thisRowWidth += nextW
}
imagePaths = imagePaths[len(row):]
rows = append(rows, row)
}
return rows
}
func thumbnailFiles(w io.Writer, imagePaths []string, width, rowWidth, cellX, cellY int) error {
padding := 2
aspectRatio := pixelAspectRatio{1, 1}
switch *m {
case modeBlock:
aspectRatio = pixelAspectRatio{cellX, cellY}
cellX = 1
case modeBlock24:
aspectRatio = pixelAspectRatio{2 * cellX, cellY}
cellX = 1
case modeSixel:
padding *= cellX
}
rows := splitRows(imagePaths, width, rowWidth)
layouts := make([][]int, len(rows))
for i, row := range rows {
layouts[i] = layoutRow(row, width*cellX, rowWidth*cellX, cellX)
}
rowImages := make([]chan image.Image, len(rows))
for i := range rowImages {
rowImages[i] = make(chan image.Image, 1)
}
errCh := make(chan error, 1)
go func() {
sem := make(chan struct{}, 20)
for i, row := range rows {
sem <- struct{}{}
go func() {
defer func() { <-sem }()
img, err := compositeImageRow(row, layouts[i], width*cellX, rowWidth*cellX, cellX, aspectRatio)
if err != nil {
select {
case errCh <- err:
default:
}
return
}
rowImages[i] <- img
}()
}
}()
for i, row := range rows {
thisRowWidth := 0
for j, filename := range row {
if j > 0 {
thisRowWidth += 2
}
thisRowWidth += max(width, runewidth.StringWidth(escapeString(filepath.Base(filename))))
}
var rowImage image.Image
select {
case err := <-errCh:
return err
case rowImage = <-rowImages[i]:
}
printImg(w, rowImage)
fmt.Fprintln(w)
realOffset := 0
for j, filename := range row {
start := divRound(layouts[i][j], cellX)
end := rowWidth
if j+1 < len(row) {
end = divRound(layouts[i][j+1], cellX)
}
fmt.Fprintf(w, "%*s", start-realOffset, "")
realOffset = start
fileNameWidth := runewidth.StringWidth(escapeString(filepath.Base(filename)))
padding := max((end-start-fileNameWidth)/2, 0)
fmt.Fprintf(w, "%*s%s", padding, "", escapeString(filepath.Base(filename)))
realOffset += padding + fileNameWidth
}
fmt.Fprintln(w)
}
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, rowWidth, cellX, cellY int) error {
files, err := readDir(dir)
if err != nil {
return err
}
files = slices.DeleteFunc(files, func(filename string) bool { return !isImage(filename) })
return thumbnailFiles(w, files, width, rowWidth, cellX, cellY)
}
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)
var files, dirs []string
if len(args) == 0 {
dirs = []string{"."}
} else {
for _, arg := range args {
if isDir(arg) {
dirs = append(dirs, arg)
} else {
files = append(files, arg)
}
}
}
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
if err := thumbnailFiles(w, files, cols, termCols, 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, termCols, cellX, cellY); err != nil {
return err
}
}
return nil
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: thumbnailer [OPTION]... [FILE]...\n")
flag.PrintDefaults()
}
flag.Parse()
if err := thumbnailer(flag.Args()); err != nil {
fmt.Fprintf(os.Stderr, "Failed: %s\n", err)
os.Exit(1)
}
}
|