merge: fast cancel on frozen link; new UI skeleton internal/tui (6.1, --ui=next)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-11-01 09:15:54 +03:00
commit 95406c3d2d
53 changed files with 6528 additions and 20 deletions

View file

@ -1,31 +1,41 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"sync/atomic"
"syscall"
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/config"
"vcom/internal/jobs"
"vcom/internal/logx"
"vcom/internal/paths"
"vcom/internal/ssh/conn"
"vcom/internal/ssh/sshconfig"
"vcom/internal/tui"
"vcom/internal/ui"
)
func main() { os.Exit(run()) }
// run follows design §9.4: flags → log → config (not fatal) → run dir → UI;
// teardown (session, temp files, run dir, log) happens after Program.Run in
// every case: normal quit, signal, or a panic Bubble Tea recovered from.
// teardown (session, jobs, connections, temp files, run dir, log) happens
// after Program.Run in every case: normal quit, signal, or a panic Bubble
// Tea recovered from.
func run() int {
configPath := flag.String("config", "", "path to vcom TOML config")
logLevel := flag.String("log-level", "", "log level: debug, info, warn, error (default warn, or $VCOM_LOG)")
debug := flag.Bool("debug", false, "shorthand for --log-level=debug")
uiFlag := flag.String("ui", "old", "user interface: old (default) or next (the new UI, work in progress)")
flag.Parse()
logger, logErr := openLog(*debug, *logLevel)
@ -59,7 +69,7 @@ func run() int {
for _, w := range info.Warnings {
slog.Warn("config", "warning", w)
}
slog.Info("starting", "config", resolvedPath, "log", logger.Path)
slog.Info("starting", "config", resolvedPath, "log", logger.Path, "ui", *uiFlag)
runDir, err := paths.CreateRunDir()
if err != nil {
@ -72,15 +82,27 @@ func run() int {
}()
}
model, err := ui.NewModel(cfg, resolvedPath)
if err != nil {
slog.Error("startup", "err", err)
fmt.Fprintf(os.Stderr, "startup error: %v\n", err)
return 1
var (
program *tea.Program
teardown func()
)
switch *uiFlag {
case "next":
program, teardown = startNext(cfg, resolvedPath, notice)
case "old", "":
model, err := ui.NewModel(cfg, resolvedPath)
if err != nil {
slog.Error("startup", "err", err)
fmt.Fprintf(os.Stderr, "startup error: %v\n", err)
return 1
}
model = model.WithStatus(notice)
program = tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
teardown = func() {}
default:
fmt.Fprintf(os.Stderr, "vcom: unknown --ui=%s (old or next)\n", *uiFlag)
return 2
}
model = model.WithStatus(notice)
program := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
// SIGTERM/SIGINT are handled by Bubble Tea itself; SIGHUP (terminal
// closed) is not. Do NOT subscribe to SIGTERM here: when our tea.Quit
@ -98,6 +120,7 @@ func run() int {
final, runErr := program.Run()
shutdown(final)
teardown()
switch {
case runErr == nil:
slog.Info("exited cleanly")
@ -128,7 +151,7 @@ func openLog(debug bool, flagLevel string) (*logx.Logger, error) {
}
// shutdown saves the session of the final model (idempotent if the quit key
// already did it).
// already did it). The new UI saves its session in stage 6.6.
func shutdown(final tea.Model) {
switch m := final.(type) {
case ui.Model:
@ -137,3 +160,54 @@ func shutdown(final tea.Model) {
m.Shutdown()
}
}
// startNext wires the new UI (design §9.4): the jobs manager, the SSH
// connection pool and the host resolver go into tui.Deps. The returned
// teardown cancels jobs (giving them 3 s to remove temp files) and closes
// every connection; it runs after Program.Run returns.
func startNext(cfg config.Config, cfgPath, notice string) (*tea.Program, func()) {
var prog atomic.Pointer[tea.Program]
send := func(m tea.Msg) {
if p := prog.Load(); p != nil {
p.Send(m)
}
}
readHome, _ := paths.ReadHome()
deps := tui.DefaultDeps(cfg, cfgPath)
deps.Notice = notice
deps.Jobs = jobs.New(func(e jobs.Event) { send(tui.JobEvent(e)) }, cfg.Transfer.MaxParallelJobs)
pool := conn.NewPool(conn.PoolOptions{
DialOptions: conn.DialOptions{
HandshakeTimeout: cfg.SSH.ConnectTimeout.Duration,
Home: readHome,
Warn: func(m string) { slog.Warn("ssh", "msg", m) },
},
KeepaliveInterval: cfg.SSH.KeepaliveInterval.Duration,
})
deps.Pool = pool
var store *sshconfig.Store
if f, err := paths.DefaultConfigFile(); err == nil {
if s, err := sshconfig.OpenStore(filepath.Dir(f)); err == nil {
store = s
} else {
slog.Warn("hosts store", "err", err)
}
}
res, err := sshconfig.NewResolver(sshconfig.Options{Home: readHome, Store: store})
if err != nil {
slog.Warn("ssh config", "err", err)
}
deps.Resolver = res
p := tea.NewProgram(tui.New(deps), tea.WithAltScreen(), tea.WithMouseCellMotion())
prog.Store(p)
return p, func() {
prog.Store(nil)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := deps.Jobs.Shutdown(ctx); err != nil {
slog.Warn("jobs shutdown", "err", err)
}
pool.Close()
}
}

View file

@ -37,16 +37,23 @@ type rstand struct {
func newRStand(t *testing.T) *rstand {
t.Helper()
home := sshtest.IsolatedHome(t)
s := &rstand{t: t, srv: sshtest.Start(t, sshtest.Options{}), kh: filepath.Join(home, ".ssh", "known_hosts")}
s.trust(s.srv.Addr)
s.pool = conn.NewPool(conn.PoolOptions{
DialOptions: conn.DialOptions{Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh}},
return newRStandWith(t, conn.PoolOptions{
KeepaliveInterval: 100 * time.Millisecond,
KeepaliveTimeout: 100 * time.Millisecond,
KeepaliveMaxMiss: 2,
ReconnectBackoff: []time.Duration{50 * time.Millisecond, 100 * time.Millisecond},
})
}
// newRStandWith uses o (keepalive, backoff); zero values are the pool
// defaults (15 s keepalive).
func newRStandWith(t *testing.T, o conn.PoolOptions) *rstand {
t.Helper()
home := sshtest.IsolatedHome(t)
s := &rstand{t: t, srv: sshtest.Start(t, sshtest.Options{}), kh: filepath.Join(home, ".ssh", "known_hosts")}
s.trust(s.srv.Addr)
o.DialOptions = conn.DialOptions{Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh}}
s.pool = conn.NewPool(o)
t.Cleanup(func() { s.pool.Close() })
return s
}
@ -505,3 +512,110 @@ func TestRemoteFreezeMidFileThenCancel(t *testing.T) {
t.Fatal("old target damaged")
}
}
// freezeCancel runs plan, freezes px once the current file passed 1 MiB and
// cancels 50 ms later; it returns the report and the time from cancel to
// return.
func freezeCancel(t *testing.T, px *sshtest.Proxy, plan *Plan) (Report, time.Duration) {
t.Helper()
ctx, cancel := context.WithCancel(bg)
defer cancel()
var once sync.Once
var mu sync.Mutex
var cancelled time.Time
done := make(chan Report, 1)
go func() {
done <- Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
if p.CurrentDone > 1<<20 {
once.Do(func() {
px.Freeze(true)
time.AfterFunc(50*time.Millisecond, func() {
mu.Lock()
cancelled = time.Now()
mu.Unlock()
cancel()
})
})
}
}})
}()
var rep Report
select {
case rep = <-done:
case <-time.After(20 * time.Second):
t.Fatal("Execute hung after cancel on a frozen link")
}
mu.Lock()
defer mu.Unlock()
if cancelled.IsZero() {
t.Fatal("never cancelled")
}
return rep, time.Since(cancelled)
}
// With the DEFAULT keepalive (15 s × 2 + 10 s) a cancel on a link frozen in
// the middle of a file must return within 3 s: the sftpfs cancel watchdog
// probes the link and tears it down. Upload and download.
func TestRemoteFreezeCancelDefaultKeepalive(t *testing.T) {
for _, dir := range []string{"upload", "download"} {
t.Run(dir, func(t *testing.T) {
s := newRStandWith(t, conn.PoolOptions{})
px := s.proxy()
remote := s.fs(px.Addr, "")
src, dst := t.TempDir(), t.TempDir()
sshtest.WriteRandom(t, filepath.Join(src, "f.bin"), 32<<20, 0o644)
old := sshtest.WriteRandom(t, filepath.Join(dst, "f.bin"), 1<<20, 0o644)
from, to := vfs.FS(local), vfs.FS(remote)
if dir == "download" {
from, to = remote, local
}
px.SetDelay(2 * time.Millisecond) // keep the copy in flight long enough to freeze it
plan := prepare(t, req(Copy, from, join(src, "f.bin"), to, dst, overwrite))
rep, el := freezeCancel(t, px, plan)
px.Freeze(false)
t.Logf("%s: returned %v after cancel, report %+v", dir, el, rep)
if el > 3*time.Second {
t.Errorf("returned %v after cancel, want <= 3s", el)
}
if rep.Done != 0 {
t.Errorf("report = %+v", rep)
}
if now, _ := os.ReadFile(filepath.Join(dst, "f.bin")); !bytes.Equal(now, old) {
t.Fatal("old target damaged")
}
})
}
}
// A slow but live link is not torn down by a cancel: the probe answers.
func TestRemoteSlowLinkCancelKeepsConn(t *testing.T) {
s := newRStandWith(t, conn.PoolOptions{})
px := s.proxy()
remote := s.fs(px.Addr, "")
src, dst := t.TempDir(), t.TempDir()
sshtest.WriteRandom(t, filepath.Join(src, "f.bin"), 8<<20, 0o644)
px.SetDelay(150 * time.Millisecond) // RTT ≈ 300 ms
plan := prepare(t, req(Copy, local, join(src, "f.bin"), remote, dst))
ctx, cancel := context.WithCancel(bg)
defer cancel()
var once sync.Once
rep := Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
if p.CurrentDone > 1<<20 {
once.Do(cancel)
}
}})
if !rep.Cancelled {
t.Errorf("report = %+v", rep)
}
time.Sleep(cancelWatchdogSettle)
if st := remote.Conn().State(); st != conn.Ready {
t.Fatalf("slow but live link torn down by cancel: state %v (%v)", st, remote.Conn().Err())
}
if _, err := remote.Stat(bg, dst); err != nil {
t.Fatalf("conn unusable after cancel: %v", err)
}
noLeftovers(t, dst)
}
// cancelWatchdogSettle covers sftpfs' cancel grace + probe timeout.
const cancelWatchdogSettle = 3 * time.Second

148
internal/tui/actions.go Normal file
View file

@ -0,0 +1,148 @@
package tui
import (
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/keys"
"vcom/internal/tui/notify"
"vcom/internal/tui/panel"
)
// actionDef is the handler of one action.
type actionDef struct {
Run func(a *App) tea.Cmd
// Enabled is checked before Run; an error is shown ("Unavailable: …")
// and Run is skipped. nil means always enabled.
Enabled func(a *App) error
}
// actionTable maps actions to handlers. Features fill it in register_*.go.
type actionTable map[keys.ActionID]actionDef
func (t actionTable) add(id keys.ActionID, run func(*App) tea.Cmd, enabled func(*App) error) {
t[id] = actionDef{Run: run, Enabled: enabled}
}
// dispatch runs action id.
func (a *App) dispatch(id keys.ActionID) tea.Cmd {
def, ok := a.actions[id]
if !ok || def.Run == nil {
return a.notify(notify.Info, a.actionHelp(id)+": not available yet")
}
if def.Enabled != nil {
if err := def.Enabled(a); err != nil {
return a.notify(notify.Warn, "Unavailable: "+err.Error())
}
}
return def.Run(a)
}
func (a *App) actionHelp(id keys.ActionID) string {
for _, ctx := range keys.Contexts() {
for _, s := range a.keys.Help(ctx) {
for _, it := range s.Items {
if it.Action == id {
return it.Help
}
}
}
}
return string(id)
}
// registerCore installs the actions of the 6.1 skeleton.
func registerCore(t actionTable) {
move := func(f func(p *panel.Model)) func(*App) tea.Cmd {
return func(a *App) tea.Cmd {
f(a.Active())
return a.selectionChanged()
}
}
t.add(keys.NavUp, move(func(p *panel.Model) { p.MoveCursor(-1) }), nil)
t.add(keys.NavDown, move(func(p *panel.Model) { p.MoveCursor(1) }), nil)
t.add(keys.NavPageUp, move(func(p *panel.Model) { p.Page(-1, false) }), nil)
t.add(keys.NavPageDown, move(func(p *panel.Model) { p.Page(1, false) }), nil)
t.add(keys.NavHalfUp, move(func(p *panel.Model) { p.Page(-1, true) }), nil)
t.add(keys.NavHalfDown, move(func(p *panel.Model) { p.Page(1, true) }), nil)
t.add(keys.NavHome, move(func(p *panel.Model) { p.SetCursor(0) }), nil)
t.add(keys.NavEnd, move(func(p *panel.Model) { p.SetCursor(p.VisibleLen() - 1) }), nil)
t.add(keys.MarkToggle, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(1) }), nil)
t.add(keys.MarkUp, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(-1) }), nil)
t.add(keys.MarkDown, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(1) }), nil)
t.add(keys.NavOpen, (*App).openSelected, nil)
t.add(keys.NavEnter, (*App).enterSelected, nil)
t.add(keys.NavParent, (*App).goParent, nil)
t.add(keys.NavBack, func(a *App) tea.Cmd { return a.history(false) }, nil)
t.add(keys.NavForward, func(a *App) tea.Cmd { return a.history(true) }, nil)
t.add(keys.PaneSwitch, func(a *App) tea.Cmd {
a.active = 1 - a.active
a.relayout()
return a.selectionChanged()
}, nil)
t.add(keys.PanesReload, func(a *App) tea.Cmd { return tea.Batch(a.reload(0), a.reload(1)) }, nil)
t.add(keys.ToggleHidden, func(a *App) tea.Cmd {
a.deps.Config.Browser.ShowHidden = !a.deps.Config.Browser.ShowHidden
o := a.panelOptions()
for _, p := range a.panels {
p.SetOptions(o)
}
if o.ShowHidden {
return a.notify(notify.Info, "Hidden files shown")
}
return a.notify(notify.Info, "Hidden files hidden")
}, nil)
t.add(keys.BrowseEscape, func(a *App) tea.Cmd { a.escapeLayer(); return a.selectionChanged() }, nil)
t.add(keys.BrowseCtrlC, func(a *App) tea.Cmd {
if a.escapeLayer() {
return a.selectionChanged()
}
return a.askQuit()
}, nil)
t.add(keys.FilterStart, (*App).startFilter, nil)
t.add(keys.ScreenInfo, func(a *App) tea.Cmd { return a.setScreen(ScreenInfo) }, nil)
t.add(keys.InfoClose, func(a *App) tea.Cmd { return a.setScreen(ScreenBrowse) }, nil)
t.add(keys.ScreenView, (*App).openView, nil)
t.add(keys.ThemeSelect, (*App).openThemeSelect, nil)
t.add(keys.HelpShow, (*App).openHelp, nil)
t.add(keys.LogShow, (*App).openLog, nil)
t.add(keys.AppQuit, (*App).askQuit, nil)
// Viewer focus machine (the motions themselves are refined in 6.3).
t.add(keys.ViewerFocus, (*App).viewerFocus, nil)
t.add(keys.ViewerCaret, (*App).viewerCaret, nil)
t.add(keys.ViewerVisual, (*App).viewerVisual, nil)
t.add(keys.ViewerBack, (*App).viewerBack, nil)
t.add(keys.ViewerClose, (*App).viewerClose, nil)
t.add(keys.NativeSelect, (*App).toggleNativeSelect, nil)
t.add(keys.PreviewDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil)
t.add(keys.PreviewUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil)
t.add(keys.ViewerLineUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil)
t.add(keys.ViewerLineDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil)
t.add(keys.ViewerPageUp, func(a *App) tea.Cmd { a.viewer.Page(-1); return nil }, nil)
t.add(keys.ViewerPageDown, func(a *App) tea.Cmd { a.viewer.Page(1); return nil }, nil)
t.add(keys.ViewerTop, func(a *App) tea.Cmd { a.viewer.Jump(false); return nil }, nil)
t.add(keys.ViewerBottom, func(a *App) tea.Cmd { a.viewer.Jump(true); return nil }, nil)
}
// escapeLayer drops the filter, then the marks of the active panel; it
// reports whether something was dropped (Esc never quits).
func (a *App) escapeLayer() bool {
p := a.Active()
if p.Filter() != "" {
p.SetFilter("")
return true
}
return p.ClearMarks()
}
// notify pushes a note and schedules its expiry.
func (a *App) notify(l notify.Level, text string) tea.Cmd {
n := a.notes.Push(l, text, a.now())
id := n.ID
return tea.Tick(notify.TTL(l), func(time.Time) tea.Msg { return noteExpiredMsg{id} })
}
type noteExpiredMsg struct{ id uint64 }

180
internal/tui/app.go Normal file
View file

@ -0,0 +1,180 @@
// Package tui is the new user interface (design §7), enabled with
// --ui=next. The App is a tea.Model with an explicit mode machine (Screen ×
// viewer focus × native selection × filter edit × modal stack); one
// function decides who owns the keyboard (inputOwner), keys resolve through
// the keys.Registry, every async result carries a Ticket and is dropped
// when stale, and View only reads state.
//
// Extension points for stages 6.2–6.6 (each feature in its own files):
// - actions: registerOps/registerViewer/registerSSH/registerArchive/
// registerMisc add handlers to the action table (register_*.go);
// - messages: a.handle(fn) for the feature's own message types;
// - job events: a.onJob(fn) for jobs.Event;
// - key bindings: keys/bindings_<feature>.go;
// - modals: internal/tui/modal.
//
// Rules: Cmd functions never capture *App (only immutable inputs: Target,
// Ticket, options, leases); no file I/O outside vfs.FS (TestImportsGuard).
package tui
import (
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/theme"
"vcom/internal/tui/keys"
"vcom/internal/tui/modal"
"vcom/internal/tui/notify"
"vcom/internal/tui/panel"
"vcom/internal/tui/style"
"vcom/internal/tui/viewer"
)
// Screen is the main screen.
type Screen uint8
const (
ScreenBrowse Screen = iota
ScreenInfo
ScreenView
)
func (s Screen) String() string {
return [...]string{"browse", "info", "view"}[s]
}
// App is the root model.
type App struct {
deps Deps
keys *keys.Registry
styles *style.Styles
theme string
screen Screen
viewBack Screen
panels [2]*panel.Model
active int
filter *textinput.Model // non-nil while the filter line is edited
viewer viewer.Model
nativeSelect bool
modals modal.Stack
notes notify.Center
req Tracker
w, h int
layout Layout
applied effects
actions actionTable
handlers []func(*App, tea.Msg) (tea.Cmd, bool)
jobHooks []func(*App, jobEvent) tea.Cmd
jobSnaps map[uint64]jobSnap
// openFile handles Enter on a non-directory entry; set by stage 6.5
// (archives) and 6.6 (edit / run menu / xdg-open) in their hooks.
openFile func(*App, panel.Entry) tea.Cmd
previewFor string // what the viewer shows / is loading (location + name)
lastClick click
quitting bool
}
type click struct {
at time.Time
pane, row int
}
// New builds the App. Call Init (Bubble Tea does) to load the panels.
func New(d Deps) *App {
d.fill()
a := &App{deps: d, keys: keys.MustDefault(), jobSnaps: map[uint64]jobSnap{}}
a.setTheme(d.Config.UI.Theme)
opts := a.panelOptions()
for i := range a.panels {
m := panel.NewMount(d.LocalFS, "/", nil, "", nil, nil)
a.panels[i] = panel.New(i, opts, []panel.Mount{m}, d.StartDirs[i])
}
a.actions = actionTable{}
registerCore(a.actions)
registerOps(a.actions)
registerViewer(a.actions)
registerSSH(a.actions)
registerArchive(a.actions)
registerMisc(a.actions)
registerOpsHooks(a)
registerViewerHooks(a)
registerSSHHooks(a)
registerArchiveHooks(a)
registerMiscHooks(a)
return a
}
func (a *App) panelOptions() panel.Options {
b := a.deps.Config.Browser
return panel.Options{
ShowHidden: b.ShowHidden,
DirsFirst: b.DirsFirst,
SortBy: b.Sort.By,
Reverse: b.Sort.Reverse,
ShowSize: b.Columns.Size,
ShowTime: b.Columns.Modified,
HumanSize: b.HumanReadableSize,
}
}
// setTheme switches the palette (unknown names fall back to the default).
func (a *App) setTheme(name string) {
p, err := theme.Resolve(name)
if err != nil {
p, _ = theme.Resolve("catppuccin-mocha")
name = p.Name
}
a.theme = name
a.styles = style.New(p)
}
// Init loads both panels.
func (a *App) Init() tea.Cmd {
var cmds []tea.Cmd
if a.deps.Notice != "" {
cmds = append(cmds, a.notify(notify.Warn, a.deps.Notice))
}
for i, p := range a.panels {
cmds = append(cmds, a.navigate(i, p.Here(), "", panel.NavReplace))
}
cmds = append(cmds, a.reconcile())
return tea.Batch(cmds...)
}
// Active returns the active panel.
func (a *App) Active() *panel.Model { return a.panels[a.active] }
// Passive returns the other panel.
func (a *App) Passive() *panel.Model { return a.panels[1-a.active] }
// Panel returns panel i.
func (a *App) Panel(i int) *panel.Model { return a.panels[i] }
// Screen returns the current screen.
func (a *App) Screen() Screen { return a.screen }
// ThemeName is the theme in use.
func (a *App) ThemeName() string { return a.theme }
// Viewer exposes the viewer model (tests, stage 6.3).
func (a *App) Viewer() *viewer.Model { return &a.viewer }
// Quitting reports whether the user confirmed quitting.
func (a *App) Quitting() bool { return a.quitting }
// handle registers a handler for feature messages; it returns true when it
// consumed the message.
func (a *App) handle(fn func(*App, tea.Msg) (tea.Cmd, bool)) { a.handlers = append(a.handlers, fn) }
// onJob registers a job-event hook.
func (a *App) onJob(fn func(*App, jobEvent) tea.Cmd) { a.jobHooks = append(a.jobHooks, fn) }
// now is the clock.
func (a *App) now() time.Time { return a.deps.Clock() }

