vcom/internal/preview/build.go
vrubelroman 5d36b76bbe feat(preview): pure Build over vfs with limits, tools timeout and fast highlighting (5B)
Build(ctx, req) never opens FIFOs, sockets or devices (Kind=Special;
U-P1-10), reads at most MaxBytes, keeps at most DirLimit directory entries
and MaxLines text lines, and honours ctx in reads, tools and highlighting.
pdftotext/pdfinfo/ffprobe run in their own process group with a 3 s timeout
and are killed with their children. A chroma formatter writes foreground
SGR only (no background, no regexp post-processing); the first
HighlightLines (400) lines are highlighted, so 64 KiB of Go takes ~20 ms
(was 190). Remote images are downloaded to an LRU cache only up to
max_remote_image_bytes (N-P1-16); a 32-entry result cache avoids rebuilds.
theme.ChromaStyle maps every built-in theme (U-P2); KindLabel fixes the
inverted label (U-P2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:57:15 +03:00

284 lines
7.2 KiB
Go

// Package preview builds the content shown for a selected entry (design
// §5.4): a pure Build(ctx, req) over vfs — no global state, no Bubble Tea.
// Non-regular files are never opened (U-P1-10); external tools run with a
// timeout and are killed with their children; text is highlighted by a
// chroma formatter that emits foreground SGR only, capped at MaxLines.
package preview
import (
"bytes"
"context"
"errors"
"fmt"
"image"
_ "image/gif" // DecodeConfig formats
_ "image/jpeg"
_ "image/png"
"io"
"io/fs"
"path"
"strings"
"time"
"unicode/utf8"
"vcom/internal/vfs"
)
// Kind of a preview.
type Kind uint8
const (
Empty Kind = iota
Directory
Text
Image
PDF
Audio
Video
Binary
Special
Error
)
func (k Kind) String() string {
return [...]string{"empty", "directory", "text", "image", "pdf", "audio", "video", "binary", "special", "error"}[k]
}
// Metadata shown next to the preview.
type Metadata struct {
Path string
Label string // KindLabel: "directory", "go", "fifo", ...
Size int64
Mode fs.FileMode
ModTime time.Time
LinkTarget string
ImageFormat string
Width, Height int
Duration, Bitrate, AudioCodec, VideoCodec, SampleRate, Channels, Dimensions string
PageCount string
}
// ImageRef is what imgview needs to draw an image; it decodes the file
// itself, off the UI goroutine.
type ImageRef struct {
Loc vfs.Location
Size int64
ModTime time.Time
Format string
Width, Height int
// Local is a local file with the image: the file itself for a local FS,
// a cached download for a remote one; "" when not available.
Local string
// TooLarge: a remote image above MaxRemoteImageBytes is not downloaded.
TooLarge bool
}
// Request describes what to preview.
type Request struct {
Loc vfs.Location
Info vfs.FileInfo // Lstat of Loc; zero → Build does the Lstat
MaxBytes int64 // bytes read for text (default 64 KiB)
MaxLines int // text lines kept (default 3000)
// HighlightLines: how many of the first lines are highlighted (default
// 400 — the chroma lexer costs ~2 ms per 1 KiB); the rest is plain. The
// viewer asks for more (up to MaxLines) when the user scrolls.
HighlightLines int
DirLimit int // directory entries kept (default 80)
ShowHidden bool // directory preview
Theme string
Tools *Tools // external utilities; nil → none
Images *ImageCache // remote image downloads; nil → no downloads
MaxRemoteImageBytes int64 // default 20 MiB
}
// Result of Build.
type Result struct {
Kind Kind
Meta Metadata
Lines []string // highlighted (foreground SGR only), one per screen line, no wrapping
Plain []string // the same lines without SGR (caret, yank)
Dir []vfs.FileInfo
Image *ImageRef
Truncated bool
// Highlighted is the number of leading Lines that carry highlighting.
Highlighted int
Err error
}
const (
defaultMaxBytes = 64 << 10
defaultMaxLines = 3000
defaultDirLimit = 80
defaultMaxRemote = 20 << 20
)
func (r *Request) defaults() {
if r.MaxBytes <= 0 {
r.MaxBytes = defaultMaxBytes
}
if r.MaxLines <= 0 {
r.MaxLines = defaultMaxLines
}
if r.HighlightLines <= 0 {
r.HighlightLines = 400
}
if r.HighlightLines > r.MaxLines {
r.HighlightLines = r.MaxLines
}
if r.DirLimit <= 0 {
r.DirLimit = defaultDirLimit
}
if r.MaxRemoteImageBytes <= 0 {
r.MaxRemoteImageBytes = defaultMaxRemote
}
}
// Build makes the preview. It honours ctx everywhere it waits (reads,
// tools, highlighting) and returns Kind=Error with Err on failure.
func Build(ctx context.Context, req Request) Result {
req.defaults()
fsys, p := req.Loc.FS, req.Loc.Path
res := Result{Meta: Metadata{Path: p}}
fail := func(err error) Result {
res.Kind, res.Err = Error, err
return res
}
if err := ctx.Err(); err != nil {
return fail(err)
}
fi := req.Info
if fi.Name == "" {
var err error
if fi, err = fsys.Lstat(ctx, p); err != nil {
return fail(err)
}
}
res.Meta.Label = KindLabel(fi)
res.Meta.Size, res.Meta.Mode, res.Meta.ModTime = fi.Size, fi.Mode, fi.ModTime
eff := fi
if fi.IsSymlink() {
res.Meta.LinkTarget, _ = fsys.ReadLink(ctx, p)
if fi.Target == nil {
res.Kind = Special
if fi.LinkErr != nil {
res.Err = fmt.Errorf("broken symlink: %w", fi.LinkErr)
}
return res
}
eff = *fi.Target
}
switch {
case eff.IsDir():
return buildDir(ctx, req, res)
case !eff.Mode.IsRegular():
res.Kind = Special // FIFO, socket, device: never opened (U-P1-10)
return res
case eff.Size == 0:
res.Kind = Empty
return res
}
head, truncated, err := readHead(ctx, fsys, p, req.MaxBytes)
if err != nil {
return fail(err)
}
if cfg, format, err := image.DecodeConfig(bytes.NewReader(head)); err == nil {
return buildImage(ctx, req, res, eff, format, cfg)
}
ext := strings.ToLower(path.Ext(p))
switch {
case ext == ".pdf":
return buildPDF(ctx, req, res)
case audioExts[ext]:
return buildMedia(ctx, req, res, Audio)
case videoExts[ext]:
return buildMedia(ctx, req, res, Video)
}
if isBinary(head) {
res.Kind = Binary
return res
}
res.Kind, res.Truncated = Text, truncated
return highlightInto(ctx, req, res, path.Base(p), string(head))
}
// readHead reads at most max bytes (and reports whether there was more).
func readHead(ctx context.Context, fsys vfs.FS, p string, max int64) ([]byte, bool, error) {
f, err := fsys.Open(ctx, p)
if err != nil {
return nil, false, err
}
defer f.Close()
stop := context.AfterFunc(ctx, func() { f.Close() })
defer stop()
buf := make([]byte, max+1)
n, err := io.ReadFull(f, buf)
if ctx.Err() != nil {
return nil, false, ctx.Err()
}
if err != nil && err != io.EOF && !errors.Is(err, io.ErrUnexpectedEOF) {
return nil, false, err
}
if int64(n) > max {
return buf[:max], true, nil
}
return buf[:n], false, nil
}
// isBinary: a NUL byte or mostly invalid UTF-8 in the sample.
func isBinary(b []byte) bool {
if bytes.IndexByte(b, 0) >= 0 {
return true
}
if len(b) > 4 {
b = b[:len(b)-4] // a rune may be cut at the end of the sample
}
bad := 0
for len(b) > 0 {
r, n := utf8.DecodeRune(b)
if r == utf8.RuneError && n == 1 {
bad++
}
b = b[n:]
}
return bad > 8
}
// KindLabel names an entry for the metadata line: "directory", "symlink",
// "fifo", "socket", "device", the lower-case extension ("go", "tar.gz"), or
// "file" (U-P2: the old label was inverted).
func KindLabel(fi vfs.FileInfo) string {
m := fi.Mode
switch {
case m.IsDir():
return "directory"
case m&fs.ModeSymlink != 0:
return "symlink"
case m&fs.ModeNamedPipe != 0:
return "fifo"
case m&fs.ModeSocket != 0:
return "socket"
case m&fs.ModeDevice != 0:
return "device"
}
name := strings.ToLower(fi.Name)
if strings.HasSuffix(name, ".tar.gz") && len(name) > 7 {
return "tar.gz"
}
ext := path.Ext(name)
if ext == "" || ext == name {
return "file"
}
return ext[1:]
}
var audioExts = map[string]bool{".mp3": true, ".flac": true, ".wav": true, ".ogg": true, ".m4a": true,
".aac": true, ".opus": true, ".wma": true}
var videoExts = map[string]bool{".mp4": true, ".mkv": true, ".webm": true, ".avi": true, ".mov": true,
".wmv": true, ".flv": true, ".m4v": true}