diff --git a/ui/model/frame_test.go b/ui/model/frame_test.go new file mode 100644 index 000000000..dbb932fe6 --- /dev/null +++ b/ui/model/frame_test.go @@ -0,0 +1,218 @@ +package model + +import ( + "fmt" + "math" + "strings" + "testing" + "time" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/ui" +) + +// framePlayer plays a moving tone, so the visualizers draw real shapes. +type framePlayer struct { + playbackFakeEngine + phase float64 +} + +func (f *framePlayer) SamplesInto(dst []float64) int { + for i := range dst { + dst[i] = 0.6 * math.Sin(f.phase+float64(i)*2*math.Pi*440/44100) + } + f.phase += 0.3 + return len(dst) +} + +func (f *framePlayer) WaveformSamplesInto(dst []float64) int { return f.SamplesInto(dst) } + +func (f *framePlayer) StereoSamplesInto(dst [][2]float64) int { + mono := make([]float64, len(dst)) + f.SamplesInto(mono) + for i, v := range mono { + dst[i] = [2]float64{v, -v} + } + return len(dst) +} + +func newFrameModel(width, height int, mode ui.VisMode) (Model, *framePlayer) { + eng := &framePlayer{playbackFakeEngine: playbackFakeEngine{playing: true, duration: 300 * time.Second, seekable: true}} + pl := playlist.New() + titles := []string{"Voodoo People", "Cœur de pirate — Ensemble", "東京 Nights", "A rather long title that will not fit in a narrow terminal at all"} + for i := range 40 { + pl.Add(playlist.Track{Path: fmt.Sprintf("/music/%02d.flac", i), Title: titles[i%len(titles)], Artist: "The Prodigy", DurationSecs: 200 + i}) + } + pl.SetIndex(3) + m := Model{player: eng, playlist: pl, vis: ui.NewVisualizer(44100), width: width, height: height, focus: focusPlaylist} + m.vis.Mode = mode + m.recomputeLayout() + return m, eng +} + +// lipglossFrame is how View drew the frame before renderFrame. +func lipglossFrame(m Model, content string) string { + frame := m.layout.frameStyle().Render(content) + padLeft := max(0, (m.width-lipgloss.Width(frame))/2) + padTop := max(0, (m.height-lipgloss.Height(frame))/2) + lines := strings.Split(frame, "\n") + for i, l := range lines { + lines[i] = strings.Repeat(" ", padLeft) + l + } + return ui.FitRect(strings.Repeat("\n", padTop)+strings.Join(lines, "\n"), m.layout.frameWidth, max(1, m.height)) +} + +// renderFrame draws the same bytes as before: every screen at every size, +// every visualizer mode on the two screens that draw it, help shown and hidden. +func TestRenderFrameMatchesLipgloss(t *testing.T) { + screens := map[string]func(*Model){ + "main": func(*Model) {}, + "full visualizer": func(m *Model) { m.fullVis = true }, + "keymap": func(m *Model) { m.keymap.visible = true }, + "file browser": func(m *Model) { m.fileBrowser.visible = true }, + "theme picker": func(m *Model) { m.themePicker.visible = true }, + "visualizer picker": func(m *Model) { m.visPicker.visible = true }, + "playlist picker": func(m *Model) { m.plPicker.visible = true }, + "playlist manager": func(m *Model) { m.plManager = plManagerState{visible: true, screen: plMgrScreenList} }, + "queue": func(m *Model) { m.queue.visible = true }, + "info": func(m *Model) { m.info.visible = true }, + "lyrics": func(m *Model) { m.lyrics.visible = true }, + "device picker": func(m *Model) { m.devicePicker.visible = true }, + "search results": func(m *Model) { m.searchOverlay.visible = true }, + "navigation browser": func(m *Model) { m.navBrowser.visible = true }, + "subscriptions": func(m *Model) { m.subs.visible = true }, + "jump": func(m *Model) { m.jump.active = true }, + "URL input": func(m *Model) { m.urlInput.active = true }, + "sign-in code": func(m *Model) { m.authCode.active = true }, + "playlist search": func(m *Model) { m.search.active = true }, + "radio search": func(m *Model) { m.netSearch.active = true }, + "simplified": func(m *Model) { m.simplified = true }, + } + sizes := [][2]int{{205, 102}, {200, 52}, {160, 45}, {120, 40}, {100, 30}, {80, 24}, {79, 23}, {72, 22}, {60, 18}, {56, 16}, {50, 14}, {40, 10}} + check := func(name string, open func(*Model), mode ui.VisMode, help bool, sz [2]int) { + m, _ := newFrameModel(sz[0], sz[1], mode) + m.hideHelpBar = !help + open(&m) + m.recomputeLayout() + if m.layout.tooSmall() { + return + } + var content string + if m.activeScreen() == screenFullVisualizer { + content = m.renderFullVisualizer() + } else { + content = strings.Join(m.mainSections(m.renderBodyRegion(), true, m.usesContentFirstLayout()), "\n") + } + if m.renderFrame(content) != lipglossFrame(m, content) { + t.Errorf("%s, mode %d, help %v, %dx%d: frames differ", name, mode, help, sz[0], sz[1]) + } + } + // Every screen at every size and help state, in one mode. + for name, open := range screens { + for _, help := range []bool{true, false} { + for _, sz := range sizes { + check(name, open, ui.VisBars, help, sz) + } + } + } + // Every mode at two sizes on the screens that draw the visualizer. + for _, name := range []string{"main", "full visualizer"} { + for mode := ui.VisMode(0); mode < ui.VisCount; mode++ { + for _, help := range []bool{true, false} { + for _, sz := range [][2]int{{205, 102}, {80, 24}} { + check(name, screens[name], mode, help, sz) + } + } + } + } + m, _ := newFrameModel(80, 24, ui.VisBars) + if content := "a\tb\r\nc\t\td\nend\r\n"; m.renderFrame(content) != lipglossFrame(m, content) { + t.Error("tabs and CRLF: frames differ") + } +} + +// A frame narrower than the terminal is centred: every row, padding rows +// included, starts with (width-frameWidth)/2 spaces and ends at frameWidth. +func TestRenderFrameCentresNarrowFrame(t *testing.T) { + m, _ := newFrameModel(100, 24, ui.VisBars) + m.layout.frameWidth = 61 // odd, so the indent rounds down: (100-61)/2 = 19 + const indent = 19 + frame := m.renderFrame("first\nsecond") + rows := strings.Split(frame, "\n") + if len(rows) > m.height { + t.Fatalf("%d rows, want at most %d", len(rows), m.height) + } + var content int + for i, row := range rows { + if row == "" { + continue // rows above the content are empty, as before + } + if !strings.HasPrefix(row, strings.Repeat(" ", indent)) || ansi.StringWidth(row) != indent+m.layout.frameWidth { + t.Fatalf("row %d = %q: want %d spaces then %d cells", i, row, indent, m.layout.frameWidth) + } + if strings.TrimSpace(row) != "" { + content++ + } + } + if content != 2 || !strings.Contains(frame, strings.Repeat(" ", indent)+strings.Repeat(" ", m.layout.paddingH)+"first") { + t.Errorf("content rows = %d, frame = %q", content, frame) + } +} + +// A line wider than the panel is cut, so it no longer pushes the rows below +// it down and the last ones off the screen. +func TestRenderFrameCutsWideLines(t *testing.T) { + m, _ := newFrameModel(80, 24, ui.VisBars) + var rows []string + for _, l := range strings.Split(m.renderFrame("first\n"+strings.Repeat("word ", 40)+"\nlast"), "\n") { + if s := strings.TrimSpace(l); s != "" { + rows = append(rows, s) + } + } + if len(rows) != 3 || rows[0] != "first" || rows[2] != "last" { + t.Fatalf("rows = %q", rows) + } +} + +func TestFullVisHelpKeepsWholeHints(t *testing.T) { + for _, w := range []int{205, 80, 72, 56, 40} { + m, _ := newFrameModel(w, 24, ui.VisWave) + m.fullVis = true + m.recomputeLayout() + help := m.fullVisHelp() + if lipgloss.Width(help) > m.layout.panelWidth || !strings.Contains(help, "Exit") { + t.Errorf("width %d: help %q", w, help) + } + } +} + +// BenchmarkPlayingFrame is one tick and one View while music plays. +func BenchmarkPlayingFrame(b *testing.B) { + for _, c := range []struct { + name string + mode ui.VisMode + full bool + w, h int + }{ + {"wave/205x102", ui.VisWave, false, 205, 102}, + {"wave/120x40", ui.VisWave, false, 120, 40}, + {"bars/205x102", ui.VisBars, false, 205, 102}, + {"wave-full/205x102", ui.VisWave, true, 205, 102}, + } { + b.Run(c.name, func(b *testing.B) { + m, eng := newFrameModel(c.w, c.h, c.mode) + m.fullVis = c.full + m.recomputeLayout() + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + eng.position = time.Duration(i) * 16 * time.Millisecond + next, _ := m.Update(tickMsg(time.Now())) + m = next.(Model) + m.View() + } + }) + } +} diff --git a/ui/model/view.go b/ui/model/view.go index bed74e09f..159f85877 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -265,8 +265,7 @@ func (m Model) View() tea.View { // Every screen now renders within the main frame, so frame and center // uniformly. - rendered := m.centerFrame(m.layout.frameStyle().Render(content)) - rendered = ui.FitRect(rendered, m.layout.frameWidth, max(1, m.height)) + rendered := m.renderFrame(content) if box := m.renderLuaSelect(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) @@ -576,23 +575,41 @@ func (m Model) renderCompactSource() string { return m.settingsSource(m.layout.panelWidth) } -// centerFrame centers a pre-rendered frame in the terminal. -func (m Model) centerFrame(frame string) string { - frameW := lipgloss.Width(frame) - frameH := lipgloss.Height(frame) - padLeft := max(0, (m.width-frameW)/2) - padTop := max(0, (m.height-frameH)/2) +// renderFrame pads content into the frame, centres it and fits it to the +// terminal in one pass. It draws what frameStyle().Render, centring and +// ui.FitRect drew, except that a line wider than the panel is cut, not wrapped. +func (m Model) renderFrame(content string) string { + l := m.layout + content = strings.ReplaceAll(content, "\t", " ") // as lipgloss did + content = strings.ReplaceAll(content, "\r\n", "\n") + lines := strings.Split(content, "\n") + height := max(1, m.height) + inner := max(1, l.frameWidth-2*l.paddingH) + side := strings.Repeat(" ", l.paddingH) + left := strings.Repeat(" ", max(0, (m.width-l.frameWidth)/2)) + blank := strings.Repeat(" ", l.frameWidth) + + out := make([]string, max(0, (height-len(lines)-2*l.paddingV)/2)) + for range l.paddingV { + out = append(out, left+blank) + } + for _, line := range lines { + out = append(out, left+side+fitLine(line, inner)+side) + } + for range l.paddingV { + out = append(out, left+blank) + } + return strings.Join(out[:min(len(out), height)], "\n") +} - if padLeft == 0 { - return strings.Repeat("\n", padTop) + frame - } - // Indent every line by padLeft spaces. - prefix := strings.Repeat(" ", padLeft) - lines := strings.Split(frame, "\n") - for i, l := range lines { - lines[i] = prefix + l +// fitLine pads or cuts s to exactly width cells. +func fitLine(s string, width int) string { + w := ansi.StringWidth(s) + if w > width { + s = ansi.Truncate(s, width, "") + w = ansi.StringWidth(s) } - return strings.Repeat("\n", padTop) + strings.Join(lines, "\n") + return s + strings.Repeat(" ", max(0, width-w)) } func (m Model) renderTitle() string { @@ -704,19 +721,36 @@ func (m Model) renderFullVisualizer() string { sections = append( sections, "", - helpKey("V", "Exit ")+ - helpKey("v", "Mode:"+m.vis.ModeName()+" ")+ - helpKey("Spc", "▶❚❚ ")+ - helpKey("<>", "Trk ")+ - helpKey("+-", "Vol ")+ - helpKey("t", "Title ")+ - helpKey("?", "Keys"), + m.fullVisHelp(), ) } return strings.Join(sections, "\n") } +// fullVisHelp keeps as many whole hints as fit the panel. +func (m Model) fullVisHelp() string { + var b strings.Builder + width := 0 + for _, h := range []string{ + helpKey("V", "Exit "), + helpKey("v", "Mode:"+m.vis.ModeName()+" "), + helpKey("Spc", "▶❚❚ "), + helpKey("<>", "Trk "), + helpKey("+-", "Vol "), + helpKey("t", "Title "), + helpKey("?", "Keys"), + } { + w := lipgloss.Width(h) + if width > 0 && width+w > m.layout.panelWidth { + break + } + b.WriteString(h) + width += w + } + return b.String() +} + // fullVisTopLine names what is playing, or just the source when the track has // been hidden. The full-screen visualizer is the view most likely to be on a // shared screen, so naming the episode has to be optional. diff --git a/ui/vis_frame.go b/ui/vis_frame.go index cf9762db5..418c72b30 100644 --- a/ui/vis_frame.go +++ b/ui/vis_frame.go @@ -19,7 +19,12 @@ func fitVisualizerFrame(frame string, cols, rows int) string { out.WriteByte('\n') } line, next, _ := strings.Cut(rest, "\n") - width := writeVisualizerLine(&out, line, cols) + width := ansi.StringWidth(line) + if width <= cols { + out.WriteString(line) + } else { // only a line that has to be cut needs walking + width = writeVisualizerLine(&out, line, cols) + } for range cols - width { out.WriteByte(' ') } diff --git a/ui/vis_frame_test.go b/ui/vis_frame_test.go new file mode 100644 index 000000000..026656391 --- /dev/null +++ b/ui/vis_frame_test.go @@ -0,0 +1,49 @@ +package ui + +import ( + "strings" + "testing" + "time" +) + +// Copying a line that fits gives the same bytes as walking it. +func TestFitVisualizerFrameMatchesWalk(t *testing.T) { + walked := func(frame string, cols, rows int) string { + var out strings.Builder + rest := frame + for row := range rows { + if row > 0 { + out.WriteByte('\n') + } + line, next, _ := strings.Cut(rest, "\n") + out.WriteString(strings.Repeat(" ", cols-writeVisualizerLine(&out, line, cols))) + rest = next + } + return out.String() + } + var frames []string + samples := benchSamplesSine(defaultFFTSize) + for mode := VisMode(0); mode < VisCount; mode++ { + v := NewVisualizer(benchSampleRate) + v.Mode, v.Cols, v.Rows = mode, 201, 20 + ctx := VisTickContext{Now: time.Now(), Playing: true, Analyze: func(spec VisAnalysisSpec) []float64 { return v.Analyze(samples, spec) }} + for range 4 { + v.Tick(ctx) + } + if d := v.syncDriverMode(); d != nil { + frames = append(frames, d.Render(v)) + } + } + frames = append(frames, + "\x1b[38;2;255;128;0m"+strings.Repeat("界 visualizer ", 12)+"\x1b[0m", + "emoji \u2764\ufe0f and e\u0301", + "\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\", + ) + for i, f := range frames { + for _, cols := range []int{201, 76, 20, 1} { + if got, want := fitVisualizerFrame(f, cols, 20), walked(f, cols, 20); got != want { + t.Errorf("frame %d at %d columns: differs", i, cols) + } + } + } +}