533
internal/tui/app_test.go Normal file
View file

@ -0,0 +1,533 @@
package tui
import (
"context"
"fmt"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/config"
"vcom/internal/testutil/fstree"
"vcom/internal/testutil/teadriver"
"vcom/internal/tui/keys"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
"vcom/internal/vfs/localfs"
"vcom/internal/vfs/vfstest"
)
const settle = 3 * time.Second
type harness struct {
t *testing.T
d *teadriver.Driver
app *App
dir string
}
type opt func(*Deps)
func newHarness(t *testing.T, fsys vfs.FS, dir string, opts ...opt) *harness {
t.Helper()
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
d := Deps{
Config: cfg,
LocalFS: fsys,
StartDirs: [2]string{dir, dir},
SetConfigKey: func(string, string, string, any) (string, error) { return "test.toml", nil },
}
for _, o := range opts {
o(&d)
}
app := New(d)
h := &harness{t: t, app: app, dir: dir}
h.d = teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(150*time.Millisecond))
h.d.Settle(settle)
h.check()
return h
}
func (h *harness) check() {
h.t.Helper()
if err := h.app.Invariants(); err != nil {
h.t.Fatalf("invariants: %v\n%s", err, h.d.Screen())
}
}
// press sends keys, settling and checking invariants after each.
func (h *harness) press(ks ...string) {
h.t.Helper()
for _, k := range ks {
h.d.Press(k)
h.d.Settle(settle)
h.check()
}
}
func (h *harness) typ(s string) {
h.t.Helper()
h.d.Type(s)
h.d.Settle(settle)
h.check()
}
func (h *harness) selected() string {
e, _ := h.app.Active().Selected()
return e.Name
}
// cursorTo moves the active panel's cursor onto name.
func (h *harness) cursorTo(name string) {
h.t.Helper()
p := h.app.Active()
for i := 0; i < p.VisibleLen(); i++ {
if e, _ := p.Visible(i); e.Name == name {
p.SetCursor(i)
return
}
}
h.t.Fatalf("%s not in panel: %s", name, h.d.Screen())
}
func tree(t *testing.T, spec fstree.Spec) string {
t.Helper()
dir := t.TempDir()
fstree.Build(t, dir, spec)
return dir
}
// gate blocks hooks until released.
type gate struct {
once sync.Once
ch chan struct{}
}
func newGate(t *testing.T) *gate {
g := &gate{ch: make(chan struct{})}
t.Cleanup(g.open)
return g
}
func (g *gate) open() { g.once.Do(func() { close(g.ch) }) }
// N-P1-1, U-P1-9: a hung ReadDir must not block Update; Esc and q work.
func TestUpdateNeverBlocks(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("f", "x")})
g := newGate(t)
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir {
<-g.ch
}
return nil
}}
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
app := New(Deps{Config: cfg, LocalFS: fsys, StartDirs: [2]string{dir, dir}})
d := teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(50*time.Millisecond))
d.Settle(time.Second) // the listings hang
for _, k := range []string{"esc", "j", "tab", "o", "o", "q"} {
start := time.Now()
d.Press(k)
if el := time.Since(start); el > 10*time.Millisecond {
t.Errorf("Update(%s) took %v", k, el)
}
}
if !strings.Contains(d.Screen(), "Quit vcom?") {
t.Fatalf("quit dialog not shown while a listing hangs:\n%s", d.Screen())
}
d.Press("q")
d.Settle(time.Second)
if !d.Quit() {
t.Fatal("q q did not quit while a listing hangs")
}
g.open()
}
// U-P1-13: a listing that arrives after a newer navigation is dropped.
func TestStaleListingIgnored(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("a"), fstree.File("a/in-a", ""), fstree.Dir("b"), fstree.File("b/in-b", "")})
g := newGate(t)
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir && filepath.Base(p) == "a" {
<-g.ch
}
return nil
}}
h := newHarness(t, fsys, dir)
h.cursorTo("a")
h.press("enter") // hangs
if h.app.Active().Path() != dir {
t.Fatal("panel changed before its listing arrived")
}
h.cursorTo("b")
h.press("enter")
if got := h.app.Active().Path(); got != filepath.Join(dir, "b") {
t.Fatalf("path = %s", got)
}
g.open()
h.d.Settle(settle)
if got := h.app.Active().Path(); got != filepath.Join(dir, "b") {
t.Fatalf("stale listing of a applied: path = %s", got)
}
if h.selected() != "in-b" && !h.d.ScreenContains("in-b") {
t.Fatalf("b's content not shown:\n%s", h.d.Screen())
}
}
// U-P1-13: a stale preview (Image) must not knock the viewer out of Caret.
func TestStalePreviewDoesNotExitCaret(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a.txt", "line1\nline2"), fstree.File("b.png", "img")})
g := newGate(t)
prev := func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
if fi.Name == "b.png" {
<-g.ch // ignores ctx on purpose: the result arrives late
return viewer.Content{Kind: viewer.Image, Title: "b.png"}, nil
}
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"line1", "line2"}}, nil
}
h := newHarness(t, localfs.New(), dir, func(d *Deps) { d.Preview = prev })
h.cursorTo("a.txt")
h.press("o")
if h.app.Viewer().Kind != viewer.Text {
t.Fatalf("preview of a.txt not loaded: %v", h.app.Viewer().Kind)
}
h.press("j") // b.png: its preview hangs
h.press("k") // back to a.txt
h.press("i")
if h.app.InputOwner() != keys.CtxCaret {
t.Fatalf("not in caret: %s", h.app.InputOwner())
}
g.open()
h.d.Settle(settle)
h.check()
if h.app.InputOwner() != keys.CtxCaret || h.app.Viewer().Kind != viewer.Text {
t.Fatalf("stale preview changed the viewer: owner %s kind %v", h.app.InputOwner(), h.app.Viewer().Kind)
}
}
func lockedFS(dir string) vfs.FS {
return &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir && filepath.Base(p) == "locked" {
return &os.PathError{Op: "open", Path: p, Err: vfs.ErrPermission}
}
return nil
}}
}
// U-P1-8: a failed navigation leaves the panel as it was.
func TestNavErrorKeepsPanel(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("locked"), fstree.File("other", "")})
h := newHarness(t, lockedFS(dir), dir)
h.cursorTo("locked")
before := h.app.Active().VisibleLen()
h.press("enter")
p := h.app.Active()
if p.Path() != dir || p.VisibleLen() != before || h.selected() != "locked" || p.Loading {
t.Fatalf("panel changed: path %s, %d entries, on %q", p.Path(), p.VisibleLen(), h.selected())
}
}
// U-P1-1: errors are visible in the status line.
func TestStatusLineShowsError(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("locked")})
h := newHarness(t, lockedFS(dir), dir)
h.cursorTo("locked")
h.press("enter")
scr := h.d.Screen()
last := strings.Split(scr, "\n")
status := last[len(last)-2]
if !strings.Contains(status, "Cannot open") || !strings.Contains(status, "permission") {
t.Fatalf("status line = %q", status)
}
// It stays at least until a key is pressed.
h.d.Settle(settle)
if !h.d.ScreenContains("Cannot open") {
t.Fatal("error vanished without a key press")
}
}
// U-P1-8: if the current directory vanishes, a refresh climbs to the
// nearest existing parent.
func TestVanishedDirClimbsUp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("x/y/z"), fstree.File("x/keep", "")})
deep := filepath.Join(dir, "x", "y", "z")
h := newHarness(t, localfs.New(), deep)
if err := os.RemoveAll(filepath.Join(dir, "x", "y")); err != nil {
t.Fatal(err)
}
h.press("ctrl+r")
if got := h.app.Active().Path(); got != filepath.Join(dir, "x") {
t.Fatalf("path = %s, want %s", got, filepath.Join(dir, "x"))
}
if got := h.app.Passive().Path(); got != filepath.Join(dir, "x") {
t.Fatalf("passive path = %s", got)
}
if !h.d.ScreenContains("vanished") {
t.Fatalf("no notice:\n%s", h.d.Screen())
}
}
// U-P1-16: q closes layers first; quitting needs confirmation; q q is fast.
func TestQClosesLayersThenConfirmsQuit(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("apple", ""), fstree.File("banana", "")})
h := newHarness(t, localfs.New(), dir)
h.press("o")
if h.app.Screen() != ScreenInfo {
t.Fatal("o did not open Info")
}
h.press("q")
if h.app.Screen() != ScreenBrowse || h.d.Quit() {
t.Fatal("q in Info did not just close Info")
}
h.press("/")
h.typ("an")
h.press("enter")
if h.app.Active().Filter() != "an" {
t.Fatalf("filter = %q", h.app.Active().Filter())
}
h.press("q")
if h.d.Quit() || !h.d.ScreenContains("Quit vcom?") {
t.Fatal("q in Browse quit without asking")
}
h.press("esc")
if h.d.Quit() || h.d.ScreenContains("Quit vcom?") {
t.Fatal("Esc in the quit dialog did not just close it")
}
h.press("esc") // drops the filter, never quits
if h.app.Active().Filter() != "" || h.d.Quit() {
t.Fatal("Esc did not drop the filter")
}
h.press("q", "q")
if !h.d.Quit() || !h.app.Quitting() {
t.Fatal("q q did not quit")
}
}
// U-P1-6: PgDn moves a page.
func TestPgDn(t *testing.T) {
var spec fstree.Spec
for i := 0; i < 200; i++ {
spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), ""))
}
h := newHarness(t, localfs.New(), tree(t, spec))
rows := h.app.Active().Rows()
if rows < 10 {
t.Fatalf("rows = %d", rows)
}
h.press("pgdown")
if c := h.app.Active().Cursor(); c != rows-1 {
t.Fatalf("cursor after PgDn = %d, want %d", c, rows-1)
}
h.press("pgdown", "pgup")
if c := h.app.Active().Cursor(); c != rows-1 {
t.Fatalf("cursor after PgDn PgUp = %d", c)
}
h.press("G")
if c := h.app.Active().Cursor(); c != 200 { // ".." + 200 files
t.Fatalf("G: cursor %d", c)
}
}
func TestInvariantsAfterEachStep(t *testing.T) {
dir := tree(t, fstree.Spec{
fstree.File("a.txt", "hello\nworld"), fstree.File("b.bin", "\x00\x01"), fstree.Dir("sub"),
fstree.File("sub/c.txt", "c"), fstree.Symlink("link", "sub"),
})
seed := time.Now().UnixNano()
t.Logf("seed %d", seed)
rng := rand.New(rand.NewSource(seed))
pool := []string{"j", "k", "o", "i", "v", "esc", "q", "/", "a", "enter", "tab", "ctrl+t", "f3",
"pgdown", "g", "G", "?", "t", "h", "l", "n", "y", "insert", "ctrl+c", "backspace", "W", "й", "п"}
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
app := New(Deps{Config: cfg, LocalFS: localfs.New(), StartDirs: [2]string{dir, dir},
SetConfigKey: func(string, string, string, any) (string, error) { return "x", nil }})
d := teadriver.New(t, app, 80, 24, teadriver.WithLongCmd(20*time.Millisecond))
d.Settle(settle)
for i := 0; i < 400; i++ {
k := pool[rng.Intn(len(pool))]
d.Press(k)
d.Settle(settle)
if err := app.Invariants(); err != nil {
t.Fatalf("step %d (%q): %v", i, k, err)
}
_ = d.Screen()
}
}
// Design §9.2: the theme is saved with config.SetKey (comments kept).
func TestThemeSelectPreservesConfigComments(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("f", "")})
cfgPath := filepath.Join(t.TempDir(), "vcom.toml")
orig := "# my settings\n[ui]\n# the look\ntheme = \"nord\"\nshow_footer = true\n"
if err := os.WriteFile(cfgPath, []byte(orig), 0o600); err != nil {
t.Fatal(err)
}
h := newHarness(t, localfs.New(), dir, func(d *Deps) {
d.Config.UI.Theme = "nord"
d.ConfigPath = cfgPath
d.SetConfigKey = config.SetKey
})
h.press("t", "down")
next := h.app.ThemeName()
if next == "nord" {
t.Fatal("no live preview")
}
h.press("enter")
data, _ := os.ReadFile(cfgPath)
got := string(data)
if !strings.Contains(got, "theme = \""+next+"\"") || !strings.Contains(got, "# my settings") ||
!strings.Contains(got, "# the look") || !strings.Contains(got, "show_footer = true") {
t.Fatalf("config after save:\n%s", got)
}
// Esc reverts the live preview and writes nothing.
h.press("t", "down", "esc")
if h.app.ThemeName() != next {
t.Fatalf("Esc kept %s", h.app.ThemeName())
}
if data2, _ := os.ReadFile(cfgPath); string(data2) != got {
t.Fatal("Esc wrote the config")
}
}
// Crutch #10/#14: under a modal, the mouse does nothing to the panels.
func TestMouseUnderModalIgnored(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", ""), fstree.File("c", "")})
h := newHarness(t, localfs.New(), dir)
h.press("q")
cur := h.app.Active().Cursor()
lr := h.app.listRect(0)
h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonLeft)
h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonWheelDown)
h.d.Settle(settle)
if h.app.Active().Cursor() != cur || h.app.active != 0 || !h.d.ScreenContains("Quit vcom?") {
t.Fatal("click under the modal acted")
}
}
func TestMarksKeptOnTab(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", "")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("a")
h.press("insert")
h.press("tab", "tab")
if h.app.Active().MarkCount() != 1 || !h.app.Active().Marked("a") {
t.Fatal("marks lost on Tab")
}
h.press("esc")
if h.app.Active().MarkCount() != 0 {
t.Fatal("Esc did not clear marks")
}
}
// U-P1-4 through the App: a click picks the visible row under the mouse.
func TestFilterVisibleIndexAndMouseApp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("abc", ""), fstree.File("bcd", ""), fstree.File("xyz", ""), fstree.File("xbz", "")})
h := newHarness(t, localfs.New(), dir)
h.press("/")
h.typ("b")
h.press("enter")
lr := h.app.listRect(0)
h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft) // third row: "..", abc, bcd
h.d.Settle(settle)
if got := h.selected(); got != "bcd" {
t.Fatalf("clicked %q, want bcd\n%s", got, h.d.Screen())
}
// A double click opens like Enter (here: a file → not available yet, no crash).
h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft)
h.d.Settle(settle)
h.check()
}
// U-P1-5 through the App: Cyrillic goes into the filter as typed.
func TestTextContextPassesRunesApp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("папка"), fstree.File("quit", "")})
h := newHarness(t, localfs.New(), dir)
h.press("/")
h.typ("папка")
if got := h.app.Active().Filter(); got != "папка" {
t.Fatalf("filter = %q", got)
}
h.press("enter")
h.press("/")
h.typ("q") // a letter here, not quit
if h.d.Quit() || h.d.ScreenContains("Quit vcom?") {
t.Fatal("q in the filter line acted as a command")
}
}
func TestNavigationHistoryAndParent(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("sub/deeper"), fstree.File("top", "")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("sub")
h.press("l")
h.cursorTo("deeper")
h.press("enter")
if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") {
t.Fatal("enter failed")
}
h.press("h")
if h.app.Active().Path() != filepath.Join(dir, "sub") || h.selected() != "deeper" {
t.Fatalf("parent: %s on %q", h.app.Active().Path(), h.selected())
}
h.press("[")
if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") {
t.Fatalf("back: %s", h.app.Active().Path())
}
h.press("]")
if h.app.Active().Path() != filepath.Join(dir, "sub") {
t.Fatalf("forward: %s", h.app.Active().Path())
}
h.press("?")
if !h.d.ScreenContains("Help") || !h.d.ScreenContains("history back") {
t.Fatalf("help:\n%s", h.d.Screen())
}
h.press("esc")
h.press("f5") // not implemented in 6.1: a note, no crash
if !h.d.ScreenContains("not available yet") {
t.Fatalf("no note for an unimplemented action:\n%s", h.d.Screen())
}
}
func TestViewScreenAndBack(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a.txt", "one\ntwo\nthree"), fstree.Dir("d")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("d")
h.press("f3")
if h.app.Screen() != ScreenBrowse {
t.Fatal("F3 on a directory opened View")
}
h.cursorTo("a.txt")
h.press("f3")
if h.app.Screen() != ScreenView || !h.d.ScreenContains("three") {
t.Fatalf("View:\n%s", h.d.Screen())
}
h.press("i", "v")
if h.app.InputOwner() != keys.CtxVisual {
t.Fatalf("owner %s", h.app.InputOwner())
}
h.press("esc", "esc")
if h.app.InputOwner() != keys.CtxViewScroll {
t.Fatalf("owner %s", h.app.InputOwner())
}
h.press("ctrl+t")
if !h.app.nativeSelect {
t.Fatal("ctrl+t")
}
h.press("esc")
if h.app.nativeSelect || h.app.Screen() != ScreenView {
t.Fatal("Esc must end native selection first")
}
h.press("q")
if h.app.Screen() != ScreenBrowse {
t.Fatal("q did not close View")
}
}

124
internal/tui/deps.go Normal file
View file

@ -0,0 +1,124 @@
package tui
import (
"context"
"io"
"os"
"strings"
"time"
"unicode/utf8"
"vcom/internal/config"
"vcom/internal/jobs"
"vcom/internal/ssh/conn"
"vcom/internal/ssh/sshconfig"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
"vcom/internal/vfs/localfs"
)
// PreviewFunc builds the preview of an entry. Stage 5B/6.3 plug
// preview.Build in here; the default reads the head of text files.
type PreviewFunc func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error)
// Deps are the App's outside world. Everything the UI touches goes through
// them, so tests substitute fakes (FaultFS, a fixed clock, a fake preview).
// This file and external.go are the only ones in internal/tui allowed to
// import os (TestImportsGuard).
type Deps struct {
Config config.Config
ConfigPath string // file the theme choice is written to ("" = default XDG path)
// SetConfigKey edits one key of the config file (default config.SetKey).
SetConfigKey func(path, section, key string, value any) (string, error)
LocalFS vfs.FS
StartDirs [2]string // initial directories of the left and right panel
Jobs *jobs.Manager
Pool *conn.Pool
Resolver *sshconfig.Resolver
Preview PreviewFunc
Clock func() time.Time
// Notice is shown in the status line at start (config warnings).
Notice string
}
// DefaultDeps fills Deps for the real program.
func DefaultDeps(cfg config.Config, configPath string) Deps {
wd, err := os.Getwd()
if err != nil {
wd, _ = os.UserHomeDir()
}
left, right := wd, wd
if cfg.Startup.LeftPath != "" {
left = expandHome(cfg.Startup.LeftPath)
}
if cfg.Startup.RightPath != "" {
right = expandHome(cfg.Startup.RightPath)
}
return Deps{
Config: cfg,
ConfigPath: configPath,
LocalFS: localfs.New(),
StartDirs: [2]string{left, right},
}
}
func expandHome(p string) string {
if p == "~" || strings.HasPrefix(p, "~/") {
if h, err := os.UserHomeDir(); err == nil {
return h + p[1:]
}
}
return p
}
func (d *Deps) fill() {
if d.SetConfigKey == nil {
d.SetConfigKey = config.SetKey
}
if d.Clock == nil {
d.Clock = time.Now
}
if d.Preview == nil {
d.Preview = defaultPreview
}
if d.LocalFS == nil {
d.LocalFS = localfs.New()
}
for i, p := range d.StartDirs {
if p == "" {
d.StartDirs[i] = "/"
}
}
}
// defaultPreview shows the head of a text file, metadata otherwise.
func defaultPreview(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error) {
p := loc.FS.Paths().Join(loc.Path, fi.Name)
meta := viewer.Content{Kind: viewer.Other, Title: fi.Name, Lines: []string{
fi.Name,
fi.Mode.String(),
fi.ModTime.Format("2006-01-02 15:04:05"),
}}
if !fi.IsRegularLike() {
return meta, nil
}
if maxBytes <= 0 {
maxBytes = 64 << 10
}
f, err := loc.FS.Open(ctx, p)
if err != nil {
return viewer.Content{}, err
}
defer f.Close()
buf, err := io.ReadAll(io.LimitReader(f, maxBytes))
if err != nil {
return viewer.Content{}, err
}
if !utf8.Valid(buf) || strings.ContainsRune(string(buf), 0) {
return meta, nil
}
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: strings.Split(strings.TrimRight(string(buf), "\n"), "\n")}, nil
}

44
internal/tui/effects.go Normal file
View file

@ -0,0 +1,44 @@
package tui
import tea "github.com/charmbracelet/bubbletea"
// Terminal side effects (mouse mode, image overlay) are not done in View or
// scattered in handlers: after every Update the desired state is compared
// with what was applied and one command fixes the difference (design §7.9).
const (
mouseUnknown int8 = iota
mouseOn
mouseOff
)
type effects struct {
mouse int8
// overlay: imgview.Desired once stage 5C/6.3 lands.
}
type desiredEffects struct {
Mouse bool
}
func (a *App) desired() desiredEffects {
return desiredEffects{Mouse: !a.nativeSelect}
}
// reconcile returns the command that brings the terminal to the desired
// state, or nil.
func (a *App) reconcile() tea.Cmd {
d := a.desired()
want := mouseOff
if d.Mouse {
want = mouseOn
}
if a.applied.mouse == want {
return nil
}
a.applied.mouse = want
if want == mouseOn {
return tea.EnableMouseCellMotion
}
return tea.DisableMouse
}

20
internal/tui/geom/geom.go Normal file
View file

