feat(tui): full preview, text viewer and image overlays (6.3)
Some checks failed
CI / test (push) Failing after 6m3s
Some checks failed
CI / test (push) Failing after 6m3s
This commit is contained in:
parent
55b24dabc6
commit
1bdff32a84
19 changed files with 1432 additions and 107 deletions
|
|
@ -9,6 +9,7 @@ import (
|
|||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
|
@ -16,6 +17,7 @@ import (
|
|||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"vcom/internal/config"
|
||||
"vcom/internal/imgview"
|
||||
"vcom/internal/jobs"
|
||||
"vcom/internal/logx"
|
||||
"vcom/internal/paths"
|
||||
|
|
@ -173,10 +175,16 @@ func shutdown(final tea.Model) {
|
|||
// every connection; it runs after Program.Run returns.
|
||||
func startNext(cfg config.Config, cfgPath, notice, runDir string) (*tea.Program, func()) {
|
||||
var prog atomic.Pointer[tea.Program]
|
||||
var pendingMu sync.Mutex
|
||||
var pending []tea.Msg
|
||||
send := func(m tea.Msg) {
|
||||
if p := prog.Load(); p != nil {
|
||||
p.Send(m)
|
||||
return
|
||||
}
|
||||
pendingMu.Lock()
|
||||
pending = append(pending, m)
|
||||
pendingMu.Unlock()
|
||||
}
|
||||
readHome, _ := paths.ReadHome()
|
||||
deps := tui.DefaultDeps(cfg, cfgPath)
|
||||
|
|
@ -208,10 +216,29 @@ func startNext(cfg config.Config, cfgPath, notice, runDir string) (*tea.Program,
|
|||
}
|
||||
deps.Resolver = res
|
||||
|
||||
p := tea.NewProgram(tui.New(deps), tea.WithAltScreen(), tea.WithMouseCellMotion())
|
||||
tty := imgview.NewSyncTTY(os.Stdout)
|
||||
images := imgview.Start(imgview.Options{
|
||||
Backend: imgview.Detect(cfg.Preview.ImageBackend, os.Getenv),
|
||||
TTY: tty,
|
||||
TmpDir: runDir,
|
||||
Tmux: os.Getenv("TMUX") != "",
|
||||
OnEvent: func(e imgview.Event) { send(tui.ImageEvent(e)) },
|
||||
})
|
||||
deps.Image = images
|
||||
p := tea.NewProgram(tui.New(deps), tea.WithAltScreen(), tea.WithMouseCellMotion(), tea.WithOutput(tty))
|
||||
prog.Store(p)
|
||||
pendingMu.Lock()
|
||||
queued := append([]tea.Msg(nil), pending...)
|
||||
pending = nil
|
||||
pendingMu.Unlock()
|
||||
go func() {
|
||||
for _, m := range queued {
|
||||
p.Send(m)
|
||||
}
|
||||
}()
|
||||
return p, func() {
|
||||
prog.Store(nil)
|
||||
images.Stop()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := deps.Jobs.Shutdown(ctx); err != nil {
|
||||
|
|
|
|||
|
|
@ -30,7 +30,8 @@ type Desired struct {
|
|||
Visible bool
|
||||
Image preview.ImageRef
|
||||
Rect Rect
|
||||
Gen uint64
|
||||
Gen uint64 // content generation, used by the UI's change detection
|
||||
Seq uint64 // effect order; zero keeps the standalone API unordered
|
||||
}
|
||||
|
||||
func (d Desired) same(o Desired) bool {
|
||||
|
|
@ -122,9 +123,13 @@ func (a *Actor) Backend() Backend {
|
|||
}
|
||||
|
||||
// Apply records the desired state and returns at once; only the latest
|
||||
// state is drawn.
|
||||
// state is drawn. Non-zero Seq values reject commands delivered out of order.
|
||||
func (a *Actor) Apply(d Desired) {
|
||||
a.mu.Lock()
|
||||
if d.Seq != 0 && a.want.Seq > d.Seq {
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
a.want, a.dirty = d, true
|
||||
a.mu.Unlock()
|
||||
select {
|
||||
|
|
|
|||
|
|
@ -340,3 +340,12 @@ func BenchmarkKittyPayloadDecoded6000x4000(b *testing.B) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestActorRejectsOutOfOrderDesired(t *testing.T) {
|
||||
a := &Actor{signal: make(chan struct{}, 1)}
|
||||
a.Apply(Desired{Visible: true, Seq: 2})
|
||||
a.Apply(Desired{Visible: false, Seq: 1})
|
||||
if !a.want.Visible || a.want.Seq != 2 {
|
||||
t.Fatalf("older desired state replaced the newer one: %#v", a.want)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@ func registerCore(t actionTable) {
|
|||
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).
|
||||
// Viewer focus machine; stage 6.3 registers the full motion set.
|
||||
t.add(keys.ViewerFocus, (*App).viewerFocus, nil)
|
||||
t.add(keys.ViewerCaret, (*App).viewerCaret, nil)
|
||||
t.add(keys.ViewerVisual, (*App).viewerVisual, nil)
|
||||
|
|
|
|||
|
|
@ -94,6 +94,9 @@ func New(d Deps) *App {
|
|||
d.fill()
|
||||
a := &App{deps: d, keys: keys.MustDefault(), jobSnaps: map[uint64]jobSnap{}}
|
||||
a.setTheme(d.Config.UI.Theme)
|
||||
if d.Config.Preview.WrapText {
|
||||
a.viewer.ToggleWrap()
|
||||
}
|
||||
opts := a.panelOptions()
|
||||
for i := range a.panels {
|
||||
m := panel.NewMount(d.LocalFS, "/", nil, "", nil, nil)
|
||||
|
|
|
|||
|
|
@ -43,6 +43,8 @@ func newHarness(t *testing.T, fsys vfs.FS, dir string, opts ...opt) *harness {
|
|||
LocalFS: fsys,
|
||||
StartDirs: [2]string{dir, dir},
|
||||
SetConfigKey: func(string, string, string, any) (string, error) { return "test.toml", nil },
|
||||
Opener: []string{"true"},
|
||||
Clipboard: func(string) error { return nil },
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&d)
|
||||
|
|
@ -349,7 +351,8 @@ func TestInvariantsAfterEachStep(t *testing.T) {
|
|||
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 }})
|
||||
SetConfigKey: func(string, string, string, any) (string, error) { return "x", nil },
|
||||
Opener: []string{"true"}, Clipboard: func(string) error { return nil }})
|
||||
d := teadriver.New(t, app, 80, 24, teadriver.WithLongCmd(20*time.Millisecond))
|
||||
d.Settle(settle)
|
||||
for i := 0; i < 400; i++ {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
|
@ -12,7 +13,10 @@ import (
|
|||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"vcom/internal/config"
|
||||
"vcom/internal/imgview"
|
||||
"vcom/internal/jobs"
|
||||
"vcom/internal/paths"
|
||||
"vcom/internal/preview"
|
||||
"vcom/internal/ssh/conn"
|
||||
"vcom/internal/ssh/sshconfig"
|
||||
"vcom/internal/state"
|
||||
|
|
@ -21,10 +25,18 @@ import (
|
|||
"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.
|
||||
// PreviewFunc is the small preview interface used by the skeleton and tests.
|
||||
type PreviewFunc func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error)
|
||||
|
||||
// PreviewBuildFunc builds a full preview, including highlighting, metadata,
|
||||
// directory listings and remote images.
|
||||
type PreviewBuildFunc func(ctx context.Context, req preview.Request) preview.Result
|
||||
|
||||
// ImageApplier is the non-blocking side of imgview.Actor used by effects.
|
||||
type ImageApplier interface {
|
||||
Apply(imgview.Desired)
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -42,8 +54,10 @@ type Deps struct {
|
|||
Pool *conn.Pool
|
||||
Resolver *sshconfig.Resolver
|
||||
|
||||
Preview PreviewFunc
|
||||
Clock func() time.Time
|
||||
Preview PreviewFunc
|
||||
BuildPreview PreviewBuildFunc
|
||||
Image ImageApplier
|
||||
Clock func() time.Time
|
||||
// Notice is shown in the status line at start (config warnings).
|
||||
Notice string
|
||||
|
||||
|
|
@ -83,6 +97,19 @@ func DefaultDeps(cfg config.Config, configPath string) Deps {
|
|||
LocalFS: localfs.New(),
|
||||
StartDirs: [2]string{left, right},
|
||||
}
|
||||
|
||||
tools := preview.FindTools()
|
||||
results := preview.NewCache(32)
|
||||
var images *preview.ImageCache
|
||||
if dir, err := paths.CacheDir(); err == nil {
|
||||
images, _ = preview.NewImageCache(filepath.Join(dir, "images"), 200<<20)
|
||||
}
|
||||
d.BuildPreview = func(ctx context.Context, req preview.Request) preview.Result {
|
||||
req.Tools = tools
|
||||
req.Images = images
|
||||
return results.Build(ctx, req)
|
||||
}
|
||||
|
||||
// A saved session wins over the start paths (only directories that
|
||||
// still exist; remote/archive panels were saved as their local place).
|
||||
if s, err := state.Load(); err == nil && (s.Left.Path != "" || s.Right.Path != "") {
|
||||
|
|
@ -126,7 +153,7 @@ func (d *Deps) fill() {
|
|||
}
|
||||
}
|
||||
|
||||
// defaultPreview shows the head of a text file, metadata otherwise.
|
||||
// defaultPreview is the lightweight fallback used by isolated UI tests.
|
||||
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{
|
||||
|
|
@ -152,5 +179,6 @@ func defaultPreview(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxB
|
|||
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
|
||||
lines := strings.Split(strings.TrimRight(string(buf), "\n"), "\n")
|
||||
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: lines, Plain: lines}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,17 @@
|
|||
package tui
|
||||
|
||||
import tea "github.com/charmbracelet/bubbletea"
|
||||
import (
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"vcom/internal/imgview"
|
||||
"vcom/internal/tui/geom"
|
||||
"vcom/internal/tui/notify"
|
||||
"vcom/internal/tui/viewer"
|
||||
)
|
||||
|
||||
// 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).
|
||||
// with what was applied and commands fix the difference (design §7.9).
|
||||
|
||||
const (
|
||||
mouseUnknown int8 = iota
|
||||
|
|
@ -13,32 +20,87 @@ const (
|
|||
)
|
||||
|
||||
type effects struct {
|
||||
mouse int8
|
||||
// overlay: imgview.Desired once stage 5C/6.3 lands.
|
||||
mouse int8
|
||||
overlay imgview.Desired
|
||||
overlaySeq uint64
|
||||
overlaySet bool
|
||||
}
|
||||
|
||||
type desiredEffects struct {
|
||||
Mouse bool
|
||||
Mouse bool
|
||||
Overlay imgview.Desired
|
||||
}
|
||||
|
||||
func (a *App) desired() desiredEffects {
|
||||
return desiredEffects{Mouse: !a.nativeSelect}
|
||||
d := desiredEffects{Mouse: !a.nativeSelect}
|
||||
d.Overlay.Visible = (a.screen == ScreenInfo || a.screen == ScreenView) &&
|
||||
a.viewer.Kind == viewer.Image && a.viewer.Image != nil && a.modals.Len() == 0
|
||||
if a.viewer.Image != nil {
|
||||
d.Overlay.Image = *a.viewer.Image
|
||||
}
|
||||
d.Overlay.Gen = a.viewer.Gen
|
||||
var r geom.Rect
|
||||
if a.screen == ScreenView {
|
||||
r = geom.Rect{X: a.layout.Viewer.X, Y: a.layout.Viewer.Y + 1, W: a.layout.Viewer.W, H: max(0, a.layout.Viewer.H-1)}
|
||||
} else if a.screen == ScreenInfo {
|
||||
r = a.layout.PreviewBody
|
||||
}
|
||||
d.Overlay.Rect = imgview.Rect{X: r.X, Y: r.Y, W: r.W, H: r.H}
|
||||
return d
|
||||
}
|
||||
|
||||
// reconcile returns the command that brings the terminal to the desired
|
||||
// state, or nil.
|
||||
// reconcile returns commands that bring the terminal to the desired state.
|
||||
func (a *App) reconcile() tea.Cmd {
|
||||
d := a.desired()
|
||||
var mouseCmd, imageCmd tea.Cmd
|
||||
want := mouseOff
|
||||
if d.Mouse {
|
||||
want = mouseOn
|
||||
}
|
||||
if a.applied.mouse == want {
|
||||
if a.applied.mouse != want {
|
||||
a.applied.mouse = want
|
||||
if want == mouseOn {
|
||||
mouseCmd = tea.EnableMouseCellMotion
|
||||
} else {
|
||||
mouseCmd = tea.DisableMouse
|
||||
}
|
||||
}
|
||||
if a.deps.Image != nil && (!a.applied.overlaySet || !sameOverlay(a.applied.overlay, d.Overlay)) {
|
||||
a.applied.overlaySeq++
|
||||
d.Overlay.Seq = a.applied.overlaySeq
|
||||
a.applied.overlay, a.applied.overlaySet = d.Overlay, true
|
||||
apply, overlay := a.deps.Image, d.Overlay
|
||||
imageCmd = func() tea.Msg {
|
||||
apply.Apply(overlay)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return tea.Batch(mouseCmd, imageCmd)
|
||||
}
|
||||
|
||||
func sameOverlay(a, b imgview.Desired) bool {
|
||||
if a.Visible != b.Visible {
|
||||
return false
|
||||
}
|
||||
if !a.Visible {
|
||||
return true
|
||||
}
|
||||
return a.Rect == b.Rect && a.Gen == b.Gen && a.Image.Local == b.Image.Local &&
|
||||
a.Image.Size == b.Image.Size && a.Image.ModTime.Equal(b.Image.ModTime)
|
||||
}
|
||||
|
||||
// ImageEvent wraps an imgview event for delivery through tea.Program.Send.
|
||||
func ImageEvent(e imgview.Event) tea.Msg { return imageEventMsg{event: e} }
|
||||
|
||||
type imageEventMsg struct{ event imgview.Event }
|
||||
|
||||
func (a *App) onImageEvent(m imageEventMsg) tea.Cmd {
|
||||
if m.event.Err == nil {
|
||||
return nil
|
||||
}
|
||||
a.applied.mouse = want
|
||||
if want == mouseOn {
|
||||
return tea.EnableMouseCellMotion
|
||||
text := "Image preview: " + m.event.Err.Error()
|
||||
if m.event.Disabled {
|
||||
text += " (backend disabled)"
|
||||
}
|
||||
return tea.DisableMouse
|
||||
return a.notify(notify.Warn, text)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,30 @@
|
|||
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.
|
||||
// Viewer actions (design §8.2).
|
||||
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
|
||||
ViewerLineUp ActionID = "viewer.lineUp"
|
||||
ViewerLineDown ActionID = "viewer.lineDown"
|
||||
ViewerPageUp ActionID = "viewer.pageUp"
|
||||
ViewerPageDown ActionID = "viewer.pageDown"
|
||||
ViewerHalfUp ActionID = "viewer.halfUp"
|
||||
ViewerHalfDown ActionID = "viewer.halfDown"
|
||||
ViewerLeft ActionID = "viewer.left"
|
||||
ViewerRight ActionID = "viewer.right"
|
||||
ViewerWordNext ActionID = "viewer.wordNext"
|
||||
ViewerWordPrev ActionID = "viewer.wordPrev"
|
||||
ViewerWordEnd ActionID = "viewer.wordEnd"
|
||||
ViewerLineStart ActionID = "viewer.lineStart"
|
||||
ViewerFirstNonBlank ActionID = "viewer.firstNonBlank"
|
||||
ViewerLineEnd ActionID = "viewer.lineEnd"
|
||||
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 {
|
||||
|
|
@ -24,8 +32,12 @@ func viewerBindings() []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: ViewerLeft, Keys: []string{"left", "h"}, Help: "left", Group: "Viewer"},
|
||||
{Context: ctx, Action: ViewerRight, Keys: []string{"right", "l"}, Help: "right", 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: ViewerHalfUp, Keys: []string{"ctrl+u"}, Help: "half page up", Group: "Viewer"},
|
||||
{Context: ctx, Action: ViewerHalfDown, Keys: []string{"ctrl+d"}, Help: "half 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"},
|
||||
|
|
@ -50,5 +62,15 @@ func viewerBindings() []Binding {
|
|||
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},
|
||||
)
|
||||
for _, ctx := range []Context{CtxCaret, CtxVisual} {
|
||||
out = append(out,
|
||||
Binding{Context: ctx, Action: ViewerWordNext, Keys: []string{"w"}, Help: "next word", Group: "Viewer"},
|
||||
Binding{Context: ctx, Action: ViewerWordPrev, Keys: []string{"b"}, Help: "previous word", Group: "Viewer"},
|
||||
Binding{Context: ctx, Action: ViewerWordEnd, Keys: []string{"e"}, Help: "end of word", Group: "Viewer"},
|
||||
Binding{Context: ctx, Action: ViewerLineStart, Keys: []string{"0"}, Help: "start of line", Group: "Viewer"},
|
||||
Binding{Context: ctx, Action: ViewerFirstNonBlank, Keys: []string{"^"}, Help: "first non-blank", Group: "Viewer"},
|
||||
Binding{Context: ctx, Action: ViewerLineEnd, Keys: []string{"$"}, Help: "end of line", Group: "Viewer"},
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,7 +86,9 @@ func (a *App) relayout() {
|
|||
switch a.screen {
|
||||
case ScreenView:
|
||||
a.viewer.SetRows(a.layout.Viewer.H - 1)
|
||||
a.viewer.SetWidth(a.layout.Viewer.W)
|
||||
case ScreenInfo:
|
||||
a.viewer.SetRows(a.layout.PreviewBody.H)
|
||||
a.viewer.SetWidth(a.layout.PreviewBody.W)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -167,6 +167,8 @@ func (a *App) viewerClose() tea.Cmd {
|
|||
back := a.viewBack
|
||||
a.screen = back
|
||||
a.relayout()
|
||||
a.req.Cancel(ReqKey{Kind: ReqPreview})
|
||||
a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce})
|
||||
a.previewFor = ""
|
||||
if back == ScreenInfo {
|
||||
return a.requestPreview(false)
|
||||
|
|
@ -278,6 +280,7 @@ func (a *App) requestPreview(now bool) tea.Cmd {
|
|||
}
|
||||
a.previewFor = key
|
||||
if !now {
|
||||
a.req.Cancel(ReqKey{Kind: ReqPreview})
|
||||
tk, _ := a.req.Begin(ReqKey{Kind: ReqPreviewDebounce})
|
||||
return tea.Tick(previewDebounce, func(time.Time) tea.Msg { return previewTickMsg{tk} })
|
||||
}
|
||||
|
|
@ -286,10 +289,15 @@ func (a *App) requestPreview(now bool) tea.Cmd {
|
|||
|
||||
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
|
||||
build, legacy := a.deps.BuildPreview, a.deps.Preview
|
||||
req := a.previewRequest(loc, fi)
|
||||
limit := a.deps.Config.Preview.MaxPreviewBytes
|
||||
return func() tea.Msg {
|
||||
c, err := build(ctx, loc, fi, limit)
|
||||
if build != nil {
|
||||
res := build(ctx, req)
|
||||
return previewMsg{Ticket: tk, For: key, Content: contentFromPreview(fi, res), Err: res.Err}
|
||||
}
|
||||
c, err := legacy(ctx, loc, fi, limit)
|
||||
return previewMsg{Ticket: tk, For: key, Content: c, Err: err}
|
||||
}
|
||||
}
|
||||
|
|
@ -306,7 +314,7 @@ func (a *App) onPreviewTick(m previewTickMsg) tea.Cmd {
|
|||
}
|
||||
|
||||
func (a *App) onPreview(m previewMsg) tea.Cmd {
|
||||
if !a.req.Accept(m.Ticket) {
|
||||
if m.For != a.previewFor || !a.req.Accept(m.Ticket) {
|
||||
return nil // stale: must not touch the viewer (U-P1-13)
|
||||
}
|
||||
if m.Err != nil {
|
||||
|
|
|
|||
86
internal/tui/preview_req.go
Normal file
86
internal/tui/preview_req.go
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"vcom/internal/preview"
|
||||
"vcom/internal/tui/viewer"
|
||||
"vcom/internal/vfs"
|
||||
)
|
||||
|
||||
func (a *App) previewRequest(loc vfs.Location, fi vfs.FileInfo) preview.Request {
|
||||
loc.Path = loc.FS.Paths().Join(loc.Path, fi.Name)
|
||||
cfg := a.deps.Config
|
||||
return preview.Request{
|
||||
Loc: loc,
|
||||
Info: fi,
|
||||
MaxBytes: cfg.Preview.MaxPreviewBytes,
|
||||
MaxLines: 3000,
|
||||
HighlightLines: 400,
|
||||
DirLimit: cfg.Preview.DirectoryPreviewLimit,
|
||||
ShowHidden: cfg.Browser.ShowHidden,
|
||||
Theme: a.theme,
|
||||
MaxRemoteImageBytes: cfg.Preview.MaxRemoteImageBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func contentFromPreview(fi vfs.FileInfo, res preview.Result) viewer.Content {
|
||||
c := viewer.Content{Kind: viewer.Other, Title: fi.Name, Image: res.Image}
|
||||
switch res.Kind {
|
||||
case preview.Text:
|
||||
c.Kind = viewer.Text
|
||||
c.Lines, c.Plain = res.Lines, res.Plain
|
||||
return c
|
||||
case preview.Image:
|
||||
c.Kind = viewer.Image
|
||||
}
|
||||
c.Lines = previewMetadata(res)
|
||||
if res.Kind == preview.Directory {
|
||||
for _, entry := range res.Dir {
|
||||
name := entry.Name
|
||||
if entry.NavigableDir() {
|
||||
name += "/"
|
||||
}
|
||||
c.Lines = append(c.Lines, name)
|
||||
}
|
||||
}
|
||||
if res.Image != nil && res.Image.TooLarge {
|
||||
c.Lines = append(c.Lines, "Remote image is too large to download")
|
||||
}
|
||||
if res.Truncated {
|
||||
c.Lines = append(c.Lines, "…")
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func previewMetadata(res preview.Result) []string {
|
||||
m := res.Meta
|
||||
var lines []string
|
||||
if m.Label != "" {
|
||||
line := m.Label
|
||||
if m.Size >= 0 {
|
||||
line += fmt.Sprintf(" · %d bytes", m.Size)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
if !m.ModTime.IsZero() {
|
||||
lines = append(lines, m.ModTime.Format("2006-01-02 15:04:05"))
|
||||
}
|
||||
if m.LinkTarget != "" {
|
||||
lines = append(lines, "→ "+m.LinkTarget)
|
||||
}
|
||||
if m.ImageFormat != "" {
|
||||
lines = append(lines, fmt.Sprintf("%s · %d×%d", strings.ToUpper(m.ImageFormat), m.Width, m.Height))
|
||||
}
|
||||
if m.Dimensions != "" {
|
||||
lines = append(lines, m.Dimensions)
|
||||
}
|
||||
if m.Duration != "" {
|
||||
lines = append(lines, m.Duration)
|
||||
}
|
||||
if m.PageCount != "" {
|
||||
lines = append(lines, m.PageCount+" pages")
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
|
@ -1,7 +1,67 @@
|
|||
package tui
|
||||
|
||||
// registerViewer adds the action handlers of stage 6.3 (stub until then).
|
||||
func registerViewer(t actionTable) {}
|
||||
import (
|
||||
"strings"
|
||||
|
||||
// registerViewerHooks adds message and job-event handlers of stage 6.3.
|
||||
func registerViewerHooks(a *App) {}
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"vcom/internal/tui/keys"
|
||||
"vcom/internal/tui/notify"
|
||||
"vcom/internal/tui/viewer"
|
||||
)
|
||||
|
||||
// registerViewer installs the full text viewer of stage 6.3.
|
||||
func registerViewer(t actionTable) {
|
||||
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.ViewerHalfUp, func(a *App) tea.Cmd { a.viewer.HalfPage(-1); return nil }, nil)
|
||||
t.add(keys.ViewerHalfDown, func(a *App) tea.Cmd { a.viewer.HalfPage(1); return nil }, nil)
|
||||
t.add(keys.ViewerLeft, func(a *App) tea.Cmd { a.viewer.MoveHorizontal(-1); return nil }, nil)
|
||||
t.add(keys.ViewerRight, func(a *App) tea.Cmd { a.viewer.MoveHorizontal(1); return nil }, nil)
|
||||
t.add(keys.ViewerWordNext, func(a *App) tea.Cmd { a.viewer.MoveWord('w'); return nil }, nil)
|
||||
t.add(keys.ViewerWordPrev, func(a *App) tea.Cmd { a.viewer.MoveWord('b'); return nil }, nil)
|
||||
t.add(keys.ViewerWordEnd, func(a *App) tea.Cmd { a.viewer.MoveWord('e'); return nil }, nil)
|
||||
t.add(keys.ViewerLineStart, func(a *App) tea.Cmd { a.viewer.LineStart(false); return nil }, nil)
|
||||
t.add(keys.ViewerFirstNonBlank, func(a *App) tea.Cmd { a.viewer.LineStart(true); return nil }, nil)
|
||||
t.add(keys.ViewerLineEnd, func(a *App) tea.Cmd { a.viewer.LineEnd(); 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)
|
||||
t.add(keys.ViewerWrap, func(a *App) tea.Cmd {
|
||||
if a.viewer.ToggleWrap() {
|
||||
return a.notify(notify.Info, "Line wrap: on")
|
||||
}
|
||||
return a.notify(notify.Info, "Line wrap: off")
|
||||
}, nil)
|
||||
t.add(keys.ViewerYankLine, (*App).yankViewer, nil)
|
||||
t.add(keys.ViewerYank, (*App).yankViewer, nil)
|
||||
}
|
||||
|
||||
// registerViewerHooks handles clipboard results.
|
||||
func registerViewerHooks(a *App) {
|
||||
a.handle(func(a *App, msg tea.Msg) (tea.Cmd, bool) {
|
||||
m, ok := msg.(viewerYankedMsg)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
if m.err != nil {
|
||||
return a.notify(notify.Error, "Clipboard: "+m.err.Error()), true
|
||||
}
|
||||
return a.notify(notify.Success, "Selection copied to the clipboard"), true
|
||||
})
|
||||
}
|
||||
|
||||
type viewerYankedMsg struct{ err error }
|
||||
|
||||
func (a *App) yankViewer() tea.Cmd {
|
||||
text := strings.Join(a.viewer.Selection(), "\n")
|
||||
if text == "" {
|
||||
return a.notify(notify.Info, "Nothing to copy")
|
||||
}
|
||||
if a.viewer.Focus == viewer.Visual {
|
||||
a.viewer.Focus = viewer.Caret
|
||||
}
|
||||
clip := a.deps.Clipboard
|
||||
return func() tea.Msg { return viewerYankedMsg{err: clip(text)} }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,6 +45,8 @@ func (a *App) update(msg tea.Msg) tea.Cmd {
|
|||
case execDoneMsg:
|
||||
a.applied.mouse = mouseUnknown // the external program may have reset it (U-P1-3)
|
||||
return nil
|
||||
case imageEventMsg:
|
||||
return a.onImageEvent(m)
|
||||
}
|
||||
for _, h := range a.handlers {
|
||||
if cmd, ok := h(a, msg); ok {
|
||||
|
|
|
|||
|
|
@ -1,15 +1,16 @@
|
|||
// 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.
|
||||
// screen. Rendering is limited to the visible window; caret and visual
|
||||
// positions are stored as graphemes and rendered by terminal cell width.
|
||||
package viewer
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/rivo/uniseg"
|
||||
|
||||
"vcom/internal/preview"
|
||||
"vcom/internal/tui/style"
|
||||
)
|
||||
|
||||
|
|
@ -19,7 +20,7 @@ type Kind uint8
|
|||
const (
|
||||
None Kind = iota
|
||||
Text // lines of text: caret and visual are possible
|
||||
Image // drawn by imgview (stage 6.3)
|
||||
Image // drawn by imgview
|
||||
Other // metadata only (binary, directory, error)
|
||||
)
|
||||
|
||||
|
|
@ -36,8 +37,13 @@ const (
|
|||
type Content struct {
|
||||
Kind Kind
|
||||
Title string
|
||||
Lines []string
|
||||
Image any // preview.ImageRef in stage 6.3
|
||||
Lines []string // possibly syntax-highlighted
|
||||
Plain []string // the same text without SGR; defaults to stripped Lines
|
||||
Image *preview.ImageRef
|
||||
}
|
||||
|
||||
type position struct {
|
||||
line, col int // col is a grapheme index, not a byte or cell offset
|
||||
}
|
||||
|
||||
// Model is the viewer state.
|
||||
|
|
@ -45,14 +51,19 @@ type Model struct {
|
|||
Focus Focus
|
||||
Kind Kind
|
||||
Gen uint64 // bumps with every SetContent (overlay effects key on it)
|
||||
Image any
|
||||
Image *preview.ImageRef
|
||||
|
||||
title string
|
||||
lines []string
|
||||
offset int
|
||||
caret int // line of the caret
|
||||
anchor int // line where Visual started
|
||||
rows int
|
||||
title string
|
||||
lines []string
|
||||
plain []string
|
||||
offset int // first source line on screen
|
||||
sub int // first wrapped segment of offset on screen
|
||||
hOffset int
|
||||
caret position
|
||||
anchor position
|
||||
rows int
|
||||
width int
|
||||
wrap bool
|
||||
}
|
||||
|
||||
// SetContent shows c. Non-text content drops the focus back to Scroll.
|
||||
|
|
@ -60,53 +71,173 @@ func (m *Model) SetContent(c Content) {
|
|||
m.Gen++
|
||||
m.Kind = c.Kind
|
||||
m.title = c.Title
|
||||
m.lines = c.Lines
|
||||
lines := c.Lines
|
||||
if len(lines) == 0 {
|
||||
lines = c.Plain
|
||||
}
|
||||
m.lines = expandTabs(lines)
|
||||
m.plain = expandTabs(c.Plain)
|
||||
if len(m.plain) != len(m.lines) {
|
||||
m.plain = make([]string, len(m.lines))
|
||||
for i, line := range m.lines {
|
||||
m.plain[i] = ansi.Strip(line)
|
||||
}
|
||||
}
|
||||
m.Image = c.Image
|
||||
m.offset, m.caret, m.anchor = 0, 0, 0
|
||||
m.offset, m.sub, m.hOffset = 0, 0, 0
|
||||
m.caret, m.anchor = position{}, position{}
|
||||
if m.Kind != Text {
|
||||
m.Focus = Scroll
|
||||
}
|
||||
}
|
||||
|
||||
func expandTabs(lines []string) []string {
|
||||
out := make([]string, len(lines))
|
||||
for i, line := range lines {
|
||||
out[i] = strings.ReplaceAll(line, "\t", " ")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Clear drops the content.
|
||||
func (m *Model) Clear() { m.SetContent(Content{}) }
|
||||
|
||||
// Lines returns the text lines.
|
||||
// Lines returns the highlighted text lines.
|
||||
func (m *Model) Lines() []string { return m.lines }
|
||||
|
||||
// Offset is the first line on screen.
|
||||
// Offset is the first source line on screen.
|
||||
func (m *Model) Offset() int { return m.offset }
|
||||
|
||||
// CaretLine is the caret line.
|
||||
func (m *Model) CaretLine() int { return m.caret }
|
||||
// CaretLine is the caret source line.
|
||||
func (m *Model) CaretLine() int { return m.caret.line }
|
||||
|
||||
// SetRows tells the viewer how many lines fit.
|
||||
func (m *Model) SetRows(n int) { m.rows = max(1, n) }
|
||||
// CaretColumn is the caret grapheme column.
|
||||
func (m *Model) CaretColumn() int { return m.caret.col }
|
||||
|
||||
// SetRows tells the viewer how many terminal rows fit.
|
||||
func (m *Model) SetRows(n int) {
|
||||
m.rows = max(1, n)
|
||||
if m.Focus != Scroll {
|
||||
m.ensureCaretVisible()
|
||||
}
|
||||
}
|
||||
|
||||
// SetWidth tells the viewer how many terminal cells fit.
|
||||
func (m *Model) SetWidth(n int) {
|
||||
m.width = max(1, n)
|
||||
if m.Focus != Scroll {
|
||||
m.ensureCaretVisible()
|
||||
return
|
||||
}
|
||||
m.sub = min(m.sub, m.wrapCount(m.offset)-1)
|
||||
}
|
||||
|
||||
// ToggleWrap switches hard wrapping and reports the new state.
|
||||
func (m *Model) ToggleWrap() bool {
|
||||
m.wrap = !m.wrap
|
||||
m.offset, m.sub, m.hOffset = m.caret.line, 0, 0
|
||||
if m.Focus == Scroll {
|
||||
m.offset, m.sub = 0, 0
|
||||
}
|
||||
m.ensureCaretVisible()
|
||||
return m.wrap
|
||||
}
|
||||
|
||||
// Wrapping reports whether hard wrapping is enabled.
|
||||
func (m *Model) Wrapping() bool { return m.wrap }
|
||||
|
||||
// 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)))
|
||||
if m.wrap {
|
||||
m.scrollWrapped(delta)
|
||||
} else {
|
||||
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.wrap {
|
||||
m.moveCaretWrapped(delta)
|
||||
} else {
|
||||
m.caret.line = max(0, min(m.caret.line+delta, max(0, len(m.lines)-1)))
|
||||
m.clampCaretColumn()
|
||||
}
|
||||
if m.caret >= m.offset+m.rows {
|
||||
m.offset = m.caret - m.rows + 1
|
||||
m.ensureCaretVisible()
|
||||
}
|
||||
|
||||
// MoveHorizontal scrolls in Scroll focus or moves the caret by graphemes.
|
||||
func (m *Model) MoveHorizontal(delta int) {
|
||||
if m.Focus == Scroll {
|
||||
if !m.wrap {
|
||||
m.hOffset = max(0, m.hOffset+delta)
|
||||
}
|
||||
return
|
||||
}
|
||||
m.caret.col = max(0, min(m.caret.col+delta, len(graphemes(m.linePlain(m.caret.line)))))
|
||||
m.ensureCaretVisible()
|
||||
}
|
||||
|
||||
// MoveWord implements w (next start), b (previous start), and e (next end).
|
||||
func (m *Model) MoveWord(word rune) {
|
||||
if m.Focus == Scroll || len(m.lines) == 0 {
|
||||
return
|
||||
}
|
||||
switch word {
|
||||
case 'w':
|
||||
m.caret = m.nextWordStart()
|
||||
case 'b':
|
||||
m.caret = m.previousWordStart()
|
||||
case 'e':
|
||||
m.caret = m.nextWordEnd()
|
||||
}
|
||||
m.ensureCaretVisible()
|
||||
}
|
||||
|
||||
// LineStart moves to column 0 or the first non-blank grapheme.
|
||||
func (m *Model) LineStart(firstNonBlank bool) {
|
||||
if m.Focus == Scroll {
|
||||
return
|
||||
}
|
||||
m.caret.col = 0
|
||||
if firstNonBlank {
|
||||
for i, g := range graphemes(m.linePlain(m.caret.line)) {
|
||||
if graphemeClass(g) != 0 {
|
||||
m.caret.col = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
m.ensureCaretVisible()
|
||||
}
|
||||
|
||||
// LineEnd moves to the last grapheme of the caret line.
|
||||
func (m *Model) LineEnd() {
|
||||
if m.Focus == Scroll {
|
||||
return
|
||||
}
|
||||
m.caret.col = max(0, len(graphemes(m.linePlain(m.caret.line)))-1)
|
||||
m.ensureCaretVisible()
|
||||
}
|
||||
|
||||
// Page scrolls by a screen.
|
||||
func (m *Model) Page(dir int) { m.Scroll(dir * max(1, m.rows-1)) }
|
||||
|
||||
// HalfPage scrolls by half a screen.
|
||||
func (m *Model) HalfPage(dir int) { m.Scroll(dir * max(1, m.rows/2)) }
|
||||
|
||||
// Jump goes to the top or the bottom.
|
||||
func (m *Model) Jump(end bool) {
|
||||
distance := len(m.lines) + m.rows
|
||||
if m.wrap {
|
||||
distance = m.rows
|
||||
for line := range m.lines {
|
||||
distance += m.wrapCount(line)
|
||||
}
|
||||
}
|
||||
if end {
|
||||
m.Scroll(len(m.lines))
|
||||
m.Scroll(distance)
|
||||
} else {
|
||||
m.Scroll(-len(m.lines))
|
||||
m.Scroll(-distance)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -116,7 +247,8 @@ func (m *Model) EnterCaret() bool {
|
|||
return false
|
||||
}
|
||||
m.Focus = Caret
|
||||
m.caret = min(m.offset, max(0, len(m.lines)-1))
|
||||
m.placeCaretAtViewport()
|
||||
m.ensureCaretVisible()
|
||||
return true
|
||||
}
|
||||
|
||||
|
|
@ -127,53 +259,409 @@ func (m *Model) EnterVisual() bool {
|
|||
return false
|
||||
}
|
||||
if m.Focus == Scroll {
|
||||
m.caret = min(m.offset, max(0, len(m.lines)-1))
|
||||
m.placeCaretAtViewport()
|
||||
}
|
||||
m.Focus = Visual
|
||||
m.ensureCaretVisible()
|
||||
m.anchor = m.caret
|
||||
return true
|
||||
}
|
||||
|
||||
// Selection returns the selected lines (Visual) or the caret line.
|
||||
// Selection returns the selected text (Visual) or the whole 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)
|
||||
if m.Focus != Visual {
|
||||
return []string{m.linePlain(m.caret.line)}
|
||||
}
|
||||
return m.lines[a : b+1]
|
||||
a, b := m.orderedSelection()
|
||||
if a.line == b.line {
|
||||
gs := graphemes(m.linePlain(a.line))
|
||||
return []string{strings.Join(sliceGraphemes(gs, a.col, b.col+1), "")}
|
||||
}
|
||||
out := make([]string, 0, b.line-a.line+1)
|
||||
out = append(out, strings.Join(sliceGraphemes(graphemes(m.linePlain(a.line)), a.col, -1), ""))
|
||||
for i := a.line + 1; i < b.line; i++ {
|
||||
out = append(out, m.linePlain(i))
|
||||
}
|
||||
out = append(out, strings.Join(sliceGraphemes(graphemes(m.linePlain(b.line)), 0, b.col+1), ""))
|
||||
return out
|
||||
}
|
||||
|
||||
// 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 w <= 0 || h <= 0 {
|
||||
return ""
|
||||
}
|
||||
rows := make([]string, 0, h)
|
||||
line, sub := m.offset, m.sub
|
||||
for len(rows) < h {
|
||||
if line >= len(m.lines) {
|
||||
if len(rows) == 0 && m.Kind == None {
|
||||
rows = append(rows, st.Muted.Render("(no preview)"))
|
||||
}
|
||||
break
|
||||
}
|
||||
text := m.lines[line]
|
||||
if m.Focus != Scroll {
|
||||
text = m.plain[line]
|
||||
}
|
||||
if m.wrap {
|
||||
parts := strings.Split(ansi.Hardwrap(text, w, true), "\n")
|
||||
segments := wrapSegments(m.linePlain(line), w)
|
||||
for i := sub; i < len(parts) && len(rows) < h; i++ {
|
||||
rows = append(rows, m.renderRow(line, parts[i], segments[i].startCell, w, st))
|
||||
}
|
||||
} else {
|
||||
rows = append(rows, m.renderRow(line, ansi.Cut(text, m.hOffset, m.hOffset+w), m.hOffset, w, st))
|
||||
}
|
||||
line++
|
||||
sub = 0
|
||||
}
|
||||
for len(rows) < h {
|
||||
rows = append(rows, "")
|
||||
}
|
||||
for i, row := range rows {
|
||||
rows[i] = ansi.Truncate(row, w, "")
|
||||
if n := ansi.StringWidth(rows[i]); n < w {
|
||||
rows[i] += strings.Repeat(" ", w-n)
|
||||
}
|
||||
}
|
||||
return strings.Join(rows[:h], "\n")
|
||||
}
|
||||
|
||||
func (m *Model) renderRow(line int, text string, startCell, width int, st *style.Styles) string {
|
||||
if m.Focus == Scroll || line >= len(m.plain) {
|
||||
return text
|
||||
}
|
||||
from, to := -1, -1
|
||||
if m.Focus == Visual {
|
||||
lo, hi = min(m.anchor, m.caret), max(m.anchor, m.caret)
|
||||
a, b := m.orderedSelection()
|
||||
if line >= a.line && line <= b.line {
|
||||
from = startCell
|
||||
to = startCell + width
|
||||
if line == a.line {
|
||||
from = max(from, cellAt(m.linePlain(a.line), a.col))
|
||||
}
|
||||
if line == b.line {
|
||||
to = min(to, cellAt(m.linePlain(b.line), b.col+1))
|
||||
}
|
||||
}
|
||||
} else if line == m.caret.line {
|
||||
from = cellAt(m.linePlain(line), m.caret.col)
|
||||
to = cellAt(m.linePlain(line), m.caret.col+1)
|
||||
if to == from {
|
||||
to++
|
||||
}
|
||||
}
|
||||
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)
|
||||
if from < 0 || to <= startCell || from >= startCell+width {
|
||||
return text
|
||||
}
|
||||
return b.String()
|
||||
left, right := max(startCell, from), min(startCell+width, to)
|
||||
plain := m.plain[line]
|
||||
before := ansi.Cut(plain, startCell, left)
|
||||
marked := ansi.Cut(plain, left, right)
|
||||
if marked == "" {
|
||||
marked = " "
|
||||
}
|
||||
after := ansi.Cut(plain, right, startCell+width)
|
||||
return before + st.ListCursor.Render(marked) + after
|
||||
}
|
||||
|
||||
// Title of the content.
|
||||
func (m *Model) Title() string { return m.title }
|
||||
|
||||
func (m *Model) linePlain(i int) string {
|
||||
if i < 0 || i >= len(m.plain) {
|
||||
return ""
|
||||
}
|
||||
return m.plain[i]
|
||||
}
|
||||
|
||||
func (m *Model) orderedSelection() (position, position) {
|
||||
a, b := m.anchor, m.caret
|
||||
if b.line < a.line || b.line == a.line && b.col < a.col {
|
||||
a, b = b, a
|
||||
}
|
||||
return a, b
|
||||
}
|
||||
|
||||
func (m *Model) clampCaretColumn() {
|
||||
m.caret.col = max(0, min(m.caret.col, len(graphemes(m.linePlain(m.caret.line)))))
|
||||
}
|
||||
|
||||
type wrapSegment struct {
|
||||
startCol int
|
||||
endCol int
|
||||
startCell int
|
||||
}
|
||||
|
||||
func wrapSegments(s string, width int) []wrapSegment {
|
||||
parts := strings.Split(ansi.Hardwrap(s, max(1, width), true), "\n")
|
||||
segments := make([]wrapSegment, 0, len(parts))
|
||||
col, cell := 0, 0
|
||||
for _, part := range parts {
|
||||
segment := wrapSegment{startCol: col, startCell: cell}
|
||||
col += len(graphemes(part))
|
||||
cell += ansi.StringWidth(part)
|
||||
segment.endCol = col
|
||||
segments = append(segments, segment)
|
||||
}
|
||||
return segments
|
||||
}
|
||||
|
||||
func caretSegment(segments []wrapSegment, col int) int {
|
||||
for i, segment := range segments {
|
||||
if col < segment.endCol {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return len(segments) - 1
|
||||
}
|
||||
|
||||
func (m *Model) wrapCount(line int) int {
|
||||
if !m.wrap {
|
||||
return 1
|
||||
}
|
||||
return len(wrapSegments(m.linePlain(line), m.width))
|
||||
}
|
||||
|
||||
func (m *Model) scrollWrapped(delta int) {
|
||||
for delta > 0 && (m.offset < len(m.lines)-1 || m.sub < m.wrapCount(m.offset)-1) {
|
||||
if m.sub+1 < m.wrapCount(m.offset) {
|
||||
m.sub++
|
||||
} else {
|
||||
m.offset++
|
||||
m.sub = 0
|
||||
}
|
||||
delta--
|
||||
}
|
||||
for delta < 0 && (m.offset > 0 || m.sub > 0) {
|
||||
if m.sub > 0 {
|
||||
m.sub--
|
||||
} else {
|
||||
m.offset--
|
||||
m.sub = m.wrapCount(m.offset) - 1
|
||||
}
|
||||
delta++
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) moveCaretWrapped(delta int) {
|
||||
if len(m.lines) == 0 {
|
||||
return
|
||||
}
|
||||
segments := wrapSegments(m.linePlain(m.caret.line), m.width)
|
||||
segment := caretSegment(segments, m.caret.col)
|
||||
column := max(0, cellAt(m.linePlain(m.caret.line), m.caret.col)-segments[segment].startCell)
|
||||
segment += delta
|
||||
for segment < 0 && m.caret.line > 0 {
|
||||
m.caret.line--
|
||||
segment += m.wrapCount(m.caret.line)
|
||||
}
|
||||
for segment >= m.wrapCount(m.caret.line) && m.caret.line < len(m.lines)-1 {
|
||||
segment -= m.wrapCount(m.caret.line)
|
||||
m.caret.line++
|
||||
}
|
||||
segments = wrapSegments(m.linePlain(m.caret.line), m.width)
|
||||
segment = max(0, min(segment, len(segments)-1))
|
||||
m.caret.col = columnAtCell(m.linePlain(m.caret.line), segments[segment].startCell+column)
|
||||
}
|
||||
|
||||
func (m *Model) placeCaretAtViewport() {
|
||||
m.caret.line = min(m.offset, max(0, len(m.lines)-1))
|
||||
if !m.wrap {
|
||||
m.caret.col = columnAtCell(m.linePlain(m.caret.line), m.hOffset)
|
||||
return
|
||||
}
|
||||
segments := wrapSegments(m.linePlain(m.caret.line), m.width)
|
||||
m.sub = max(0, min(m.sub, len(segments)-1))
|
||||
m.caret.col = segments[m.sub].startCol
|
||||
}
|
||||
|
||||
func (m *Model) ensureCaretVisible() {
|
||||
if len(m.lines) == 0 {
|
||||
return
|
||||
}
|
||||
m.caret.line = max(0, min(m.caret.line, len(m.lines)-1))
|
||||
m.clampCaretColumn()
|
||||
m.offset = max(0, min(m.offset, len(m.lines)-1))
|
||||
if !m.wrap {
|
||||
if m.caret.line < m.offset {
|
||||
m.offset = m.caret.line
|
||||
}
|
||||
if m.caret.line >= m.offset+m.rows {
|
||||
m.offset = m.caret.line - m.rows + 1
|
||||
}
|
||||
cell := cellAt(m.linePlain(m.caret.line), m.caret.col)
|
||||
if cell < m.hOffset {
|
||||
m.hOffset = cell
|
||||
}
|
||||
if cell >= m.hOffset+m.width {
|
||||
m.hOffset = cell - m.width + 1
|
||||
}
|
||||
return
|
||||
}
|
||||
m.sub = max(0, min(m.sub, m.wrapCount(m.offset)-1))
|
||||
segments := wrapSegments(m.linePlain(m.caret.line), m.width)
|
||||
segment := caretSegment(segments, m.caret.col)
|
||||
if m.caret.line < m.offset || m.caret.line == m.offset && segment < m.sub {
|
||||
m.offset, m.sub = m.caret.line, segment
|
||||
return
|
||||
}
|
||||
line, sub, row := m.offset, m.sub, 0
|
||||
for line < m.caret.line || line == m.caret.line && sub <= segment {
|
||||
if line == m.caret.line && sub == segment {
|
||||
if row >= m.rows {
|
||||
m.offset, m.sub = m.caret.line, max(0, segment-m.rows+1)
|
||||
}
|
||||
return
|
||||
}
|
||||
row++
|
||||
if sub+1 < m.wrapCount(line) {
|
||||
sub++
|
||||
} else {
|
||||
line++
|
||||
sub = 0
|
||||
}
|
||||
}
|
||||
m.offset, m.sub = m.caret.line, max(0, segment-m.rows+1)
|
||||
}
|
||||
|
||||
func (m *Model) nextWordStart() position {
|
||||
p := m.caret
|
||||
gs := graphemes(m.linePlain(p.line))
|
||||
if p.col < len(gs) && graphemeClass(gs[p.col]) != 0 {
|
||||
class := graphemeClass(gs[p.col])
|
||||
for p.col < len(gs) && graphemeClass(gs[p.col]) == class {
|
||||
p.col++
|
||||
}
|
||||
}
|
||||
for {
|
||||
gs = graphemes(m.linePlain(p.line))
|
||||
for p.col < len(gs) && graphemeClass(gs[p.col]) == 0 {
|
||||
p.col++
|
||||
}
|
||||
if p.col < len(gs) || p.line == len(m.lines)-1 {
|
||||
return p
|
||||
}
|
||||
p.line++
|
||||
p.col = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) previousWordStart() position {
|
||||
p := m.caret
|
||||
for {
|
||||
gs := graphemes(m.linePlain(p.line))
|
||||
p.col = min(p.col, len(gs))
|
||||
if p.col == 0 {
|
||||
if p.line == 0 {
|
||||
return position{}
|
||||
}
|
||||
p.line--
|
||||
p.col = len(graphemes(m.linePlain(p.line)))
|
||||
continue
|
||||
}
|
||||
p.col--
|
||||
if graphemeClass(gs[p.col]) == 0 {
|
||||
continue
|
||||
}
|
||||
class := graphemeClass(gs[p.col])
|
||||
for p.col > 0 && graphemeClass(gs[p.col-1]) == class {
|
||||
p.col--
|
||||
}
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) nextWordEnd() position {
|
||||
p := m.caret
|
||||
gs := graphemes(m.linePlain(p.line))
|
||||
if p.col < len(gs) {
|
||||
p.col++
|
||||
}
|
||||
for {
|
||||
gs = graphemes(m.linePlain(p.line))
|
||||
for p.col < len(gs) && graphemeClass(gs[p.col]) == 0 {
|
||||
p.col++
|
||||
}
|
||||
if p.col < len(gs) {
|
||||
class := graphemeClass(gs[p.col])
|
||||
for p.col+1 < len(gs) && graphemeClass(gs[p.col+1]) == class {
|
||||
p.col++
|
||||
}
|
||||
return p
|
||||
}
|
||||
if p.line == len(m.lines)-1 {
|
||||
return m.lastWordEnd()
|
||||
}
|
||||
p.line++
|
||||
p.col = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) lastWordEnd() position {
|
||||
for line := len(m.lines) - 1; line >= 0; line-- {
|
||||
gs := graphemes(m.linePlain(line))
|
||||
for col := len(gs) - 1; col >= 0; col-- {
|
||||
if graphemeClass(gs[col]) != 0 {
|
||||
return position{line: line, col: col}
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.caret
|
||||
}
|
||||
|
||||
func graphemes(s string) []string {
|
||||
g := uniseg.NewGraphemes(s)
|
||||
var out []string
|
||||
for g.Next() {
|
||||
out = append(out, g.Str())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func sliceGraphemes(gs []string, from, to int) []string {
|
||||
from = max(0, min(from, len(gs)))
|
||||
if to < 0 || to > len(gs) {
|
||||
to = len(gs)
|
||||
}
|
||||
to = max(from, to)
|
||||
return gs[from:to]
|
||||
}
|
||||
|
||||
func cellAt(s string, col int) int {
|
||||
gs := graphemes(s)
|
||||
col = max(0, min(col, len(gs)))
|
||||
width := 0
|
||||
for _, g := range gs[:col] {
|
||||
width += ansi.StringWidth(g)
|
||||
}
|
||||
return width
|
||||
}
|
||||
|
||||
func columnAtCell(s string, cell int) int {
|
||||
gs := graphemes(s)
|
||||
width := 0
|
||||
for i, g := range gs {
|
||||
next := width + ansi.StringWidth(g)
|
||||
if next > cell {
|
||||
return i
|
||||
}
|
||||
width = next
|
||||
}
|
||||
return len(gs)
|
||||
}
|
||||
|
||||
func graphemeClass(g string) int {
|
||||
r := []rune(g)[0]
|
||||
if unicode.IsSpace(r) {
|
||||
return 0
|
||||
}
|
||||
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
|
|
|||
307
internal/tui/viewer/viewer_test.go
Normal file
307
internal/tui/viewer/viewer_test.go
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
package viewer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/muesli/termenv"
|
||||
|
||||
"vcom/internal/theme"
|
||||
"vcom/internal/tui/style"
|
||||
)
|
||||
|
||||
func testStyles(t *testing.T) *style.Styles {
|
||||
t.Helper()
|
||||
p, err := theme.Resolve("nord")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return style.New(p)
|
||||
}
|
||||
|
||||
func TestUP03_CaretAsciiAndTrueColorNoPanic(t *testing.T) {
|
||||
for _, profile := range []termenv.Profile{termenv.Ascii, termenv.TrueColor} {
|
||||
t.Run(fmt.Sprint(profile), func(t *testing.T) {
|
||||
previous := lipgloss.ColorProfile()
|
||||
lipgloss.SetColorProfile(profile)
|
||||
defer lipgloss.SetColorProfile(previous)
|
||||
m := Model{}
|
||||
m.SetRows(4)
|
||||
m.SetWidth(12)
|
||||
m.SetContent(Content{Kind: Text, Lines: []string{"one", "two", "three"}, Plain: []string{"one", "two", "three"}})
|
||||
if !m.EnterCaret() || !m.EnterVisual() {
|
||||
t.Fatal("caret/visual unavailable for text")
|
||||
}
|
||||
m.MoveHorizontal(1)
|
||||
m.Scroll(1)
|
||||
if got := ansi.Strip(m.Render(12, 4, testStyles(t))); !strings.Contains(got, "two") {
|
||||
t.Fatalf("render:\n%s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaretCJKColumns(t *testing.T) {
|
||||
m := Model{}
|
||||
m.SetRows(3)
|
||||
m.SetWidth(4)
|
||||
m.SetContent(Content{Kind: Text, Plain: []string{"a界b"}, Lines: []string{"a界b"}})
|
||||
m.EnterCaret()
|
||||
m.MoveHorizontal(1)
|
||||
if got := m.CaretColumn(); got != 1 {
|
||||
t.Fatalf("column = %d, want 1 grapheme", got)
|
||||
}
|
||||
m.EnterVisual()
|
||||
m.MoveHorizontal(1)
|
||||
if got := m.CaretColumn(); got != 2 {
|
||||
t.Fatalf("column = %d, want 2 graphemes", got)
|
||||
}
|
||||
if got := cellAt(m.linePlain(0), m.CaretColumn()); got != 3 {
|
||||
t.Fatalf("cell = %d, want 3 (CJK is two cells)", got)
|
||||
}
|
||||
if got := strings.Join(m.Selection(), ""); got != "界b" {
|
||||
t.Fatalf("selection = %q", got)
|
||||
}
|
||||
if got := ansi.Strip(m.Render(4, 1, testStyles(t))); ansi.StringWidth(got) != 4 || !strings.Contains(got, "界") {
|
||||
t.Fatalf("render = %q (width %d)", got, ansi.StringWidth(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisualSelectionAcrossLines(t *testing.T) {
|
||||
m := Model{}
|
||||
m.SetRows(5)
|
||||
m.SetWidth(20)
|
||||
m.SetContent(Content{Kind: Text, Plain: []string{"alpha", "beta", "gamma"}})
|
||||
m.EnterCaret()
|
||||
m.LineEnd()
|
||||
m.EnterVisual()
|
||||
m.Scroll(2)
|
||||
m.LineStart(false)
|
||||
m.MoveHorizontal(1)
|
||||
want := []string{"a", "beta", "ga"}
|
||||
got := m.Selection()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("selection = %#v", got)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("selection[%d] = %q, want %q", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapScrollsByVisibleRows(t *testing.T) {
|
||||
m := Model{}
|
||||
m.SetRows(2)
|
||||
m.SetWidth(4)
|
||||
m.ToggleWrap()
|
||||
m.SetContent(Content{Kind: Text, Plain: []string{"abcdefgh", "ijkl"}})
|
||||
m.Scroll(1)
|
||||
if m.offset != 0 || m.sub != 1 {
|
||||
t.Fatalf("offset = %d/%d, want wrapped segment 0/1", m.offset, m.sub)
|
||||
}
|
||||
if got := ansi.Strip(m.Render(4, 1, testStyles(t))); !strings.HasPrefix(got, "efgh") {
|
||||
t.Fatalf("second wrapped segment = %q", got)
|
||||
}
|
||||
m.Scroll(1)
|
||||
if m.offset != 1 || m.sub != 0 {
|
||||
t.Fatalf("offset = %d/%d, want next source line", m.offset, m.sub)
|
||||
}
|
||||
}
|
||||
|
||||
func newTextModel(lines []string, width, rows int, wrap bool) Model {
|
||||
m := Model{}
|
||||
m.SetRows(rows)
|
||||
m.SetWidth(width)
|
||||
if wrap {
|
||||
m.ToggleWrap()
|
||||
}
|
||||
m.SetContent(Content{Kind: Text, Plain: lines})
|
||||
return m
|
||||
}
|
||||
|
||||
func TestWrapMatchesHardwrapAndEndCaret(t *testing.T) {
|
||||
m := newTextModel([]string{"a界b"}, 2, 3, true)
|
||||
if got := m.wrapCount(0); got != 3 {
|
||||
t.Fatalf("wrapCount = %d, want 3 Hardwrap segments", got)
|
||||
}
|
||||
segments := wrapSegments(m.linePlain(0), 2)
|
||||
wantCells := []int{0, 1, 3}
|
||||
for i, want := range wantCells {
|
||||
if segments[i].startCell != want {
|
||||
t.Errorf("segment %d starts at cell %d, want %d", i, segments[i].startCell, want)
|
||||
}
|
||||
}
|
||||
m.EnterCaret()
|
||||
m.MoveHorizontal(3)
|
||||
if got := caretSegment(segments, m.CaretColumn()); got != 2 {
|
||||
t.Fatalf("end caret segment = %d, want last segment 2", got)
|
||||
}
|
||||
|
||||
m = newTextModel([]string{"abcd"}, 2, 1, true)
|
||||
m.EnterCaret()
|
||||
m.MoveHorizontal(4)
|
||||
if m.offset != 0 || m.sub != 1 {
|
||||
t.Fatalf("end caret viewport = %d/%d, want 0/1", m.offset, m.sub)
|
||||
}
|
||||
m.Scroll(1)
|
||||
if m.CaretColumn() != 4 || m.offset != 0 || m.sub != 1 {
|
||||
t.Fatalf("moving at end created a segment: caret %d, viewport %d/%d", m.CaretColumn(), m.offset, m.sub)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderNeverExceedsCellWidth(t *testing.T) {
|
||||
for _, wrap := range []bool{false, true} {
|
||||
for _, width := range []int{1, 2, 3} {
|
||||
m := newTextModel([]string{"a界b"}, width, 4, wrap)
|
||||
if wrap {
|
||||
m.EnterCaret()
|
||||
m.MoveHorizontal(2)
|
||||
} else {
|
||||
m.MoveHorizontal(1)
|
||||
}
|
||||
for row, rendered := range strings.Split(m.Render(width, 4, testStyles(t)), "\n") {
|
||||
if got := ansi.StringWidth(rendered); got > width {
|
||||
t.Errorf("wrap=%v width=%d row=%d has cell width %d: %q", wrap, width, row, got, rendered)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeKeepsCaretVisible(t *testing.T) {
|
||||
m := newTextModel([]string{"abcdefgh"}, 4, 2, true)
|
||||
m.EnterCaret()
|
||||
m.MoveHorizontal(8)
|
||||
m.SetRows(1)
|
||||
if m.offset != 0 || m.sub != 1 {
|
||||
t.Fatalf("after row resize viewport = %d/%d, want 0/1", m.offset, m.sub)
|
||||
}
|
||||
m.SetWidth(2)
|
||||
if m.offset != 0 || m.sub != 3 {
|
||||
t.Fatalf("after width resize viewport = %d/%d, want 0/3", m.offset, m.sub)
|
||||
}
|
||||
|
||||
m = newTextModel([]string{"abcdefgh", "ijkl"}, 4, 2, false)
|
||||
m.EnterCaret()
|
||||
m.Scroll(1)
|
||||
m.LineEnd()
|
||||
m.SetRows(1)
|
||||
if m.offset != 1 {
|
||||
t.Fatalf("after row resize offset = %d, want caret line 1", m.offset)
|
||||
}
|
||||
m.MoveHorizontal(4)
|
||||
m.SetWidth(2)
|
||||
if cell := cellAt(m.linePlain(m.caret.line), m.caret.col); cell < m.hOffset || cell >= m.hOffset+m.width {
|
||||
t.Fatalf("after width resize caret cell %d outside [%d,%d)", cell, m.hOffset, m.hOffset+m.width)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnterModesUseVisibleViewportPosition(t *testing.T) {
|
||||
for _, visual := range []bool{false, true} {
|
||||
m := newTextModel([]string{"abcdef"}, 2, 1, true)
|
||||
m.Scroll(2)
|
||||
if visual {
|
||||
m.EnterVisual()
|
||||
} else {
|
||||
m.EnterCaret()
|
||||
}
|
||||
if m.CaretColumn() != 4 {
|
||||
t.Errorf("wrapped visual=%v caret column = %d, want 4", visual, m.CaretColumn())
|
||||
}
|
||||
if visual && m.anchor.col != 4 {
|
||||
t.Errorf("visual anchor column = %d, want 4", m.anchor.col)
|
||||
}
|
||||
|
||||
m = newTextModel([]string{"abcdef"}, 2, 1, false)
|
||||
m.MoveHorizontal(3)
|
||||
if visual {
|
||||
m.EnterVisual()
|
||||
} else {
|
||||
m.EnterCaret()
|
||||
}
|
||||
if m.CaretColumn() != 3 {
|
||||
t.Errorf("horizontal visual=%v caret column = %d, want 3", visual, m.CaretColumn())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJumpCrossesAllWrappedSegments(t *testing.T) {
|
||||
m := newTextModel([]string{"abcdefghij"}, 2, 2, true)
|
||||
m.EnterCaret()
|
||||
m.Jump(true)
|
||||
if m.CaretColumn() != 8 || m.sub != 3 {
|
||||
t.Fatalf("jump to end: caret %d, sub %d; want 8, 3", m.CaretColumn(), m.sub)
|
||||
}
|
||||
m.Jump(false)
|
||||
if m.CaretColumn() != 0 || m.offset != 0 || m.sub != 0 {
|
||||
t.Fatalf("jump to start: caret %d, viewport %d/%d", m.CaretColumn(), m.offset, m.sub)
|
||||
}
|
||||
|
||||
m = newTextModel([]string{"abcdefghij"}, 2, 2, true)
|
||||
m.Jump(true)
|
||||
if m.offset != 0 || m.sub != 4 {
|
||||
t.Fatalf("scroll jump to end = %d/%d, want 0/4", m.offset, m.sub)
|
||||
}
|
||||
m.Jump(false)
|
||||
if m.offset != 0 || m.sub != 0 {
|
||||
t.Fatalf("scroll jump to start = %d/%d, want 0/0", m.offset, m.sub)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWordMotionsCrossLinesAndSkipTrailingSpaces(t *testing.T) {
|
||||
m := newTextModel([]string{"one ", " two", "", "three!"}, 20, 4, false)
|
||||
m.EnterCaret()
|
||||
m.MoveWord('e')
|
||||
if m.caret != (position{line: 0, col: 2}) {
|
||||
t.Fatalf("first e = %+v, want line 0 col 2", m.caret)
|
||||
}
|
||||
m.MoveWord('e')
|
||||
if m.caret != (position{line: 1, col: 4}) {
|
||||
t.Fatalf("cross-line e = %+v, want line 1 col 4", m.caret)
|
||||
}
|
||||
m.MoveWord('w')
|
||||
if m.caret != (position{line: 3, col: 0}) {
|
||||
t.Fatalf("cross-line w = %+v, want line 3 col 0", m.caret)
|
||||
}
|
||||
m.MoveWord('b')
|
||||
if m.caret != (position{line: 1, col: 2}) {
|
||||
t.Fatalf("cross-line b = %+v, want line 1 col 2", m.caret)
|
||||
}
|
||||
m.MoveWord('b')
|
||||
if m.caret != (position{line: 0, col: 0}) {
|
||||
t.Fatalf("second b = %+v, want line 0 col 0", m.caret)
|
||||
}
|
||||
|
||||
m = newTextModel([]string{"one", "two "}, 20, 2, false)
|
||||
m.EnterCaret()
|
||||
m.LineEnd()
|
||||
m.MoveWord('e')
|
||||
if m.caret != (position{line: 1, col: 2}) {
|
||||
t.Fatalf("e before trailing spaces = %+v, want line 1 col 2", m.caret)
|
||||
}
|
||||
m.MoveWord('e')
|
||||
if m.caret != (position{line: 1, col: 2}) {
|
||||
t.Fatalf("e stuck in trailing spaces: %+v", m.caret)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCaretMove64K(b *testing.B) {
|
||||
lines := make([]string, 64*1024)
|
||||
for i := range lines {
|
||||
lines[i] = fmt.Sprintf("line %d: some text to move through", i)
|
||||
}
|
||||
m := Model{}
|
||||
m.SetRows(30)
|
||||
m.SetWidth(100)
|
||||
m.SetContent(Content{Kind: Text, Plain: lines})
|
||||
m.EnterCaret()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
m.LineEnd()
|
||||
m.LineStart(false)
|
||||
}
|
||||
}
|
||||
195
internal/tui/viewer_actions_test.go
Normal file
195
internal/tui/viewer_actions_test.go
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"vcom/internal/imgview"
|
||||
"vcom/internal/preview"
|
||||
"vcom/internal/testutil/fstree"
|
||||
"vcom/internal/tui/keys"
|
||||
"vcom/internal/tui/viewer"
|
||||
"vcom/internal/vfs"
|
||||
"vcom/internal/vfs/localfs"
|
||||
)
|
||||
|
||||
type recordingImages struct {
|
||||
mu sync.Mutex
|
||||
desired []imgview.Desired
|
||||
}
|
||||
|
||||
func (r *recordingImages) Apply(d imgview.Desired) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.desired = append(r.desired, d)
|
||||
}
|
||||
|
||||
func (r *recordingImages) last() imgview.Desired {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if len(r.desired) == 0 {
|
||||
return imgview.Desired{}
|
||||
}
|
||||
return r.desired[len(r.desired)-1]
|
||||
}
|
||||
|
||||
func (r *recordingImages) count() int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return len(r.desired)
|
||||
}
|
||||
|
||||
func TestPreviewDebounceSingleFlight(t *testing.T) {
|
||||
var spec fstree.Spec
|
||||
for i := 0; i < 60; i++ {
|
||||
spec = append(spec, fstree.File(fmt.Sprintf("f%02d", i), "text"))
|
||||
}
|
||||
var calls atomic.Int32
|
||||
h := newHarness(t, localfs.New(), tree(t, spec), func(d *Deps) {
|
||||
d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
|
||||
calls.Add(1)
|
||||
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{fi.Name}}, nil
|
||||
}
|
||||
})
|
||||
h.press("o")
|
||||
before := calls.Load()
|
||||
for i := 0; i < 50; i++ {
|
||||
h.d.Press("j")
|
||||
}
|
||||
h.d.Settle(settle)
|
||||
h.check()
|
||||
if got := calls.Load() - before; got != 1 {
|
||||
t.Fatalf("50 rapid cursor moves caused %d preview builds, want 1 (total %d)", got, calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlayHiddenUnderModal(t *testing.T) {
|
||||
images := &recordingImages{}
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("image.png", "fake")}), func(d *Deps) {
|
||||
d.Image = images
|
||||
d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
|
||||
return viewer.Content{Kind: viewer.Image, Title: fi.Name, Image: &preview.ImageRef{Local: "fake.png"}}, nil
|
||||
}
|
||||
})
|
||||
h.cursorTo("image.png")
|
||||
h.press("o")
|
||||
if got := images.last(); !got.Visible || got.Image.Local != "fake.png" {
|
||||
t.Fatalf("overlay was not shown: %#v", got)
|
||||
}
|
||||
h.press("?")
|
||||
if !h.d.ScreenContains("Help") {
|
||||
t.Fatal("help modal did not open")
|
||||
}
|
||||
if got := images.last(); got.Visible {
|
||||
t.Fatalf("overlay stayed visible under a modal: %#v", got)
|
||||
}
|
||||
h.press("esc")
|
||||
if got := images.last(); !got.Visible {
|
||||
t.Fatal("overlay was not restored after closing the modal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewIsPure(t *testing.T) {
|
||||
images := &recordingImages{}
|
||||
var previews atomic.Int32
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "text")}), func(d *Deps) {
|
||||
d.Image = images
|
||||
d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
|
||||
previews.Add(1)
|
||||
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"text"}}, nil
|
||||
}
|
||||
})
|
||||
h.cursorTo("a.txt")
|
||||
h.press("o")
|
||||
calls, applies := previews.Load(), images.count()
|
||||
before := h.d.Screen()
|
||||
for i := 0; i < 1000; i++ {
|
||||
if got := h.app.View(); got != before {
|
||||
t.Fatalf("View changed between identical calls at %d", i)
|
||||
}
|
||||
}
|
||||
if previews.Load() != calls || images.count() != applies {
|
||||
t.Fatalf("View triggered dependencies: previews %d→%d, overlays %d→%d", calls, previews.Load(), applies, images.count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisualReachableFromViewAndInfo(t *testing.T) {
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one\ntwo")}))
|
||||
h.cursorTo("a.txt")
|
||||
h.press("o", "i", "v")
|
||||
if h.app.InputOwner() != keys.CtxVisual {
|
||||
t.Fatalf("Info did not enter Visual: %s", h.app.InputOwner())
|
||||
}
|
||||
h.press("q", "f3", "v")
|
||||
if h.app.InputOwner() != keys.CtxVisual || h.app.Screen() != ScreenView {
|
||||
t.Fatalf("View did not enter Visual: screen %s, owner %s", h.app.Screen(), h.app.InputOwner())
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewerYankUsesPlainText(t *testing.T) {
|
||||
var copied string
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one")}), func(d *Deps) {
|
||||
d.Clipboard = func(s string) error { copied = s; return nil }
|
||||
d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
|
||||
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"\x1b[31mone\x1b[0m"}, Plain: []string{"one"}}, nil
|
||||
}
|
||||
})
|
||||
h.cursorTo("a.txt")
|
||||
h.press("o", "i", "v", "l", "y")
|
||||
if copied != "on" {
|
||||
t.Fatalf("copied %q, want plain selected text %q", copied, "on")
|
||||
}
|
||||
if strings.Contains(copied, "\x1b") {
|
||||
t.Fatal("ANSI escape copied to clipboard")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewCancelledWhenViewCloses(t *testing.T) {
|
||||
g := newGate(t)
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one")}), func(d *Deps) {
|
||||
d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
|
||||
<-g.ch
|
||||
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"one"}}, nil
|
||||
}
|
||||
})
|
||||
h.cursorTo("a.txt")
|
||||
h.press("f3")
|
||||
if !h.app.req.Pending(ReqKey{Kind: ReqPreview}) {
|
||||
t.Fatal("preview request was not started")
|
||||
}
|
||||
h.press("q")
|
||||
if h.app.req.Pending(ReqKey{Kind: ReqPreview}) {
|
||||
t.Fatal("closing View left its preview request running")
|
||||
}
|
||||
g.open()
|
||||
}
|
||||
|
||||
func TestMouseRestoredAfterExternalProcess(t *testing.T) {
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one")}))
|
||||
if h.app.applied.mouse != mouseOn {
|
||||
t.Fatal("mouse was not enabled initially")
|
||||
}
|
||||
h.d.Send(execDoneMsg{})
|
||||
h.d.Settle(settle)
|
||||
if h.app.applied.mouse != mouseOn {
|
||||
t.Fatal("mouse was not restored after external process")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewResultRejectedDuringNextDebounce(t *testing.T) {
|
||||
h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "a"), fstree.File("b.txt", "b")}))
|
||||
h.cursorTo("a.txt")
|
||||
h.press("o")
|
||||
before := h.app.Viewer().Title()
|
||||
tk, _ := h.app.req.Begin(ReqKey{Kind: ReqPreview})
|
||||
h.cursorTo("b.txt")
|
||||
_ = h.app.requestPreview(false)
|
||||
h.app.onPreview(previewMsg{Ticket: tk, For: "a.txt", Content: viewer.Content{Kind: viewer.Text, Title: "stale"}})
|
||||
if got := h.app.Viewer().Title(); got != before {
|
||||
t.Fatalf("stale preview %q replaced %q during debounce", got, before)
|
||||
}
|
||||
}
|
||||
|
|
@ -352,7 +352,7 @@ remote↔remote.
|
|||
(нет `.vcom-part-*`) — N-P2-11; `TestHostsListNotATarget` — N-P2-10; `TestRenameRejectsSlash` — U-P2;
|
||||
`TestPassiveCursorKeptAfterCopy` — U-P1-7; `TestDirSizeShowsUnreadable` — N-P1-14.
|
||||
|
||||
### 6.3 Вьюер, превью, картинки (L; параллельно)
|
||||
### 6.3 Вьюер, превью, картинки (L; параллельно) ✅ done
|
||||
- **Файлы:** `internal/tui/viewer/*`, `internal/tui/{viewer_actions.go,preview_req.go,clipboard.go}`,
|
||||
`internal/tui/keys/bindings_viewer.go`.
|
||||
- **Сделать:** Info/View, debounce + Tracker для превью (§7.7), TextViewer (scroll/caret/visual/yank, по ячейкам,
|
||||
|
|
|
|||
|
|
@ -374,3 +374,21 @@
|
|||
- **Сессия.** Без изменений в формате `state`. Remote/archive-панель сохраняется как локальный каталог, из
|
||||
которого в неё вошли (`LocalPlace`), с фокусом на имени архива. Сохраняется раз в 30 с при изменениях (Cmd), по
|
||||
`tui.Signal` (Cmd, затем выход) и в `Shutdown`.
|
||||
|
||||
- **6.3 viewer/preview/imgview.**
|
||||
- `DefaultDeps` подключает настоящий `preview.Cache`/`Build`, внешние утилиты и `ImageCache` (200 МиБ).
|
||||
`preview.Request` получает полный `Location` файла, лимиты, тему и видимость скрытых файлов; старый
|
||||
небольшой `PreviewFunc` оставлен для изолированных UI-тестов. В `viewer.Content` передаются и подсвеченные,
|
||||
и plain-строки: caret/visual/yank не копируют ANSI.
|
||||
- TextViewer хранит caret и visual в графемах, переводит их в terminal cells и рендерит только видимое окно.
|
||||
Реализованы горизонтальная прокрутка, `w/b/e/0/^/$`, полстраницы, `W`, yank строки/выделения. Wrap использует
|
||||
фактические сегменты `ansi.Hardwrap`, а не `ceil(width)`: CJK и resize не уводят caret за viewport.
|
||||
Добавлены регрессии для CJK, границ графем, wrapped jump/scroll, word motions между строками, Ascii/TrueColor.
|
||||
- Preview при смене выделения отменяет предыдущий запрос уже в начале debounce; результат дополнительно сверяется
|
||||
с `previewFor`. Закрытие View отменяет и запрос, и debounce.
|
||||
- `imgview.Actor` подключён к reconcile через `Deps.Image`. У `Desired` есть монотонный `Seq`: команды Bubble Tea
|
||||
могут выполняться в другом порядке, но устаревший Apply не покажет картинку поверх модалки или после закрытия.
|
||||
`main` использует общий `SyncTTY`, останавливает actor в teardown и ставит в очередь события backend, возникшие
|
||||
до запуска event loop.
|
||||
- Приёмочные тесты из плана добавлены: debounce 50 движений → один Build, overlay под модалкой, чистый View,
|
||||
Visual из Info/View, восстановление мыши, CJK и Ascii/TrueColor. `BenchmarkCaretMove64K` — около 22 мкс.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue