package main import ( "bufio" "flag" "fmt" "image" _ "image/gif" _ "image/jpeg" _ "image/png" "io" "os" "path/filepath" "slices" 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") 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") } } type pixelAspectRatio struct { x, y int } func compositeImageRow(imagePaths []string, width, rowWidth, cellX int, aspectRatio pixelAspectRatio) (image.Image, error) { var logicalWidth, maxHeight int for i, filename := range imagePaths { if i > 0 { logicalWidth += 2 * cellX } fileNameWidth := cellX * runewidth.StringWidth(filepath.Base(filename)) logicalWidth += max(width, fileNameWidth) imageWidth, imageHeight, err := imageDimensions(filename) if err != nil { return nil, err } maxHeight = max(maxHeight, imageHeight*width/(imageWidth*aspectRatio.y/aspectRatio.x)) } bounds := image.Rect(0, 0, rowWidth, maxHeight) result := image.NewRGBA(bounds) offset := 0 for _, filename := range imagePaths { img, err := load(filename) if err != nil { return nil, err } height := img.Bounds().Dy() * width / (img.Bounds().Dx() * aspectRatio.y / aspectRatio.x) imageWidth := max(width, cellX*runewidth.StringWidth(filepath.Base(filename))) start := (offset*rowWidth + logicalWidth - 1) / logicalWidth end := ((offset+imageWidth)*rowWidth + logicalWidth - 1) / logicalWidth 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) offset += imageWidth + 2*cellX } 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(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) 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, 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(filepath.Base(filename))) } var rowImage image.Image select { case err := <-errCh: return err case rowImage = <-rowImages[i]: } printImg(w, rowImage) fmt.Fprintln(w) offset := 0 realOffset := 0 for i, filename := range row { if i > 0 { offset += 2 } start := (offset*rowWidth + thisRowWidth - 1) / thisRowWidth fmt.Fprintf(w, "%*s", start-realOffset, "") realOffset = start fileNameWidth := runewidth.StringWidth(filepath.Base(filename)) offset += max(width, fileNameWidth) end := (offset*rowWidth + thisRowWidth - 1) / thisRowWidth padding := (end - start - fileNameWidth) / 2 fmt.Fprintf(w, "%*s%s", padding, "", 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) } }