@ -0,0 +1,20 @@
// Package geom holds the screen rectangles shared by layout, rendering and
// mouse hit-testing (one source of truth: design §7.3).
package geom
// Rect is a cell rectangle; W or H of 0 means empty.
type Rect struct{ X, Y, W, H int }
// Contains reports whether cell (x, y) is inside r.
func (r Rect) Contains(x, y int) bool {
return x >= r.X && x < r.X+r.W && y >= r.Y && y < r.Y+r.H
}
// Empty reports whether r has no cells.
func (r Rect) Empty() bool { return r.W <= 0 || r.H <= 0 }
// Center returns a w×h rectangle centered in r (clamped to r).
func (r Rect) Center(w, h int) Rect {
w, h = min(w, r.W), min(h, r.H)
return Rect{X: r.X + (r.W-w)/2, Y: r.Y + (r.H-h)/2, W: w, H: h}
}

61
internal/tui/help.go Normal file
View file

@ -0,0 +1,61 @@
package tui
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/keys"
"vcom/internal/tui/modal"
)
// openHelp shows the bindings of the context that owned input, generated
// from the registry (design §7.4).
func (a *App) openHelp() tea.Cmd {
ctx := a.inputOwner()
var lines []string
for i, s := range a.keys.Help(ctx) {
if i > 0 {
lines = append(lines, "")
}
lines = append(lines, "── "+s.Title+" ──")
w := 0
for _, it := range s.Items {
w = max(w, ansi.StringWidth(it.Keys))
}
for _, it := range s.Items {
lines = append(lines, fmt.Sprintf(" %s%s %s", it.Keys, strings.Repeat(" ", w-ansi.StringWidth(it.Keys)), it.Help))
}
}
a.openModal(modal.NewText("Help: "+contextTitle(ctx), lines), nil)
return nil
}
func contextTitle(c keys.Context) string {
switch c {
case keys.CtxBrowse:
return "panels"
case keys.CtxInfo:
return "info"
case keys.CtxViewScroll:
return "viewer"
}
return c.String()
}
// openLog is "L": the message log, newest last.
func (a *App) openLog() tea.Cmd {
var lines []string
for _, n := range a.notes.Log() {
lines = append(lines, fmt.Sprintf("%s %-5s %s", n.At.Format("15:04:05"), n.Level, n.Text))
}
if len(lines) == 0 {
lines = []string{"(no messages)"}
}
l := modal.NewText("Messages", lines)
a.openModal(l, nil)
l.Key(keys.ModalEnd, tea.KeyMsg{})
return nil
}

View file

@ -0,0 +1,119 @@
package tui
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
)
// forbidden imports in internal/tui/** (design §7.13): the UI reaches files
// only through vfs.FS, so "forgot the remote case" cannot compile.
var forbidden = map[string]bool{
"os": true,
"os/exec": true,
"io/fs": true,
"path/filepath": true,
"syscall": true,
"vcom/internal/vfs/localfs": true,
"github.com/pkg/sftp": true,
"vcom/internal/fs": true,
"vcom/internal/fs/remote": true,
"vcom/internal/ui": true,
"vcom/internal/homedir": true,
"github.com/atotto/clipboard": false, // allowed (clipboard.go, stage 6.3)
}
// allowed files (relative to internal/tui): factories and external programs.
var importAllow = map[string]bool{
"deps.go": true,
"external.go": true,
}
func goFiles(t *testing.T) []string {
t.Helper()
var out []string
err := filepath.Walk(".", func(p string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if !fi.IsDir() && strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, "_test.go") {
out = append(out, p)
}
return nil
})
if err != nil {
t.Fatal(err)
}
return out
}
func TestImportsGuard(t *testing.T) {
fset := token.NewFileSet()
files := goFiles(t)
if len(files) < 10 {
t.Fatalf("only %d files found", len(files))
}
for _, p := range files {
f, err := parser.ParseFile(fset, p, nil, parser.ImportsOnly)
if err != nil {
t.Fatal(err)
}
for _, imp := range f.Imports {
path, _ := strconv.Unquote(imp.Path.Value)
if forbidden[path] && !importAllow[filepath.ToSlash(p)] {
t.Errorf("%s imports %s: go through vfs.FS / Deps instead", p, path)
}
}
}
}
// Design §7.4: key strings are compared only in internal/tui/keys; elsewhere
// keys are resolved to actions.
func TestNoRawKeyMatching(t *testing.T) {
fset := token.NewFileSet()
for _, p := range goFiles(t) {
if strings.HasPrefix(filepath.ToSlash(p), "keys/") {
continue
}
f, err := parser.ParseFile(fset, p, nil, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.BinaryExpr:
if x.Op == token.EQL || x.Op == token.NEQ {
if isStringCall(x.X) && isStringLit(x.Y) || isStringCall(x.Y) && isStringLit(x.X) {
t.Errorf("%s: msg.String() compared with a literal; use keys.Registry", fset.Position(x.Pos()))
}
}
case *ast.CallExpr:
if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Matches" {
if id, ok := sel.X.(*ast.Ident); ok && id.Name == "key" {
t.Errorf("%s: key.Matches; use keys.Registry", fset.Position(x.Pos()))
}
}
}
return true
})
}
}
func isStringCall(e ast.Expr) bool {
c, ok := e.(*ast.CallExpr)
if !ok || len(c.Args) != 0 {
return false
}
sel, ok := c.Fun.(*ast.SelectorExpr)
return ok && sel.Sel.Name == "String"
}
func isStringLit(e ast.Expr) bool {
b, ok := e.(*ast.BasicLit)
return ok && b.Kind == token.STRING
}

87
internal/tui/jobs.go Normal file
View file

