diff --git a/internal/preview/build.go b/internal/preview/build.go new file mode 100644 index 0000000..8ec6cbc --- /dev/null +++ b/internal/preview/build.go @@ -0,0 +1,284 @@ +// 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} diff --git a/internal/preview/cache.go b/internal/preview/cache.go new file mode 100644 index 0000000..29fd5a4 --- /dev/null +++ b/internal/preview/cache.go @@ -0,0 +1,229 @@ +package preview + +import ( + "container/list" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "path" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "vcom/internal/vfs" +) + +// ImageCache keeps downloaded remote images in a local directory, keyed by +// (volume, path, size, mtime), evicting least recently used files above a +// total size budget (default 200 MiB). +type ImageCache struct { + dir string + max int64 + + mu sync.Mutex + lru *list.List // of *cached, front = most recent + byKey map[string]*list.Element + total int64 +} + +type cached struct { + key string + path string + size int64 +} + +// NewImageCache uses dir (created 0700). Files already there are kept up to +// the budget (oldest removed first), so the cache survives restarts. +func NewImageCache(dir string, maxBytes int64) (*ImageCache, error) { + if maxBytes <= 0 { + maxBytes = 200 << 20 + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + c := &ImageCache{dir: dir, max: maxBytes, lru: list.New(), byKey: map[string]*list.Element{}} + ents, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + type old struct { + name string + size int64 + mt time.Time + } + var files []old + for _, e := range ents { + fi, err := e.Info() + if err != nil || !fi.Mode().IsRegular() { + continue + } + if strings.HasPrefix(e.Name(), ".tmp-") { // an interrupted download + _ = os.Remove(filepath.Join(dir, e.Name())) + continue + } + files = append(files, old{e.Name(), fi.Size(), fi.ModTime()}) + } + sort.Slice(files, func(i, j int) bool { return files[i].mt.After(files[j].mt) }) + for _, f := range files { + c.add(strings.TrimSuffix(f.name, path.Ext(f.name)), filepath.Join(dir, f.name), f.size) + } + c.evict() + return c, nil +} + +func cacheKey(vol vfs.VolumeID, p string, size int64, mt time.Time) string { + h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d\x00%d", vol, p, size, mt.UnixNano()))) + return hex.EncodeToString(h[:16]) +} + +// add appends at the back (least recent): used while loading. +func (c *ImageCache) add(key, p string, size int64) { + c.byKey[key] = c.lru.PushBack(&cached{key: key, path: p, size: size}) + c.total += size +} + +func (c *ImageCache) evict() { + for c.total > c.max && c.lru.Len() > 1 { + e := c.lru.Back() + it := e.Value.(*cached) + c.lru.Remove(e) + delete(c.byKey, it.key) + c.total -= it.size + _ = os.Remove(it.path) + } +} + +// Fetch returns a local copy of p on fsys, downloading it if needed. +func (c *ImageCache) Fetch(ctx context.Context, fsys vfs.FS, p string, size int64, mt time.Time) (string, error) { + key := cacheKey(fsys.Volume(), p, size, mt) + c.mu.Lock() + if e, ok := c.byKey[key]; ok { + c.lru.MoveToFront(e) + lp := e.Value.(*cached).path + c.mu.Unlock() + return lp, nil + } + c.mu.Unlock() + + src, err := fsys.Open(ctx, p) + if err != nil { + return "", err + } + defer src.Close() + tmp, err := os.CreateTemp(c.dir, ".tmp-*") + if err != nil { + return "", err + } + n, err := io.Copy(tmp, &ctxRead{ctx: ctx, r: io.LimitReader(src, size+1)}) + if cerr := tmp.Close(); err == nil { + err = cerr + } + if err == nil && n != size { + err = fmt.Errorf("%s changed while downloading (%d of %d bytes)", p, n, size) + } + final := filepath.Join(c.dir, key+strings.ToLower(path.Ext(p))) + if err == nil { + err = os.Rename(tmp.Name(), final) + } + if err != nil { + _ = os.Remove(tmp.Name()) + return "", err + } + c.mu.Lock() + defer c.mu.Unlock() + if _, ok := c.byKey[key]; !ok { + c.byKey[key] = c.lru.PushFront(&cached{key: key, path: final, size: n}) + c.total += n + c.evict() + } + return final, nil +} + +type ctxRead struct { + ctx context.Context + r io.Reader +} + +func (c *ctxRead) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + return c.r.Read(p) +} + +// Cache keeps the last results (default 32) by (volume, path, size, mtime, +// theme, limits), so moving the cursor back and forth does not rebuild. +type Cache struct { + mu sync.Mutex + max int + lru *list.List + byKey map[resultKey]*list.Element +} + +type resultKey struct { + vol vfs.VolumeID + path string + size int64 + mtime int64 + theme string + maxBytes int64 + maxLines, dirLimit int + highlight int + hidden bool +} + +type resultEntry struct { + key resultKey + res Result +} + +// NewCache returns a result cache with room for max results (≤ 0 → 32). +func NewCache(max int) *Cache { + if max <= 0 { + max = 32 + } + return &Cache{max: max, lru: list.New(), byKey: map[resultKey]*list.Element{}} +} + +// Build returns a cached result or builds and caches it. Errors and +// cancelled builds are not cached. +func (c *Cache) Build(ctx context.Context, req Request) Result { + req.defaults() + if req.Info.Name == "" { + fi, err := req.Loc.FS.Lstat(ctx, req.Loc.Path) + if err != nil { + return Result{Kind: Error, Err: err, Meta: Metadata{Path: req.Loc.Path}} + } + req.Info = fi + } + k := resultKey{req.Loc.FS.Volume(), req.Loc.Path, req.Info.Size, req.Info.ModTime.UnixNano(), req.Theme, + req.MaxBytes, req.MaxLines, req.DirLimit, req.HighlightLines, req.ShowHidden} + c.mu.Lock() + if e, ok := c.byKey[k]; ok { + c.lru.MoveToFront(e) + r := e.Value.(*resultEntry).res + c.mu.Unlock() + return r + } + c.mu.Unlock() + r := Build(ctx, req) + if r.Err != nil || r.Kind == Error { + return r + } + c.mu.Lock() + defer c.mu.Unlock() + if _, ok := c.byKey[k]; !ok { + c.byKey[k] = c.lru.PushFront(&resultEntry{key: k, res: r}) + for c.lru.Len() > c.max { + e := c.lru.Back() + c.lru.Remove(e) + delete(c.byKey, e.Value.(*resultEntry).key) + } + } + return r +} diff --git a/internal/preview/dir.go b/internal/preview/dir.go new file mode 100644 index 0000000..fba6d5f --- /dev/null +++ b/internal/preview/dir.go @@ -0,0 +1,39 @@ +package preview + +import ( + "context" + "sort" + "strings" + + "vcom/internal/vfs" +) + +// buildDir lists a directory, keeping at most DirLimit entries (dirs first, +// then by name). Hidden entries are dropped unless ShowHidden. +func buildDir(ctx context.Context, req Request, res Result) Result { + ents, err := req.Loc.FS.ReadDir(ctx, req.Loc.Path) + if err != nil { + res.Kind, res.Err = Error, err + return res + } + kept := ents[:0] + for _, e := range ents { + if req.ShowHidden || !strings.HasPrefix(e.Name, ".") { + kept = append(kept, e) + } + } + sort.Slice(kept, func(i, j int) bool { + di, dj := kept[i].NavigableDir(), kept[j].NavigableDir() + if di != dj { + return di + } + return strings.ToLower(kept[i].Name) < strings.ToLower(kept[j].Name) + }) + res.Kind = Directory + if len(kept) > req.DirLimit { + kept, res.Truncated = kept[:req.DirLimit], true + } + res.Dir = make([]vfs.FileInfo, len(kept)) // do not pin the full listing + copy(res.Dir, kept) + return res +} diff --git a/internal/preview/highlight.go b/internal/preview/highlight.go new file mode 100644 index 0000000..9b7069b --- /dev/null +++ b/internal/preview/highlight.go @@ -0,0 +1,109 @@ +package preview + +import ( + "context" + "fmt" + "strings" + + "github.com/alecthomas/chroma/v2" + "github.com/alecthomas/chroma/v2/lexers" + "github.com/alecthomas/chroma/v2/styles" + + "vcom/internal/theme" +) + +// highlightInto fills Lines/Plain for text. The formatter writes SGR for +// foreground colour, bold, italic and underline only — never a background +// (no post-processing regexps). ctx is checked every 256 tokens. +func highlightInto(ctx context.Context, req Request, res Result, name, src string) Result { + plain, cut := textLines(src, req.MaxLines) + res.Plain = plain + res.Truncated = res.Truncated || cut + n := min(req.HighlightLines, len(plain)) + lines, err := Highlight(ctx, name, strings.Join(plain[:n], "\n"), req.Theme) + if err != nil { + res.Kind, res.Err = Error, err + res.Lines, res.Plain = nil, nil + return res + } + if len(lines) != n { + lines, n = plain[:n], 0 // a lexer that changed the text: show it plain + } + res.Lines = make([]string, 0, len(plain)) + res.Lines = append(append(res.Lines, lines...), plain[n:]...) + res.Highlighted = n + return res +} + +// Highlight returns src (already normalised: LF, no tabs) as highlighted +// lines for the given vcom theme. +func Highlight(ctx context.Context, name, src, themeName string) ([]string, error) { + lexer := lexers.Match(name) + if lexer == nil { + lexer = lexers.Analyse(src) + } + if lexer == nil { + return strings.Split(src, "\n"), nil + } + lexer = chroma.Coalesce(lexer) + style := styles.Get(theme.ChromaStyle(themeName)) + it, err := lexer.Tokenise(nil, src) + if err != nil { + return nil, err + } + sgr := map[chroma.TokenType]string{} + var lines []string + var cur strings.Builder + n := 0 + for tok := it(); tok != chroma.EOF; tok = it() { + if n++; n&255 == 0 { + if err := ctx.Err(); err != nil { + return nil, err + } + } + code, ok := sgr[tok.Type] + if !ok { + code = sgrFor(style.Get(tok.Type)) + sgr[tok.Type] = code + } + for i, seg := range strings.Split(tok.Value, "\n") { + if i > 0 { + lines = append(lines, cur.String()) + cur.Reset() + } + if seg == "" { + continue + } + if code != "" { + cur.WriteString(code) + cur.WriteString(seg) + cur.WriteString("\x1b[0m") + } else { + cur.WriteString(seg) + } + } + } + lines = append(lines, cur.String()) + return lines, nil +} + +// sgrFor renders a style entry as a foreground-only SGR sequence. +func sgrFor(e chroma.StyleEntry) string { + var parts []string + if e.Bold == chroma.Yes { + parts = append(parts, "1") + } + if e.Italic == chroma.Yes { + parts = append(parts, "3") + } + if e.Underline == chroma.Yes { + parts = append(parts, "4") + } + if e.Colour.IsSet() { + parts = append(parts, fmt.Sprintf("38;2;%d;%d;%d", e.Colour.Red(), e.Colour.Green(), e.Colour.Blue())) + } + if len(parts) == 0 { + return "" + } + return "\x1b[" + strings.Join(parts, ";") + "m" +} diff --git a/internal/preview/image.go b/internal/preview/image.go new file mode 100644 index 0000000..059a754 --- /dev/null +++ b/internal/preview/image.go @@ -0,0 +1,30 @@ +package preview + +import ( + "context" + "image" + + "vcom/internal/vfs" +) + +// buildImage reports format and size; imgview decodes later. A remote image +// is downloaded to the cache only up to MaxRemoteImageBytes (N-P1-16). +func buildImage(ctx context.Context, req Request, res Result, fi vfs.FileInfo, format string, cfg image.Config) Result { + res.Kind = Image + res.Meta.ImageFormat, res.Meta.Width, res.Meta.Height = format, cfg.Width, cfg.Height + ref := &ImageRef{Loc: req.Loc, Size: fi.Size, ModTime: fi.ModTime, Format: format, Width: cfg.Width, Height: cfg.Height} + res.Image = ref + switch { + case req.Loc.FS.Kind() == vfs.KindLocal: + ref.Local = req.Loc.Path + case fi.Size > req.MaxRemoteImageBytes: + ref.TooLarge = true + case req.Images != nil: + p, err := req.Images.Fetch(ctx, req.Loc.FS, req.Loc.Path, fi.Size, fi.ModTime) + if err != nil { + res.Err = err + } + ref.Local = p + } + return res +} diff --git a/internal/preview/media.go b/internal/preview/media.go new file mode 100644 index 0000000..6082328 --- /dev/null +++ b/internal/preview/media.go @@ -0,0 +1,150 @@ +package preview + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + + "vcom/internal/vfs" +) + +// localPath returns the path tools can read, or "" for a non-local FS. +func localPath(req Request) string { + if req.Loc.FS.Kind() == vfs.KindLocal { + return req.Loc.Path + } + return "" +} + +func message(res Result, k Kind, lines ...string) Result { + res.Kind, res.Lines, res.Plain = k, lines, lines + return res +} + +// buildPDF: the text of the first 3 pages via pdftotext, page count via +// pdfinfo. +func buildPDF(ctx context.Context, req Request, res Result) Result { + lp := localPath(req) + switch { + case lp == "": + return message(res, PDF, "PDF on a remote file system: text preview is not available.") + case req.Tools == nil || req.Tools.PdfToText == "": + return message(res, PDF, "PDF file. Install poppler-utils (pdftotext) for a text preview.") + } + out, err := req.Tools.run(ctx, req.MaxBytes, req.Tools.PdfToText, "-l", "3", "-layout", "-nopgbrk", lp, "-") + if err != nil { + res.Kind, res.Err = Error, err + return res + } + if req.Tools.PdfInfo != "" { + if info, err := req.Tools.run(ctx, 64<<10, req.Tools.PdfInfo, lp); err == nil { + for _, line := range strings.Split(string(info), "\n") { + if v, ok := strings.CutPrefix(line, "Pages:"); ok { + res.Meta.PageCount = strings.TrimSpace(v) + } + } + } + } + res.Kind = PDF + res.Plain, res.Truncated = textLines(string(out), req.MaxLines) + res.Lines = res.Plain + return res +} + +// buildMedia: duration, bitrate, codecs via ffprobe. +func buildMedia(ctx context.Context, req Request, res Result, k Kind) Result { + lp := localPath(req) + switch { + case lp == "": + return message(res, k, "Media file on a remote file system: metadata is not available.") + case req.Tools == nil || req.Tools.FFProbe == "": + return message(res, k, "Media file. Install ffmpeg (ffprobe) for metadata.") + } + out, err := req.Tools.run(ctx, 1<<20, req.Tools.FFProbe, "-v", "quiet", "-print_format", "json", + "-show_format", "-show_streams", lp) + if err != nil { + res.Kind, res.Err = Error, err + return res + } + var info struct { + Format struct { + Duration string `json:"duration"` + Bitrate string `json:"bit_rate"` + } `json:"format"` + Streams []struct { + CodecType string `json:"codec_type"` + CodecName string `json:"codec_name"` + SampleRate string `json:"sample_rate"` + Channels int `json:"channels"` + Width int `json:"width"` + Height int `json:"height"` + } `json:"streams"` + } + if err := json.Unmarshal(out, &info); err != nil { + res.Kind, res.Err = Error, fmt.Errorf("ffprobe output: %w", err) + return res + } + m := &res.Meta + if secs, err := strconv.ParseFloat(info.Format.Duration, 64); err == nil { + s := int(secs) + if s >= 3600 { + m.Duration = fmt.Sprintf("%d:%02d:%02d", s/3600, s%3600/60, s%60) + } else { + m.Duration = fmt.Sprintf("%d:%02d", s/60, s%60) + } + } + if bps, err := strconv.ParseInt(info.Format.Bitrate, 10, 64); err == nil { + m.Bitrate = fmt.Sprintf("%d kbps", bps/1000) + } + for _, st := range info.Streams { + switch st.CodecType { + case "video": + if m.VideoCodec == "" { + m.VideoCodec = st.CodecName + if st.Width > 0 { + m.Dimensions = fmt.Sprintf("%dx%d", st.Width, st.Height) + } + } + case "audio": + if m.AudioCodec == "" { + m.AudioCodec = st.CodecName + if st.SampleRate != "" { + m.SampleRate = st.SampleRate + " Hz" + } + m.Channels = channels(st.Channels) + } + } + } + var lines []string + add := func(label, v string) { + if v != "" { + lines = append(lines, fmt.Sprintf("%-11s %s", label+":", v)) + } + } + add("Duration", m.Duration) + add("Bitrate", m.Bitrate) + add("Video", m.VideoCodec) + add("Resolution", m.Dimensions) + add("Audio", m.AudioCodec) + add("Rate", m.SampleRate) + add("Channels", m.Channels) + return message(res, k, lines...) +} + +func channels(n int) string { + switch n { + case 0: + return "" + case 1: + return "mono" + case 2: + return "stereo" + case 6: + return "5.1" + case 8: + return "7.1" + } + return fmt.Sprintf("%d ch", n) +} diff --git a/internal/preview/preview.test b/internal/preview/preview.test new file mode 100755 index 0000000..6992a53 Binary files /dev/null and b/internal/preview/preview.test differ diff --git a/internal/preview/preview_test.go b/internal/preview/preview_test.go new file mode 100644 index 0000000..d7f41cc --- /dev/null +++ b/internal/preview/preview_test.go @@ -0,0 +1,387 @@ +package preview + +import ( + "bytes" + "context" + "errors" + "fmt" + "image" + "image/color" + "image/png" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/theme" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +var ( + bg = context.Background() + local = localfs.New() +) + +func at(p string) vfs.Location { return vfs.Location{FS: local, Path: p} } + +func pngBytes(t testing.TB, w, h int) []byte { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + img.Set(0, 0, color.RGBA{255, 0, 0, 255}) + var b bytes.Buffer + if err := png.Encode(&b, img); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +func TestFifoNotRead(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.FIFO("pipe"), fstree.Symlink("ln", "pipe")}) + for _, name := range []string{"pipe", "ln"} { + t0 := time.Now() + res := Build(bg, Request{Loc: at(filepath.Join(dir, name))}) + if el := time.Since(t0); el > 50*time.Millisecond { + t.Fatalf("%s: took %v (U-P1-10: a FIFO must not be opened)", name, el) + } + if res.Kind != Special || res.Err != nil { + t.Fatalf("%s: %+v", name, res) + } + } + if res := Build(bg, Request{Loc: at("/dev/zero")}); res.Kind != Special { + t.Fatalf("/dev/zero: %v", res.Kind) + } +} + +// fakeTool writes an executable shell script. +func fakeTool(t *testing.T, body string) string { + p := filepath.Join(t.TempDir(), "tool") + if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func TestToolTimeout(t *testing.T) { + dir := t.TempDir() + pdf := filepath.Join(dir, "doc.pdf") + _ = os.WriteFile(pdf, []byte("%PDF-1.4 not really"), 0o644) + // The script's child (sleep) keeps stdout open: only a group kill ends it. + tools := &Tools{PdfToText: fakeTool(t, "sleep 10 & wait"), Timeout: 3 * time.Second} + t0 := time.Now() + res := Build(bg, Request{Loc: at(pdf), Tools: tools}) + el := time.Since(t0) + if el > 3500*time.Millisecond { + t.Fatalf("returned after %v", el) + } + if res.Kind != Error || !errors.Is(res.Err, ErrToolTimeout) { + t.Fatalf("%+v", res) + } + + // A working tool: output is used and capped. + tools = &Tools{PdfToText: fakeTool(t, `yes "page text" | head -c 100000`), Timeout: 3 * time.Second} + res = Build(bg, Request{Loc: at(pdf), Tools: tools, MaxBytes: 1000}) + if res.Kind != PDF || len(strings.Join(res.Plain, "\n")) > 1000 || res.Plain[0] != "page text" { + t.Fatalf("pdf %v %d lines err=%v", res.Kind, len(res.Plain), res.Err) + } +} + +func TestBuildCancelled(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("a.go", "package a\n")}) + ctx, cancel := context.WithCancel(bg) + cancel() + res := Build(ctx, Request{Loc: at(filepath.Join(dir, "a.go"))}) + if res.Kind != Error || !errors.Is(res.Err, context.Canceled) { + t.Fatalf("%+v", res) + } + // Cancel during a slow read. + ctx, cancel = context.WithCancel(bg) + slow := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpRead { + cancel() + time.Sleep(10 * time.Millisecond) + } + return nil + }} + res = Build(ctx, Request{Loc: vfs.Location{FS: slow, Path: filepath.Join(dir, "a.go")}}) + if !errors.Is(res.Err, context.Canceled) { + t.Fatalf("mid-read: %+v", res) + } + // Cancel during highlighting of a big file. + src := strings.Repeat("func f() { x := 1; _ = x }\n", 3000) + ctx, cancel = context.WithCancel(bg) + time.AfterFunc(time.Millisecond, cancel) + if _, err := Highlight(ctx, "big.go", src, "nord"); err != nil && !errors.Is(err, context.Canceled) { + t.Fatal(err) + } +} + +func TestHighlightNoBackgroundSGR(t *testing.T) { + src := "package main\n\n// comment\nfunc main() {\n\tprintln(\"hi\", 42)\n}\n" + plain, _ := textLines(src, 100) + for _, th := range theme.Names() { + lines, err := Highlight(bg, "main.go", strings.Join(plain, "\n"), th) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(lines, "\n") + if !strings.Contains(joined, "\x1b[") { + t.Fatalf("%s: nothing highlighted", th) + } + for _, seq := range strings.Split(joined, "\x1b[")[1:] { + params := strings.Split(seq[:strings.IndexByte(seq, 'm')], ";") + for i := 0; i < len(params); i++ { + switch p := params[i]; { + case p == "38" && i+1 < len(params) && params[i+1] == "2": + i += 4 // 38;2;r;g;b + case p == "38": + i += 2 // 38;5;n + case p == "48" || p == "49" || (len(p) == 2 && p[0] == '4') || (len(p) == 3 && p[:2] == "10"): + t.Fatalf("%s: background SGR %q", th, params) + } + } + } + if len(lines) != len(plain) { + t.Fatalf("%s: %d lines for %d", th, len(lines), len(plain)) + } + } + // Lines and Plain match line by line. + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("m.go", src)}) + res := Build(bg, Request{Loc: at(filepath.Join(dir, "m.go")), Theme: "dracula"}) + if res.Kind != Text || len(res.Lines) != len(res.Plain) || res.Plain[4] != " println(\"hi\", 42)" { + t.Fatalf("%+v", res.Plain) + } +} + +func goSource(tb testing.TB) string { + b, err := os.ReadFile("highlight.go") + if err != nil { + tb.Fatal(err) + } + var s strings.Builder + for s.Len() < 64<<10 { + s.Write(b) + } + return s.String()[:64<<10] +} + +func BenchmarkPreviewGo64K(b *testing.B) { + dir := b.TempDir() + p := filepath.Join(dir, "big.go") + _ = os.WriteFile(p, []byte(goSource(b)), 0o644) + b.ResetTimer() + for range b.N { + if res := Build(bg, Request{Loc: at(p), Theme: "github-dark"}); res.Kind != Text { + b.Fatal(res.Kind) + } + } +} + +// A loose gate for the benchmark (target ≤ 40 ms, measured ~20 ms; was +// 190 ms). The margin covers -race (≈ ×8). +func TestPreviewGo64KFast(t *testing.T) { + if testing.Short() { + t.Skip() + } + r := testing.Benchmark(BenchmarkPreviewGo64K) + if per := time.Duration(r.NsPerOp()); per > 400*time.Millisecond { + t.Fatalf("Build on 64 KiB of Go: %v per op", per) + } +} + +// remote makes a local FS look remote (no tools, no direct image path). +type remote struct{ vfs.FS } + +func (remote) Kind() vfs.Kind { return vfs.KindSFTP } +func (remote) Volume() vfs.VolumeID { return "ssh:test" } + +func TestRemoteImageSizeLimit(t *testing.T) { + dir := t.TempDir() + small := filepath.Join(dir, "small.png") + _ = os.WriteFile(small, pngBytes(t, 40, 30), 0o644) + big := filepath.Join(dir, "big.png") + data := pngBytes(t, 40, 30) + _ = os.WriteFile(big, append(data, make([]byte, 50000)...), 0o644) // decodable header, large file + cacheDir := filepath.Join(t.TempDir(), "img") + cache, err := NewImageCache(cacheDir, 0) + if err != nil { + t.Fatal(err) + } + opens := 0 + rfs := remote{&vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpOpen { + opens++ + } + return nil + }}} + res := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: big}, Images: cache, MaxRemoteImageBytes: 10000}) + if res.Kind != Image || res.Image == nil || !res.Image.TooLarge || res.Image.Local != "" { + t.Fatalf("big: %+v", res.Image) + } + if ents, _ := os.ReadDir(cacheDir); len(ents) != 0 { + t.Fatal("a too large remote image was downloaded (N-P1-16)") + } + res = Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000}) + if res.Image == nil || res.Image.Local == "" || res.Meta.Width != 40 || res.Meta.Height != 30 { + t.Fatalf("small: %+v %v", res.Image, res.Err) + } + if b, _ := os.ReadFile(res.Image.Local); !bytes.Equal(b, pngBytes(t, 40, 30)) { + t.Fatal("cached copy differs") + } + before := opens + again := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000}) + if again.Image.Local != res.Image.Local || opens-before != 1 { // head read only, no second download + t.Fatalf("cache miss: opens %d", opens-before) + } + // Local images are referenced in place. + if r := Build(bg, Request{Loc: at(small)}); r.Image == nil || r.Image.Local != small { + t.Fatalf("local: %+v", r.Image) + } +} + +func TestImageCacheEvicts(t *testing.T) { + dir := t.TempDir() + src := t.TempDir() + c, err := NewImageCache(filepath.Join(dir, "c"), 2500) + if err != nil { + t.Fatal(err) + } + var paths []string + for i := range 3 { + p := filepath.Join(src, fmt.Sprintf("%d.png", i)) + _ = os.WriteFile(p, make([]byte, 1000), 0o644) + lp, err := c.Fetch(bg, remote{local}, p, 1000, time.Unix(int64(i), 0)) + if err != nil { + t.Fatal(err) + } + paths = append(paths, lp) + } + if _, err := os.Stat(paths[0]); !os.IsNotExist(err) { + t.Fatal("oldest entry not evicted") + } + if _, err := os.Stat(paths[2]); err != nil { + t.Fatal(err) + } + // Reopened: kept within the budget. + c2, err := NewImageCache(filepath.Join(dir, "c"), 1500) + if err != nil || c2.total > 1500 { + t.Fatalf("%v total=%d", err, c2.total) + } +} + +func TestDirPreviewLimited(t *testing.T) { + dir := t.TempDir() + var spec fstree.Spec + for i := range 100 { + spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), "")) + } + spec = append(spec, fstree.Dir("zdir"), fstree.File(".hidden", ""), fstree.Symlink("alink", "zdir")) + fstree.Build(t, dir, spec) + res := Build(bg, Request{Loc: at(dir), DirLimit: 10}) + if res.Kind != Directory || len(res.Dir) != 10 || !res.Truncated { + t.Fatalf("%v %d %v", res.Kind, len(res.Dir), res.Truncated) + } + if res.Dir[0].Name != "alink" || res.Dir[1].Name != "zdir" || res.Dir[2].Name != "f000" { + t.Fatalf("order %s %s %s", res.Dir[0].Name, res.Dir[1].Name, res.Dir[2].Name) + } + for _, e := range res.Dir { + if e.Name == ".hidden" { + t.Fatal("hidden shown") + } + } + if cap(res.Dir) > 10 { + t.Fatalf("result pins the full listing: cap %d", cap(res.Dir)) + } + if res := Build(bg, Request{Loc: at(dir), DirLimit: 1000, ShowHidden: true}); len(res.Dir) != 103 || res.Truncated { + t.Fatalf("all: %d", len(res.Dir)) + } +} + +func TestKindLabel(t *testing.T) { + cases := map[string]vfs.FileInfo{ + "directory": {Name: "src", Mode: os.ModeDir}, + "symlink": {Name: "l.go", Mode: os.ModeSymlink}, + "fifo": {Name: "p", Mode: os.ModeNamedPipe}, + "socket": {Name: "s", Mode: os.ModeSocket}, + "device": {Name: "zero", Mode: os.ModeDevice | os.ModeCharDevice}, + "go": {Name: "main.go"}, + "tar.gz": {Name: "a.TAR.GZ"}, + "file": {Name: "Makefile"}, + } + for want, fi := range cases { + if got := KindLabel(fi); got != want { + t.Errorf("KindLabel(%q) = %q, want %q", fi.Name, got, want) + } + } + if KindLabel(vfs.FileInfo{Name: ".bashrc"}) != "file" { + t.Error("dot-file") + } +} + +func TestBuildKinds(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.File("empty", ""), + fstree.File("bin", "a\x00b\x00c"), + fstree.File("long.txt", strings.Repeat("line\n", 5000)), + fstree.Symlink("broken", "nowhere"), + fstree.File("song.mp3", "ID3 not really"), + }) + _ = os.WriteFile(filepath.Join(dir, "pic.png"), pngBytes(t, 7, 5), 0o644) + kinds := map[string]Kind{"empty": Empty, "bin": Binary, "long.txt": Text, "broken": Special, "pic.png": Image, "song.mp3": Audio} + for name, want := range kinds { + res := Build(bg, Request{Loc: at(filepath.Join(dir, name)), MaxLines: 100}) + if res.Kind != want { + t.Errorf("%s: kind %v (%v), want %v", name, res.Kind, res.Err, want) + } + if name == "long.txt" && (len(res.Lines) != 100 || !res.Truncated) { + t.Errorf("long: %d lines truncated=%v", len(res.Lines), res.Truncated) + } + } + if res := Build(bg, Request{Loc: at(filepath.Join(dir, "broken"))}); res.Meta.LinkTarget != "nowhere" { + t.Error("link target") + } + // The result cache returns the same result without rebuilding. + c := NewCache(2) + opens := 0 + cfs := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpOpen { + opens++ + } + return nil + }} + loc := vfs.Location{FS: cfs, Path: filepath.Join(dir, "long.txt")} + r1 := c.Build(bg, Request{Loc: loc}) + r2 := c.Build(bg, Request{Loc: loc}) + if opens != 1 || len(r1.Lines) != len(r2.Lines) { + t.Fatalf("cache: opens=%d", opens) + } + if res := c.Build(bg, Request{Loc: vfs.Location{FS: local, Path: "/nonexistent"}}); !errors.Is(res.Err, syscall.ENOENT) { + t.Fatalf("missing: %v", res.Err) + } +} + +func TestHighlightWindow(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "big.go") + _ = os.WriteFile(p, []byte(goSource(t)), 0o644) + res := Build(bg, Request{Loc: at(p), HighlightLines: 50}) + if res.Highlighted != 50 || !strings.Contains(res.Lines[10]+res.Lines[0], "\x1b[") { + t.Fatalf("highlighted %d", res.Highlighted) + } + for i := 50; i < len(res.Lines); i++ { + if res.Lines[i] != res.Plain[i] { + t.Fatalf("line %d highlighted beyond the window", i) + } + } + full := Build(bg, Request{Loc: at(p), HighlightLines: 3000}) + if full.Highlighted != len(full.Plain) { + t.Fatalf("full: %d of %d", full.Highlighted, len(full.Plain)) + } +} diff --git a/internal/preview/text.go b/internal/preview/text.go new file mode 100644 index 0000000..fff8399 --- /dev/null +++ b/internal/preview/text.go @@ -0,0 +1,16 @@ +package preview + +import "strings" + +// textLines normalises text for display (CRLF → LF, tab → 4 spaces) and +// splits it into at most max lines. +func textLines(src string, max int) (lines []string, truncated bool) { + src = strings.ReplaceAll(src, "\r\n", "\n") + src = strings.ReplaceAll(src, "\t", " ") + src = strings.TrimSuffix(src, "\n") + lines = strings.Split(src, "\n") + if len(lines) > max { + lines, truncated = lines[:max], true + } + return lines, truncated +} diff --git a/internal/preview/tools.go b/internal/preview/tools.go new file mode 100644 index 0000000..8814978 --- /dev/null +++ b/internal/preview/tools.go @@ -0,0 +1,78 @@ +package preview + +import ( + "bytes" + "context" + "errors" + "fmt" + "os/exec" + "syscall" + "time" +) + +// Tools are the external utilities, looked up once at start. +type Tools struct { + PdfToText string + PdfInfo string + FFProbe string + Timeout time.Duration // per run; default 3 s +} + +// FindTools looks the utilities up in $PATH. +func FindTools() *Tools { + look := func(name string) string { + p, _ := exec.LookPath(name) + return p + } + return &Tools{PdfToText: look("pdftotext"), PdfInfo: look("pdfinfo"), FFProbe: look("ffprobe"), Timeout: 3 * time.Second} +} + +// ErrToolTimeout: the tool was killed after Tools.Timeout. +var ErrToolTimeout = errors.New("timed out") + +// run executes prog with a timeout. The tool gets its own process group and +// the whole group is killed on timeout or cancel, so a child holding stdout +// open cannot make Wait hang. Output beyond max bytes is discarded. +func (t *Tools) run(ctx context.Context, max int64, prog string, args ...string) ([]byte, error) { + timeout := t.Timeout + if timeout <= 0 { + timeout = 3 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + cmd := exec.CommandContext(ctx, prog, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + cmd.WaitDelay = 200 * time.Millisecond + out := &capped{max: max} + cmd.Stdout = out + err := cmd.Run() + if ctx.Err() == context.DeadlineExceeded { + return nil, fmt.Errorf("%s: %w after %v", prog, ErrToolTimeout, timeout) + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + if err != nil { + return nil, fmt.Errorf("%s: %w", prog, err) + } + return out.b.Bytes(), nil +} + +// capped keeps the first max bytes and swallows the rest (the tool is not +// killed by a broken pipe halfway through). +type capped struct { + b bytes.Buffer + max int64 +} + +func (c *capped) Write(p []byte) (int, error) { + if room := c.max - int64(c.b.Len()); room > 0 { + if int64(len(p)) > room { + c.b.Write(p[:room]) + } else { + c.b.Write(p) + } + } + return len(p), nil +} diff --git a/internal/theme/chroma.go b/internal/theme/chroma.go new file mode 100644 index 0000000..fc5f3d5 --- /dev/null +++ b/internal/theme/chroma.go @@ -0,0 +1,36 @@ +package theme + +import "strings" + +// chromaStyles maps every built-in theme to the closest chroma style +// (U-P2: the old table knew 7 of the themes and fell back to catppuccin). +var chromaStyles = map[string]string{ + "catppuccin-mocha": "catppuccin-mocha", + "catppuccin-macchiato": "catppuccin-macchiato", + "catppuccin-lavender": "catppuccin-mocha", + "tokyo-night": "tokyonight-night", + "gruvbox-dark": "gruvbox", + "nord": "nord", + "one-dark": "onedark", + "everforest": "evergarden", + "github-dark": "github-dark", + "ayu-dark": "doom-one", + "breeze": "nordic", + "cyberpunk": "aura-theme-dark", + "dracula": "dracula", + "eldritch": "aura-theme-dark-soft", + "kanagawa": "tokyonight-storm", + "kanagawa-paper": "tokyonight-moon", + "rose-pine": "rose-pine", + "solarized-dark": "solarized-dark", + "vesper": "monokai", +} + +// ChromaStyle returns the chroma style name for a theme (unknown themes get +// the default theme's style). +func ChromaStyle(theme string) string { + if s, ok := chromaStyles[strings.ToLower(strings.TrimSpace(theme))]; ok { + return s + } + return chromaStyles[builtInThemes[0]] +} diff --git a/internal/theme/chroma_test.go b/internal/theme/chroma_test.go new file mode 100644 index 0000000..a45fedc --- /dev/null +++ b/internal/theme/chroma_test.go @@ -0,0 +1,26 @@ +package theme + +import ( + "testing" + + "github.com/alecthomas/chroma/v2/styles" +) + +func TestEveryThemeHasChromaStyle(t *testing.T) { + for _, name := range Names() { + s, ok := chromaStyles[name] + if !ok { + t.Errorf("theme %q has no chroma mapping", name) + continue + } + if _, ok := styles.Registry[s]; !ok { + t.Errorf("theme %q maps to unknown chroma style %q", name, s) + } + } + if len(chromaStyles) != len(Names()) { + t.Errorf("mapping has %d entries for %d themes", len(chromaStyles), len(Names())) + } + if ChromaStyle("no-such-theme") != "catppuccin-mocha" { + t.Error("fallback") + } +}