From dc95bc9426e4d38c8edd847ace61d999bedc15b3 Mon Sep 17 00:00:00 2001 From: david s <15107452+davidszp@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:22:06 +0200 Subject: [PATCH 1/4] perf(ui): draw the frame in one pass View drew every frame through frameStyle().Render, which wraps, aligns and pads each line, then centred it and fitted it with FitRect: three passes over the whole screen, measuring each line up to four times. While music plays a screen redraws 20 to 60 times a second, so this was most of cliamp's CPU. renderFrame pads, centres and fits in one pass that measures each line once. A test compares it with the old path, byte for byte, on every screen in every visualizer mode at 12 sizes (17,640 frames, identical). A line wider than the panel is now cut instead of wrapped; a wrapped line pushed the rows below it off the screen. Only the full-screen visualizer's key line did that, in narrow terminals, so it now keeps whole hints. Co-Authored-By: Claude Opus 5.5 --- ui/model/frame_test.go | 175 +++++++++++++++++++++++++++++++++++++++++ ui/model/view.go | 81 +++++++++++++------ 2 files changed, 232 insertions(+), 24 deletions(-) create mode 100644 ui/model/frame_test.go diff --git a/ui/model/frame_test.go b/ui/model/frame_test.go new file mode 100644 index 000000000..0a64a775b --- /dev/null +++ b/ui/model/frame_test.go @@ -0,0 +1,175 @@ +package model + +import ( + "fmt" + "math" + "strings" + "testing" + "time" + + "charm.land/lipgloss/v2" + + "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 on every screen, at every size, +// in every visualizer mode, with the help bar 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}} + for name, open := range screens { + for mode := ui.VisMode(0); mode < ui.VisCount; mode++ { + for _, help := range []bool{true, false} { + for _, sz := range sizes { + m, _ := newFrameModel(sz[0], sz[1], mode) + m.hideHelpBar = !help + open(&m) + m.recomputeLayout() + if m.layout.tooSmall() { + continue + } + content := m.renderFullVisualizer() + if m.activeScreen() != screenFullVisualizer { + 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]) + } + } + } + } + } + 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 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..999de65bf 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,40 @@ 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) + blank := strings.Repeat(" ", l.frameWidth) + + out := make([]string, max(0, (height-len(lines)-2*l.paddingV)/2)) + for range l.paddingV { + out = append(out, blank) + } + for _, line := range lines { + out = append(out, side+fitLine(line, inner)+side) + } + for range l.paddingV { + out = append(out, 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 +720,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. From 8a464d00081d92236c34eeb3f89e808adf1c5ee1 Mon Sep 17 00:00:00 2001 From: david s <15107452+davidszp@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:22:06 +0200 Subject: [PATCH 2/4] perf(ui): measure common text without grapheme segmentation After the one-pass frame, measuring was still the largest cost of a frame: ansi.StringWidth segments every line into grapheme clusters, and visualizer lines were measured twice, in fitVisualizerFrame and the frame. Nearly everything on screen is ASCII, Latin letters, punctuation, box drawing, blocks and braille with CSI colour codes, where one rune is one cell. cellwidth.String counts runes for that text, about ten times faster on a braille line, and hands anything else to ansi.StringWidth. Its test checks every rune it counts against ansi.StringWidth. fitVisualizerFrame copies a line that fits; a test checks the bytes match the old walk for every visualizer mode. Co-Authored-By: Claude Opus 5.5 --- internal/cellwidth/cellwidth.go | 70 ++++++++++++++++++++++++++++ internal/cellwidth/cellwidth_test.go | 50 ++++++++++++++++++++ ui/model/view.go | 5 +- ui/vis_frame.go | 9 +++- ui/vis_frame_test.go | 49 +++++++++++++++++++ 5 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 internal/cellwidth/cellwidth.go create mode 100644 internal/cellwidth/cellwidth_test.go create mode 100644 ui/vis_frame_test.go diff --git a/internal/cellwidth/cellwidth.go b/internal/cellwidth/cellwidth.go new file mode 100644 index 000000000..6939c9cb5 --- /dev/null +++ b/internal/cellwidth/cellwidth.go @@ -0,0 +1,70 @@ +// Package cellwidth measures the terminal width of styled text. For the text +// a frame is mostly made of it counts runes, which is exact there and much +// cheaper than ansi.StringWidth's grapheme segmentation. +package cellwidth + +import ( + "unicode/utf8" + + "github.com/charmbracelet/x/ansi" +) + +// String is the width of s in cells, as ansi.StringWidth gives it. +func String(s string) int { + if w, ok := fast(s); ok { + return w + } + return ansi.StringWidth(s) +} + +// fast counts the cells of s if every rune is one cell and every escape +// sequence is CSI. +func fast(s string) (int, bool) { + w := 0 + for i := 0; i < len(s); { + c := s[i] + switch { + case c >= 0x20 && c < 0x7f: + w++ + i++ + case c == 0x1b: + if i+1 >= len(s) || s[i+1] != '[' { + return 0, false + } + j := i + 2 + for j < len(s) && s[j] >= 0x20 && s[j] <= 0x3f { + j++ + } + if j >= len(s) || s[j] < 0x40 || s[j] > 0x7e { + return 0, false + } + i = j + 1 + case c < 0x80: + return 0, false + default: + r, n := utf8.DecodeRuneInString(s[i:]) + if !narrow(r) { + return 0, false + } + w++ + i += n + } + } + return w, true +} + +// narrow reports whether r is one cell and never joins the rune before it: +// Latin letters, punctuation, box drawing, blocks, shapes and braille. +func narrow(r rune) bool { + switch { + case r >= 0xa0 && r <= 0x24f: + return r != 0xad // soft hyphen + case r >= 0x2010 && r <= 0x2027: + return true + case r >= 0x2500 && r <= 0x25ff: + return r != 0x25fd && r != 0x25fe // wide emoji squares + case r >= 0x2800 && r <= 0x28ff: + return true + } + return false +} diff --git a/internal/cellwidth/cellwidth_test.go b/internal/cellwidth/cellwidth_test.go new file mode 100644 index 000000000..a678ece00 --- /dev/null +++ b/internal/cellwidth/cellwidth_test.go @@ -0,0 +1,50 @@ +package cellwidth + +import ( + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" +) + +func TestStringMatchesAnsi(t *testing.T) { + var cases []string + for r := rune(0); r <= 0x2fff; r++ { + if narrow(r) { + cases = append(cases, string(r), "a"+string(r)+"b", string(r)+string(r)) + } + } + cases = append(cases, + "", + "\x1b[38;2;255;0;0m⣿⣿⡇\x1b[0m ▸ Album · 1:30", + "\x1b[1;4mbold\x1b[m", + "wide 日本語 text", + "emoji \u2764\ufe0f here", + "combining e\u0301", + "\x1b]8;;https://x\x1b\\link\x1b]8;;\x1b\\", + "tab\there", + "soft\u00adhyphen", + "\x1b[", + "\x1b[38;5", + "bad \xff utf-8", + ) + for _, s := range cases { + if got, want := String(s), ansi.StringWidth(s); got != want { + t.Errorf("%q: width %d, want %d", s, got, want) + } + } +} + +func BenchmarkString(b *testing.B) { + line := strings.Repeat("\x1b[38;2;120;200;255m⣿⡇⠀⢸\x1b[0m", 50) + b.Run("cellwidth", func(b *testing.B) { + for b.Loop() { + String(line) + } + }) + b.Run("ansi", func(b *testing.B) { + for b.Loop() { + ansi.StringWidth(line) + } + }) +} diff --git a/ui/model/view.go b/ui/model/view.go index 999de65bf..f1f69f467 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -12,6 +12,7 @@ import ( "github.com/bjarneo/cliamp/external/radio" "github.com/bjarneo/cliamp/favorites" + "github.com/bjarneo/cliamp/internal/cellwidth" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/provider" "github.com/bjarneo/cliamp/ui" @@ -603,10 +604,10 @@ func (m Model) renderFrame(content string) string { // fitLine pads or cuts s to exactly width cells. func fitLine(s string, width int) string { - w := ansi.StringWidth(s) + w := cellwidth.String(s) if w > width { s = ansi.Truncate(s, width, "") - w = ansi.StringWidth(s) + w = cellwidth.String(s) } return s + strings.Repeat(" ", max(0, width-w)) } diff --git a/ui/vis_frame.go b/ui/vis_frame.go index cf9762db5..49f47418d 100644 --- a/ui/vis_frame.go +++ b/ui/vis_frame.go @@ -4,6 +4,8 @@ import ( "strings" "github.com/charmbracelet/x/ansi" + + "github.com/bjarneo/cliamp/internal/cellwidth" ) func fitVisualizerFrame(frame string, cols, rows int) string { @@ -19,7 +21,12 @@ func fitVisualizerFrame(frame string, cols, rows int) string { out.WriteByte('\n') } line, next, _ := strings.Cut(rest, "\n") - width := writeVisualizerLine(&out, line, cols) + width := cellwidth.String(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) + } + } + } +} From 07be1ed9abfd518f64a8fabce1dcb0ceea7d2ad6 Mon Sep 17 00:00:00 2001 From: david s <15107452+davidszp@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:10:25 +0200 Subject: [PATCH 3/4] perf(ui): use ansi.StringWidth, trim the frame test, centre narrow frames Review changes on #704: - Remove internal/cellwidth. fitLine and fitVisualizerFrame measure with ansi.StringWidth, so core has one source of text width. - Cover every screen at every size in one mode, and every mode at two sizes on the main and full-visualizer screens, instead of the full cross product. TestRenderFrameMatchesLipgloss compares 784 frames, and go test -race ./ui/model takes 9.6 s, not 131 s. - Prefix every row with max(0, (width-frameWidth)/2) spaces, so a frame narrower than the terminal is centred. TestRenderFrameCentresNarrowFrame covers it. Co-Authored-By: Claude Sonnet 5.5 --- internal/cellwidth/cellwidth.go | 70 -------------------------- internal/cellwidth/cellwidth_test.go | 50 ------------------- ui/model/frame_test.go | 75 +++++++++++++++++++++------- ui/model/view.go | 12 ++--- ui/vis_frame.go | 4 +- 5 files changed, 65 insertions(+), 146 deletions(-) delete mode 100644 internal/cellwidth/cellwidth.go delete mode 100644 internal/cellwidth/cellwidth_test.go diff --git a/internal/cellwidth/cellwidth.go b/internal/cellwidth/cellwidth.go deleted file mode 100644 index 6939c9cb5..000000000 --- a/internal/cellwidth/cellwidth.go +++ /dev/null @@ -1,70 +0,0 @@ -// Package cellwidth measures the terminal width of styled text. For the text -// a frame is mostly made of it counts runes, which is exact there and much -// cheaper than ansi.StringWidth's grapheme segmentation. -package cellwidth - -import ( - "unicode/utf8" - - "github.com/charmbracelet/x/ansi" -) - -// String is the width of s in cells, as ansi.StringWidth gives it. -func String(s string) int { - if w, ok := fast(s); ok { - return w - } - return ansi.StringWidth(s) -} - -// fast counts the cells of s if every rune is one cell and every escape -// sequence is CSI. -func fast(s string) (int, bool) { - w := 0 - for i := 0; i < len(s); { - c := s[i] - switch { - case c >= 0x20 && c < 0x7f: - w++ - i++ - case c == 0x1b: - if i+1 >= len(s) || s[i+1] != '[' { - return 0, false - } - j := i + 2 - for j < len(s) && s[j] >= 0x20 && s[j] <= 0x3f { - j++ - } - if j >= len(s) || s[j] < 0x40 || s[j] > 0x7e { - return 0, false - } - i = j + 1 - case c < 0x80: - return 0, false - default: - r, n := utf8.DecodeRuneInString(s[i:]) - if !narrow(r) { - return 0, false - } - w++ - i += n - } - } - return w, true -} - -// narrow reports whether r is one cell and never joins the rune before it: -// Latin letters, punctuation, box drawing, blocks, shapes and braille. -func narrow(r rune) bool { - switch { - case r >= 0xa0 && r <= 0x24f: - return r != 0xad // soft hyphen - case r >= 0x2010 && r <= 0x2027: - return true - case r >= 0x2500 && r <= 0x25ff: - return r != 0x25fd && r != 0x25fe // wide emoji squares - case r >= 0x2800 && r <= 0x28ff: - return true - } - return false -} diff --git a/internal/cellwidth/cellwidth_test.go b/internal/cellwidth/cellwidth_test.go deleted file mode 100644 index a678ece00..000000000 --- a/internal/cellwidth/cellwidth_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package cellwidth - -import ( - "strings" - "testing" - - "github.com/charmbracelet/x/ansi" -) - -func TestStringMatchesAnsi(t *testing.T) { - var cases []string - for r := rune(0); r <= 0x2fff; r++ { - if narrow(r) { - cases = append(cases, string(r), "a"+string(r)+"b", string(r)+string(r)) - } - } - cases = append(cases, - "", - "\x1b[38;2;255;0;0m⣿⣿⡇\x1b[0m ▸ Album · 1:30", - "\x1b[1;4mbold\x1b[m", - "wide 日本語 text", - "emoji \u2764\ufe0f here", - "combining e\u0301", - "\x1b]8;;https://x\x1b\\link\x1b]8;;\x1b\\", - "tab\there", - "soft\u00adhyphen", - "\x1b[", - "\x1b[38;5", - "bad \xff utf-8", - ) - for _, s := range cases { - if got, want := String(s), ansi.StringWidth(s); got != want { - t.Errorf("%q: width %d, want %d", s, got, want) - } - } -} - -func BenchmarkString(b *testing.B) { - line := strings.Repeat("\x1b[38;2;120;200;255m⣿⡇⠀⢸\x1b[0m", 50) - b.Run("cellwidth", func(b *testing.B) { - for b.Loop() { - String(line) - } - }) - b.Run("ansi", func(b *testing.B) { - for b.Loop() { - ansi.StringWidth(line) - } - }) -} diff --git a/ui/model/frame_test.go b/ui/model/frame_test.go index 0a64a775b..1e1257bcf 100644 --- a/ui/model/frame_test.go +++ b/ui/model/frame_test.go @@ -8,6 +8,7 @@ import ( "time" "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/ui" @@ -64,8 +65,8 @@ func lipglossFrame(m Model, content string) string { 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 on every screen, at every size, -// in every visualizer mode, with the help bar shown and hidden. +// 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) {}, @@ -91,24 +92,36 @@ func TestRenderFrameMatchesLipgloss(t *testing.T) { "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 + } + content := m.renderFullVisualizer() + if m.activeScreen() != screenFullVisualizer { + 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 sizes { - m, _ := newFrameModel(sz[0], sz[1], mode) - m.hideHelpBar = !help - open(&m) - m.recomputeLayout() - if m.layout.tooSmall() { - continue - } - content := m.renderFullVisualizer() - if m.activeScreen() != screenFullVisualizer { - 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]) - } + for _, sz := range [][2]int{{205, 102}, {80, 24}} { + check(name, screens[name], mode, help, sz) } } } @@ -119,6 +132,34 @@ func TestRenderFrameMatchesLipgloss(t *testing.T) { } } +// 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) { diff --git a/ui/model/view.go b/ui/model/view.go index f1f69f467..159f85877 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -12,7 +12,6 @@ import ( "github.com/bjarneo/cliamp/external/radio" "github.com/bjarneo/cliamp/favorites" - "github.com/bjarneo/cliamp/internal/cellwidth" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/provider" "github.com/bjarneo/cliamp/ui" @@ -587,27 +586,28 @@ func (m Model) renderFrame(content string) string { 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, blank) + out = append(out, left+blank) } for _, line := range lines { - out = append(out, side+fitLine(line, inner)+side) + out = append(out, left+side+fitLine(line, inner)+side) } for range l.paddingV { - out = append(out, blank) + out = append(out, left+blank) } return strings.Join(out[:min(len(out), height)], "\n") } // fitLine pads or cuts s to exactly width cells. func fitLine(s string, width int) string { - w := cellwidth.String(s) + w := ansi.StringWidth(s) if w > width { s = ansi.Truncate(s, width, "") - w = cellwidth.String(s) + w = ansi.StringWidth(s) } return s + strings.Repeat(" ", max(0, width-w)) } diff --git a/ui/vis_frame.go b/ui/vis_frame.go index 49f47418d..418c72b30 100644 --- a/ui/vis_frame.go +++ b/ui/vis_frame.go @@ -4,8 +4,6 @@ import ( "strings" "github.com/charmbracelet/x/ansi" - - "github.com/bjarneo/cliamp/internal/cellwidth" ) func fitVisualizerFrame(frame string, cols, rows int) string { @@ -21,7 +19,7 @@ func fitVisualizerFrame(frame string, cols, rows int) string { out.WriteByte('\n') } line, next, _ := strings.Cut(rest, "\n") - width := cellwidth.String(line) + width := ansi.StringWidth(line) if width <= cols { out.WriteString(line) } else { // only a line that has to be cut needs walking From e59fa64059af8f7e806994f8b967499f7bf8ba48 Mon Sep 17 00:00:00 2001 From: david s <15107452+davidszp@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:07:59 +0200 Subject: [PATCH 4/4] test(ui): render only the active screen in the frame test check in TestRenderFrameMatchesLipgloss called renderFullVisualizer for every case and dropped the result on 20 of the 21 screens. It now tests activeScreen first and renders only that screen's content. The test compares the same frames as before. Co-Authored-By: Claude Fable 5.2 --- ui/model/frame_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ui/model/frame_test.go b/ui/model/frame_test.go index 1e1257bcf..dbb932fe6 100644 --- a/ui/model/frame_test.go +++ b/ui/model/frame_test.go @@ -100,8 +100,10 @@ func TestRenderFrameMatchesLipgloss(t *testing.T) { if m.layout.tooSmall() { return } - content := m.renderFullVisualizer() - if m.activeScreen() != screenFullVisualizer { + 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) {