@ -0,0 +1,87 @@
package tui
import (
"fmt"
"sort"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/jobs"
"vcom/internal/tui/notify"
)
// JobEvent wraps a jobs.Event for the program: main passes
// func(e jobs.Event) { program.Send(tui.JobEvent(e)) } as the jobs notify
// callback.
func JobEvent(e jobs.Event) tea.Msg { return jobEventMsg{E: e} }
type jobEventMsg struct{ E jobs.Event }
// jobEvent is what feature hooks receive.
type jobEvent = jobEventMsg
type jobSnap = jobs.Snapshot
// onJobEvent keeps snapshots for the status line and runs feature hooks
// (stage 6.2 opens progress/conflict modals there). Without a hook a
// finished job is reported in the status line.
func (a *App) onJobEvent(m jobEventMsg) tea.Cmd {
var cmds []tea.Cmd
switch e := m.E.(type) {
case jobs.Started:
a.jobSnaps[uint64(e.Snapshot.ID)] = e.Snapshot
case jobs.ProgressTick:
for _, s := range e.Snapshots {
a.jobSnaps[uint64(s.ID)] = s
}
case jobs.Finished:
delete(a.jobSnaps, uint64(e.Snapshot.ID))
if len(a.jobHooks) == 0 {
cmds = append(cmds, a.reportJob(e.Snapshot))
}
case jobs.Asked:
if len(a.jobHooks) == 0 {
cmds = append(cmds, a.notify(notify.Warn, fmt.Sprintf("Job %q is waiting for an answer", a.jobTitle(e.Question.Job))))
}
}
for _, h := range a.jobHooks {
cmds = append(cmds, h(a, m))
}
return tea.Batch(cmds...)
}
func (a *App) jobTitle(id jobs.ID) string {
if s, ok := a.jobSnaps[uint64(id)]; ok {
return s.Title
}
return fmt.Sprint(id)
}
func (a *App) reportJob(s jobs.Snapshot) tea.Cmd {
switch s.State {
case jobs.Done:
return a.notify(notify.Success, s.Title+": done")
case jobs.Cancelled:
return a.notify(notify.Warn, s.Title+": cancelled")
default:
return a.notify(notify.Error, fmt.Sprintf("%s: %v", s.Title, s.Err))
}
}
// activeJobs returns running/queued snapshots by ID.
func (a *App) activeJobs() []jobs.Snapshot {
out := make([]jobs.Snapshot, 0, len(a.jobSnaps))
for _, s := range a.jobSnaps {
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// activeJobCount prefers the manager (authoritative) over snapshots.
func (a *App) activeJobCount() int {
if a.deps.Jobs != nil {
return a.deps.Jobs.Active()
}
return len(a.jobSnaps)
}

View file

@ -0,0 +1,4 @@
package keys
// archiveBindings holds the extra bindings of archives (stage 6.5).
func archiveBindings() []Binding { return nil }

View file

@ -0,0 +1,139 @@
package keys
// Browse/Info actions (design §8.1).
const (
NavUp ActionID = "nav.up"
NavDown ActionID = "nav.down"
NavPageUp ActionID = "nav.pageUp"
NavPageDown ActionID = "nav.pageDown"
NavHalfUp ActionID = "nav.halfUp"
NavHalfDown ActionID = "nav.halfDown"
NavHome ActionID = "nav.home"
NavEnd ActionID = "nav.end"
NavOpen ActionID = "nav.open" // Enter: dispatch by entry type
NavEnter ActionID = "nav.enter" // l/→: enter directory or archive
NavParent ActionID = "nav.parent" // h/←/Backspace
NavBack ActionID = "nav.back"
NavForward ActionID = "nav.forward"
PaneSwitch ActionID = "pane.switch"
PaneMirror ActionID = "pane.mirror"
PanesReload ActionID = "panes.reload"
MarkToggle ActionID = "mark.toggle" // Insert: mark and move down
MarkUp ActionID = "mark.up"
MarkDown ActionID = "mark.down"
BrowseEscape ActionID = "browse.escape" // Esc: drop filter, then marks
BrowseCtrlC ActionID = "browse.ctrlC" // like Esc; quits from a clean Browse
DirSize ActionID = "dir.size"
FilterStart ActionID = "filter.start"
ToggleHidden ActionID = "view.hidden"
SortMenu ActionID = "sort.menu"
ScreenInfo ActionID = "screen.info"
ScreenView ActionID = "screen.view"
FileRename ActionID = "file.rename"
FileEdit ActionID = "file.edit"
FileCopy ActionID = "file.copy"
FileMove ActionID = "file.move"
FileMkdir ActionID = "file.mkdir"
FileTrash ActionID = "file.trash"
FileDelete ActionID = "file.delete" // permanent
ArchiveNew ActionID = "archive.create"
ArchiveUnzip ActionID = "archive.extract"
PathYank ActionID = "path.yank"
SSHHosts ActionID = "ssh.hosts"
ThemeSelect ActionID = "theme.select"
JobsList ActionID = "jobs.list"
LogShow ActionID = "log.show"
HelpShow ActionID = "help.show"
AppQuit ActionID = "app.quit"
// Info only.
ViewerFocus ActionID = "viewer.focus"
PreviewDown ActionID = "preview.scrollDown"
PreviewUp ActionID = "preview.scrollUp"
NativeSelect ActionID = "viewer.nativeSelect"
InfoClose ActionID = "screen.infoClose"
FilterCommit ActionID = "filter.commit"
FilterCancel ActionID = "filter.cancel"
FilterClearAll ActionID = "filter.clear"
)
// browseCommon is shared by Browse and Info (Info adds its own keys and
// closes on q/Esc instead of quitting).
func browseCommon() []Binding {
return []Binding{
{Action: NavUp, Keys: []string{"up", "k"}, Help: "cursor up", Group: "Navigation"},
{Action: NavDown, Keys: []string{"down", "j"}, Help: "cursor down", Group: "Navigation"},
{Action: NavPageUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "Navigation"},
{Action: NavPageDown, Keys: []string{"pgdown", "ctrl+f"}, Help: "page down", Group: "Navigation"},
{Action: NavHalfUp, Keys: []string{"ctrl+u"}, Help: "half page up", Group: "Navigation"},
{Action: NavHalfDown, Keys: []string{"ctrl+d"}, Help: "half page down", Group: "Navigation"},
{Action: NavHome, Keys: []string{"home", "g"}, Help: "first entry", Group: "Navigation"},
{Action: NavEnd, Keys: []string{"end", "G"}, Help: "last entry", Group: "Navigation"},
{Action: NavOpen, Keys: []string{"enter"}, Help: "open", Group: "Navigation", Footer: true},
{Action: NavEnter, Keys: []string{"right", "l"}, Help: "enter directory", Group: "Navigation"},
{Action: NavParent, Keys: []string{"left", "h", "backspace"}, Help: "parent directory", Group: "Navigation"},
{Action: NavBack, Keys: []string{"alt+left", "["}, Help: "history back", Group: "Navigation"},
{Action: NavForward, Keys: []string{"alt+right", "]"}, Help: "history forward", Group: "Navigation"},
{Action: PaneSwitch, Keys: []string{"tab"}, Help: "switch pane", Group: "Panels", Footer: true},
{Action: PaneMirror, Keys: []string{"p"}, Help: "mirror: other pane to this place", Group: "Panels"},
{Action: PanesReload, Keys: []string{"ctrl+r"}, Help: "reload panes", Group: "Panels"},
{Action: MarkToggle, Keys: []string{"insert"}, Help: "mark and move down", Group: "Marks"},
{Action: MarkUp, Keys: []string{"shift+up", "K"}, Help: "mark moving up", Group: "Marks"},
{Action: MarkDown, Keys: []string{"shift+down", "J"}, Help: "mark moving down", Group: "Marks"},
{Action: DirSize, Keys: []string{" "}, Help: "directory size", Group: "Files"},
{Action: FilterStart, Keys: []string{"/"}, Help: "filter", Group: "Panels", Footer: true},
{Action: ToggleHidden, Keys: []string{"."}, Help: "show hidden files", Group: "Panels"},
{Action: SortMenu, Keys: []string{"S"}, Help: "sort menu", Group: "Panels"},
{Action: ScreenView, Keys: []string{"f3", "v"}, Help: "view file", Group: "Files", Footer: true},
{Action: FileRename, Keys: []string{"f2", "r"}, Help: "rename", Group: "Files"},
{Action: FileEdit, Keys: []string{"f4"}, Help: "edit", Group: "Files", Footer: true},
{Action: FileCopy, Keys: []string{"f5", "c"}, Help: "copy", Group: "Files", Footer: true},
{Action: FileMove, Keys: []string{"f6", "m"}, Help: "move", Group: "Files", Footer: true},
{Action: FileMkdir, Keys: []string{"f7", "n"}, Help: "make directory", Group: "Files", Footer: true},
{Action: FileTrash, Keys: []string{"f8", "delete", "x"}, Help: "move to trash", Group: "Files", Footer: true},
{Action: FileDelete, Keys: []string{"f20", "X"}, Help: "delete permanently", Group: "Files"},
{Action: ArchiveNew, Keys: []string{"a"}, Help: "create archive", Group: "Files"},
{Action: ArchiveUnzip, Keys: []string{"e", "f11"}, Help: "extract archive", Group: "Files"},
{Action: PathYank, Keys: []string{"y"}, Help: "copy path to clipboard", Group: "Files"},
{Action: SSHHosts, Keys: []string{"s", "f12"}, Help: "SSH hosts", Group: "Panels"},
{Action: ThemeSelect, Keys: []string{"t"}, Help: "choose theme", Group: "Other"},
{Action: JobsList, Keys: []string{"B"}, Help: "background jobs", Group: "Other"},
{Action: LogShow, Keys: []string{"L"}, Help: "message log", Group: "Other"},
{Action: HelpShow, Keys: []string{"f1", "?"}, Help: "help", Group: "Other", Footer: true},
}
}
func browseBindings() []Binding {
var out []Binding
for _, b := range browseCommon() {
b.Context = CtxBrowse
out = append(out, b)
}
out = append(out,
Binding{Context: CtxBrowse, Action: BrowseEscape, Keys: []string{"esc"}, Help: "clear filter, then marks", Group: "Marks"},
Binding{Context: CtxBrowse, Action: BrowseCtrlC, Keys: []string{"ctrl+c"}},
Binding{Context: CtxBrowse, Action: ScreenInfo, Keys: []string{"o", "f9"}, Help: "info / preview", Group: "Panels", Footer: true},
Binding{Context: CtxBrowse, Action: AppQuit, Keys: []string{"q", "f10"}, Help: "quit", Group: "Other", Footer: true},
)
for _, b := range browseCommon() {
b.Context = CtxInfo
b.Footer = false
out = append(out, b)
}
out = append(out,
Binding{Context: CtxInfo, Action: InfoClose, Keys: []string{"o", "f9", "q", "f10", "esc", "ctrl+c"}, Help: "close info", Group: "Info", Footer: true},
Binding{Context: CtxInfo, Action: ViewerFocus, Keys: []string{"i"}, Help: "cursor in preview", Group: "Info", Footer: true},
Binding{Context: CtxInfo, Action: PreviewDown, Keys: []string{"ctrl+e"}, Help: "scroll preview down", Group: "Info"},
Binding{Context: CtxInfo, Action: PreviewUp, Keys: []string{"ctrl+y"}, Help: "scroll preview up", Group: "Info"},
Binding{Context: CtxInfo, Action: NativeSelect, Keys: []string{"ctrl+t"}, Help: "select with the terminal mouse", Group: "Info"},
)
// Filter line (text context): only control keys.
out = append(out,
Binding{Context: CtxFilterEdit, Action: FilterCommit, Keys: []string{"enter"}, Help: "keep filter", Group: "Filter", Footer: true},
Binding{Context: CtxFilterEdit, Action: FilterCancel, Keys: []string{"esc", "ctrl+c"}, Help: "drop filter", Group: "Filter", Footer: true},
Binding{Context: CtxFilterEdit, Action: FilterClearAll, Keys: []string{"ctrl+u"}, Help: "clear text", Group: "Filter"},
Binding{Context: CtxFilterEdit, Action: NavUp, Keys: []string{"up"}, Help: "cursor up", Group: "Filter"},
Binding{Context: CtxFilterEdit, Action: NavDown, Keys: []string{"down"}, Help: "cursor down", Group: "Filter"},
)
return out
}

View file

@ -0,0 +1,4 @@
package keys
// miscBindings holds the extra bindings of stage 6.6 (sort menu, run menu).
func miscBindings() []Binding { return nil }

View file

@ -0,0 +1,42 @@
package keys
// Actions shared by modal contexts (design §8.4). Dialog button hotkeys are
// not in the table: a Dialog matches them itself (see Translate).
const (
ModalConfirm ActionID = "modal.confirm"
ModalCancel ActionID = "modal.cancel"
ModalNext ActionID = "modal.next"
ModalPrev ActionID = "modal.prev"
ModalUp ActionID = "modal.up"
ModalDown ActionID = "modal.down"
ModalPgUp ActionID = "modal.pageUp"
ModalPgDown ActionID = "modal.pageDown"
ModalHome ActionID = "modal.home"
ModalEnd ActionID = "modal.end"
ModalClear ActionID = "modal.clear"
)
func modalBindings() []Binding {
d, in, l := CtxModalDialog, CtxModalInput, CtxModalList
return []Binding{
{Context: d, Action: ModalConfirm, Keys: []string{"enter"}, Help: "press focused button", Group: "Dialog", Footer: true},
{Context: d, Action: ModalNext, Keys: []string{"tab", "right", "l"}, Help: "next button", Group: "Dialog"},
{Context: d, Action: ModalPrev, Keys: []string{"shift+tab", "left", "h"}, Help: "previous button", Group: "Dialog"},
{Context: d, Action: ModalCancel, Keys: []string{"esc", "ctrl+c", "q"}, Help: "cancel", Group: "Dialog", Footer: true},
{Context: in, Action: ModalConfirm, Keys: []string{"enter"}, Help: "OK", Group: "Input", Footer: true},
{Context: in, Action: ModalCancel, Keys: []string{"esc", "ctrl+c"}, Help: "cancel", Group: "Input", Footer: true},
{Context: in, Action: ModalNext, Keys: []string{"tab", "down"}, Help: "next field", Group: "Input"},
{Context: in, Action: ModalPrev, Keys: []string{"shift+tab", "up"}, Help: "previous field", Group: "Input"},
{Context: in, Action: ModalClear, Keys: []string{"ctrl+u"}, Help: "clear field", Group: "Input"},
{Context: l, Action: ModalUp, Keys: []string{"up", "k"}, Help: "up", Group: "List"},
{Context: l, Action: ModalDown, Keys: []string{"down", "j"}, Help: "down", Group: "List"},
{Context: l, Action: ModalPgUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "List"},
{Context: l, Action: ModalPgDown, Keys: []string{"pgdown", "ctrl+f", " "}, Help: "page down", Group: "List"},
{Context: l, Action: ModalHome, Keys: []string{"home", "g"}, Help: "first", Group: "List"},
{Context: l, Action: ModalEnd, Keys: []string{"end", "G"}, Help: "last", Group: "List"},
{Context: l, Action: ModalConfirm, Keys: []string{"enter"}, Help: "choose", Group: "List", Footer: true},
{Context: l, Action: ModalCancel, Keys: []string{"esc", "q", "ctrl+c", "f1", "?"}, Help: "close", Group: "List", Footer: true},
}
}

View file

@ -0,0 +1,5 @@
package keys
// opsBindings holds the extra bindings of file operations (stage 6.2:
// progress and conflict modals). Browse keys live in bindings_browse.go.
func opsBindings() []Binding { return nil }

View file

@ -0,0 +1,5 @@
package keys
// sshBindings holds the extra bindings of SSH (stage 6.4: host list,
// prompts). Browse keys live in bindings_browse.go.
func sshBindings() []Binding { return nil }

View file

@ -0,0 +1,54 @@
package keys
// Viewer actions (design §8.2). Stage 6.1 binds scrolling and the focus
// transitions; stage 6.3 adds the caret/visual motions (w/b/e, 0/^/$, ...)
// to this file.
const (
ViewerLineUp ActionID = "viewer.lineUp"
ViewerLineDown ActionID = "viewer.lineDown"
ViewerPageUp ActionID = "viewer.pageUp"
ViewerPageDown ActionID = "viewer.pageDown"
ViewerTop ActionID = "viewer.top"
ViewerBottom ActionID = "viewer.bottom"
ViewerCaret ActionID = "viewer.caret"
ViewerVisual ActionID = "viewer.visual"
ViewerYank ActionID = "viewer.yank"
ViewerYankLine ActionID = "viewer.yankLine"
ViewerWrap ActionID = "viewer.wrap"
ViewerBack ActionID = "viewer.back" // Esc: one focus step back
ViewerClose ActionID = "viewer.close" // q/F3: close View / unfocus Info
)
func viewerBindings() []Binding {
motion := func(ctx Context) []Binding {
return []Binding{
{Context: ctx, Action: ViewerLineUp, Keys: []string{"up", "k"}, Help: "up", Group: "Viewer"},
{Context: ctx, Action: ViewerLineDown, Keys: []string{"down", "j"}, Help: "down", Group: "Viewer"},
{Context: ctx, Action: ViewerPageUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "Viewer"},
{Context: ctx, Action: ViewerPageDown, Keys: []string{"pgdown", "ctrl+f"}, Help: "page down", Group: "Viewer"},
{Context: ctx, Action: ViewerTop, Keys: []string{"home", "g"}, Help: "top", Group: "Viewer"},
{Context: ctx, Action: ViewerBottom, Keys: []string{"end", "G"}, Help: "bottom", Group: "Viewer"},
{Context: ctx, Action: ViewerWrap, Keys: []string{"W"}, Help: "wrap lines", Group: "Viewer"},
{Context: ctx, Action: NativeSelect, Keys: []string{"ctrl+t"}, Help: "select with the terminal mouse", Group: "Viewer"},
{Context: ctx, Action: ViewerBack, Keys: []string{"esc"}, Help: "back", Group: "Viewer", Footer: true},
{Context: ctx, Action: ViewerClose, Keys: []string{"q", "f3", "ctrl+c"}, Help: "close", Group: "Viewer", Footer: true},
}
}
var out []Binding
out = append(out, motion(CtxViewScroll)...)
out = append(out,
Binding{Context: CtxViewScroll, Action: ViewerCaret, Keys: []string{"i"}, Help: "cursor mode", Group: "Viewer", Footer: true},
Binding{Context: CtxViewScroll, Action: ViewerVisual, Keys: []string{"v"}, Help: "visual selection", Group: "Viewer"},
)
out = append(out, motion(CtxCaret)...)
out = append(out,
Binding{Context: CtxCaret, Action: ViewerVisual, Keys: []string{"v"}, Help: "visual selection", Group: "Viewer", Footer: true},
Binding{Context: CtxCaret, Action: ViewerYankLine, Keys: []string{"y y"}, Help: "copy line", Group: "Viewer", Footer: true},
)
out = append(out, motion(CtxVisual)...)
out = append(out,
Binding{Context: CtxVisual, Action: ViewerCaret, Keys: []string{"v"}, Help: "end selection", Group: "Viewer"},
Binding{Context: CtxVisual, Action: ViewerYank, Keys: []string{"y"}, Help: "copy selection", Group: "Viewer", Footer: true},
)
return out
}

View file

@ -0,0 +1,34 @@
package keys
import "unicode"
// DefaultBindings collects the bindings of every feature file. Features add
// their own bindings_<feature>.go so parallel work does not touch one file.
func DefaultBindings() []Binding {
var out []Binding
for _, part := range [][]Binding{
browseBindings(), modalBindings(), viewerBindings(),
opsBindings(), sshBindings(), archiveBindings(), miscBindings(),
} {
out = append(out, part...)
}
return out
}
// Translate maps a key typed in the ЙЦУКЕН layout to its QWERTY name, for
// matching per-modal hotkeys (dialog buttons) the same way Resolve does.
// Other keys are returned unchanged.
func Translate(k string) string {
rs := []rune(k)
if len(rs) != 1 {
return k
}
q, ok := jcuken[unicode.ToLower(rs[0])]
if !ok {
return k
}
if unicode.IsUpper(rs[0]) {
q = unicode.ToUpper(q)
}
return string(q)
}

308
internal/tui/keys/keys.go Normal file
View file

@ -0,0 +1,308 @@
// Package keys is the single key-routing table of the new UI (design §7.4,
// §8): actions are named by ActionID, bound per input Context, and resolved
// from tea.KeyMsg in one place. Help and the footer are generated from the
// same table, so they cannot drift from what the keys do.
//
// Command contexts also accept keys typed in the Russian ЙЦУКЕН layout
// (й→q, …); text contexts (filter line, input fields) never translate and
// let everything except a few control keys through to the text field
// (U-P1-5: "папка" stays "папка").
package keys
import (
"fmt"
"sort"
"strings"
tea "github.com/charmbracelet/bubbletea"
)
// ActionID names an action: "nav.down", "file.copy", "viewer.visual", ...
type ActionID string
// Pending is returned by Resolve when the key started a chord ("y" of
// "y y"); the caller does nothing and waits for the next key.
const Pending ActionID = "keys.pending"
// Context is who owns the keyboard right now (see App.inputOwner).
type Context uint8
const (
CtxBrowse Context = iota
CtxInfo
CtxFilterEdit
CtxViewScroll
CtxCaret
CtxVisual
CtxModalDialog
CtxModalInput
CtxModalList
CtxModalProgress
CtxModalConflict
CtxModalPrompt
numContexts
)
// Contexts lists every context (for tests and help).
func Contexts() []Context {
out := make([]Context, numContexts)
for i := range out {
out[i] = Context(i)
}
return out
}
var ctxNames = [...]string{
"browse", "info", "filter", "view", "caret", "visual",
"dialog", "input", "list", "progress", "conflict", "prompt",
}
func (c Context) String() string {
if int(c) < len(ctxNames) {
return ctxNames[c]
}
return fmt.Sprintf("Context(%d)", uint8(c))
}
// IsText reports whether c edits text: only a few control keys are bound,
// everything else goes to the text field untranslated.
func (c Context) IsText() bool {
return c == CtxFilterEdit || c == CtxModalInput || c == CtxModalPrompt
}
// textKeys are the only keys a text context may bind.
var textKeys = map[string]bool{
"enter": true, "esc": true, "tab": true, "shift+tab": true,
"up": true, "down": true, "ctrl+c": true, "ctrl+u": true,
}
// Binding binds keys to an action in one context.
type Binding struct {
Context Context
Action ActionID
// Keys in tea.KeyMsg.String() form ("j", "ctrl+f", "f5", "shift+up").
// A chord is space separated: "y y".
Keys []string
Help string // one line for help; "" hides the binding from help
Group string // help section ("Navigation", "Files", ...)
Footer bool // shown in the footer
}
// Registry resolves keys. It keeps a small chord buffer per context; it is
// not safe for concurrent use (it lives in the UI goroutine).
type Registry struct {
byCtx [numContexts]map[string]ActionID // key or chord → action
prefixes [numContexts]map[string]bool // chord prefixes
bindings []Binding
pendingCtx Context
pending string
}
// New builds a registry from bindings. It fails on a key bound twice in one
// context or a text context binding a non-control key.
func New(bindings []Binding) (*Registry, error) {
r := &Registry{bindings: bindings}
for i := range r.byCtx {
r.byCtx[i] = map[string]ActionID{}
r.prefixes[i] = map[string]bool{}
}
var errs []string
for _, b := range bindings {
if b.Context >= numContexts {
errs = append(errs, fmt.Sprintf("%s: bad context %d", b.Action, b.Context))
continue
}
for _, k := range b.Keys {
if b.Context.IsText() && !textKeys[k] {
errs = append(errs, fmt.Sprintf("%s: %q binds a typing key in text context %s", b.Action, k, b.Context))
continue
}
if prev, dup := r.byCtx[b.Context][k]; dup && prev != b.Action {
errs = append(errs, fmt.Sprintf("%s: %q in %s already bound to %s", b.Action, k, b.Context, prev))
continue
}
r.byCtx[b.Context][k] = b.Action
parts := strings.Fields(k)
for i := 1; i < len(parts); i++ {
r.prefixes[b.Context][strings.Join(parts[:i], " ")] = true
}
}
}
if len(errs) > 0 {
return r, fmt.Errorf("keys: %s", strings.Join(errs, "; "))
}
return r, nil
}
// MustDefault returns the registry of DefaultBindings and panics on a
// conflict (a programming error caught by TestNoDuplicateKeysPerContext).
func MustDefault() *Registry {
r, err := New(DefaultBindings())
if err != nil {
panic(err)
}
return r
}
// Resolve maps a key in ctx to an action. ok is false when the key is not
// bound (in a text context: when it must go to the text field). A chord
// prefix yields (Pending, true). Changing context drops a pending chord.
func (r *Registry) Resolve(ctx Context, msg tea.KeyMsg) (ActionID, bool) {
key := msg.String()
if ctx != r.pendingCtx {
r.pending = ""
r.pendingCtx = ctx
}
if ctx.IsText() {
if !textKeys[key] {
return "", false
}
a, ok := r.byCtx[ctx][key]
return a, ok
}
cands := []string{key}
if t, ok := translate(msg); ok {
cands = append(cands, t)
}
if r.pending != "" {
prefix := r.pending
r.pending = ""
for _, k := range cands {
chord := prefix + " " + k
if a, ok := r.byCtx[ctx][chord]; ok {
return a, true
}
if r.prefixes[ctx][chord] {
r.pending = chord
return Pending, true
}
}
// Not a continuation: fall through and treat the key on its own.
}
for _, k := range cands {
if r.prefixes[ctx][k] {
r.pending = k
return Pending, true
}
if a, ok := r.byCtx[ctx][k]; ok {
return a, true
}
}
return "", false
}
// Reset drops a pending chord.
func (r *Registry) Reset() { r.pending = "" }
// Keys returns the keys bound to action in ctx, in declaration order.
func (r *Registry) Keys(ctx Context, a ActionID) []string {
for _, b := range r.bindings {
if b.Context == ctx && b.Action == a {
return b.Keys
}
}
return nil
}
// HelpItem is one line of help or footer.
type HelpItem struct {
Action ActionID
Keys string // "F5/c"
Help string
}
// Section is a group of help items.
type Section struct {
Title string
Items []HelpItem
}
// Help lists the bindings of ctx grouped by section, in declaration order.
func (r *Registry) Help(ctx Context) []Section {
var out []Section
idx := map[string]int{}
for _, b := range r.bindings {
if b.Context != ctx || b.Help == "" {
continue
}
g := b.Group
if g == "" {
g = "Keys"
}
i, ok := idx[g]
if !ok {
i = len(out)
idx[g] = i
out = append(out, Section{Title: g})
}
out[i].Items = append(out[i].Items, HelpItem{Action: b.Action, Keys: KeyLabel(b.Keys), Help: b.Help})
}
return out
}
// Footer lists the footer bindings of ctx.
func (r *Registry) Footer(ctx Context) []HelpItem {
var out []HelpItem
for _, b := range r.bindings {
if b.Context == ctx && b.Footer {
out = append(out, HelpItem{Action: b.Action, Keys: KeyLabel(b.Keys[:1]), Help: b.Help})
}
}
return out
}
// Actions lists every action bound in ctx (sorted).
func (r *Registry) Actions(ctx Context) []ActionID {
seen := map[ActionID]bool{}
for _, a := range r.byCtx[ctx] {
seen[a] = true
}
out := make([]ActionID, 0, len(seen))
for a := range seen {
out = append(out, a)
}
sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
return out
}
// KeyLabel renders keys for humans: "F5/c", "Shift+↓/J", "y y".
func KeyLabel(ks []string) string {
parts := make([]string, len(ks))
for i, k := range ks {
parts[i] = label(k)
}
return strings.Join(parts, "/")
}
var keyLabels = map[string]string{
"up": "↑", "down": "↓", "left": "←", "right": "→", "enter": "Enter", "esc": "Esc",
"tab": "Tab", "shift+tab": "Shift+Tab", "backspace": "Backspace", "delete": "Del",
"insert": "Ins", "pgup": "PgUp", "pgdown": "PgDn", "home": "Home", "end": "End",
" ": "Space", "f20": "Shift+F8",
}
func label(k string) string {
if strings.Contains(k, " ") && k != " " {
ps := strings.Fields(k)
for i, p := range ps {
ps[i] = label(p)
}
return strings.Join(ps, " ")
}
if l, ok := keyLabels[k]; ok {
return l
}
if len(k) >= 2 && k[0] == 'f' && k[1] >= '0' && k[1] <= '9' {
return "F" + k[1:]
}
out := k
for _, mod := range []string{"ctrl+", "alt+", "shift+"} {
if strings.HasPrefix(out, mod) {
rest := strings.TrimPrefix(out, mod)
out = strings.ToUpper(mod[:1]) + mod[1:] + label(rest)
break
}
}
return out
}

View file

@ -0,0 +1,141 @@
package keys
import (
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
)
func runeKey(s string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} }
// U-P1-16: one key in one context = one action.
func TestNoDuplicateKeysPerContext(t *testing.T) {
if _, err := New(DefaultBindings()); err != nil {
t.Fatal(err)
}
r, err := New([]Binding{
{Context: CtxBrowse, Action: "a", Keys: []string{"x"}},
{Context: CtxBrowse, Action: "b", Keys: []string{"x"}},
})
if err == nil || r == nil {
t.Fatal("duplicate key not reported")
}
if _, err := New([]Binding{{Context: CtxFilterEdit, Action: "a", Keys: []string{"q"}}}); err == nil {
t.Fatal("text context binding a typing key not reported")
}
}
// U-P1-5: ЙЦУКЕН is translated for commands only.
func TestLayoutTranslationCommandsOnly(t *testing.T) {
r := MustDefault()
if a, ok := r.Resolve(CtxBrowse, runeKey("й")); !ok || a != AppQuit {
t.Errorf("Browse й = %q %v, want %s", a, ok, AppQuit)
}
if a, ok := r.Resolve(CtxBrowse, runeKey("с")); !ok || a != FileCopy {
t.Errorf("Browse с = %q %v, want %s", a, ok, FileCopy)
}
if a, ok := r.Resolve(CtxBrowse, runeKey("Р")); ok {
t.Errorf("Browse Р (H) resolved to %q", a)
}
if a, ok := r.Resolve(CtxBrowse, runeKey("П")); !ok || a != NavEnd {
t.Errorf("Browse П (G) = %q %v, want %s", a, ok, NavEnd)
}
for _, ctx := range []Context{CtxFilterEdit, CtxModalInput} {
if a, ok := r.Resolve(ctx, runeKey("й")); ok {
t.Errorf("%s: й resolved to %q", ctx, a)
}
if a, ok := r.Resolve(ctx, runeKey("q")); ok {
t.Errorf("%s: q resolved to %q (must be typable)", ctx, a)
}
}
if got := Translate("н"); got != "y" {
t.Errorf("Translate(н) = %q", got)
}
}
func TestTextContextPassesRunes(t *testing.T) {
r := MustDefault()
for _, ctx := range []Context{CtxFilterEdit, CtxModalInput} {
for _, ch := range "папка q/j" {
k := runeKey(string(ch))
if ch == ' ' {
k = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}}
}
if a, ok := r.Resolve(ctx, k); ok {
t.Errorf("%s: %q resolved to %q", ctx, ch, a)
}
}
if a, ok := r.Resolve(ctx, tea.KeyMsg{Type: tea.KeyEnter}); !ok || a == "" {
t.Errorf("%s: enter not resolved", ctx)
}
}
}
func TestChordYY(t *testing.T) {
r := MustDefault()
if a, ok := r.Resolve(CtxCaret, runeKey("y")); !ok || a != Pending {
t.Fatalf("first y = %q %v, want Pending", a, ok)
}
if a, ok := r.Resolve(CtxCaret, runeKey("y")); !ok || a != ViewerYankLine {
t.Fatalf("y y = %q %v, want %s", a, ok, ViewerYankLine)
}
// A non-continuing key drops the chord and acts on its own.
r.Resolve(CtxCaret, runeKey("y"))
if a, ok := r.Resolve(CtxCaret, runeKey("j")); !ok || a != ViewerLineDown {
t.Fatalf("y j = %q %v, want %s", a, ok, ViewerLineDown)
}
if a, _ := r.Resolve(CtxCaret, runeKey("y")); a != Pending {
t.Fatal("chord did not restart")
}
// A context change drops it too.
if a, ok := r.Resolve(CtxVisual, runeKey("y")); !ok || a != ViewerYank {
t.Fatalf("visual y = %q %v", a, ok)
}
if a, _ := r.Resolve(CtxCaret, runeKey("y")); a != Pending {
t.Fatal("chord survived a context change")
}
// In the ЙЦУКЕН layout too.
r.Reset()
r.Resolve(CtxCaret, runeKey("н"))
if a, _ := r.Resolve(CtxCaret, runeKey("н")); a != ViewerYankLine {
t.Fatalf("н н = %q", a)
}
}
func TestHelpGeneratedFromRegistry(t *testing.T) {
r := MustDefault()
var found bool
for _, s := range r.Help(CtxBrowse) {
for _, it := range s.Items {
if it.Action == FileCopy {
found = true
if it.Keys != "F5/c" || it.Help != "copy" || s.Title != "Files" {
t.Errorf("copy help = %+v in %q", it, s.Title)
}
}
}
}
if !found {
t.Fatal("file.copy missing from help")
}
var foot []string
for _, it := range r.Footer(CtxBrowse) {
foot = append(foot, it.Keys+" "+it.Help)
}
if !strings.Contains(strings.Join(foot, "|"), "F5 copy") {
t.Errorf("footer = %v", foot)
}
if got := KeyLabel([]string{"f20", "X", "shift+up", "y y", " "}); got != "Shift+F8/X/Shift+↑/y y/Space" {
t.Errorf("KeyLabel = %q", got)
}
for _, ctx := range Contexts() {
for _, s := range r.Help(ctx) {
for _, it := range s.Items {
if it.Keys == "" {
t.Errorf("%s: %s has no keys", ctx, it.Action)
}
}
}
}
}

View file

@ -0,0 +1,35 @@
package keys
import (
"unicode"
tea "github.com/charmbracelet/bubbletea"
)
// jcuken maps the Russian ЙЦУКЕН layout to the US QWERTY key in the same
// position (lower case; upper case is derived).
var jcuken = map[rune]rune{
'й': 'q', 'ц': 'w', 'у': 'e', 'к': 'r', 'е': 't', 'н': 'y', 'г': 'u', 'ш': 'i', 'щ': 'o', 'з': 'p',
'х': '[', 'ъ': ']', 'ф': 'a', 'ы': 's', 'в': 'd', 'а': 'f', 'п': 'g', 'р': 'h', 'о': 'j', 'л': 'k',
'д': 'l', 'ж': ';', 'э': '\'', 'я': 'z', 'ч': 'x', 'с': 'c', 'м': 'v', 'и': 'b', 'т': 'n', 'ь': 'm',
'б': ',', 'ю': '.', 'ё': '`',
}
// translate returns the QWERTY key name for a single Cyrillic rune key
// (with alt preserved). Only command contexts use it.
func translate(msg tea.KeyMsg) (string, bool) {
if msg.Type != tea.KeyRunes || len(msg.Runes) != 1 {
return "", false
}
r := msg.Runes[0]
upper := unicode.IsUpper(r)
q, ok := jcuken[unicode.ToLower(r)]
if !ok {
return "", false
}
if upper {
q = unicode.ToUpper(q)
}
k := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{q}, Alt: msg.Alt}
return k.String(), true
}

92
internal/tui/layout.go Normal file
View file

@ -0,0 +1,92 @@
package tui
import (
"vcom/internal/tui/geom"
"vcom/internal/tui/panel"
)
// Layout holds every screen rectangle. Rendering, mouse hit-tests and the
// image overlay use the same values (design §7.3).
type Layout struct {
W, H int
Panes [2]geom.Rect // empty when the pane is hidden (Info shows only the active one)
Preview geom.Rect // Info: the preview box (with border)
PreviewBody geom.Rect // inside the preview border
Viewer geom.Rect // View screen: full content area
Status geom.Rect
Footer geom.Rect
Screen geom.Rect // whole terminal (modals center in it)
}
// computeLayout splits the terminal for the current screen.
func computeLayout(w, h int, screen Screen, active int, footer bool, previewPct, gap int) Layout {
l := Layout{W: w, H: h, Screen: geom.Rect{W: w, H: h}}
bottom := 1
if footer && h >= 8 {
bottom = 2
}
l.Status = geom.Rect{X: 0, Y: h - bottom, W: w, H: 1}
if bottom == 2 {
l.Footer = geom.Rect{X: 0, Y: h - 1, W: w, H: 1}
}
body := geom.Rect{W: w, H: max(0, h-bottom)}
switch screen {
case ScreenView:
l.Viewer = body
case ScreenInfo:
pct := previewPct
if pct < 20 || pct > 80 {
pct = 50
}
pw := body.W * pct / 100
lw := body.W - pw
l.Panes[active] = geom.Rect{X: 0, Y: 0, W: lw, H: body.H}
l.Preview = geom.Rect{X: lw, Y: 0, W: pw, H: body.H}
l.PreviewBody = geom.Rect{X: lw + 1, Y: 2, W: max(0, pw-2), H: max(0, body.H-3)}
default:
gap = max(0, min(gap, 4))
lw := (body.W - gap) / 2
l.Panes[0] = geom.Rect{X: 0, Y: 0, W: lw, H: body.H}
l.Panes[1] = geom.Rect{X: lw + gap, Y: 0, W: body.W - lw - gap, H: body.H}
}
return l
}
// paneAt returns the pane whose rectangle contains (x, y).
func (l Layout) paneAt(x, y int) (int, bool) {
for i, r := range l.Panes {
if !r.Empty() && r.Contains(x, y) {
return i, true
}
}
return 0, false
}
// listRect is the rows area of pane i given its filter state.
func (a *App) listRect(i int) geom.Rect {
return panel.ListRect(a.layout.Panes[i], a.filterRow(i))
}
func (a *App) filterRow(i int) bool {
return a.panels[i].Filter() != "" || (a.filter != nil && i == a.active)
}
// relayout recomputes the layout and tells panels and the viewer their
// sizes. Called after every Update (cheap) so View stays pure.
func (a *App) relayout() {
c := a.deps.Config.UI
a.layout = computeLayout(a.w, a.h, a.screen, a.active, c.ShowFooter, c.PreviewWidthPercent, c.PaneGap)
for i, p := range a.panels {
r := a.layout.Panes[i]
if r.Empty() {
r = a.layout.Panes[a.active]
}
p.SetRows(panel.ListRect(r, a.filterRow(i)).H)
}
switch a.screen {
case ScreenView:
a.viewer.SetRows(a.layout.Viewer.H - 1)
case ScreenInfo:
a.viewer.SetRows(a.layout.PreviewBody.H)
}
}

