diff --git a/internal/tui/panel/entry.go b/internal/tui/panel/entry.go new file mode 100644 index 0000000..331e0a9 --- /dev/null +++ b/internal/tui/panel/entry.go @@ -0,0 +1,124 @@ +package panel + +import ( + "sort" + "strings" + + "vcom/internal/vfs" +) + +// Category drives the color and icon of a row. +type Category uint8 + +const ( + CatFile Category = iota + CatDir + CatLinkDir // symlink to a directory: navigable (U-P1-2) + CatLink // symlink to a file + CatBroken // dangling symlink + CatExec // regular (or link to regular) with an x bit + CatSpecial // FIFO, socket, device + CatParent // ".." +) + +// Entry is a row: the file info plus fields computed once per listing. +type Entry struct { + vfs.FileInfo + Parent bool // the ".." row + Cat Category + lower string // sort and filter key + ext string +} + +// Navigable reports whether Enter/l goes into the entry (directory or link +// to one). +func (e Entry) Navigable() bool { return e.Parent || e.NavigableDir() } + +func classify(fi vfs.FileInfo) Category { + switch { + case fi.IsDir(): + return CatDir + case fi.IsSymlink() && fi.Target == nil: + return CatBroken + case fi.IsSymlink() && fi.Target.IsDir(): + return CatLinkDir + case fi.IsRegularLike() && execBits(fi): + return CatExec + case fi.IsSymlink(): + return CatLink + case fi.Mode.IsRegular(): + return CatFile + } + return CatSpecial +} + +func execBits(fi vfs.FileInfo) bool { + m := fi.Mode + if fi.IsSymlink() && fi.Target != nil { + m = fi.Target.Mode + } + return m.Perm()&0o111 != 0 +} + +func buildEntries(infos []vfs.FileInfo, o Options, parent bool) []Entry { + out := make([]Entry, 0, len(infos)+1) + if parent { + out = append(out, Entry{FileInfo: vfs.FileInfo{Name: ".."}, Parent: true, Cat: CatParent}) + } + start := len(out) + for _, fi := range infos { + if fi.Name == "" || fi.Name == "." || fi.Name == ".." { + continue + } + if !o.ShowHidden && strings.HasPrefix(fi.Name, ".") { + continue + } + lower := strings.ToLower(fi.Name) + ext := "" + if i := strings.LastIndexByte(lower, '.'); i > 0 { + ext = lower[i+1:] + } + out = append(out, Entry{FileInfo: fi, Cat: classify(fi), lower: lower, ext: ext}) + } + rest := out[start:] + sort.SliceStable(rest, func(i, j int) bool { return less(rest[i], rest[j], o) }) + return out +} + +func less(a, b Entry, o Options) bool { + if o.DirsFirst { + ad, bd := a.Navigable(), b.Navigable() + if ad != bd { + return ad + } + } + var c int + switch o.SortBy { + case "size": + c = cmp(a.Size, b.Size) + case "modified", "mtime", "time": + c = cmp(a.ModTime.UnixNano(), b.ModTime.UnixNano()) + case "ext", "extension": + c = strings.Compare(a.ext, b.ext) + } + if c == 0 { + c = strings.Compare(a.lower, b.lower) + } + if c == 0 { + c = strings.Compare(a.Name, b.Name) + } + if o.Reverse { + return c > 0 + } + return c < 0 +} + +func cmp[T int64](a, b T) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} diff --git a/internal/tui/panel/lru.go b/internal/tui/panel/lru.go new file mode 100644 index 0000000..72a4f3d --- /dev/null +++ b/internal/tui/panel/lru.go @@ -0,0 +1,44 @@ +package panel + +// lru is a small bounded string map for cursor memory (oldest evicted). +type lru struct { + cap int + m map[string]string + order []string // oldest first +} + +func newLRU(n int) *lru { return &lru{cap: n, m: map[string]string{}} } + +func (l *lru) get(k string) (string, bool) { + v, ok := l.m[k] + if ok { + l.touch(k) + } + return v, ok +} + +func (l *lru) put(k, v string) { + if _, ok := l.m[k]; ok { + l.m[k] = v + l.touch(k) + return + } + l.m[k] = v + l.order = append(l.order, k) + for len(l.order) > l.cap { + delete(l.m, l.order[0]) + l.order = l.order[1:] + } +} + +func (l *lru) touch(k string) { + for i, o := range l.order { + if o == k { + copy(l.order[i:], l.order[i+1:]) + l.order[len(l.order)-1] = k + return + } + } +} + +func (l *lru) len() int { return len(l.m) } diff --git a/internal/tui/panel/panel.go b/internal/tui/panel/panel.go new file mode 100644 index 0000000..34ea4ad --- /dev/null +++ b/internal/tui/panel/panel.go @@ -0,0 +1,594 @@ +// Package panel is one file panel of the new UI (design §7.8): a stack of +// mounts (local → archive → archive-in-archive, or a remote host), the +// listing of the current directory, cursor, marks, filter, history and +// cursor memory. It does no I/O: the App reads directories asynchronously +// and applies the result as one transaction (Apply), so a failed +// navigation never leaves the panel half-changed (U-P1-8). +package panel + +import ( + "strings" + "sync/atomic" + + "vcom/internal/vfs" +) + +var mountIDs atomic.Uint64 + +// Mount is one level of the panel's FS stack. +type Mount struct { + ID uint64 + FS vfs.FS + Root string // ".." in Root leaves this mount + // Return is where ".." from Root goes (the directory holding the + // archive, the local directory before connecting); nil on the bottom + // local mount. ReturnFocus is the name put under the cursor there. + Return *vfs.Location + ReturnFocus string + // Release drops the mount's reference (lease, archive index); called + // once when no snapshot of the panel uses the mount any more. + Release func() + // Acquire returns another reference for a mirrored panel (lease + // Acquire); nil means the mount can be shared as is (local). + Acquire func() (release func()) +} + +// NewMount builds a mount with a fresh ID. +func NewMount(fsys vfs.FS, root string, ret *vfs.Location, retFocus string, release func(), acquire func() func()) Mount { + return Mount{ID: mountIDs.Add(1), FS: fsys, Root: root, Return: ret, ReturnFocus: retFocus, Release: release, Acquire: acquire} +} + +// Source is what the panel lists. +type Source uint8 + +const ( + SourceDir Source = iota // a directory of the top mount's FS + SourceHosts // the SSH host list (stage 6.4): not an FS, never a target +) + +// Target is a place to navigate to. +type Target struct { + Mounts []Mount + Path string +} + +// FS is the file system of the target's top mount. +func (t Target) FS() vfs.FS { return t.Mounts[len(t.Mounts)-1].FS } + +// Location of the target. +func (t Target) Location() vfs.Location { return vfs.Location{FS: t.FS(), Path: t.Path} } + +// Snapshot is a history entry. +type Snapshot struct { + Target + Focus string +} + +// NavMode tells Apply how the navigation affects history. +type NavMode uint8 + +const ( + NavPush NavMode = iota // a new place: current one goes to history + NavBack // history back + NavForward // history forward + NavReplace // same history slot (climb to an existing parent) +) + +// Options are the listing options (same for every FS, N-P2-7). +type Options struct { + ShowHidden bool + DirsFirst bool + SortBy string // name | size | modified | ext + Reverse bool + ShowSize bool + ShowTime bool + HumanSize bool +} + +const historyMax = 100 + +// Model is one panel. +type Model struct { + ID int + Source Source + Opts Options + // Badge is a short connection state shown in the title ("⚠ lost"); + // set by the App from conn events. + Badge string + // Loading is set while a listing for this panel is in flight. + Loading bool + + mounts []Mount + path string + entries []Entry + gen uint64 // bumps whenever entries or visible change (render cache) + visible []int + cursor int // index into visible + offset int + rows int // list rows on screen (for paging); set by SetRows + marks map[string]bool + filter string + history []Snapshot + future []Snapshot + memory *lru + cache rowCache +} + +// New makes an empty panel at target (call Apply with a listing). +func New(id int, opts Options, mounts []Mount, path string) *Model { + return &Model{ID: id, Opts: opts, mounts: mounts, path: path, marks: map[string]bool{}, memory: newLRU(200), rows: 20} +} + +// Mounts returns the mount stack (do not modify). +func (p *Model) Mounts() []Mount { return p.mounts } + +// Top is the top mount. +func (p *Model) Top() Mount { return p.mounts[len(p.mounts)-1] } + +// FS of the top mount. +func (p *Model) FS() vfs.FS { return p.Top().FS } + +// Path in the top mount's FS. +func (p *Model) Path() string { return p.path } + +// Location is where the panel stands. +func (p *Model) Location() vfs.Location { return vfs.Location{FS: p.FS(), Path: p.path} } + +// Here is the current place as a Target. +func (p *Model) Here() Target { + return Target{Mounts: append([]Mount(nil), p.mounts...), Path: p.path} +} + +// Gen changes with every change of what the panel shows. +func (p *Model) Gen() uint64 { return p.gen } + +func (p *Model) bump() { p.gen++ } + +// Filter returns the current filter text. +func (p *Model) Filter() string { return p.filter } + +// Entries returns all entries of the directory (sorted, ".." first). +func (p *Model) Entries() []Entry { return p.entries } + +// VisibleLen is the number of rows after the filter. +func (p *Model) VisibleLen() int { return len(p.visible) } + +// Visible returns the i-th visible entry. +func (p *Model) Visible(i int) (Entry, bool) { + if i < 0 || i >= len(p.visible) { + return Entry{}, false + } + return p.entries[p.visible[i]], true +} + +// Cursor is the cursor position in the visible rows. +func (p *Model) Cursor() int { return p.cursor } + +// Offset is the first visible row on screen. +func (p *Model) Offset() int { return p.offset } + +// Selected is the entry under the cursor (always one of the visible rows). +func (p *Model) Selected() (Entry, bool) { return p.Visible(p.cursor) } + +// SetRows tells the panel how many list rows are on screen. +func (p *Model) SetRows(n int) { + p.rows = max(1, n) + p.follow() +} + +// Rows is the number of list rows on screen. +func (p *Model) Rows() int { return p.rows } + +func (p *Model) key(loc vfs.Location) string { + if loc.FS == nil { + return loc.Path + } + return string(loc.FS.Volume()) + "\x00" + loc.Path +} + +// rememberCursor stores the selected name for the current directory. +func (p *Model) rememberCursor() { + if e, ok := p.Selected(); ok && !e.Parent { + p.memory.put(p.key(p.Location()), e.Name) + } +} + +// Apply installs a successful listing of target as one transaction: +// location, entries, history and cursor change together. focus is the name +// to put the cursor on ("" = remembered name for that directory). Mounts no +// longer used by the panel or its history are released. +func (p *Model) Apply(t Target, infos []vfs.FileInfo, focus string, mode NavMode) { + old := p.liveMounts() + cur := Snapshot{Target: p.Here(), Focus: p.selectedName()} + p.rememberCursor() + switch mode { + case NavPush: + p.history = append(p.history, cur) + if len(p.history) > historyMax { + p.history = p.history[len(p.history)-historyMax:] + } + p.future = nil + case NavBack: + if n := len(p.history); n > 0 { + p.history = p.history[:n-1] + } + p.future = append(p.future, cur) + case NavForward: + if n := len(p.future); n > 0 { + p.future = p.future[:n-1] + } + p.history = append(p.history, cur) + } + p.mounts = t.Mounts + p.path = t.Path + p.Loading = false + if focus == "" { + focus, _ = p.memory.get(p.key(p.Location())) + } + p.filter = "" + p.marks = map[string]bool{} + p.setEntries(infos) + p.cursor = 0 + p.offset = 0 + if i := p.indexOf(focus); i >= 0 { + p.cursor = i + } + p.follow() + p.releaseDropped(old) +} + +// Reload replaces the entries of the current directory, keeping the cursor +// on the same name; if that entry is gone the cursor stays at the same +// index, i.e. on its neighbour (U-P1-7). Marks of vanished names drop, +// the filter stays. +func (p *Model) Reload(infos []vfs.FileInfo) { + name := p.selectedName() + idx := p.cursor + p.Loading = false + p.setEntries(infos) + present := map[string]bool{} + for _, e := range p.entries { + present[e.Name] = true + } + for m := range p.marks { + if !present[m] { + delete(p.marks, m) + } + } + if i := p.indexOf(name); i >= 0 { + p.cursor = i + } else { + p.cursor = max(0, min(idx, len(p.visible)-1)) + } + p.follow() +} + +// SetOptions changes listing options and re-sorts. +func (p *Model) SetOptions(o Options) { + name := p.selectedName() + p.Opts = o + infos := make([]vfs.FileInfo, 0, len(p.entries)) + for _, e := range p.entries { + if !e.Parent { + infos = append(infos, e.FileInfo) + } + } + p.setEntries(infos) + if i := p.indexOf(name); i >= 0 { + p.cursor = i + } else { + p.cursor = 0 + } + p.follow() +} + +func (p *Model) selectedName() string { + if e, ok := p.Selected(); ok && !e.Parent { + return e.Name + } + return "" +} + +// indexOf finds name among the visible rows. +func (p *Model) indexOf(name string) int { + if name == "" { + return -1 + } + for i, ei := range p.visible { + if p.entries[ei].Name == name && !p.entries[ei].Parent { + return i + } + } + return -1 +} + +func (p *Model) setEntries(infos []vfs.FileInfo) { + p.entries = buildEntries(infos, p.Opts, p.HasParent()) + p.bump() + p.refilter() +} + +// HasParent reports whether ".." leads somewhere. +func (p *Model) HasParent() bool { + if p.Source == SourceHosts { + return true + } + _, _, _, ok := p.ParentTarget() + return ok +} + +// ParentTarget is where ".." goes and the name to focus there. ok is false +// at the very root; leaving reports that the top mount is left. +func (p *Model) ParentTarget() (t Target, focus string, leaving bool, ok bool) { + top := p.Top() + ops := top.FS.Paths() + if ops.Clean(p.path) != ops.Clean(top.Root) { + parent := ops.Dir(p.path) + if parent == p.path { + return Target{}, "", false, false + } + return Target{Mounts: p.Here().Mounts, Path: parent}, ops.Base(p.path), false, true + } + if len(p.mounts) < 2 { + return Target{}, "", false, false + } + below := append([]Mount(nil), p.mounts[:len(p.mounts)-1]...) + path := below[len(below)-1].Root + if top.Return != nil { + path = top.Return.Path + } + return Target{Mounts: below, Path: path}, top.ReturnFocus, true, true +} + +// ChildTarget is the target for entering directory name in the top mount. +func (p *Model) ChildTarget(name string) Target { + return Target{Mounts: p.Here().Mounts, Path: p.FS().Paths().Join(p.path, name)} +} + +// History. + +// BackTarget is the previous place in history. +func (p *Model) BackTarget() (Snapshot, bool) { + if len(p.history) == 0 { + return Snapshot{}, false + } + return p.history[len(p.history)-1], true +} + +// ForwardTarget is the next place in history. +func (p *Model) ForwardTarget() (Snapshot, bool) { + if len(p.future) == 0 { + return Snapshot{}, false + } + return p.future[len(p.future)-1], true +} + +// liveMounts returns the IDs of every mount referenced by the panel. +func (p *Model) liveMounts() map[uint64]Mount { + out := map[uint64]Mount{} + add := func(ms []Mount) { + for _, m := range ms { + out[m.ID] = m + } + } + add(p.mounts) + for _, s := range p.history { + add(s.Mounts) + } + for _, s := range p.future { + add(s.Mounts) + } + return out +} + +// releaseDropped releases mounts that were referenced before and are not +// any more. History entries that point into a mount the panel has left are +// dropped first: a closed archive or host is not reopened from history. +func (p *Model) releaseDropped(before map[uint64]Mount) { + cur := map[uint64]bool{} + for _, m := range p.mounts { + cur[m.ID] = true + } + keep := func(ss []Snapshot) []Snapshot { + out := ss[:0] + for _, s := range ss { + ok := true + for _, m := range s.Mounts { + ok = ok && cur[m.ID] + } + if ok { + out = append(out, s) + } + } + return out + } + p.history = keep(p.history) + p.future = keep(p.future) + after := p.liveMounts() + for id, m := range before { + if _, ok := after[id]; !ok && m.Release != nil { + m.Release() + } + } +} + +// Close releases every mount (the panel is going away). +func (p *Model) Close() { + before := p.liveMounts() + p.mounts = p.mounts[:0] + p.history, p.future = nil, nil + for _, m := range before { + if m.Release != nil { + m.Release() + } + } +} + +// MirrorOf makes p show the same place as o: every mount is re-acquired so +// leaving it in one panel does not break the other (U-P1-14, N-P1-12). +func (p *Model) MirrorOf(o *Model, infos []vfs.FileInfo) { + ms := make([]Mount, len(o.mounts)) + for i, m := range o.mounts { + c := m + c.ID = mountIDs.Add(1) + if m.Acquire != nil { + c.Release = m.Acquire() + } else { + c.Release = nil + } + ms[i] = c + } + p.Apply(Target{Mounts: ms, Path: o.path}, infos, o.selectedName(), NavPush) +} + +// Filter. + +// SetFilter shows only entries whose name contains s (case-insensitive); +// the cursor stays on the same entry if it is still visible. +func (p *Model) SetFilter(s string) { + if s == p.filter { + return + } + name := p.selectedName() + p.filter = s + p.refilter() + if i := p.indexOf(name); i >= 0 { + p.cursor = i + } else { + p.cursor = 0 + } + p.offset = 0 + p.follow() +} + +func (p *Model) refilter() { + p.visible = p.visible[:0] + f := strings.ToLower(p.filter) + for i, e := range p.entries { + if f == "" || e.Parent || strings.Contains(e.lower, f) { + p.visible = append(p.visible, i) + } + } + p.bump() + p.cursor = max(0, min(p.cursor, len(p.visible)-1)) +} + +// Marks. + +// Marked reports whether name is marked. +func (p *Model) Marked(name string) bool { return p.marks[name] } + +// MarkCount is the number of marked entries (visible or not). +func (p *Model) MarkCount() int { return len(p.marks) } + +// ToggleMark marks or unmarks the entry under the cursor ("..": no-op). +func (p *Model) ToggleMark() { + e, ok := p.Selected() + if !ok || e.Parent { + return + } + if p.marks[e.Name] { + delete(p.marks, e.Name) + } else { + p.marks[e.Name] = true + } + p.bump() +} + +// ClearMarks drops every mark; it reports whether there were any. +func (p *Model) ClearMarks() bool { + if len(p.marks) == 0 { + return false + } + p.marks = map[string]bool{} + p.bump() + return true +} + +// Targets returns what an operation acts on: the marked entries that are +// visible, or the entry under the cursor if none is marked. hiddenMarked +// counts marked entries hidden by the filter — they are NOT included, and +// the operation dialog says so. +func (p *Model) Targets() (out []Entry, hiddenMarked int) { + if len(p.marks) > 0 { + seen := 0 + for _, i := range p.visible { + e := p.entries[i] + if p.marks[e.Name] && !e.Parent { + out = append(out, e) + seen++ + } + } + hiddenMarked = len(p.marks) - seen + if len(out) > 0 { + return out, hiddenMarked + } + } + if e, ok := p.Selected(); ok && !e.Parent { + out = append(out, e) + } + return out, hiddenMarked +} + +// Cursor movement. + +// MoveCursor moves by delta rows (clamped). +func (p *Model) MoveCursor(delta int) { + p.SetCursor(p.cursor + delta) +} + +// SetCursor puts the cursor on visible row i (clamped). +func (p *Model) SetCursor(i int) { + if len(p.visible) == 0 { + p.cursor = 0 + return + } + n := max(0, min(i, len(p.visible)-1)) + if n != p.cursor { + p.cursor = n + p.bump() + } + p.follow() +} + +// Page moves by a screen (dir = ±1) or half a screen (half). +func (p *Model) Page(dir int, half bool) { + step := max(1, p.rows-1) + if half { + step = max(1, p.rows/2) + } + p.MoveCursor(dir * step) +} + +// Scroll moves the view by delta rows, dragging the cursor along when it +// would leave the screen (mouse wheel). +func (p *Model) Scroll(delta int) { + maxOff := max(0, len(p.visible)-p.rows) + p.offset = max(0, min(p.offset+delta, maxOff)) + if p.cursor < p.offset { + p.cursor = p.offset + } + if p.cursor >= p.offset+p.rows { + p.cursor = p.offset + p.rows - 1 + } + p.bump() +} + +// RowAt maps a list row on screen (0 = first) to a visible index. +func (p *Model) RowAt(row int) (int, bool) { + i := p.offset + row + if row < 0 || row >= p.rows || i >= len(p.visible) { + return 0, false + } + return i, true +} + +func (p *Model) follow() { + if p.cursor < p.offset { + p.offset = p.cursor + } + if p.cursor >= p.offset+p.rows { + p.offset = p.cursor - p.rows + 1 + } + p.offset = max(0, min(p.offset, max(0, len(p.visible)-p.rows))) +} diff --git a/internal/tui/panel/panel_test.go b/internal/tui/panel/panel_test.go new file mode 100644 index 0000000..d11fce4 --- /dev/null +++ b/internal/tui/panel/panel_test.go @@ -0,0 +1,309 @@ +package panel + +import ( + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/charmbracelet/x/ansi" + + "vcom/internal/theme" + "vcom/internal/tui/geom" + "vcom/internal/tui/style" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" +) + +var local = localfs.New() + +func infos(names ...string) []vfs.FileInfo { + out := make([]vfs.FileInfo, len(names)) + for i, n := range names { + mode := fs.FileMode(0o644) + if strings.HasSuffix(n, "/") { + n = strings.TrimSuffix(n, "/") + mode = fs.ModeDir | 0o755 + } + out[i] = vfs.FileInfo{Name: n, Mode: mode, Size: int64(len(n)), ModTime: time.Unix(0, 0)} + } + return out +} + +func newPanel(path string, names ...string) *Model { + m := NewMount(local, "/", nil, "", nil, nil) + p := New(0, Options{ShowHidden: true, DirsFirst: true}, []Mount{m}, path) + p.Apply(Target{Mounts: []Mount{m}, Path: path}, infos(names...), "", NavReplace) + return p +} + +func names(p *Model) []string { + var out []string + for i := 0; i < p.VisibleLen(); i++ { + e, _ := p.Visible(i) + out = append(out, e.Name) + } + return out +} + +// U-P1-4: with a filter, row N on screen is the N-th visible entry. +func TestFilterVisibleIndexAndMouse(t *testing.T) { + p := newPanel("/d", "a", "b", "c", "abc", "dir/") + p.SetRows(10) + p.SetFilter("B") + if got := strings.Join(names(p), ","); got != "..,abc,b" { + t.Fatalf("visible = %s", got) + } + i, ok := p.RowAt(2) // third row on screen + if !ok { + t.Fatal("row 2 not mapped") + } + p.SetCursor(i) + if e, _ := p.Selected(); e.Name != "b" { + t.Fatalf("selected %q, want b", e.Name) + } + if _, ok := p.RowAt(3); ok { + t.Fatal("row past the end mapped") + } + // The cursor stays on the same entry when the filter changes. + p.SetFilter("") + if e, _ := p.Selected(); e.Name != "b" { + t.Fatalf("after clearing the filter: %q", e.Name) + } +} + +func TestFilterResetOnDirChange(t *testing.T) { + p := newPanel("/d", "a", "b", "sub/") + p.SetFilter("a") + p.SetCursor(1) + p.ToggleMark() + p.Apply(p.ChildTarget("sub"), infos("x", "y"), "", NavPush) + if p.Filter() != "" || p.MarkCount() != 0 || p.VisibleLen() != 3 { + t.Fatalf("filter %q marks %d visible %v", p.Filter(), p.MarkCount(), names(p)) + } + // Back restores the cursor from memory. + snap, ok := p.BackTarget() + if !ok || snap.Path != "/d" || snap.Focus != "a" { + t.Fatalf("history = %+v", snap) + } + p.Apply(snap.Target, infos("a", "b", "sub/"), snap.Focus, NavBack) + if e, _ := p.Selected(); e.Name != "a" { + t.Fatalf("back: cursor on %q", e.Name) + } + if f, ok := p.ForwardTarget(); !ok || f.Path != "/d/sub" { + t.Fatalf("future = %+v", f) + } +} + +func TestTargetsExcludeHiddenMarks(t *testing.T) { + p := newPanel("/d", "apple", "banana", "cherry") + for _, n := range []string{"apple", "banana", "cherry"} { + p.SetCursor(p.indexOf(n)) + p.ToggleMark() + } + p.SetFilter("an") + ts, hidden := p.Targets() + if len(ts) != 1 || ts[0].Name != "banana" || hidden != 2 { + t.Fatalf("targets %v hidden %d", ts, hidden) + } + // Nothing marked: the cursor entry; ".." is never a target. + p.ClearMarks() + p.SetFilter("") + p.SetCursor(0) + if ts, _ := p.Targets(); len(ts) != 0 { + t.Fatalf("'..' became a target: %v", ts) + } + p.SetCursor(2) + if ts, _ := p.Targets(); len(ts) != 1 || ts[0].Name != "banana" { + t.Fatalf("cursor target %v", ts) + } +} + +// U-P1-7: after an operation both panels on the same directory reload, each +// keeping its own cursor; a deleted entry leaves the cursor on its index. +func TestReloadKeepsCursorPerPane(t *testing.T) { + a := newPanel("/d", "a", "b", "c", "d") + b := newPanel("/d", "a", "b", "c", "d") + a.SetCursor(a.indexOf("b")) + b.SetCursor(b.indexOf("d")) + a.Reload(infos("a", "b", "c", "d", "e")) + b.Reload(infos("a", "b", "c", "d", "e")) + if ea, _ := a.Selected(); ea.Name != "b" { + t.Errorf("a: %q", ea.Name) + } + if eb, _ := b.Selected(); eb.Name != "d" { + t.Errorf("b: %q", eb.Name) + } +} + +func TestDeletedItemCursorStaysAtIndex(t *testing.T) { + p := newPanel("/d", "a", "b", "c", "d") + p.SetCursor(p.indexOf("b")) + idx := p.Cursor() + p.Reload(infos("a", "c", "d")) + if p.Cursor() != idx { + t.Fatalf("cursor %d, want %d", p.Cursor(), idx) + } + if e, _ := p.Selected(); e.Name != "c" { + t.Fatalf("on %q, want the neighbour c", e.Name) + } + p.SetCursor(p.VisibleLen() - 1) + p.Reload(infos("a")) + if e, _ := p.Selected(); e.Name != "a" { + t.Fatalf("last deleted: on %q", e.Name) + } +} + +// U-P1-2: a symlink to a directory is navigable, a broken one is not. +func TestSymlinkDirNavigable(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "real"), 0o755); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(dir, "f.sh"), []byte("#!/bin/sh"), 0o755) + os.Symlink("real", filepath.Join(dir, "linkdir")) + os.Symlink("f.sh", filepath.Join(dir, "linkfile")) + os.Symlink("missing", filepath.Join(dir, "broken")) + ents, err := local.ReadDir(context.Background(), dir) + if err != nil { + t.Fatal(err) + } + m := NewMount(local, "/", nil, "", nil, nil) + p := New(0, Options{ShowHidden: true, DirsFirst: true}, []Mount{m}, dir) + p.Apply(Target{Mounts: []Mount{m}, Path: dir}, ents, "", NavReplace) + want := map[string]Category{"real": CatDir, "linkdir": CatLinkDir, "linkfile": CatExec, "broken": CatBroken, "f.sh": CatExec} + for i := 0; i < p.VisibleLen(); i++ { + e, _ := p.Visible(i) + if e.Parent { + continue + } + if e.Cat != want[e.Name] { + t.Errorf("%s: cat %d, want %d", e.Name, e.Cat, want[e.Name]) + } + if e.Navigable() != (e.Name == "real" || e.Name == "linkdir") { + t.Errorf("%s: navigable = %v", e.Name, e.Navigable()) + } + } + // Directories (and links to them) sort first. + if got := names(p); got[1] != "linkdir" || got[2] != "real" { + t.Errorf("order = %v", got) + } +} + +func TestMountsReleasedWhenLeft(t *testing.T) { + released := 0 + base := NewMount(local, "/", nil, "", nil, nil) + p := New(0, Options{}, []Mount{base}, "/data") + p.Apply(Target{Mounts: []Mount{base}, Path: "/data"}, infos("a.zip"), "", NavReplace) + arc := NewMount(otherFS{local}, "/", &vfs.Location{FS: local, Path: "/data"}, "a.zip", func() { released++ }, nil) + p.Apply(Target{Mounts: []Mount{base, arc}, Path: "/"}, infos("inside", "dir/"), "", NavPush) + p.Apply(p.ChildTarget("dir"), infos("x"), "", NavPush) + if released != 0 { + t.Fatal("released while inside") + } + // ".." twice leaves the archive with the cursor on it. + tg, focus, leaving, ok := p.ParentTarget() + if !ok || leaving { + t.Fatalf("parent in archive: %+v %v %v", tg, leaving, ok) + } + p.Apply(tg, infos("inside", "dir/"), focus, NavPush) + tg, focus, leaving, ok = p.ParentTarget() + if !ok || !leaving || tg.Path != "/data" || focus != "a.zip" || len(tg.Mounts) != 1 { + t.Fatalf("leaving: %+v %q %v %v", tg, focus, leaving, ok) + } + p.Apply(tg, infos("a.zip"), focus, NavPush) + if released != 1 { + t.Fatalf("released %d times", released) + } + if e, _ := p.Selected(); e.Name != "a.zip" { + t.Fatalf("cursor on %q", e.Name) + } + for s, ok := p.BackTarget(); ok; s, ok = p.BackTarget() { + if len(s.Mounts) != 1 { + t.Fatal("history still points into the closed archive") + } + p.Apply(s.Target, infos("a.zip"), s.Focus, NavBack) + } +} + +func TestMirrorAcquires(t *testing.T) { + acquired, released := 0, 0 + base := NewMount(local, "/", nil, "", nil, nil) + remote := NewMount(otherFS{local}, "/", &vfs.Location{FS: local, Path: "/"}, "", func() { released++ }, + func() func() { acquired++; return func() { released++ } }) + a := New(0, Options{}, []Mount{base}, "/") + a.Apply(Target{Mounts: []Mount{base, remote}, Path: "/srv"}, infos("x"), "", NavPush) + b := New(1, Options{}, []Mount{base}, "/") + b.MirrorOf(a, infos("x")) + if acquired != 1 || b.Path() != "/srv" || len(b.Mounts()) != 2 { + t.Fatalf("acquired %d path %s", acquired, b.Path()) + } + a.Close() + if released != 1 { + t.Fatalf("released %d after closing a", released) + } + b.Close() + if released != 2 { + t.Fatalf("released %d after closing b", released) + } +} + +func TestRenderFitsAndMarks(t *testing.T) { + p := newPanel("/d", "alpha", "beta", "gamma", "dir/") + p.SetCursor(2) + p.ToggleMark() + st := style.New(mustPalette(t)) + r := geom.Rect{W: 40, H: 8} + p.SetRows(ListRect(r, false).H) + out := p.Render(View{Rect: r, Active: true, Title: "/d", Styles: st}) + lines := strings.Split(ansi.Strip(out), "\n") + if len(lines) != 8 { + t.Fatalf("%d lines", len(lines)) + } + for _, l := range lines { + if ansi.StringWidth(l) != 40 { + t.Fatalf("line width %d: %q", ansi.StringWidth(l), l) + } + } + if !strings.Contains(lines[4], "* alpha") || !strings.Contains(lines[3], "dir/") { + t.Fatalf("render:\n%s", strings.Join(lines, "\n")) + } + p.SetFilter("et") + out = ansi.Strip(p.Render(View{Rect: r, Active: true, Title: "/d", Styles: st})) + if !strings.Contains(out, "/et") { + t.Fatalf("filter row missing:\n%s", out) + } +} + +func BenchmarkRender20k(b *testing.B) { + var ns []string + for i := 0; i < 20000; i++ { + ns = append(ns, fmt.Sprintf("file-%05d.txt", i)) + } + p := newPanel("/big", ns...) + st := style.New(mustPalette(b)) + r := geom.Rect{W: 100, H: 50} + p.SetRows(ListRect(r, false).H) + b.ResetTimer() + for i := 0; i < b.N; i++ { + p.MoveCursor(1) + _ = p.Render(View{Rect: r, Active: true, Title: "/big", Styles: st}) + } +} + +func mustPalette(t testing.TB) theme.Palette { + pal, err := theme.Resolve("catppuccin-mocha") + if err != nil { + t.Fatal(err) + } + return pal +} + +// otherFS is the local FS posing as another volume (archive, remote). +type otherFS struct{ vfs.FS } + +func (otherFS) Volume() vfs.VolumeID { return "other" } diff --git a/internal/tui/panel/render.go b/internal/tui/panel/render.go new file mode 100644 index 0000000..2399338 --- /dev/null +++ b/internal/tui/panel/render.go @@ -0,0 +1,213 @@ +package panel + +import ( + "fmt" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/geom" + "vcom/internal/tui/style" +) + +// View describes how to draw the panel. +type View struct { + Rect geom.Rect + Active bool + // FilterLine is the filter row content while the filter is edited + // (with the text cursor); "" shows the committed filter, if any. + FilterLine string + Title string // path as the App wants it shown + Styles *style.Styles +} + +func (v View) filterRow(p *Model) bool { return v.FilterLine != "" || p.filter != "" } + +// ListRect is where the rows are inside the panel rectangle r: border, +// title row, optional filter row. Rendering and mouse hit-tests both use it. +func ListRect(r geom.Rect, filterRow bool) geom.Rect { + h := r.H - 3 // borders + title + if filterRow { + h-- + } + return geom.Rect{X: r.X + 1, Y: r.Y + 2, W: max(0, r.W-2), H: max(0, h)} +} + +// ListRectFor is ListRect for the panel's current state. +func (p *Model) ListRectFor(v View) geom.Rect { return ListRect(v.Rect, v.filterRow(p)) } + +type rowKey struct { + gen, styles uint64 + idx int + cursor, active bool + marked bool + width int + showSize, showTm bool +} + +type rowCache struct { + m map[rowKey]string +} + +func (c *rowCache) get(k rowKey, rows int, build func() string) string { + if s, ok := c.m[k]; ok { + return s + } + if c.m == nil || len(c.m) > 4*max(rows, 16) { + c.m = make(map[rowKey]string, 4*max(rows, 16)) + } + s := build() + c.m[k] = s + return s +} + +// Render draws the panel into v.Rect. +func (p *Model) Render(v View) string { + st := v.Styles + r := v.Rect + if r.W < 4 || r.H < 3 { + return "" + } + inner := r.W - 2 + lr := p.ListRectFor(v) // the App keeps p.rows == lr.H via SetRows (View stays pure) + + var b strings.Builder + title := v.Title + if p.Badge != "" { + title += " " + p.Badge + } + if p.Loading { + title += " …" + } + ts := st.PaneTitle + if v.Active { + ts = st.PaneTitleActive + } + b.WriteString(ts.Render(pad(ansi.Truncate(title, inner, "…"), inner))) + for row := 0; row < lr.H; row++ { + b.WriteByte('\n') + i := p.offset + row + if i >= len(p.visible) { + b.WriteString(strings.Repeat(" ", inner)) + continue + } + e := p.entries[p.visible[i]] + k := rowKey{gen: p.gen, styles: st.Gen, idx: i, cursor: i == p.cursor, active: v.Active, + marked: p.marks[e.Name], width: inner, showSize: p.Opts.ShowSize, showTm: p.Opts.ShowTime} + b.WriteString(p.cache.get(k, lr.H, func() string { return p.renderRow(e, k, st) })) + } + if v.filterRow(p) { + b.WriteByte('\n') + line := v.FilterLine + if line == "" { + line = "/" + p.filter + } + b.WriteString(st.FilterLine.Render(pad(ansi.Truncate(line, inner, "…"), inner))) + } + border := st.PaneBorder + if v.Active { + border = st.PaneBorderActive + } + return border.Width(inner).Render(b.String()) +} + +func (p *Model) renderRow(e Entry, k rowKey, st *style.Styles) string { + w := k.width + sizeW, timeW := 0, 0 + if k.showSize && w >= 30 { + sizeW = 8 + } + if k.showTm && w >= 50 { + timeW = 16 + } + nameW := w - 2 - sizeW - timeW + if sizeW > 0 { + nameW-- + } + if timeW > 0 { + nameW-- + } + mark := " " + if k.marked { + mark = "* " + } + name := e.Name + switch e.Cat { + case CatDir, CatLinkDir, CatParent: + name += "/" + } + if e.IsSymlink() { + name = "~" + name + } + line := mark + pad(ansi.Truncate(name, max(1, nameW), "…"), max(1, nameW)) + if sizeW > 0 { + line += " " + fmt.Sprintf("%*s", sizeW, sizeText(e, p.Opts.HumanSize)) + } + if timeW > 0 { + line += " " + timeText(e) + } + line = pad(ansi.Truncate(line, w, ""), w) + var s lipgloss.Style + switch { + case k.cursor && k.active: + return st.RowCursor.Render(line) + case k.cursor: + return st.RowCursorPassive.Render(line) + case k.marked: + s = st.RowMarked + case e.Cat == CatDir || e.Cat == CatLinkDir || e.Cat == CatParent: + s = st.Dir + case e.Cat == CatLink: + s = st.Link + case e.Cat == CatBroken || e.Cat == CatSpecial: + s = st.RowMuted + case e.Cat == CatExec: + s = st.Exec + default: + s = st.Row + } + return s.Render(line) +} + +func sizeText(e Entry, human bool) string { + switch e.Cat { + case CatParent: + return "UP" + case CatDir, CatLinkDir: + return "DIR" + } + if !human { + return fmt.Sprint(e.Size) + } + return HumanSize(e.Size) +} + +// HumanSize formats bytes as 1.2K / 34M. +func HumanSize(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%dB", n) + } + div, exp := int64(unit), 0 + for x := n / unit; x >= unit && exp < 5; x /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f%c", float64(n)/float64(div), "KMGTPE"[exp]) +} + +func timeText(e Entry) string { + if e.Parent || e.ModTime.IsZero() { + return strings.Repeat(" ", 16) + } + return e.ModTime.In(time.Local).Format("2006-01-02 15:04") +} + +func pad(s string, w int) string { + if n := ansi.StringWidth(s); n < w { + return s + strings.Repeat(" ", w-n) + } + return s +}