View file

@ -0,0 +1,210 @@
package modal
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/keys"
"vcom/internal/tui/style"
)
// KV is one "Label: value" line of a Dialog.
type KV struct{ Label, Value string }
// Button of a Dialog. Key is a single-key hotkey ("y"); it is matched in
// the ЙЦУКЕН layout too and wins over the Dialog's own cancel keys.
type Button struct {
Label string
Key string
Value any
Danger bool // drawn in the danger color when focused
Default bool // focused when the dialog opens
Cancel bool // pressing it closes as Cancelled
}
// Dialog is a structured confirmation (crutch #14: no heuristics on text).
// Enter presses the focused button, Tab/←/→ move focus, hotkeys press their
// button, Esc/Ctrl+C/q cancel.
type Dialog struct {
Title string
Fields []KV
Text []string // free paragraphs, wrapped
Warnings []string
Buttons []Button
Width int // preferred content width (default 60)
focus int
init bool
}
func (d *Dialog) Context() keys.Context { return keys.CtxModalDialog }
func (d *Dialog) setup() {
if d.init {
return
}
d.init = true
for i, b := range d.Buttons {
if b.Default {
d.focus = i
}
}
}
// Focused is the index of the focused button.
func (d *Dialog) Focused() int { d.setup(); return d.focus }
func (d *Dialog) press(i int) Outcome {
b := d.Buttons[i]
if b.Cancel {
return Outcome{Close: true, Cancelled: true, Value: b.Value}
}
return Done(b.Value)
}
func (d *Dialog) Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) {
d.setup()
if k.Type == tea.KeyRunes && len(k.Runes) == 1 {
ks := k.String()
for i, b := range d.Buttons {
if b.Key != "" && (b.Key == ks || b.Key == keys.Translate(ks)) {
return d.press(i), nil
}
}
}
switch a {
case keys.ModalConfirm:
if len(d.Buttons) == 0 {
return Done(nil), nil
}
return d.press(d.focus), nil
case keys.ModalNext:
if n := len(d.Buttons); n > 0 {
d.focus = (d.focus + 1) % n
}
case keys.ModalPrev:
if n := len(d.Buttons); n > 0 {
d.focus = (d.focus + n - 1) % n
}
case keys.ModalCancel:
return Cancel(), nil
}
return Keep, nil
}
// layout renders the content lines; btnRow is the line of the buttons and
// spans their cell ranges on it.
func (d *Dialog) layout(maxW, maxH int, st *style.Styles) (lines []string, btnRow int, spans [][2]int) {
d.setup()
want := d.Width
if want == 0 {
want = 60
}
cw := innerWidth(maxW, want)
var body []string
for _, f := range d.Fields {
l := st.ModalLabel.Render(f.Label+": ") + f.Value
body = append(body, ansi.Truncate(l, cw, "…"))
}
for _, p := range d.Text {
if len(body) > 0 && len(d.Fields) > 0 {
body = append(body, "")
}
body = append(body, strings.Split(ansi.Wrap(p, cw, ""), "\n")...)
}
for _, w := range d.Warnings {
for _, l := range strings.Split(ansi.Wrap("! "+w, cw, ""), "\n") {
body = append(body, st.ModalWarning.Render(l))
}
}
// Buttons line.
var b strings.Builder
x := 0
for i, btn := range d.Buttons {
if i > 0 {
b.WriteString(" ")
x += 2
}
label := btn.Label
if btn.Key != "" {
label = fmt.Sprintf("%s (%s)", btn.Label, btn.Key)
}
s := st.Button
if i == d.focus {
s = st.ButtonFocused
if btn.Danger {
s = st.ButtonDanger
}
}
r := s.Render(label)
w := ansi.StringWidth(r)
spans = append(spans, [2]int{x, x + w})
x += w
b.WriteString(r)
}
// Keep the buttons visible: cut the body if the modal is too tall
// (border 2 + title 1 + blank 1 + buttons 1).
room := maxH - 5
if room < 0 {
room = 0
}
if len(body) > room {
cut := len(body) - room + 1
if room == 0 {
body = nil
} else {
body = append(body[:room-1], st.Muted.Render(fmt.Sprintf("… %d more lines", cut)))
}
}
lines = append(lines, body...)
if len(d.Buttons) > 0 {
if len(body) > 0 {
lines = append(lines, "")
}
btnRow = len(lines)
lines = append(lines, b.String())
}
return lines, btnRow, spans
}
func (d *Dialog) View(maxW, maxH int, st *style.Styles) string {
lines, _, _ := d.layout(maxW, maxH, st)
return frame(st, d.Title, lines, maxW)
}
func (d *Dialog) Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) {
if m.Action != tea.MouseActionPress || m.Button != tea.MouseButtonLeft {
return Keep, nil
}
_, row, spans := d.layout(w, h, st)
cx, cy := x-2, y-1 // border + padding
if d.Title != "" {
cy--
}
if cy != row {
return Keep, nil
}
for i, s := range spans {
if cx >= s[0] && cx < s[1] {
d.focus = i
return d.press(i), nil
}
}
return Keep, nil
}
// Confirm builds a yes/no dialog. With danger the default focus is on the
// cancel button (permanent delete, U-P0-4).
func Confirm(title string, text string, yes string, danger bool) *Dialog {
return &Dialog{
Title: title,
Text: []string{text},
Buttons: []Button{
{Label: yes, Key: "y", Value: true, Danger: danger, Default: !danger},
{Label: "Cancel", Key: "n", Cancel: true, Default: danger},
},
}
}

144
internal/tui/modal/input.go Normal file
View file

@ -0,0 +1,144 @@
package modal
import (
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/keys"
"vcom/internal/tui/style"
)
// Field of an Input modal.
type Field struct {
Label string
Value string
Placeholder string
Secret bool
}
// Input is a form of one or more text fields (mkdir, rename, SSH host).
// Every typed key goes to the focused field untranslated ("q" is a letter
// here, U section 7). Enter submits ([]string of values), Esc cancels.
type Input struct {
Title string
Text string // optional line above the fields
// Validate is called on Enter; an error is shown and the modal stays.
Validate func(values []string) error
Width int
fields []textinput.Model
labels []string
focus int
err string
}
// NewInput builds an Input.
func NewInput(title string, fields ...Field) *Input {
in := &Input{Title: title}
for _, f := range fields {
ti := textinput.New()
ti.Prompt = ""
ti.SetValue(f.Value)
ti.Placeholder = f.Placeholder
ti.CursorEnd()
if f.Secret {
ti.EchoMode = textinput.EchoPassword
}
in.fields = append(in.fields, ti)
in.labels = append(in.labels, f.Label)
}
if len(in.fields) > 0 {
in.fields[0].Focus()
}
return in
}
func (in *Input) Context() keys.Context { return keys.CtxModalInput }
// Values returns the current field values.
func (in *Input) Values() []string {
out := make([]string, len(in.fields))
for i, f := range in.fields {
out[i] = f.Value()
}
return out
}
func (in *Input) setFocus(i int) {
in.fields[in.focus].Blur()
in.focus = i
in.fields[in.focus].Focus()
}
func (in *Input) Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) {
n := len(in.fields)
switch a {
case keys.ModalConfirm:
vals := in.Values()
if in.Validate != nil {
if err := in.Validate(vals); err != nil {
in.err = err.Error()
return Keep, nil
}
}
return Done(vals), nil
case keys.ModalCancel:
return Cancel(), nil
case keys.ModalNext:
if n > 1 {
in.setFocus((in.focus + 1) % n)
}
return Keep, nil
case keys.ModalPrev:
if n > 1 {
in.setFocus((in.focus + n - 1) % n)
}
return Keep, nil
case keys.ModalClear:
if n > 0 {
in.fields[in.focus].SetValue("")
}
return Keep, nil
}
if n == 0 {
return Keep, nil
}
in.err = ""
var cmd tea.Cmd
in.fields[in.focus], cmd = in.fields[in.focus].Update(k)
return Keep, cmd
}
func (in *Input) View(maxW, maxH int, st *style.Styles) string {
want := in.Width
if want == 0 {
want = 56
}
cw := innerWidth(maxW, want)
var lines []string
if in.Text != "" {
lines = append(lines, strings.Split(ansi.Wrap(in.Text, cw, ""), "\n")...)
}
lw := 0
for _, l := range in.labels {
lw = max(lw, ansi.StringWidth(l))
}
for i := range in.fields {
f := &in.fields[i]
f.Width = max(4, cw-lw-3)
label := st.ModalLabel.Render(in.labels[i] + strings.Repeat(" ", lw-ansi.StringWidth(in.labels[i])) + " ")
lines = append(lines, ansi.Truncate(label+"▏"+f.View(), cw, ""))
}
if in.err != "" {
lines = append(lines, st.NoteError.Render(ansi.Truncate(in.err, cw, "…")))
}
lines, _, _ = clip(lines, in.focus, max(1, maxH-3))
return frame(st, in.Title, lines, maxW)
}
func (in *Input) Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) {
return Keep, nil
}

244
internal/tui/modal/list.go Normal file
View file

@ -0,0 +1,244 @@
package modal
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/keys"
"vcom/internal/tui/style"
)
// Item of a List. A Header item is a section title: drawn, never selected.
type Item struct {
Label string
Detail string // right-aligned, muted
Value any
Header bool
}
// List is a scrollable list of choices (theme, sort, hosts, jobs) or, with
// no selectable items, a scrollable text (help, message log). It never
// grows past the screen: on a small terminal it scrolls (crutch #10).
type List struct {
Title string
Items []Item
Width int
// OnMove is called when the cursor lands on another item (live theme
// preview); its command is returned with the key's.
OnMove func(Item) tea.Cmd
cursor int // index into Items (a selectable one), -1 for text lists
offset int // first visible row
page int // rows shown last time (for PgUp/PgDn)
init bool
}
// NewList builds a list with the cursor on the first selectable item, or on
// the item whose Value equals selected (if any).
func NewList(title string, items []Item, selected any) *List {
l := &List{Title: title, Items: items, cursor: -1}
for i, it := range items {
if it.Header {
continue
}
if l.cursor < 0 {
l.cursor = i
}
if selected != nil && it.Value == selected {
l.cursor = i
break
}
}
return l
}
// NewText builds a read-only scrollable text.
func NewText(title string, lines []string) *List {
items := make([]Item, len(lines))
for i, s := range lines {
items[i] = Item{Label: s, Header: true}
}
return &List{Title: title, Items: items, cursor: -1}
}
func (l *List) Context() keys.Context { return keys.CtxModalList }
// Cursor returns the selected item index (-1 for a text list).
func (l *List) Cursor() int { return l.cursor }
// Offset returns the first visible row.
func (l *List) Offset() int { return l.offset }
func (l *List) selectable(i int) bool { return i >= 0 && i < len(l.Items) && !l.Items[i].Header }
// move the cursor by delta selectable steps (text lists scroll instead).
func (l *List) move(delta int) tea.Cmd {
if l.cursor < 0 {
l.offset = max(0, min(l.offset+delta, len(l.Items)-max(1, l.page)))
return nil
}
old := l.cursor
step := 1
if delta < 0 {
step = -1
}
for n := abs(delta); n > 0; n-- {
i := l.cursor + step
for i >= 0 && i < len(l.Items) && !l.selectable(i) {
i += step
}
if !l.selectable(i) {
break
}
l.cursor = i
}
l.follow()
if l.cursor != old && l.OnMove != nil {
return l.OnMove(l.Items[l.cursor])
}
return nil
}
func (l *List) jump(toEnd bool) tea.Cmd {
if l.cursor < 0 {
if toEnd {
l.offset = max(0, len(l.Items)-max(1, l.page))
} else {
l.offset = 0
}
return nil
}
if toEnd {
return l.move(len(l.Items))
}
return l.move(-len(l.Items))
}
func (l *List) follow() {
if l.page <= 0 {
return
}
if l.cursor < l.offset {
l.offset = l.cursor
// Show the section header right above, if any.
if l.offset > 0 && l.Items[l.offset-1].Header {
l.offset--
}
}
if l.cursor >= l.offset+l.page {
l.offset = l.cursor - l.page + 1
}
}
func (l *List) Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) {
page := max(1, l.page-1)
switch a {
case keys.ModalUp:
return Keep, l.move(-1)
case keys.ModalDown:
return Keep, l.move(1)
case keys.ModalPgUp:
return Keep, l.move(-page)
case keys.ModalPgDown:
return Keep, l.move(page)
case keys.ModalHome:
return Keep, l.jump(false)
case keys.ModalEnd:
return Keep, l.jump(true)
case keys.ModalConfirm:
if l.cursor < 0 {
return Cancel(), nil
}
return Done(l.Items[l.cursor].Value), nil
case keys.ModalCancel:
return Cancel(), nil
}
return Keep, nil
}
// rows is how many item rows fit in maxH (border 2 + title 1).
func (l *List) rows(maxH int) int { return max(1, min(len(l.Items), maxH-3)) }
func (l *List) View(maxW, maxH int, st *style.Styles) string {
want := l.Width
if want == 0 {
want = 4
for _, it := range l.Items {
want = max(want, ansi.StringWidth(it.Label)+ansi.StringWidth(it.Detail)+4)
}
want = min(want, 76)
}
cw := innerWidth(maxW, want)
n := l.rows(maxH)
if !l.init || n != l.page {
l.init = true
l.page = n
l.follow()
}
l.offset = max(0, min(l.offset, max(0, len(l.Items)-n)))
var lines []string
for i := l.offset; i < len(l.Items) && len(lines) < n; i++ {
lines = append(lines, l.renderItem(i, cw, st))
}
title := l.Title
if len(l.Items) > n {
title = fmt.Sprintf("%s %d–%d/%d", l.Title, l.offset+1, l.offset+len(lines), len(l.Items))
}
return frame(st, title, lines, maxW)
}
func (l *List) renderItem(i, cw int, st *style.Styles) string {
it := l.Items[i]
if it.Header {
s := ansi.Truncate(it.Label, cw, "…")
if l.cursor >= 0 {
return st.Section.Render(s)
}
return s
}
label := ansi.Truncate(it.Label, max(1, cw-ansi.StringWidth(it.Detail)-1), "…")
gap := max(1, cw-ansi.StringWidth(label)-ansi.StringWidth(it.Detail))
line := label + strings.Repeat(" ", gap) + st.Muted.Render(it.Detail)
if i == l.cursor {
return st.ListCursor.Render(ansi.Strip(label) + strings.Repeat(" ", gap) + it.Detail)
}
return line
}
func (l *List) Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) {
switch m.Button {
case tea.MouseButtonWheelUp:
return Keep, l.move(-3)
case tea.MouseButtonWheelDown:
return Keep, l.move(3)
case tea.MouseButtonLeft:
if m.Action != tea.MouseActionPress {
return Keep, nil
}
row := y - 2 // border + title
i := l.offset + row
if row < 0 || row >= l.page || !l.selectable(i) {
return Keep, nil
}
if i == l.cursor {
return Done(l.Items[i].Value), nil
}
l.cursor = i
l.follow()
if l.OnMove != nil {
return Keep, l.OnMove(l.Items[i])
}
return Keep, nil
}
return Keep, nil
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}

View file

@ -0,0 +1,234 @@
package modal
import (
"fmt"
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"vcom/internal/theme"
"vcom/internal/tui/geom"
"vcom/internal/tui/keys"
"vcom/internal/tui/style"
)
var reg = keys.MustDefault()
func st(t *testing.T) *style.Styles {
t.Helper()
p, err := theme.Resolve("catppuccin-mocha")
if err != nil {
t.Fatal(err)
}
return style.New(p)
}
func key(s string) tea.KeyMsg {
switch s {
case "enter":
return tea.KeyMsg{Type: tea.KeyEnter}
case "esc":
return tea.KeyMsg{Type: tea.KeyEsc}
case "tab":
return tea.KeyMsg{Type: tea.KeyTab}
case "pgdown":
return tea.KeyMsg{Type: tea.KeyPgDown}
case "down":
return tea.KeyMsg{Type: tea.KeyDown}
}
return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)}
}
// press sends k to the stack's top modal the way the App does.
func press(s *Stack, k string) tea.Cmd {
km := key(k)
a, _ := reg.Resolve(s.Top().Context(), km)
return s.Key(a, km)
}
func TestDialogButtonsAndHotkeys(t *testing.T) {
var got []Outcome
open := func(d *Dialog) *Stack {
s := &Stack{}
s.Push(d, func(o Outcome) tea.Cmd { got = append(got, o); return nil })
return s
}
quit := func() *Dialog {
return &Dialog{Title: "Quit?", Buttons: []Button{
{Label: "Quit", Key: "q", Value: "quit", Default: true},
{Label: "Back", Key: "n", Cancel: true},
}}
}
// Enter presses the default button.
s := open(quit())
press(s, "enter")
if s.Len() != 0 || len(got) != 1 || got[0].Value != "quit" || got[0].Cancelled {
t.Fatalf("enter: %+v", got)
}
// A button hotkey wins over the dialog's cancel key (q q quits fast).
s = open(quit())
press(s, "q")
if got[1].Value != "quit" {
t.Fatalf("q: %+v", got[1])
}
// ЙЦУКЕН hotkey.
s = open(quit())
press(s, "т")
if !got[2].Cancelled {
t.Fatalf("т (n): %+v", got[2])
}
// Tab moves focus, Enter presses it.
s = open(quit())
press(s, "tab")
press(s, "enter")
if !got[3].Cancelled {
t.Fatalf("tab enter: %+v", got[3])
}
// Esc cancels; unknown keys keep it open.
s = open(quit())
press(s, "z")
if s.Len() != 1 {
t.Fatal("unbound key closed the dialog")
}
press(s, "esc")
if !got[4].Cancelled {
t.Fatalf("esc: %+v", got[4])
}
// Danger confirm: focus on Cancel, Enter cancels, y confirms.
d := Confirm("Delete permanently?", "3 items", "Delete", true)
if d.Focused() != 1 {
t.Fatal("permanent delete must default to Cancel")
}
s = open(d)
press(s, "enter")
if !got[5].Cancelled {
t.Fatal("enter on danger confirm did not cancel")
}
s = open(Confirm("Delete permanently?", "3 items", "Delete", true))
press(s, "y")
if got[6].Value != true {
t.Fatalf("y: %+v", got[6])
}
// Mouse: a click on a button presses it, a click elsewhere does not.
styles := st(t)
screen := geom.Rect{W: 80, H: 24}
s = open(quit())
box := s.Box(screen, styles)
view := ansi.Strip(s.Top().View(80, 24, styles))
lines := strings.Split(view, "\n")
for row, l := range lines {
if col := strings.Index(l, "Back"); col >= 0 {
x := box.X + ansi.StringWidth(l[:col])
s.Mouse(tea.MouseMsg{X: x, Y: box.Y + row, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}, screen, styles)
}
}
if len(got) != 8 || !got[7].Cancelled {
t.Fatalf("click on Back: %+v", got)
}
}
// Crutch #10: tall modals (help, theme list) on a small terminal must fit
// and scroll.
func TestModalScrollsOnSmallTerminal(t *testing.T) {
styles := st(t)
var lines []string
for i := 0; i < 100; i++ {
lines = append(lines, fmt.Sprintf("line %03d %s", i, strings.Repeat("x", 90)))
}
s := &Stack{}
s.Push(NewText("Help", lines), nil)
screen := geom.Rect{W: 72, H: 18}
v := s.Top().View(screen.W, screen.H, styles)
if w, h := lipgloss.Width(v), lipgloss.Height(v); w > 72 || h > 18 {
t.Fatalf("modal %d×%d does not fit 72×18", w, h)
}
if !strings.Contains(ansi.Strip(v), "line 000") || strings.Contains(ansi.Strip(v), "line 050") {
t.Fatal("wrong initial window")
}
press(s, "pgdown")
v = ansi.Strip(s.Top().View(screen.W, screen.H, styles))
if strings.Contains(v, "line 000") {
t.Fatal("PgDn did not scroll")
}
for i := 0; i < 20; i++ {
press(s, "pgdown")
}
v = ansi.Strip(s.Top().View(screen.W, screen.H, styles))
if !strings.Contains(v, "line 099") {
t.Fatal("cannot scroll to the end")
}
// A selectable list keeps the cursor visible.
var items []Item
for i := 0; i < 50; i++ {
items = append(items, Item{Label: fmt.Sprintf("theme-%02d", i), Value: i})
}
var moved []any
l := NewList("Theme", items, 40)
l.OnMove = func(it Item) tea.Cmd { moved = append(moved, it.Value); return nil }
s.Push(l, nil)
v = ansi.Strip(s.Top().View(screen.W, screen.H, styles))
if !strings.Contains(v, "theme-40") {
t.Fatal("preselected item not visible")
}
press(s, "down")
if len(moved) != 1 || moved[0] != 41 {
t.Fatalf("OnMove = %v", moved)
}
// The overlay keeps the base around the box.
base := strings.Repeat(strings.Repeat(".", 72)+"\n", 17) + strings.Repeat(".", 72)
out := ansi.Strip(s.Render(base, screen, styles))
if lipgloss.Height(out) != 18 || !strings.HasPrefix(out, "...") {
t.Fatalf("overlay broke the base:\n%s", out)
}
}
func TestMouseOutsideModalIgnored(t *testing.T) {
styles := st(t)
screen := geom.Rect{W: 80, H: 24}
closed := false
s := &Stack{}
s.Push(Confirm("Sure?", "text", "OK", false), func(Outcome) tea.Cmd { closed = true; return nil })
box := s.Box(screen, styles)
s.Mouse(tea.MouseMsg{X: box.X - 1, Y: box.Y, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}, screen, styles)
s.Mouse(tea.MouseMsg{X: 0, Y: 0, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}, screen, styles)
if closed || s.Len() != 1 {
t.Fatal("click outside the modal acted")
}
}
func TestInputTypesEverything(t *testing.T) {
in := NewInput("New directory", Field{Label: "Name"})
in.Validate = func(v []string) error {
if strings.Contains(v[0], "/") {
return fmt.Errorf("name must not contain /")
}
return nil
}
var res Outcome
s := &Stack{}
s.Push(in, func(o Outcome) tea.Cmd { res = o; return nil })
for _, r := range "qпапка/" {
press(s, string(r))
}
press(s, "enter")
if s.Len() != 1 {
t.Fatal("invalid value accepted")
}
if !strings.Contains(ansi.Strip(in.View(80, 24, st(t))), "must not contain") {
t.Fatal("validation error not shown")
}
s.Key(keys.ModalClear, tea.KeyMsg{Type: tea.KeyCtrlU})
for _, r := range "qпапка" {
press(s, string(r))
}
press(s, "enter")
if v, ok := res.Value.([]string); !ok || v[0] != "qпапка" {
t.Fatalf("value = %#v", res.Value)
}
}

225
internal/tui/modal/stack.go Normal file
View file

@ -0,0 +1,225 @@
// Package modal is the modal stack of the new UI (design §7.5): Dialog
// (structured confirm), Input (one or more text fields), List (choices,
// help, logs). While a modal is open it gets every key and mouse event; a
// click outside it is ignored, nothing under it changes.
//
// A modal never closes itself through side effects: Key/Mouse return an
// Outcome, the Stack pops it and runs the onClose callback given to Push.
// Stage 6.2/6.4 add Progress, Conflict and Prompt modals in this package.
package modal
import (
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/geom"
"vcom/internal/tui/keys"
"vcom/internal/tui/style"
)
// Outcome of a key or mouse event.
type Outcome struct {
Close bool
Cancelled bool // closed by Esc/q/Ctrl+C or a Cancel button
Value any
}
// Keep leaves the modal open.
var Keep = Outcome{}
// Done closes with value v.
func Done(v any) Outcome { return Outcome{Close: true, Value: v} }
// Cancel closes as cancelled.
func Cancel() Outcome { return Outcome{Close: true, Cancelled: true} }
// Modal is one layer of the stack.
type Modal interface {
// Context selects the key table (keys.CtxModalDialog, ...).
Context() keys.Context
// Key gets the resolved action ("" if the key is unbound) and the raw
// key (text fields, button hotkeys).
Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd)
// Mouse gets an event at (x, y) relative to the modal's top-left
// corner; w×h is the space View was given.
Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd)
// View renders the modal into at most maxW×maxH cells; a modal taller
// than that scrolls itself.
View(maxW, maxH int, st *style.Styles) string
}
type entry struct {
id uint64
m Modal
onClose func(Outcome) tea.Cmd
}
// Stack of modals; the top one owns input.
type Stack struct {
entries []entry
nextID uint64
}
// Push opens m; onClose (may be nil) runs when it closes, with its outcome.
func (s *Stack) Push(m Modal, onClose func(Outcome) tea.Cmd) uint64 {
s.nextID++
s.entries = append(s.entries, entry{id: s.nextID, m: m, onClose: onClose})
return s.nextID
}
// Len is the number of open modals.
func (s *Stack) Len() int { return len(s.entries) }
// Top returns the top modal (nil if none).
func (s *Stack) Top() Modal {
if len(s.entries) == 0 {
return nil
}
return s.entries[len(s.entries)-1].m
}
// TopID returns the id of the top modal (0 if none).
func (s *Stack) TopID() uint64 {
if len(s.entries) == 0 {
return 0
}
return s.entries[len(s.entries)-1].id
}
// Has reports whether modal id is open.
func (s *Stack) Has(id uint64) bool {
for _, e := range s.entries {
if e.id == id {
return true
}
}
return false
}
// Get returns modal id.
func (s *Stack) Get(id uint64) Modal {
for _, e := range s.entries {
if e.id == id {
return e.m
}
}
return nil
}
// CloseByID removes modal id without running onClose (e.g. its job ended);
// it reports whether it was open.
func (s *Stack) CloseByID(id uint64) bool {
for i, e := range s.entries {
if e.id == id {
s.entries = append(s.entries[:i], s.entries[i+1:]...)
return true
}
}
return false
}
func (s *Stack) finish(o Outcome, cmd tea.Cmd) tea.Cmd {
if !o.Close || len(s.entries) == 0 {
return cmd
}
e := s.entries[len(s.entries)-1]
s.entries = s.entries[:len(s.entries)-1]
if e.onClose != nil {
return tea.Batch(cmd, e.onClose(o))
}
return cmd
}
// Key routes a key to the top modal.
func (s *Stack) Key(a keys.ActionID, k tea.KeyMsg) tea.Cmd {
top := s.Top()
if top == nil {
return nil
}
return s.finish(top.Key(a, k))
}
// Mouse routes a mouse event to the top modal if it is inside the modal's
// box (screen is the area modals are centered in); events outside are
// swallowed.
func (s *Stack) Mouse(m tea.MouseMsg, screen geom.Rect, st *style.Styles) tea.Cmd {
top := s.Top()
if top == nil {
return nil
}
box := s.Box(screen, st)
if !box.Contains(m.X, m.Y) {
return nil
}
return s.finish(top.Mouse(m, m.X-box.X, m.Y-box.Y, screen.W, screen.H, st))
}
// Box is where the top modal is drawn inside screen.
func (s *Stack) Box(screen geom.Rect, st *style.Styles) geom.Rect {
top := s.Top()
if top == nil {
return geom.Rect{}
}
v := top.View(screen.W, screen.H, st)
return screen.Center(lipgloss.Width(v), lipgloss.Height(v))
}
// Render draws the top modal centered over base (screen-sized).
func (s *Stack) Render(base string, screen geom.Rect, st *style.Styles) string {
top := s.Top()
if top == nil {
return base
}
v := top.View(screen.W, screen.H, st)
box := screen.Center(lipgloss.Width(v), lipgloss.Height(v))
return Overlay(base, v, box.X, box.Y)
}
// Overlay draws box over base with its top-left corner at (x, y).
func Overlay(base, box string, x, y int) string {
lines := strings.Split(base, "\n")
for i, bl := range strings.Split(box, "\n") {
row := y + i
if row < 0 || row >= len(lines) {
continue
}
line := lines[row]
w := ansi.StringWidth(line)
if w < x {
line += strings.Repeat(" ", x-w)
w = x
}
left := ansi.Truncate(line, x, "")
right := ansi.TruncateLeft(line, x+ansi.StringWidth(bl), "")
lines[row] = left + bl + right
}
return strings.Join(lines, "\n")
}
// frame wraps content in the modal border with a title.
func frame(st *style.Styles, title string, body []string, maxW int) string {
content := strings.Join(body, "\n")
if title != "" {
content = st.ModalTitle.Render(ansi.Truncate(title, max(1, maxW-4), "…")) + "\n" + content
}
return st.Modal.Render(content)
}
// innerWidth is the content width for a modal given maxW (border + padding).
func innerWidth(maxW, want int) int {
return max(8, min(want, maxW-4))
}
// clip returns at most n lines starting at off and whether lines were cut
// above/below.
func clip(lines []string, off, n int) (out []string, above, below bool) {
if n <= 0 {
return nil, len(lines) > 0, false
}
off = max(0, min(off, max(0, len(lines)-n)))
end := min(len(lines), off+n)
return lines[off:end], off > 0, end < len(lines)
}

321
internal/tui/modes.go Normal file
View file

@ -0,0 +1,321 @@
package tui
import (
"context"
"errors"
"fmt"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/keys"
"vcom/internal/tui/notify"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
)
// inputOwner decides who gets the keyboard — the one place that does
// (design §7.3).
func (a *App) inputOwner() keys.Context {
switch {
case a.modals.Len() > 0:
return a.modals.Top().Context()
case a.filter != nil:
return keys.CtxFilterEdit
case a.screen == ScreenView:
return viewerCtx(a.viewer.Focus)
case a.screen == ScreenInfo && a.viewer.Focus != viewer.Scroll:
return viewerCtx(a.viewer.Focus)
case a.screen == ScreenInfo:
return keys.CtxInfo
}
return keys.CtxBrowse
}
// InputOwner is inputOwner for tests and features.
func (a *App) InputOwner() keys.Context { return a.inputOwner() }
func viewerCtx(f viewer.Focus) keys.Context {
switch f {
case viewer.Caret:
return keys.CtxCaret
case viewer.Visual:
return keys.CtxVisual
}
return keys.CtxViewScroll
}
// Invariants checks the allowed state combinations (design §7.2); tests
// call it after every step.
func (a *App) Invariants() error {
var errs []error
if a.viewer.Focus != viewer.Scroll && (a.screen == ScreenBrowse || a.viewer.Kind != viewer.Text) {
errs = append(errs, fmt.Errorf("viewer focus %d on screen %s with kind %d", a.viewer.Focus, a.screen, a.viewer.Kind))
}
if a.nativeSelect && a.screen == ScreenBrowse {
errs = append(errs, errors.New("native selection in Browse"))
}
if a.filter != nil && (a.screen == ScreenView || a.modals.Len() > 0) {
errs = append(errs, fmt.Errorf("filter edited on %s with %d modals", a.screen, a.modals.Len()))
}
if a.active != 0 && a.active != 1 {
errs = append(errs, fmt.Errorf("active pane %d", a.active))
}
for i, p := range a.panels {
if n := p.VisibleLen(); n > 0 && (p.Cursor() < 0 || p.Cursor() >= n) {
errs = append(errs, fmt.Errorf("pane %d cursor %d of %d", i, p.Cursor(), n))
}
}
return errors.Join(errs...)
}
// setScreen switches the screen; leaving Info/View resets the viewer focus
// and native selection.
func (a *App) setScreen(s Screen) tea.Cmd {
if s == a.screen {
return nil
}
prev := a.screen
a.screen = s
if s == ScreenBrowse || (prev == ScreenView && s == ScreenInfo) {
a.viewer.Focus = viewer.Scroll
a.nativeSelect = false
}
if s == ScreenView && a.filter != nil {
a.commitFilter()
}
a.relayout()
switch s {
case ScreenInfo:
a.previewFor = ""
return a.requestPreview(false)
case ScreenBrowse:
a.req.Cancel(ReqKey{Kind: ReqPreview})
a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce})
a.previewFor = ""
}
return nil
}
// openView is F3/v: the selected file full screen.
func (a *App) openView() tea.Cmd {
e, ok := a.Active().Selected()
if !ok || e.Parent || e.Navigable() {
return a.notify(notify.Info, "Not a file")
}
a.viewBack = a.screen
a.screen = ScreenView
a.viewer.Focus = viewer.Scroll
if a.filter != nil {
a.commitFilter()
}
a.relayout()
a.previewFor = ""
return a.requestPreview(true)
}
// Viewer focus transitions (design §7.2).
func (a *App) viewerFocus() tea.Cmd {
if !a.viewer.EnterCaret() {
return a.notify(notify.Info, "Preview is not text")
}
return nil
}
func (a *App) viewerCaret() tea.Cmd {
switch a.viewer.Focus {
case viewer.Visual:
a.viewer.Focus = viewer.Caret
case viewer.Scroll:
if !a.viewer.EnterCaret() {
return a.notify(notify.Info, "Not text")
}
}
return nil
}
func (a *App) viewerVisual() tea.Cmd {
if !a.viewer.EnterVisual() {
return a.notify(notify.Info, "Not text")
}
return nil
}
// viewerBack is Esc: one focus step back, then close.
func (a *App) viewerBack() tea.Cmd {
if a.nativeSelect {
return a.toggleNativeSelect()
}
switch a.viewer.Focus {
case viewer.Visual:
a.viewer.Focus = viewer.Caret
return nil
case viewer.Caret:
a.viewer.Focus = viewer.Scroll
return nil
}
return a.viewerClose()
}
// viewerClose is q/F3: close View, or drop the focus in Info.
func (a *App) viewerClose() tea.Cmd {
a.nativeSelect = false
if a.screen == ScreenView {
a.viewer.Focus = viewer.Scroll
back := a.viewBack
a.screen = back
a.relayout()
a.previewFor = ""
if back == ScreenInfo {
return a.requestPreview(false)
}
return nil
}
a.viewer.Focus = viewer.Scroll
return nil
}
func (a *App) toggleNativeSelect() tea.Cmd {
if a.screen == ScreenBrowse {
return nil
}
a.nativeSelect = !a.nativeSelect
if a.nativeSelect {
return a.notify(notify.Info, "Terminal mouse selection: Ctrl+T or Esc to end")
}
return nil
}
// Filter line.
func (a *App) startFilter() tea.Cmd {
ti := textinput.New()
ti.Prompt = "/"
ti.SetValue(a.Active().Filter())
ti.CursorEnd()
ti.Focus()
a.filter = &ti
a.relayout()
return nil
}
func (a *App) commitFilter() {
a.filter = nil
a.relayout()
}
// filterKey handles a key while the filter line owns input.
func (a *App) filterKey(act keys.ActionID, ok bool, k tea.KeyMsg) tea.Cmd {
p := a.Active()
if ok {
switch act {
case keys.FilterCommit:
a.commitFilter()
case keys.FilterCancel:
p.SetFilter("")
a.commitFilter()
case keys.FilterClearAll:
a.filter.SetValue("")
p.SetFilter("")
case keys.NavUp:
p.MoveCursor(-1)
case keys.NavDown:
p.MoveCursor(1)
}
return a.selectionChanged()
}
ti, cmd := a.filter.Update(k)
a.filter = &ti
p.SetFilter(ti.Value())
return tea.Batch(cmd, a.selectionChanged())
}
// Preview requests (design §7.7): cursor moves are debounced 100 ms, one
// preview in flight per app, stale results dropped.
const previewDebounce = 100 * time.Millisecond
type previewTickMsg struct{ Ticket Ticket }
type previewMsg struct {
Ticket Ticket
For string
Content viewer.Content
Err error
}
// selectionChanged is called after anything that may move the cursor.
func (a *App) selectionChanged() tea.Cmd {
if a.screen != ScreenInfo {
return nil
}
return a.requestPreview(false)
}
func (a *App) previewKey() (string, vfs.Location, vfs.FileInfo, bool) {
p := a.Active()
e, ok := p.Selected()
if !ok || e.Parent {
return "", vfs.Location{}, vfs.FileInfo{}, false
}
loc := p.Location()
return fmt.Sprintf("%s\x00%s\x00%s", loc.FS.Volume(), loc.Path, e.Name), loc, e.FileInfo, true
}
func (a *App) requestPreview(now bool) tea.Cmd {
key, loc, fi, ok := a.previewKey()
if !ok {
a.req.Cancel(ReqKey{Kind: ReqPreview})
a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce})
a.previewFor = ""
a.viewer.Clear()
return nil
}
if key == a.previewFor {
return nil
}
a.previewFor = key
if !now {
tk, _ := a.req.Begin(ReqKey{Kind: ReqPreviewDebounce})
return tea.Tick(previewDebounce, func(time.Time) tea.Msg { return previewTickMsg{tk} })
}
return a.startPreview(key, loc, fi)
}
func (a *App) startPreview(key string, loc vfs.Location, fi vfs.FileInfo) tea.Cmd {
tk, ctx := a.req.Begin(ReqKey{Kind: ReqPreview})
build := a.deps.Preview
limit := a.deps.Config.Preview.MaxPreviewBytes
return func() tea.Msg {
c, err := build(ctx, loc, fi, limit)
return previewMsg{Ticket: tk, For: key, Content: c, Err: err}
}
}
func (a *App) onPreviewTick(m previewTickMsg) tea.Cmd {
if !a.req.Accept(m.Ticket) {
return nil
}
key, loc, fi, ok := a.previewKey()
if !ok || key != a.previewFor {
return nil
}
return a.startPreview(key, loc, fi)
}
func (a *App) onPreview(m previewMsg) tea.Cmd {
if !a.req.Accept(m.Ticket) {
return nil // stale: must not touch the viewer (U-P1-13)
}
if m.Err != nil {
if errors.Is(m.Err, context.Canceled) {
return nil
}
a.viewer.SetContent(viewer.Content{Kind: viewer.Other, Lines: []string{"Preview failed: " + cleanErr(m.Err).Error()}})
return nil
}
a.viewer.SetContent(m.Content)
return nil
}

184
internal/tui/nav.go Normal file
View file

@ -0,0 +1,184 @@
package tui
import (
"context"
"errors"
"fmt"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/notify"
"vcom/internal/tui/panel"
"vcom/internal/vfs"
)
// listingMsg is the result of a directory read for pane.
type listingMsg struct {
Ticket Ticket
Pane int
Target panel.Target
Infos []vfs.FileInfo
Err error
Focus string
Mode panel.NavMode
Reload bool // refresh of the current directory (keep cursor, filter)
Climb bool // a refresh whose directory vanished: walking up
}
// readDir is the Cmd reading t; it captures only immutable inputs.
func readDir(ctx context.Context, tk Ticket, pane int, t panel.Target, focus string, mode panel.NavMode, reload, climb bool) tea.Cmd {
return func() tea.Msg {
infos, err := t.FS().ReadDir(ctx, t.Path)
return listingMsg{Ticket: tk, Pane: pane, Target: t, Infos: infos, Err: err, Focus: focus, Mode: mode, Reload: reload, Climb: climb}
}
}
// navigate starts the transaction "show t in pane". The panel changes only
// when the listing arrives and succeeds (U-P1-8); a newer navigation of the
// same pane makes this one stale (U-P1-13).
func (a *App) navigate(pane int, t panel.Target, focus string, mode panel.NavMode) tea.Cmd {
tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: pane})
a.panels[pane].Loading = true
return readDir(ctx, tk, pane, t, focus, mode, false, false)
}
// reload re-reads the current directory of pane.
func (a *App) reload(pane int) tea.Cmd {
p := a.panels[pane]
if p.Source != panel.SourceDir {
return nil
}
tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: pane})
p.Loading = true
return readDir(ctx, tk, pane, p.Here(), "", panel.NavReplace, true, false)
}
// invalidate reloads every panel showing one of locs (after an operation:
// each panel keeps its own cursor; U-P1-7, N-P1-11).
func (a *App) invalidate(locs []vfs.Location) tea.Cmd {
var cmds []tea.Cmd
for i, p := range a.panels {
for _, l := range locs {
if p.Location().Same(l) {
cmds = append(cmds, a.reload(i))
break
}
}
}
return tea.Batch(cmds...)
}
func (a *App) onListing(m listingMsg) tea.Cmd {
if !a.req.Accept(m.Ticket) {
return nil // stale: a newer navigation of this pane won
}
p := a.panels[m.Pane]
p.Loading = false
if m.Err != nil {
if (m.Reload || m.Climb) && errors.Is(m.Err, vfs.ErrNotExist) {
// The directory vanished: walk up to the nearest existing parent.
tmp := panel.New(-1, p.Opts, m.Target.Mounts, m.Target.Path)
if t, _, _, ok := tmp.ParentTarget(); ok {
tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: m.Pane})
p.Loading = true
return readDir(ctx, tk, m.Pane, t, "", panel.NavReplace, false, true)
}
}
if errors.Is(m.Err, context.Canceled) {
return nil
}
return a.notify(notify.Error, fmt.Sprintf("Cannot open %s: %v", displayPath(m.Target.Location()), cleanErr(m.Err)))
}
if m.Reload {
p.Reload(m.Infos)
} else {
p.Apply(m.Target, m.Infos, m.Focus, m.Mode)
}
var cmd tea.Cmd
if m.Climb {
cmd = a.notify(notify.Warn, "Directory vanished, moved up to "+displayPath(p.Location()))
}
if m.Pane == a.active {
return tea.Batch(cmd, a.selectionChanged())
}
return cmd
}
// openSelected is Enter: go into directories (and links to them), up on
// "..". Files are dispatched by stage 6.6 (edit / run menu / xdg-open).
func (a *App) openSelected() tea.Cmd {
e, ok := a.Active().Selected()
if !ok {
return nil
}
if e.Parent {
return a.goParent()
}
if e.Navigable() {
return a.enterSelected()
}
if a.openFile != nil {
return a.openFile(a, e)
}
return a.notify(notify.Info, "Opening files: not available yet")
}
// enterSelected is l/→: enter a directory; nothing on files.
func (a *App) enterSelected() tea.Cmd {
p := a.Active()
e, ok := p.Selected()
if !ok {
return nil
}
if e.Parent {
return a.goParent()
}
if !e.Navigable() {
return nil
}
return a.navigate(a.active, p.ChildTarget(e.Name), "", panel.NavPush)
}
// goParent is h/←/Backspace and Enter on "..".
func (a *App) goParent() tea.Cmd {
p := a.Active()
t, focus, _, ok := p.ParentTarget()
if !ok {
return nil
}
return a.navigate(a.active, t, focus, panel.NavPush)
}
// history goes back (or forward) in the active panel.
func (a *App) history(forward bool) tea.Cmd {
p := a.Active()
snap, ok := p.BackTarget()
mode := panel.NavBack
if forward {
snap, ok = p.ForwardTarget()
mode = panel.NavForward
}
if !ok {
return nil
}
return a.navigate(a.active, snap.Target, snap.Focus, mode)
}
// displayPath renders a location for messages and titles.
func displayPath(l vfs.Location) string {
if l.FS == nil || l.FS.Kind() == vfs.KindLocal {
return l.Path
}
return l.FS.Label() + ":" + l.Path
}
// cleanErr drops the "op path:" prefix of a path error (the message
// already names the path).
func cleanErr(err error) error {
if u, ok := err.(interface{ Unwrap() error }); ok {
if in := u.Unwrap(); in != nil {
return in
}
}
return err
}

View file

@ -0,0 +1,142 @@
// Package notify is the notification center of the new UI (design §7.6):
// short messages shown in the status line with a time-to-live by level and
// a log of the last 200 for the "L" list. Notifications are not modals, so
// a timer can only ever hide its own note (U-P1-1, crutch #13).
//
// The center does no timing itself: Push returns the note and its TTL; the
// App schedules tea.Tick(ttl, expiredMsg{ID}) and calls Expire(ID) — only
// that note is affected. Errors stay until a key is pressed after the TTL.
package notify
import "time"
// Level of a note.
type Level uint8
const (
Info Level = iota
Success
Warn
Error
)
func (l Level) String() string {
switch l {
case Info:
return "info"
case Success:
return "ok"
case Warn:
return "warn"
case Error:
return "error"
}
return "?"
}
// TTL is how long a note of level l stays: Info/Success 3 s, Warn 6 s,
// Error at least 3 s and then until the next key press.
func TTL(l Level) time.Duration {
if l == Warn {
return 6 * time.Second
}
return 3 * time.Second
}
// LogSize is how many notes Log keeps.
const LogSize = 200
// Note is one notification.
type Note struct {
ID uint64
Level Level
Text string
At time.Time
ttlDone bool // the TTL timer fired
keyHit bool // (Error) a key was pressed after Push
hidden bool
}
// Center holds notes. Not safe for concurrent use (UI goroutine only).
type Center struct {
nextID uint64
live []*Note // not yet hidden, oldest first
log []Note // ring, oldest first
}
// Push adds a note and returns it; schedule Expire(n.ID) after TTL(n.Level).
func (c *Center) Push(l Level, text string, now time.Time) Note {
c.nextID++
n := &Note{ID: c.nextID, Level: l, Text: text, At: now}
c.live = append(c.live, n)
c.log = append(c.log, *n)
if len(c.log) > LogSize {
c.log = c.log[len(c.log)-LogSize:]
}
return *n
}
// Expire is called when the TTL timer of note id fires. It hides that note
// only — an Error note stays until a key was pressed.
func (c *Center) Expire(id uint64) {
for _, n := range c.live {
if n.ID != id {
continue
}
n.ttlDone = true
if n.Level != Error || n.keyHit {
n.hidden = true
}
}
c.compact()
}
// KeyPressed dismisses Error notes whose minimum time has passed and marks
// younger ones to go when their timer fires.
func (c *Center) KeyPressed() {
for _, n := range c.live {
if n.Level != Error {
continue
}
n.keyHit = true
if n.ttlDone {
n.hidden = true
}
}
c.compact()
}
// Dismiss hides note id at once.
func (c *Center) Dismiss(id uint64) {
for _, n := range c.live {
if n.ID == id {
n.hidden = true
}
}
c.compact()
}
func (c *Center) compact() {
out := c.live[:0]
for _, n := range c.live {
if !n.hidden {
out = append(out, n)
}
}
for i := len(out); i < len(c.live); i++ {
c.live[i] = nil
}
c.live = out
}
// Current is the note to show: the newest one still alive.
func (c *Center) Current() (Note, bool) {
if len(c.live) == 0 {
return Note{}, false
}
return *c.live[len(c.live)-1], true
}
// Log returns the last LogSize notes, oldest first.
func (c *Center) Log() []Note { return append([]Note(nil), c.log...) }

View file

@ -0,0 +1,81 @@
package notify
import (
"fmt"
"testing"
"time"
)
var t0 = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
func TestNoteTTLByLevel(t *testing.T) {
if TTL(Info) != 3*time.Second || TTL(Success) != 3*time.Second || TTL(Warn) != 6*time.Second || TTL(Error) != 3*time.Second {
t.Fatal("TTL table")
}
var c Center
info := c.Push(Info, "copied", t0)
c.Expire(info.ID)
if _, ok := c.Current(); ok {
t.Fatal("info survived its TTL")
}
// Error: the timer alone does not hide it; a key afterwards does.
e := c.Push(Error, "boom", t0)
c.Expire(e.ID)
if n, ok := c.Current(); !ok || n.ID != e.ID {
t.Fatal("error hidden by its timer without a key press")
}
c.KeyPressed()
if _, ok := c.Current(); ok {
t.Fatal("error not dismissed by a key after its TTL")
}
// Error: a key before the minimum time does not hide it at once.
e2 := c.Push(Error, "boom2", t0)
c.KeyPressed()
if n, ok := c.Current(); !ok || n.ID != e2.ID {
t.Fatal("error dismissed before its minimum time")
}
c.Expire(e2.ID)
if _, ok := c.Current(); ok {
t.Fatal("error with an earlier key press not hidden when its timer fired")
}
}
// Crutch #13: a timer closed whatever was showing.
func TestTimerClosesOnlyOwnNote(t *testing.T) {
var c Center
a := c.Push(Info, "a", t0)
b := c.Push(Warn, "b", t0)
c.Expire(a.ID)
if n, ok := c.Current(); !ok || n.ID != b.ID {
t.Fatalf("current = %+v %v, want b", n, ok)
}
c.Expire(a.ID) // twice: no effect
c.Expire(999) // unknown: no effect
if n, _ := c.Current(); n.ID != b.ID {
t.Fatal("stray expire hid b")
}
c.Expire(b.ID)
if _, ok := c.Current(); ok {
t.Fatal("b survived")
}
// An older live note shows again when a newer one goes.
x := c.Push(Warn, "x", t0)
y := c.Push(Info, "y", t0)
c.Expire(y.ID)
if n, _ := c.Current(); n.ID != x.ID {
t.Fatal("older note not shown")
}
}
func TestLogRing(t *testing.T) {
var c Center
for i := 0; i < LogSize+50; i++ {
c.Push(Info, fmt.Sprint(i), t0)
}
l := c.Log()
if len(l) != LogSize || l[0].Text != "50" || l[len(l)-1].Text != fmt.Sprint(LogSize+49) {
t.Fatalf("log: %d entries, first %q", len(l), l[0].Text)
}
}

124
internal/tui/panel/entry.go Normal file
View file

@ -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
}

44
internal/tui/panel/lru.go Normal file
View file

@ -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) }

594
internal/tui/panel/panel.go Normal file
View file

@ -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)))
}

View file

@ -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" }

View file

@ -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
}

45
internal/tui/quit.go Normal file
View file

@ -0,0 +1,45 @@
package tui
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/modal"
)
// askQuit is q/F10 in Browse (and Ctrl+C with nothing to clear). With
// confirm_quit or running jobs it asks; "q q" quits fast because the Quit
// button's hotkey is q (U-P1-16). Running jobs are cancelled and cleaned
// up by main's teardown (jobs.Shutdown).
func (a *App) askQuit() tea.Cmd {
n := a.activeJobCount()
if !a.deps.Config.Behavior.ConfirmQuit && n == 0 {
return a.quit()
}
d := &modal.Dialog{
Title: "Quit vcom?",
Buttons: []modal.Button{
{Label: "Quit", Key: "q", Value: true, Default: true},
{Label: "Back", Key: "n", Cancel: true},
},
}
if n > 0 {
d.Title = "Quit and cancel operations?"
d.Warnings = []string{fmt.Sprintf("%d operation(s) running: they will be cancelled and their temp files removed", n)}
d.Buttons[0].Label = "Cancel them and quit"
d.Buttons[0].Danger = true
}
a.openModal(d, func(o modal.Outcome) tea.Cmd {
if o.Cancelled {
return nil
}
return a.quit()
})
return nil
}
func (a *App) quit() tea.Cmd {
a.quitting = true
return tea.Quit
}

View file

@ -0,0 +1,7 @@
package tui
// registerArchive adds the action handlers of stage 6.5 (stub until then).
func registerArchive(t actionTable) {}
// registerArchiveHooks adds message and job-event handlers of stage 6.5.
func registerArchiveHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerMisc adds the action handlers of stage 6.6 (stub until then).
func registerMisc(t actionTable) {}
// registerMiscHooks adds message and job-event handlers of stage 6.6.
func registerMiscHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerOps adds the action handlers of stage 6.2 (stub until then).
func registerOps(t actionTable) {}
// registerOpsHooks adds message and job-event handlers of stage 6.2.
func registerOpsHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerSSH adds the action handlers of stage 6.4 (stub until then).
func registerSSH(t actionTable) {}
// registerSSHHooks adds message and job-event handlers of stage 6.4.
func registerSSHHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerViewer adds the action handlers of stage 6.3 (stub until then).
func registerViewer(t actionTable) {}
// registerViewerHooks adds message and job-event handlers of stage 6.3.
func registerViewerHooks(a *App) {}

98
internal/tui/status.go Normal file
View file

@ -0,0 +1,98 @@
package tui
import (
"fmt"
"strings"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/notify"
"vcom/internal/tui/viewer"
)
// modeBadge names the mode shown at the left of the status line.
func (a *App) modeBadge() string {
switch {
case a.nativeSelect:
return "SELECT"
case a.filter != nil:
return "FILTER"
case a.viewer.Focus == viewer.Visual && a.screen != ScreenBrowse:
return "VISUAL"
case a.viewer.Focus == viewer.Caret && a.screen != ScreenBrowse:
return "CARET"
case a.screen == ScreenView:
return "VIEW"
case a.screen == ScreenInfo:
return "INFO"
}
return ""
}
// statusLine: mode badge and current note on the left; jobs and the
// connection state of the active panel on the right (design §7.6).
func (a *App) statusLine() string {
st := a.styles
w := a.layout.Status.W
var left strings.Builder
if b := a.modeBadge(); b != "" {
left.WriteString(st.Badge.Render(b))
left.WriteString(st.Status.Render(" "))
}
if n, ok := a.notes.Current(); ok {
s := st.NoteInfo
switch n.Level {
case notify.Success:
s = st.NoteOK
case notify.Warn:
s = st.NoteWarn
case notify.Error:
s = st.NoteError
}
left.WriteString(s.Render(n.Text))
} else if e, ok := a.Active().Selected(); ok && !e.Parent {
left.WriteString(st.Status.Render(e.Name))
}
var right []string
if jobs := a.activeJobs(); len(jobs) > 0 {
j := jobs[0]
pct := ""
if t := j.Progress.BytesTotal; t > 0 {
pct = fmt.Sprintf(" %d%%", j.Progress.BytesDone*100/t)
}
r := fmt.Sprintf("⟳ %s%s", j.Title, pct)
if len(jobs) > 1 {
r += fmt.Sprintf(" · +%d", len(jobs)-1)
}
right = append(right, r)
}
if b := a.Active().Badge; b != "" {
right = append(right, b)
}
r := st.Status.Render(strings.Join(right, " "))
rw := ansi.StringWidth(r)
l := ansi.Truncate(left.String(), max(0, w-rw-1), "…")
gap := max(0, w-ansi.StringWidth(l)-rw)
return l + st.Status.Render(strings.Repeat(" ", gap)) + r
}
// footerLine lists the footer bindings of the context owning input.
func (a *App) footerLine() string {
st := a.styles
w := a.layout.Footer.W
var b strings.Builder
used := 0
for _, it := range a.keys.Footer(a.inputOwner()) {
k := st.FooterKey.Render(it.Keys)
h := st.Footer.Render(" " + it.Help + " ")
n := ansi.StringWidth(k) + ansi.StringWidth(h)
if used+n > w {
break
}
b.WriteString(k)
b.WriteString(h)
used += n
}
return b.String() + st.Footer.Render(strings.Repeat(" ", max(0, w-used)))
}

102
internal/tui/style/style.go Normal file
View file

@ -0,0 +1,102 @@
// Package style builds every lipgloss style of the new UI once per theme
// (design §7.10): render code never calls lipgloss.NewStyle. Gen changes
// with every theme switch and is part of every render-cache key.
package style
import (
"sync/atomic"
"github.com/charmbracelet/lipgloss"
"vcom/internal/theme"
)
var gens atomic.Uint64
// Styles of one theme.
type Styles struct {
Gen uint64
Pal theme.Palette
// Panels.
PaneBorder lipgloss.Style
PaneBorderActive lipgloss.Style
PaneTitle lipgloss.Style
PaneTitleActive lipgloss.Style
Row lipgloss.Style
RowCursor lipgloss.Style // cursor in the active pane
RowCursorPassive lipgloss.Style // cursor in the passive pane
RowMarked lipgloss.Style
RowMuted lipgloss.Style
Dir lipgloss.Style
Link lipgloss.Style
Exec lipgloss.Style
FilterLine lipgloss.Style
// Status line and footer.
Status lipgloss.Style
Badge lipgloss.Style
NoteInfo lipgloss.Style
NoteOK lipgloss.Style
NoteWarn lipgloss.Style
NoteError lipgloss.Style
Footer lipgloss.Style
FooterKey lipgloss.Style
// Modals.
Modal lipgloss.Style
ModalTitle lipgloss.Style
ModalLabel lipgloss.Style
ModalWarning lipgloss.Style
Button lipgloss.Style
ButtonFocused lipgloss.Style
ButtonDanger lipgloss.Style
ListCursor lipgloss.Style
Muted lipgloss.Style
Text lipgloss.Style
Section lipgloss.Style
}
// New builds the styles of p.
func New(p theme.Palette) *Styles {
base := lipgloss.NewStyle().Foreground(p.Text)
return &Styles{
Gen: gens.Add(1),
Pal: p,
PaneBorder: lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(p.Border),
PaneBorderActive: lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(p.BorderActive),
PaneTitle: lipgloss.NewStyle().Foreground(p.Muted),
PaneTitleActive: lipgloss.NewStyle().Foreground(p.ActivePath).Bold(true),
Row: base,
RowCursor: lipgloss.NewStyle().Foreground(p.Text).Background(p.Selection).Bold(true),
RowCursorPassive: lipgloss.NewStyle().Foreground(p.Text).Background(p.Hover),
RowMarked: lipgloss.NewStyle().Foreground(p.Marked).Bold(true),
RowMuted: lipgloss.NewStyle().Foreground(p.Muted),
Dir: lipgloss.NewStyle().Foreground(p.Folder).Bold(true),
Link: lipgloss.NewStyle().Foreground(p.Accent),
Exec: lipgloss.NewStyle().Foreground(p.ExecFile),
FilterLine: lipgloss.NewStyle().Foreground(p.Accent),
Status: lipgloss.NewStyle().Foreground(p.Text).Background(p.StatusBar),
Badge: lipgloss.NewStyle().Foreground(p.Background).Background(p.Accent).Bold(true).Padding(0, 1),
NoteInfo: lipgloss.NewStyle().Foreground(p.Info).Background(p.StatusBar),
NoteOK: lipgloss.NewStyle().Foreground(p.Success).Background(p.StatusBar),
NoteWarn: lipgloss.NewStyle().Foreground(p.Warning).Background(p.StatusBar).Bold(true),
NoteError: lipgloss.NewStyle().Foreground(p.Danger).Background(p.StatusBar).Bold(true),
Footer: lipgloss.NewStyle().Foreground(p.Muted).Background(p.Footer),
FooterKey: lipgloss.NewStyle().Foreground(p.FooterKey).Background(p.Footer).Bold(true),
Modal: lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(p.BorderActive).Padding(0, 1),
ModalTitle: lipgloss.NewStyle().Foreground(p.Accent).Bold(true),
ModalLabel: lipgloss.NewStyle().Foreground(p.Muted),
ModalWarning: lipgloss.NewStyle().Foreground(p.Warning),
Button: lipgloss.NewStyle().Foreground(p.Text).Padding(0, 1),
ButtonFocused: lipgloss.NewStyle().Foreground(p.Background).Background(p.ConfirmButton).Bold(true).Padding(0, 1),
ButtonDanger: lipgloss.NewStyle().Foreground(p.Background).Background(p.Danger).Bold(true).Padding(0, 1),
ListCursor: lipgloss.NewStyle().Foreground(p.Text).Background(p.Selection).Bold(true),
Muted: lipgloss.NewStyle().Foreground(p.Muted),
Text: base,
Section: lipgloss.NewStyle().Foreground(p.HelpNav).Bold(true),
}
}

View file

@ -0,0 +1,54 @@
package tui
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/theme"
"vcom/internal/tui/modal"
"vcom/internal/tui/notify"
)
type themeSavedMsg struct {
Theme string
Path string
Err error
}
// openThemeSelect is "t": a list with live preview; Enter keeps and saves
// the theme with config.SetKey (comments kept, design §9.2), Esc reverts.
func (a *App) openThemeSelect() tea.Cmd {
orig := a.theme
var items []modal.Item
for _, n := range theme.Names() {
items = append(items, modal.Item{Label: n, Value: n})
}
l := modal.NewList("Theme", items, orig)
l.OnMove = func(it modal.Item) tea.Cmd {
a.setTheme(it.Value.(string)) // runs in Update: no I/O
return nil
}
a.openModal(l, func(o modal.Outcome) tea.Cmd {
if o.Cancelled {
a.setTheme(orig)
return nil
}
name := o.Value.(string)
a.setTheme(name)
a.deps.Config.UI.Theme = name
set, path := a.deps.SetConfigKey, a.deps.ConfigPath
return func() tea.Msg {
p, err := set(path, "ui", "theme", name)
return themeSavedMsg{Theme: name, Path: p, Err: err}
}
})
return nil
}
func (a *App) onThemeSaved(m themeSavedMsg) tea.Cmd {
if m.Err != nil {
return a.notify(notify.Error, fmt.Sprintf("Theme %s not saved: %v", m.Theme, m.Err))
}
return a.notify(notify.Success, fmt.Sprintf("Theme %s saved to %s", m.Theme, m.Path))
}

95
internal/tui/tracker.go Normal file
View file

@ -0,0 +1,95 @@
package tui
import "context"
// ReqKind is a kind of async request.
type ReqKind uint8
const (
ReqList ReqKind = iota
ReqPreview
ReqPreviewDebounce
ReqDirSize
ReqMount
ReqConnect
ReqFeature // features (6.2–6.6) use ReqKey.Extra to tell their requests apart
)
// ReqKey identifies a request slot: a newer request with the same key
// supersedes the older one.
type ReqKey struct {
Kind ReqKind
Pane int
Extra string
}
// Ticket travels with every async message. Update accepts a message only if
// its ticket is still current (design §7.7, U-P1-13).
type Ticket struct {
Key ReqKey
Gen uint64
}
type slot struct {
gen uint64
cancel context.CancelFunc
live bool
}
// Tracker hands out tickets. UI goroutine only.
type Tracker struct {
gen uint64
slots map[ReqKey]*slot
}
// Begin starts a request for k: the previous one with the same key is
// cancelled and its ticket becomes stale.
func (t *Tracker) Begin(k ReqKey) (Ticket, context.Context) {
if t.slots == nil {
t.slots = map[ReqKey]*slot{}
}
if s := t.slots[k]; s != nil && s.cancel != nil {
s.cancel()
}
t.gen++
ctx, cancel := context.WithCancel(context.Background())
t.slots[k] = &slot{gen: t.gen, cancel: cancel, live: true}
return Ticket{Key: k, Gen: t.gen}, ctx
}
// Accept reports whether tk is the current ticket of its key; if so the
// request is finished (its context released) and the slot freed.
func (t *Tracker) Accept(tk Ticket) bool {
s := t.slots[tk.Key]
if s == nil || !s.live || s.gen != tk.Gen {
return false
}
s.live = false
s.cancel()
delete(t.slots, tk.Key)
return true
}
// Pending reports whether a request for k is in flight.
func (t *Tracker) Pending(k ReqKey) bool {
s := t.slots[k]
return s != nil && s.live
}
// Cancel cancels the request for k (its ticket becomes stale).
func (t *Tracker) Cancel(k ReqKey) {
if s := t.slots[k]; s != nil {
s.cancel()
delete(t.slots, k)
}
}
// CancelAll cancels every request of kind.
func (t *Tracker) CancelAll(kind ReqKind) {
for k, s := range t.slots {
if k.Kind == kind {
s.cancel()
delete(t.slots, k)
}
}
}

154
internal/tui/update.go Normal file
View file

@ -0,0 +1,154 @@
package tui
import (
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/keys"
"vcom/internal/tui/modal"
)
// doubleClick is the max interval between clicks of a double click.
const doubleClick = 400 * time.Millisecond
// Update is the single entry point of the model. It never blocks: all I/O
// runs in Cmds (N-P1-1).
func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmd := a.update(msg)
a.relayout()
return a, tea.Batch(cmd, a.reconcile())
}
func (a *App) update(msg tea.Msg) tea.Cmd {
switch m := msg.(type) {
case tea.WindowSizeMsg:
a.w, a.h = m.Width, m.Height
return nil
case tea.KeyMsg:
return a.key(m)
case tea.MouseMsg:
return a.mouse(m)
case listingMsg:
return a.onListing(m)
case previewTickMsg:
return a.onPreviewTick(m)
case previewMsg:
return a.onPreview(m)
case noteExpiredMsg:
a.notes.Expire(m.id)
return nil
case themeSavedMsg:
return a.onThemeSaved(m)
case jobEventMsg:
return a.onJobEvent(m)
case execDoneMsg:
a.applied.mouse = mouseUnknown // the external program may have reset it (U-P1-3)
return nil
}
for _, h := range a.handlers {
if cmd, ok := h(a, msg); ok {
return cmd
}
}
return nil
}
func (a *App) key(k tea.KeyMsg) tea.Cmd {
a.notes.KeyPressed()
if a.nativeSelect && k.Type == tea.KeyEsc && a.modals.Len() == 0 {
return a.toggleNativeSelect()
}
ctx := a.inputOwner()
act, ok := a.keys.Resolve(ctx, k)
if ok && act == keys.Pending {
return nil
}
switch {
case a.modals.Len() > 0:
return a.modals.Key(act, k)
case ctx == keys.CtxFilterEdit:
return a.filterKey(act, ok, k)
case ok:
return a.dispatch(act)
}
return nil
}
// mouse routes mouse events: everything to the top modal while one is open
// (clicks outside it are ignored); otherwise by Layout hit-test.
func (a *App) mouse(m tea.MouseMsg) tea.Cmd {
if a.modals.Len() > 0 {
return a.modals.Mouse(m, a.layout.Screen, a.styles)
}
if a.nativeSelect {
return nil
}
switch m.Button {
case tea.MouseButtonWheelUp, tea.MouseButtonWheelDown:
d := 3
if m.Button == tea.MouseButtonWheelUp {
d = -3
}
if a.screen == ScreenView || (a.screen == ScreenInfo && a.layout.Preview.Contains(m.X, m.Y)) {
a.viewer.Scroll(d)
return nil
}
if i, ok := a.layout.paneAt(m.X, m.Y); ok {
a.panels[i].Scroll(d)
if i == a.active {
return a.selectionChanged()
}
}
return nil
}
if m.Action != tea.MouseActionPress || a.screen == ScreenView {
return nil
}
i, ok := a.layout.paneAt(m.X, m.Y)
if !ok {
return nil
}
if m.Button == tea.MouseButtonRight {
if a.screen == ScreenInfo {
return a.setScreen(ScreenBrowse)
}
return a.setScreen(ScreenInfo)
}
if m.Button != tea.MouseButtonLeft || a.filter != nil && i != a.active {
return nil
}
if i != a.active {
a.active = i
}
lr := a.listRect(i)
if !lr.Contains(m.X, m.Y) {
return a.selectionChanged()
}
row, ok := a.panels[i].RowAt(m.Y - lr.Y)
if !ok {
return a.selectionChanged()
}
now := a.now()
double := a.lastClick.pane == i && a.lastClick.row == row && now.Sub(a.lastClick.at) <= doubleClick
a.lastClick = click{at: now, pane: i, row: row}
a.panels[i].SetCursor(row)
if double {
a.lastClick = click{}
return a.dispatch(keys.NavOpen)
}
return a.selectionChanged()
}
// openModal pushes m; a filter being edited is committed first (the filter
// line never coexists with a modal).
func (a *App) openModal(m modal.Modal, onClose func(modal.Outcome) tea.Cmd) uint64 {
if a.filter != nil {
a.commitFilter()
}
a.keys.Reset()
return a.modals.Push(m, onClose)
}
// execDoneMsg is sent after an external program (editor, run) returns.
type execDoneMsg struct{ Err error }

133
internal/tui/view.go Normal file
View file

@ -0,0 +1,133 @@
package tui
import (
"strconv"
"strings"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/geom"
"vcom/internal/tui/panel"
"vcom/internal/vfs"
)
// View renders the screen. It only reads state (design §7.9): sizes were
// set in Update (relayout), effects are applied by reconcile.
func (a *App) View() string {
if a.w <= 0 || a.h <= 0 {
return ""
}
canvas := make([]string, a.h)
blank := strings.Repeat(" ", a.w)
for i := range canvas {
canvas[i] = blank
}
draw := func(r geom.Rect, s string) {
if r.Empty() || s == "" {
return
}
for i, line := range strings.Split(s, "\n") {
y := r.Y + i
if i >= r.H || y >= len(canvas) {
break
}
canvas[y] = place(canvas[y], ansi.Truncate(line, r.W, ""), r.X, a.w)
}
}
switch a.screen {
case ScreenView:
draw(a.layout.Viewer, a.renderViewer())
default:
for i, p := range a.panels {
r := a.layout.Panes[i]
if r.Empty() {
continue
}
draw(r, p.Render(panel.View{
Rect: r,
Active: i == a.active,
FilterLine: a.filterLine(i),
Title: a.paneTitle(p),
Styles: a.styles,
}))
}
if a.screen == ScreenInfo {
draw(a.layout.Preview, a.renderPreview())
}
}
draw(a.layout.Status, a.statusLine())
if !a.layout.Footer.Empty() {
draw(a.layout.Footer, a.footerLine())
}
out := strings.Join(canvas, "\n")
return a.modals.Render(out, a.layout.Screen, a.styles)
}
// place writes s into line at column x.
func place(line, s string, x, w int) string {
left := ansi.Truncate(line, x, "")
if n := ansi.StringWidth(left); n < x {
left += strings.Repeat(" ", x-n)
}
right := ansi.TruncateLeft(line, x+ansi.StringWidth(s), "")
out := left + s + right
if n := ansi.StringWidth(out); n < w {
out += strings.Repeat(" ", w-n)
}
return out
}
func (a *App) filterLine(i int) string {
if a.filter == nil || i != a.active {
return ""
}
return a.filter.View()
}
func (a *App) paneTitle(p *panel.Model) string {
if p.Source == panel.SourceHosts {
return "SSH hosts"
}
t := displayPath(p.Location())
if n := p.MarkCount(); n > 0 {
t += " [" + strconv.Itoa(n) + " marked]"
}
return t
}
func (a *App) renderPreview() string {
r := a.layout.Preview
if r.W < 4 || r.H < 3 {
return ""
}
inner := r.W - 2
title := a.viewer.Title()
if title == "" {
if e, ok := a.Active().Selected(); ok && !e.Parent {
title = e.Name
}
}
body := a.viewer.Render(inner, a.layout.PreviewBody.H, a.styles)
content := a.styles.PaneTitle.Render(pad(ansi.Truncate(title, inner, "…"), inner)) + "\n" + body
return a.styles.PaneBorder.Width(inner).Render(content)
}
func (a *App) renderViewer() string {
r := a.layout.Viewer
title := a.viewer.Title()
if title == "" {
title = "View"
}
head := a.styles.PaneTitleActive.Render(pad(ansi.Truncate(title, r.W, "…"), r.W))
return head + "\n" + a.viewer.Render(r.W, max(0, r.H-1), a.styles)
}
func pad(s string, w int) string {
if n := ansi.StringWidth(s); n < w {
return s + strings.Repeat(" ", w-n)
}
return s
}
// locationOf is a helper for features: the active panel's location.
func (a *App) locationOf(i int) vfs.Location { return a.panels[i].Location() }

View file

@ -0,0 +1,179 @@
// Package viewer shows file content in the Info preview and the View
// screen. Stage 6.1 provides the model the App's state machine needs
// (Kind, Focus, Gen, scrolling, a line caret); stage 6.3 replaces the
// rendering with the real TextViewer (cell-accurate caret/visual, wrap,
// yank) and images through imgview.
package viewer
import (
"strings"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/style"
)
// Kind of content.
type Kind uint8
const (
None Kind = iota
Text // lines of text: caret and visual are possible
Image // drawn by imgview (stage 6.3)
Other // metadata only (binary, directory, error)
)
// Focus of the viewer.
type Focus uint8
const (
Scroll Focus = iota // keys scroll
Caret // a cursor in the text
Visual // a selection
)
// Content is what a preview produced.
type Content struct {
Kind Kind
Title string
Lines []string
Image any // preview.ImageRef in stage 6.3
}
// Model is the viewer state.
type Model struct {
Focus Focus
Kind Kind
Gen uint64 // bumps with every SetContent (overlay effects key on it)
Image any
title string
lines []string
offset int
caret int // line of the caret
anchor int // line where Visual started
rows int
}
// SetContent shows c. Non-text content drops the focus back to Scroll.
func (m *Model) SetContent(c Content) {
m.Gen++
m.Kind = c.Kind
m.title = c.Title
m.lines = c.Lines
m.Image = c.Image
m.offset, m.caret, m.anchor = 0, 0, 0
if m.Kind != Text {
m.Focus = Scroll
}
}
// Clear drops the content.
func (m *Model) Clear() { m.SetContent(Content{}) }
// Lines returns the text lines.
func (m *Model) Lines() []string { return m.lines }
// Offset is the first line on screen.
func (m *Model) Offset() int { return m.offset }
// CaretLine is the caret line.
func (m *Model) CaretLine() int { return m.caret }
// SetRows tells the viewer how many lines fit.
func (m *Model) SetRows(n int) { m.rows = max(1, n) }
// Scroll moves the view (Scroll focus) or the caret (Caret/Visual).
func (m *Model) Scroll(delta int) {
if m.Focus == Scroll {
m.offset = max(0, min(m.offset+delta, max(0, len(m.lines)-m.rows)))
return
}
m.caret = max(0, min(m.caret+delta, max(0, len(m.lines)-1)))
if m.caret < m.offset {
m.offset = m.caret
}
if m.caret >= m.offset+m.rows {
m.offset = m.caret - m.rows + 1
}
}
// Page scrolls by a screen.
func (m *Model) Page(dir int) { m.Scroll(dir * max(1, m.rows-1)) }
// Jump goes to the top or the bottom.
func (m *Model) Jump(end bool) {
if end {
m.Scroll(len(m.lines))
} else {
m.Scroll(-len(m.lines))
}
}
// EnterCaret puts the caret on the first visible line (text only).
func (m *Model) EnterCaret() bool {
if m.Kind != Text {
return false
}
m.Focus = Caret
m.caret = min(m.offset, max(0, len(m.lines)-1))
return true
}
// EnterVisual starts a selection at the caret (from Scroll: at the first
// visible line).
func (m *Model) EnterVisual() bool {
if m.Kind != Text {
return false
}
if m.Focus == Scroll {
m.caret = min(m.offset, max(0, len(m.lines)-1))
}
m.Focus = Visual
m.anchor = m.caret
return true
}
// Selection returns the selected lines (Visual) or the caret line.
func (m *Model) Selection() []string {
if len(m.lines) == 0 {
return nil
}
a, b := m.caret, m.caret
if m.Focus == Visual {
a, b = min(m.anchor, m.caret), max(m.anchor, m.caret)
}
return m.lines[a : b+1]
}
// Render draws the visible window into w×h.
func (m *Model) Render(w, h int, st *style.Styles) string {
var b strings.Builder
lo, hi := m.caret, m.caret
if m.Focus == Visual {
lo, hi = min(m.anchor, m.caret), max(m.anchor, m.caret)
}
for row := 0; row < h; row++ {
if row > 0 {
b.WriteByte('\n')
}
i := m.offset + row
line := ""
if i < len(m.lines) {
line = ansi.Truncate(strings.ReplaceAll(m.lines[i], "\t", " "), w, "")
} else if i == 0 && m.Kind == None {
line = st.Muted.Render("(no preview)")
}
if n := ansi.StringWidth(line); n < w {
line += strings.Repeat(" ", w-n)
}
if m.Focus != Scroll && i >= lo && i <= hi && i < len(m.lines) {
line = st.ListCursor.Render(ansi.Strip(line))
}
b.WriteString(line)
}
return b.String()
}
// Title of the content.
func (m *Model) Title() string { return m.title }

View file

@ -0,0 +1,76 @@
package sftpfs
import (
"context"
"errors"
"io"
"path/filepath"
"testing"
"time"
"vcom/internal/testutil/sshtest"
"vcom/internal/vfs"
)
// A read stuck on a frozen link is released shortly after the ctx the file
// was opened with is cancelled, even with the default 15 s keepalive.
func TestFileCancelReleasesStuckRead(t *testing.T) {
s := newStand(t, sshtest.Options{})
px := s.proxy()
f := s.fs(px.Addr)
p := filepath.Join(t.TempDir(), "big")
sshtest.WriteRandom(t, p, 4<<20, 0o644)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fl, err := f.Open(ctx, p)
if err != nil {
t.Fatal(err)
}
defer fl.Close()
px.Freeze(true)
defer px.Freeze(false)
res := make(chan error, 1)
go func() {
_, err := io.Copy(io.Discard, fl)
res <- err
}()
time.Sleep(50 * time.Millisecond)
cancel()
start := time.Now()
select {
case err := <-res:
if !errors.Is(err, vfs.ErrConnLost) {
t.Errorf("err = %v, want ErrConnLost", err)
}
case <-time.After(5 * time.Second):
t.Fatal("stuck read not released")
}
if el := time.Since(start); el > cancelGrace+cancelProbeTimeout+time.Second {
t.Errorf("released after %v", el)
}
}
// Cancelling the ctx of a file on a live link with no stuck operation
// leaves the connection alone.
func TestFileCancelLiveLinkUntouched(t *testing.T) {
s := newStand(t, sshtest.Options{})
f := s.fs("")
p := filepath.Join(t.TempDir(), "small")
sshtest.WriteRandom(t, p, 1000, 0o644)
ctx, cancel := context.WithCancel(context.Background())
fl, err := f.Open(ctx, p)
if err != nil {
t.Fatal(err)
}
cancel()
if _, err := io.Copy(io.Discard, fl); err != nil {
t.Fatal(err)
}
time.Sleep(cancelGrace + 200*time.Millisecond)
if err := fl.Close(); err != nil {
t.Fatal(err)
}
if err := f.Conn().Err(); err != nil {
t.Fatalf("conn: %v", err)
}
}

View file

@ -16,6 +16,7 @@ import (
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/sftp"
@ -266,7 +267,7 @@ func (f *FS) Open(ctx context.Context, p string) (vfs.File, error) {
if err != nil {
return nil, f.wrap("open", p, err)
}
return &file{f: sf, fs: f, path: p}, nil
return newFile(ctx, f, sf, p), nil
}
// Create opens p for writing. CreateExcl fails with vfs.ErrExist on any
@ -295,7 +296,7 @@ func (f *FS) Create(ctx context.Context, p string, perm fs.FileMode, mode vfs.Cr
}
return nil, f.wrap("create", p, err)
}
return &file{f: sf, fs: f, path: p}, nil
return newFile(ctx, f, sf, p), nil
}
func (f *FS) Mkdir(ctx context.Context, p string, perm fs.FileMode) error {
@ -378,11 +379,48 @@ func (f *FS) Exec(ctx context.Context, argv []string) ([]byte, error) {
return out, f.mapErr(err)
}
// Cancel watchdog for open files: when the ctx a file was opened with is
// cancelled while one of its operations is still running, wait
// cancelGrace for it to return (a live link returns at the next chunk),
// then probe the connection; no keepalive reply within cancelProbeTimeout
// marks it Lost, which fails the stuck request at once. On a slow but live
// link the probe succeeds and nothing is torn down. Variables for tests.
var (
cancelGrace = 300 * time.Millisecond
cancelProbeTimeout = 1500 * time.Millisecond
)
// file is an open remote file.
type file struct {
f *sftp.File
fs *FS
path string
inflight atomic.Int32
stop func() bool // unregisters the cancel watchdog
}
func newFile(ctx context.Context, f *FS, sf *sftp.File, p string) *file {
fl := &file{f: sf, fs: f, path: p}
fl.stop = context.AfterFunc(ctx, fl.onCancel)
return fl
}
func (fl *file) onCancel() {
// No early exit on inflight == 0: an operation may be just starting.
t := time.NewTimer(cancelGrace)
defer t.Stop()
<-t.C
if fl.inflight.Load() == 0 {
return
}
_ = fl.fs.c.Probe(context.Background(), cancelProbeTimeout)
}
// track marks an operation in flight for the cancel watchdog.
func (fl *file) track() func() {
fl.inflight.Add(1)
return func() { fl.inflight.Add(-1) }
}
func (fl *file) err(op string, err error) error {
@ -393,16 +431,19 @@ func (fl *file) err(op string, err error) error {
}
func (fl *file) Read(p []byte) (int, error) {
defer fl.track()()
n, err := fl.f.Read(p)
return n, fl.err("read", err)
}
func (fl *file) ReadAt(p []byte, off int64) (int, error) {
defer fl.track()()
n, err := fl.f.ReadAt(p, off)
return n, fl.err("read", err)
}
func (fl *file) Write(p []byte) (int, error) {
defer fl.track()()
n, err := fl.f.Write(p)
return n, fl.err("write", err)
}
@ -411,19 +452,29 @@ func (fl *file) Write(p []byte) (int, error) {
// source should expose Size() int64 (os.File, bytes.Reader, the transfer
// engine's ctx reader), otherwise pkg/sftp falls back to sequential writes.
func (fl *file) ReadFrom(r io.Reader) (int64, error) {
defer fl.track()()
n, err := fl.f.ReadFrom(r)
return n, fl.err("write", err)
}
// WriteTo lets io.Copy use concurrent reads.
func (fl *file) WriteTo(w io.Writer) (int64, error) {
defer fl.track()()
n, err := fl.f.WriteTo(w)
return n, fl.err("read", err)
}
func (fl *file) Close() error { return fl.err("close", fl.f.Close()) }
// Close closes the remote handle. A Close racing a stuck operation (the
// transfer engine closes on cancel) is covered by the cancel watchdog too.
func (fl *file) Close() error {
defer fl.track()()
err := fl.f.Close()
fl.stop()
return fl.err("close", err)
}
func (fl *file) Stat() (vfs.FileInfo, error) {
defer fl.track()()
fi, err := fl.f.Stat()
if err != nil {
return vfs.FileInfo{}, fl.err("stat", err)
@ -435,5 +486,6 @@ func (fl *file) Sync() error {
if !fl.fs.caps.Fsync {
return &fs.PathError{Op: "sync", Path: fl.path, Err: vfs.ErrUnsupported}
}
defer fl.track()()
return fl.err("sync", fl.f.Sync())
}

View file

@ -174,3 +174,52 @@
листает (слияние каталогов); для одиночного файла в корне `ToDir` (≤ 4 корня → Lstat вместо ReadDir) остаток не
замечается. Варианты: после Retry с новым поколением соединения удалять temp прошлой попытки (executor знает его
имя), или листать `ToDir` при наличии `partPrefix`-подозрений. Тест `TestOverwriteThenDrop` это только логирует.
## Латентность отмены на замёрзшей сети (после 3.7)
- **Сторожок отмены в `sftpfs.File`:** файл запоминает ctx, с которым его открыли (`Open/Create`), и регистрирует
`context.AfterFunc`. При отмене ждём `cancelGrace` (300 мс); если операция файла (Read/Write/ReadFrom/WriteTo/
Close/Stat/Sync) всё ещё идёт — `Conn.Probe(cancelProbeTimeout = 1,5 с)`. Нет ответа на keepalive → `Lost`,
транспорт закрыт, pkg/sftp сразу возвращает ошибку (и `ReadFrom`, и висящий `Close`). Живая, но медленная сеть
отвечает на probe — ничего не рвём (`TestRemoteSlowLinkCancelKeepsConn`, RTT 300 мс). Регистрация снимается в
`Close`. Это не требует изменений в `transfer`: движок и так открывает файлы с ctx джобы.
- Итог при дефолтном keepalive (15 с × 2 + 10 с): freeze посреди файла → cancel → возврат ≈ 1,8 с (upload и
download; было до ~40 с). Тесты: `TestRemoteFreezeCancelDefaultKeepalive` (transfer, ≤ 3 с, старая цель цела),
`TestFileCancelReleasesStuckRead`, `TestFileCancelLiveLinkUntouched` (sftpfs).
- **Компромисс:** на очень медленном канале с большой очередью неотправленных данных ответ на keepalive может
прийти позже 1,5 с, и соединение будет признано потерянным после отмены (только после отмены — без отмены
сторожок не работает). Последствие — reconnect при следующем действии, данные не страдают. Значения — переменные
пакета, их легко поднять.
## 6.1 Каркас нового UI `internal/tui`
- **Пакеты:** `tui` (App), `tui/keys`, `tui/notify`, `tui/modal`, `tui/panel`, плюс два вспомогательных сверх плана:
`tui/style` (все lipgloss-стили строятся один раз на тему, `Gen` входит в ключи кэшей — §7.10) и `tui/geom`
(`Rect` — общий для layout, рендера и hit-test). `tui/viewer` в 6.1 — минимальная модель (Kind/Focus/Gen,
прокрутка, построчный caret/visual), чтобы машина состояний и тесты 6.1 работали; 6.3 заменяет рендер.
- **Контексты keys** сверх §7.4: `CtxModalConflict`, `CtxModalPrompt` (под 6.2/6.4; Prompt — текстовый). Клавиша
Shift+F8 — это `f20` (так её шлёт xterm; у Bubble Tea v1 нет имени `shift+f8`), Shift+Delete в v1 не различается —
остаётся `X`. Горячие клавиши кнопок Dialog матчатся самим Dialog (в т. ч. в ЙЦУКЕН через `keys.Translate`) и
имеют приоритет над `q` = отмена, поэтому «q q» в диалоге выхода выходит.
- **Modal API:** `Key(action, rawKey)` + `Mouse(msg, relX, relY, w, h, styles)` + `View`, без `ID()` — id выдаёт
`Stack.Push`, `onClose func(Outcome) tea.Cmd` (замыкание на `*App` выполняется синхронно в Update, не в Cmd).
- **Уведомления:** `Center` не считает время сам: `Push` → App планирует `tea.Tick(TTL, noteExpiredMsg{id})` →
`Expire(id)` скрывает только свою заметку; Error дополнительно ждёт нажатия (`KeyPressed`).
- **Panel:** история хранит снимки со стеком mount-ов, но без отдельного `Acquire` на каждый снимок: при выходе из
mount-а (архив/хост) снимки, ссылающиеся на него, выбрасываются, и mount освобождается, когда его не держит ни
текущее место, ни история (вперёд в закрытый архив не вернуться — проще и без утечек). Mirror (`MirrorOf`)
делает `Acquire` у каждого mount-а. Размеры каталогов (`sizes`) и бейдж соединения — поля для 6.2/6.4.
- **Точки расширения App** (чтобы 6.2–6.6 не трогали `app.go`): `register<Feature>(actionTable)` и
`register<Feature>Hooks(*App)` в `register_*.go`; `a.handle(fn)` для своих сообщений; `a.onJob(fn)` для событий
jobs; `a.openFile` — Enter на не-каталоге (6.5 архивы, 6.6 edit/run/open); `a.invalidate(locs)` после операций;
`a.openModal`, `a.notify`, `a.navigate`, `a.req` (Tracker, `ReqFeature` + `Extra` для своих запросов). Действие
без обработчика показывает «…: not available yet».
- **Превью по умолчанию** (`Deps.Preview`, до 5B/6.3): голова текстового файла через `vfs.FS.Open`, иначе метаданные.
- **Imports guard** проверяет не-тестовые файлы (`_test.go` пропускаются — тестам нужны `os`/`localfs` для стенда);
allowlist `deps.go`, `external.go`. Дополнительно `TestNoRawKeyMatching`: вне `keys/` нет `x.String() == "…"` и
`key.Matches` (§7.4).
- **main:** `--ui=next` (по умолчанию `old`). Pool (keepalive/таймаут из `[ssh]`), jobs (`max_parallel_jobs`,
notify → `program.Send(tui.JobEvent(e))` через atomic-указатель на программу), Resolver + Store в `Deps`;
teardown после `Run`: `jobs.Shutdown(3 с)`, `pool.Close()`. SyncTTY и imgview — после 5C (их пакетов ещё нет).
Сессия нового UI — 6.6. Ручной прогон в pty в этой среде невозможен (нет терминала, отвечающего на запрос цвета
фона lipgloss); проверено драйвером.