From 3b5470ff8e3244b3b17cb3e67a40cd3628288301 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Fr=C3=B6ssman?= Date: Fri, 20 Nov 2026 10:02:00 +0100 Subject: [PATCH] use internal tui package in place of bubbletea The usage is simple enough that it isn't a lot of code and the performance increases just from this change alone. --- go.mod | 8 +- go.sum | 15 - internal/pipmix/frame_bench_test.go | 87 ++++ internal/pipmix/help.go | 77 ++-- internal/pipmix/keys.go | 58 ++- internal/pipmix/loop.go | 142 +++++++ internal/pipmix/meters.go | 27 +- internal/pipmix/meters_test.go | 18 +- internal/pipmix/mixer.go | 52 ++- internal/pipmix/mixer_test.go | 79 ++-- internal/pipmix/mouse.go | 59 ++- internal/pipmix/options_test.go | 8 +- internal/pipmix/pipmix.go | 43 +- internal/pipmix/view.go | 593 +++++++++++++++------------- internal/pipmix/view_test.go | 59 +++ internal/tui/event.go | 77 ++++ internal/tui/grid.go | 114 ++++++ internal/tui/pen.go | 129 ++++++ internal/tui/pen_test.go | 66 ++++ internal/tui/screen.go | 118 ++++++ internal/tui/screen_test.go | 133 +++++++ internal/tui/style.go | 75 ++++ internal/tui/term.go | 154 ++++++++ 23 files changed, 1667 insertions(+), 524 deletions(-) create mode 100644 internal/pipmix/frame_bench_test.go create mode 100644 internal/pipmix/loop.go create mode 100644 internal/pipmix/view_test.go create mode 100644 internal/tui/event.go create mode 100644 internal/tui/grid.go create mode 100644 internal/tui/pen.go create mode 100644 internal/tui/pen_test.go create mode 100644 internal/tui/screen.go create mode 100644 internal/tui/screen_test.go create mode 100644 internal/tui/style.go create mode 100644 internal/tui/term.go diff --git a/go.mod b/go.mod index aacfd68..1e205a6 100644 --- a/go.mod +++ b/go.mod @@ -3,25 +3,23 @@ module github.com/some-programs/pipmix go 1.27 require ( - charm.land/bubbletea/v2 v2.1.2 - charm.land/lipgloss/v2 v2.1.1 + github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c github.com/charmbracelet/x/ansi v0.11.10 + github.com/charmbracelet/x/term v0.2.2 github.com/godbus/dbus/v5 v5.2.4 + github.com/muesli/cancelreader v0.2.2 github.com/pelletier/go-toml/v2 v2.4.3 github.com/peterbourgon/ff/v3 v3.4.0 ) require ( github.com/charmbracelet/colorprofile v0.4.3 // indirect - github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c // indirect - github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/mattn/go-runewidth v0.0.31 // indirect - github.com/muesli/cancelreader v0.2.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/xo/terminfo v1.3.1 // indirect golang.org/x/sync v0.25.0 // indirect diff --git a/go.sum b/go.sum index 88e86a7..0027256 100644 --- a/go.sum +++ b/go.sum @@ -1,23 +1,9 @@ -charm.land/bubbletea/v2 v2.1.2-0.20261112134521-6b30ecf3280d h1:vUXQwg+Wu2W/j3meguShWTWeKGgeKOrmbIpX+K37yVA= -charm.land/bubbletea/v2 v2.1.2-0.20261112134521-6b30ecf3280d/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= -charm.land/bubbletea/v2 v2.1.2 h1:vB3XAcHhLB2gR3HOHpwO3lHB3nbvaowIgL3e5x/DUZo= -charm.land/bubbletea/v2 v2.1.2/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= -charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc= -charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc= -github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= -github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= -github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f h1:D2JpB65eehsnkEwEG401dMBSNYtTDgvKXZZSl7ZCxWI= -github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c h1:izHJ6cjHd9HGtre1J+c/+QE3rQZ2t4EZH6BqykQbpjc= github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= -github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= -github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= github.com/charmbracelet/x/ansi v0.11.10 h1:GjcX3+rAk+8wDX/jY0XwrZstxkjRcLkYU3TvwzZWiRA= github.com/charmbracelet/x/ansi v0.11.10/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= -github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA= -github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I= github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= @@ -36,7 +22,6 @@ github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5I github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= -github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/peterbourgon/ff/v3 v3.4.0 h1:QBvM/rizZM1cB0p0lGMdmR7HxZeI/ZrBWB4DqLkMUBc= diff --git a/internal/pipmix/frame_bench_test.go b/internal/pipmix/frame_bench_test.go new file mode 100644 index 0000000..4514551 --- /dev/null +++ b/internal/pipmix/frame_bench_test.go @@ -0,0 +1,87 @@ +package pipmix + +import ( + "fmt" + "testing" + + "github.com/some-programs/pipmix/internal/pulse" + "github.com/some-programs/pipmix/internal/pw" + "github.com/some-programs/pipmix/internal/tui" +) + +// benchMixer returns a mixer on the playback tab of a w×h terminal with +// more streams than fit, all metered. +func benchMixer(w, h int) mixer { + snap := testSnapshot() + for i := range 20 { + snap.Nodes = append(snap.Nodes, pw.Node{ID: uint32(100 + i), Class: pw.Playback, Name: fmt.Sprint("n", i), Title: fmt.Sprint("Player ", i), Channels: stereo(0.5)}) + } + m := newMixer(pw.NewClient(nil), nil, pulse.NewMeter(nil, 0), quitKeys(), defaultOptions()) + m.snap = snap + m.fill = make(map[uint32][]float64) + for _, n := range snap.Nodes { + m.fill[n.ID] = make([]float64, len(n.Channels)) + } + m.setSize(w, h) + m.refocus() + m.setTab(tabPlayback) + return m +} + +// setBenchLevels moves every meter, keeping them below the faders. +func setBenchLevels(m *mixer, i int) { + for id, levels := range m.fill { + for ch := range levels { + levels[ch] = float64((int(id)*13+ch*29+i*7)%100) / 250 + } + } +} + +type countWriter struct{ n int } + +func (w *countWriter) Write(p []byte) (int, error) { + w.n += len(p) + return len(p), nil +} + +// BenchmarkFrameMeters measures a frame in which only the meters moved. +func BenchmarkFrameMeters(b *testing.B) { + m := benchMixer(200, 50) + g := tui.NewGrid(0, 0) + var w countWriter + s := tui.NewScreen(&w) + m.draw(g) + if err := s.Flush(g); err != nil { + b.Fatal(err) + } + w.n = 0 + i := 0 + for b.Loop() { + setBenchLevels(&m, i) + i++ + m.drawMeters(g) + if err := s.Flush(g); err != nil { + b.Fatal(err) + } + } + b.ReportMetric(float64(w.n)/float64(b.N), "bytes/frame") +} + +// BenchmarkFrameFull measures a frame after an event, which redraws the +// whole screen. +func BenchmarkFrameFull(b *testing.B) { + m := benchMixer(200, 50) + g := tui.NewGrid(0, 0) + var w countWriter + s := tui.NewScreen(&w) + i := 0 + for b.Loop() { + setBenchLevels(&m, i) + i++ + m.draw(g) + if err := s.Flush(g); err != nil { + b.Fatal(err) + } + } + b.ReportMetric(float64(w.n)/float64(b.N), "bytes/frame") +} diff --git a/internal/pipmix/help.go b/internal/pipmix/help.go index bb4460a..cc246ab 100644 --- a/internal/pipmix/help.go +++ b/internal/pipmix/help.go @@ -4,63 +4,65 @@ import ( "slices" "strings" - "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" + + "github.com/some-programs/pipmix/internal/tui" ) var ( - helpSectionStyle = lipgloss.NewStyle().Bold(true) - helpRuleStyle = ansi.Style{}.Underline(true).UnderlineColor(ansi.BrightBlack) + helpSectionStyle = tui.Style{Attrs: tui.Bold} + helpRuleStyle = tui.Style{Attrs: tui.Underline, UnderlineColor: tui.BrightBlack} ) const helpGap = 3 type helpLine struct { - text string - rule bool // underlined separator at the end of a binding + text string + style tui.Style + rule bool // underlined separator at the end of a binding } -// helpLines formats the current tab's help into columns fitting width and height. -func (m *mixer) helpLines(width, height int) []string { +// helpColumns arranges the current tab's help into columns fitting width +// and height. +func (m *mixer) helpColumns(width, height int) [][]helpLine { var blocks [][]helpLine for _, s := range m.tabSections() { blocks = append(blocks, helpBlock(s, width)) } - columns := arrangeColumns(blocks, width, height) - lines := make([]string, tallest(columns)) - for i := range lines { - var b strings.Builder + return arrangeColumns(blocks, width, height) +} + +// scrollHelp scrolls the help by delta lines, within its length. +func (m *mixer) scrollHelp(delta int) { + h := m.listHeight() + n := tallest(m.helpColumns(m.width, h)) + m.helpOff = max(0, min(m.helpOff+delta, n-h)) +} + +// drawHelp draws the visible lines of the help into the h rows of the list. +func (m *mixer) drawHelp(g *tui.Grid, h int) { + columns := m.helpColumns(m.width, h) + widths := make([]int, len(columns)) + for c, col := range columns { + widths[c] = columnWidth(col) + } + for i := m.helpOff; i < min(tallest(columns), m.helpOff+h); i++ { + p := g.Pen(0, listTop+i-m.helpOff, m.width) for c, col := range columns { if c > 0 { - b.WriteString(strings.Repeat(" ", helpGap)) + p.Repeat(" ", helpGap, plain) } var line helpLine if i < len(col) { line = col[i] } - text := fit(line.text, columnWidth(col)) + st, pad := line.style, plain if line.rule { - text = helpRuleStyle.Styled(text) + st, pad = helpRuleStyle, helpRuleStyle } - b.WriteString(text) + p.Fit(line.text, widths[c], st, pad) } - lines[i] = fit(b.String(), width) } - return lines -} - -// scrollHelp scrolls the help by delta lines, within its length. -func (m *mixer) scrollHelp(delta int) { - h := m.listHeight() - n := len(m.helpLines(m.width, h)) - m.helpOff = max(0, min(m.helpOff+delta, n-h)) -} - -// helpView renders the visible lines of the help. -func (m *mixer) helpView(width, height int) []string { - lines := m.helpLines(width, height) - end := min(len(lines), m.helpOff+height) - return lines[min(m.helpOff, end):end] } func tallest(columns [][]helpLine) int { @@ -97,7 +99,7 @@ func helpBlock(s section, width int) []helpLine { } } textIndent := len(indent) + keysWidth + 2 - lines := []helpLine{{text: helpSectionStyle.Render(ansi.Truncate(s.title, width, "…"))}} + lines := []helpLine{{text: ansi.Truncate(s.title, width, "…"), style: helpSectionStyle}} for _, b := range s.bindings { inputs := b.inputs() text := strings.Split(ansi.Wrap(b.help, max(1, width-textIndent), ""), "\n") @@ -110,7 +112,7 @@ func helpBlock(s section, width int) []helpLine { if r < len(text) { line += strings.Repeat(" ", textIndent-ansi.StringWidth(line)) + text[r] } - lines = append(lines, helpLine{ansi.Truncate(line, width, "…"), r == rows-1}) + lines = append(lines, helpLine{text: ansi.Truncate(line, width, "…"), rule: r == rows-1}) } } return lines @@ -160,12 +162,3 @@ func arrangeColumns(blocks [][]helpLine, width, height int) [][]helpLine { } return best } - -// fit truncates or pads s to width cells. -func fit(s string, width int) string { - if width <= 0 { - return "" - } - s = ansi.Truncate(s, width, "…") - return s + strings.Repeat(" ", max(0, width-ansi.StringWidth(s))) -} diff --git a/internal/pipmix/keys.go b/internal/pipmix/keys.go index ecad8eb..ac980e6 100644 --- a/internal/pipmix/keys.go +++ b/internal/pipmix/keys.go @@ -2,15 +2,13 @@ package pipmix import ( "slices" - - tea "charm.land/bubbletea/v2" ) type binding struct { keys []string help string mouse string - do func(m *mixer) tea.Cmd + do func(m *mixer) command } type section struct { @@ -20,10 +18,10 @@ type section struct { func volumeKeys(o options) section { return section{"Volume", []binding{ - {[]string{"l", "right", "+", "="}, "Louder by " + percentText(o.step), "click or drag on a bar", func(m *mixer) tea.Cmd { return m.changeVolume(m.opts.step) }}, - {[]string{"h", "left", "-"}, "Quieter by " + percentText(o.step), "", func(m *mixer) tea.Cmd { return m.changeVolume(-m.opts.step) }}, - {[]string{"L", "shift+right"}, "Louder by " + percentText(o.fineStep), "", func(m *mixer) tea.Cmd { return m.changeVolume(m.opts.fineStep) }}, - {[]string{"H", "shift+left"}, "Quieter by " + percentText(o.fineStep), "", func(m *mixer) tea.Cmd { return m.changeVolume(-m.opts.fineStep) }}, + {[]string{"l", "right", "+", "="}, "Louder by " + percentText(o.step), "click or drag on a bar", func(m *mixer) command { return m.changeVolume(m.opts.step) }}, + {[]string{"h", "left", "-"}, "Quieter by " + percentText(o.step), "", func(m *mixer) command { return m.changeVolume(-m.opts.step) }}, + {[]string{"L", "shift+right"}, "Louder by " + percentText(o.fineStep), "", func(m *mixer) command { return m.changeVolume(m.opts.fineStep) }}, + {[]string{"H", "shift+left"}, "Quieter by " + percentText(o.fineStep), "", func(m *mixer) command { return m.changeVolume(-m.opts.fineStep) }}, {[]string{"c", "u"}, "Set volume to 100%", "middle click on a bar", (*mixer).setVolume100}, {[]string{"m"}, "Mute or unmute", "click 🔊, or right click", (*mixer).toggleMute}, {[]string{"space"}, "Lock or unlock the channels", "", (*mixer).toggleLock}, @@ -59,27 +57,27 @@ func cardKeys() section { } func navigationKeys() section { - page := func(f func(n int) int) func(m *mixer) tea.Cmd { - return func(m *mixer) tea.Cmd { + page := func(f func(n int) int) func(m *mixer) command { + return func(m *mixer) command { m.moveItems(f(m.pageItems())) return nil } } return section{"Navigation", []binding{ - {[]string{"k", "up", "ctrl+p"}, "Move up", "click", func(m *mixer) tea.Cmd { m.move(-1); return nil }}, - {[]string{"j", "down", "ctrl+n"}, "Move down", "", func(m *mixer) tea.Cmd { m.move(1); return nil }}, + {[]string{"k", "up", "ctrl+p"}, "Move up", "click", func(m *mixer) command { m.move(-1); return nil }}, + {[]string{"j", "down", "ctrl+n"}, "Move down", "", func(m *mixer) command { m.move(1); return nil }}, {[]string{"ctrl+b", "pgup", "alt+v"}, "Page up", "", page(func(n int) int { return -n })}, {[]string{"ctrl+f", "pgdown", "ctrl+v"}, "Page down", "", page(func(n int) int { return n })}, {[]string{"ctrl+u"}, "Half page up", "", page(func(n int) int { return -max(n/2, 1) })}, {[]string{"ctrl+d"}, "Half page down", "", page(func(n int) int { return max(n/2, 1) })}, - {[]string{"g", "home"}, "Go to top", "", func(m *mixer) tea.Cmd { m.moveItems(-1 << 30); return nil }}, - {[]string{"G", "end"}, "Go to bottom", "", func(m *mixer) tea.Cmd { m.moveItems(1 << 30); return nil }}, + {[]string{"g", "home"}, "Go to top", "", func(m *mixer) command { m.moveItems(-1 << 30); return nil }}, + {[]string{"G", "end"}, "Go to bottom", "", func(m *mixer) command { m.moveItems(1 << 30); return nil }}, }} } func tabKeys() section { - set := func(f func(tab) tab) func(m *mixer) tea.Cmd { - return func(m *mixer) tea.Cmd { + set := func(f func(tab) tab) func(m *mixer) command { + return func(m *mixer) command { m.setTab(f(m.tab)) return nil } @@ -102,7 +100,7 @@ func tabKeys() section { func generalKeys() section { return section{"General", []binding{ - {[]string{"?"}, "Help for this tab", "", func(m *mixer) tea.Cmd { + {[]string{"?"}, "Help for this tab", "", func(m *mixer) command { m.help, m.helpOff = true, 0 return nil }}, @@ -113,24 +111,24 @@ func generalKeys() section { func menuKeys() section { return section{"Menu", []binding{ - {[]string{"k", "up", "ctrl+p"}, "Move up", "wheel", func(m *mixer) tea.Cmd { m.moveMenu(-1); return nil }}, - {[]string{"j", "down", "ctrl+n"}, "Move down", "", func(m *mixer) tea.Cmd { m.moveMenu(1); return nil }}, - {[]string{"g", "home"}, "Go to top", "", func(m *mixer) tea.Cmd { m.moveMenu(-len(m.menu.items)); return nil }}, - {[]string{"G", "end"}, "Go to bottom", "", func(m *mixer) tea.Cmd { m.moveMenu(len(m.menu.items)); return nil }}, - {[]string{"enter", "space"}, "Choose", "click", func(m *mixer) tea.Cmd { m.choose(); return nil }}, - {[]string{"esc", "q"}, "Close", "click outside", func(m *mixer) tea.Cmd { m.menu = nil; return nil }}, + {[]string{"k", "up", "ctrl+p"}, "Move up", "wheel", func(m *mixer) command { m.moveMenu(-1); return nil }}, + {[]string{"j", "down", "ctrl+n"}, "Move down", "", func(m *mixer) command { m.moveMenu(1); return nil }}, + {[]string{"g", "home"}, "Go to top", "", func(m *mixer) command { m.moveMenu(-len(m.menu.items)); return nil }}, + {[]string{"G", "end"}, "Go to bottom", "", func(m *mixer) command { m.moveMenu(len(m.menu.items)); return nil }}, + {[]string{"enter", "space"}, "Choose", "click", func(m *mixer) command { m.choose(); return nil }}, + {[]string{"esc", "q"}, "Close", "click outside", func(m *mixer) command { m.menu = nil; return nil }}, }} } func helpScreenKeys() section { return section{"Help", []binding{ - {[]string{"?", "q", "esc"}, "Close help", "", func(m *mixer) tea.Cmd { m.help = false; return nil }}, - {[]string{"k", "up", "ctrl+p"}, "Scroll up", "wheel", func(m *mixer) tea.Cmd { m.scrollHelp(-1); return nil }}, - {[]string{"j", "down", "ctrl+n"}, "Scroll down", "", func(m *mixer) tea.Cmd { m.scrollHelp(1); return nil }}, - {[]string{"ctrl+b", "pgup", "alt+v"}, "Page up", "", func(m *mixer) tea.Cmd { m.scrollHelp(-m.listHeight()); return nil }}, - {[]string{"ctrl+f", "pgdown", "ctrl+v"}, "Page down", "", func(m *mixer) tea.Cmd { m.scrollHelp(m.listHeight()); return nil }}, - {[]string{"g", "home"}, "Go to top", "", func(m *mixer) tea.Cmd { m.scrollHelp(-1 << 30); return nil }}, - {[]string{"G", "end"}, "Go to bottom", "", func(m *mixer) tea.Cmd { m.scrollHelp(1 << 30); return nil }}, + {[]string{"?", "q", "esc"}, "Close help", "", func(m *mixer) command { m.help = false; return nil }}, + {[]string{"k", "up", "ctrl+p"}, "Scroll up", "wheel", func(m *mixer) command { m.scrollHelp(-1); return nil }}, + {[]string{"j", "down", "ctrl+n"}, "Scroll down", "", func(m *mixer) command { m.scrollHelp(1); return nil }}, + {[]string{"ctrl+b", "pgup", "alt+v"}, "Page up", "", func(m *mixer) command { m.scrollHelp(-m.listHeight()); return nil }}, + {[]string{"ctrl+f", "pgdown", "ctrl+v"}, "Page down", "", func(m *mixer) command { m.scrollHelp(m.listHeight()); return nil }}, + {[]string{"g", "home"}, "Go to top", "", func(m *mixer) command { m.scrollHelp(-1 << 30); return nil }}, + {[]string{"G", "end"}, "Go to bottom", "", func(m *mixer) command { m.scrollHelp(1 << 30); return nil }}, }} } @@ -173,7 +171,7 @@ func (m *mixer) sections() []section { return m.tabSections() } -func (m *mixer) handleKey(key string) tea.Cmd { +func (m *mixer) handleKey(key string) command { for _, s := range m.sections() { for _, b := range s.bindings { if slices.Contains(b.keys, key) { diff --git a/internal/pipmix/loop.go b/internal/pipmix/loop.go new file mode 100644 index 0000000..48b09bd --- /dev/null +++ b/internal/pipmix/loop.go @@ -0,0 +1,142 @@ +package pipmix + +import ( + "context" + "os/signal" + "syscall" + "time" + + "github.com/some-programs/pipmix/internal/tui" +) + +// A message tells the mixer that something happened, such as a new +// PipeWire snapshot or an expired notice. +type message any + +// A command does work, such as waiting for an update, away from the event +// loop, and returns the message to hand the mixer when done, or nil. +type command func() message + +type quitMsg struct{} + +// quit is the command that ends the event loop. +func quit() message { return quitMsg{} } + +// after returns a command that returns msg after d. +func after(d time.Duration, msg message) command { + return func() message { + time.Sleep(d) + return msg + } +} + +// terminalOptions returns the terminal modes the mixer needs. +func terminalOptions(o options) tui.Options { + return tui.Options{Mouse: o.mouse, Focus: true} +} + +// run shows m on the terminal until a quit key or a signal to stop. +func run(ctx context.Context, m *mixer) error { + ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP) + defer stop() + t, err := tui.Open(terminalOptions(m.opts)) + if err != nil { + return err + } + defer t.Close() + + msgs := make(chan message, 16) + exec := func(c command) { + if c == nil { + return + } + go func() { + if msg := c(); msg != nil { + select { + case msgs <- msg: + case <-ctx.Done(): + } + } + }() + } + for _, c := range m.init() { + exec(c) + } + + var ( + grid = tui.NewGrid(0, 0) + screen = tui.NewScreen(t) + frame = time.Second / time.Duration(m.opts.fps) + ticker = time.NewTicker(frame) + timer = time.NewTimer(frame) + tickC <-chan time.Time // the ticker's channel while the meters move + frameC <-chan time.Time // the timer's channel while a frame waits + sized bool // the size of the terminal is known + full bool // the screen needs drawing + meters bool // the meters need drawing + drawn time.Time // when the last frame was drawn + ) + ticker.Stop() + timer.Stop() + for { + select { + case <-ctx.Done(): + return nil + case ev := <-t.Events(): + switch ev := ev.(type) { + case tui.ResizeEvent: + m.setSize(ev.Width, ev.Height) + m.watchMeters() + sized = true + case tui.KeyEvent: + exec(m.handleKey(string(ev))) + m.watchMeters() + case tui.MouseEvent: + exec(m.handleMouse(ev)) + m.watchMeters() + default: + exec(m.update(ev)) + } + full = true + case msg := <-msgs: + if _, ok := msg.(quitMsg); ok { + return nil + } + exec(m.update(msg)) + full = true + case <-tickC: + exec(m.tickMetering()) + meters = true + case <-frameC: + frameC = nil + } + + if m.ticking != (tickC != nil) { + if m.ticking { + ticker.Reset(frame) + tickC = ticker.C + } else { + ticker.Stop() + tickC = nil + } + } + if !sized || !full && !meters || frameC != nil { + continue + } + if wait := frame - time.Since(drawn); wait > 0 { + timer.Reset(wait) + frameC = timer.C + continue + } + if full { + m.draw(grid) + } else { + m.drawMeters(grid) + } + full, meters = false, false + drawn = time.Now() + if err := screen.Flush(grid); err != nil { + return err + } + } +} diff --git a/internal/pipmix/meters.go b/internal/pipmix/meters.go index 9f3c612..059b637 100644 --- a/internal/pipmix/meters.go +++ b/internal/pipmix/meters.go @@ -7,8 +7,6 @@ import ( "strconv" "time" - tea "charm.land/bubbletea/v2" - "github.com/some-programs/pipmix/internal/pulse" "github.com/some-programs/pipmix/internal/pw" ) @@ -52,14 +50,11 @@ const ( var meterLookFlags = []string{"solid", "shade", "dot"} -type ( - meterMsg struct{} - meterTickMsg struct{} -) +type meterMsg struct{} // waitMeter waits for the next meter snapshot, unless a wait is already // pending. -func (m *mixer) waitMeter() tea.Cmd { +func (m *mixer) waitMeter() command { if m.meter == nil || m.meterWaiting { return nil } @@ -67,12 +62,12 @@ func (m *mixer) waitMeter() tea.Cmd { return m.nextMeter() } -func (m *mixer) nextMeter() tea.Cmd { +func (m *mixer) nextMeter() command { if m.meter == nil { return nil } updated := m.meter.Updated() - return func() tea.Msg { + return func() message { <-updated return meterMsg{} } @@ -147,7 +142,7 @@ func (m *mixer) watchMeters() { m.meter.Watch(targets) } -func (m *mixer) startMetering() tea.Cmd { +func (m *mixer) startMetering() command { if m.ticking { return nil } @@ -159,10 +154,12 @@ func (m *mixer) startMetering() tea.Cmd { return m.waitMeter() } m.ticking = true - return tea.Tick(time.Second/time.Duration(m.opts.fps), func(time.Time) tea.Msg { return meterTickMsg{} }) + return nil } -func (m *mixer) tickMetering() tea.Cmd { +// tickMetering moves the meters on. The event loop calls it every frame +// while m.ticking is set. +func (m *mixer) tickMetering() command { snap := &pulse.Snapshot{} if m.meter != nil { snap = m.meter.Snapshot() @@ -171,7 +168,7 @@ func (m *mixer) tickMetering() tea.Cmd { m.ticking = false return m.waitMeter() } - return tea.Tick(time.Second/time.Duration(m.opts.fps), func(time.Time) tea.Msg { return meterTickMsg{} }) + return nil } // setLevels updates the fill and peak positions at now and reports whether @@ -326,7 +323,7 @@ func channelLevel(levels []float64, ch int) float64 { return 0 } -func (m *mixer) toggleMeterAlways() tea.Cmd { +func (m *mixer) toggleMeterAlways() command { switch m.opts.meters { case metersOff: return notify("Meters are off (-meter.disable)") @@ -338,7 +335,7 @@ func (m *mixer) toggleMeterAlways() tea.Cmd { return notify("Meters always, focused or not") } -func (m *mixer) toggleMeters() tea.Cmd { +func (m *mixer) toggleMeters() command { if m.meter == nil { return notify("Meters are off (-meter.disable)") } diff --git a/internal/pipmix/meters_test.go b/internal/pipmix/meters_test.go index acdfc5e..92835f2 100644 --- a/internal/pipmix/meters_test.go +++ b/internal/pipmix/meters_test.go @@ -7,11 +7,9 @@ import ( "testing" "time" - tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" - "github.com/some-programs/pipmix/internal/pulse" "github.com/some-programs/pipmix/internal/pw" + "github.com/some-programs/pipmix/internal/tui" ) func meterSnapshot() *pw.Snapshot { @@ -208,11 +206,11 @@ func TestLevels(t *testing.T) { func TestMeterFocus(t *testing.T) { m := testMixer() m.snap = meterSnapshot() - m.update(tea.BlurMsg{}) + m.update(tui.BlurEvent{}) if got := m.meterTargets(); len(got) != 0 { t.Errorf("targets while not focused %v, want none", targetKeys(got)) } - m.update(tea.FocusMsg{}) + m.update(tui.FocusEvent{}) if got := m.meterTargets(); len(got) == 0 { t.Error("no targets once focused again") } @@ -234,7 +232,8 @@ func TestBarLevel(t *testing.T) { {1, 0.3, 0.7, false, meterSolid, "███▓▓▓█▓▓▓█░░░░░"}, {1, 0.5, 0, true, meterSolid, "▓▓▓▓▓▓▓▓▓▓█░░░░░"}, } { - if got := ansi.Strip(bar(tc.v, tc.level, tc.peak, 16, 1.5, tc.muted, tc.look)); got != tc.want { + got := penText(16, func(p *tui.Pen) { drawBar(p, tc.v, tc.level, tc.peak, 16, 1.5, tc.muted, tc.look) }) + if got != tc.want { t.Errorf("bar(%v, %v, %v, 16, %v, look %d) = %q, want %q", tc.v, tc.level, tc.peak, tc.muted, tc.look, got, tc.want) } } @@ -248,7 +247,8 @@ func TestBarLevel(t *testing.T) { {0.5, 0, meterDot, "░░░░█░░░░░░░░░░░"}, {0.5, 0.7, meterOff, "░░░░░░░░░░░░░░░░"}, } { - if got := ansi.Strip(meterBar(tc.level, tc.peak, 16, 1.5, tc.look)); got != tc.want { + got := penText(16, func(p *tui.Pen) { drawMeterBar(p, tc.level, tc.peak, 16, 1.5, tc.look) }) + if got != tc.want { t.Errorf("meterBar(%v, %v, 16, look %d) = %q, want %q", tc.level, tc.peak, tc.look, got, tc.want) } } @@ -293,7 +293,7 @@ func TestMeterWaitOnce(t *testing.T) { m.meter = pulse.NewMeter(nil, 0) m.meterWaiting = true // as after init - for _, msg := range []tea.Msg{tea.BlurMsg{}, tea.FocusMsg{}} { + for _, msg := range []message{tui.BlurEvent{}, tui.FocusEvent{}} { if cmd := m.update(msg); cmd != nil { t.Errorf("%T with a wait pending: got a command, want none", msg) } @@ -302,7 +302,7 @@ func TestMeterWaitOnce(t *testing.T) { if cmd := m.update(meterMsg{}); cmd == nil || !m.meterWaiting { t.Fatal("snapshot with settled levels: no new wait") } - if cmd := m.update(tea.FocusMsg{}); cmd != nil { + if cmd := m.update(tui.FocusEvent{}); cmd != nil { t.Error("focus after the new wait: got a command, want none") } } diff --git a/internal/pipmix/mixer.go b/internal/pipmix/mixer.go index abccb9a..ed72edf 100644 --- a/internal/pipmix/mixer.go +++ b/internal/pipmix/mixer.go @@ -5,11 +5,10 @@ import ( "strconv" "time" - tea "charm.land/bubbletea/v2" - "github.com/some-programs/pipmix/internal/mpris" "github.com/some-programs/pipmix/internal/pulse" "github.com/some-programs/pipmix/internal/pw" + "github.com/some-programs/pipmix/internal/tui" ) const noticeTime = 5 * time.Second @@ -112,6 +111,7 @@ type mixer struct { dot map[uint32][]float64 dotHold map[uint32][]time.Time levelsAt time.Time + meterRows []meterRow // where the last draw put meters ticking bool meterWaiting bool // a waitMeter command is pending blurred bool @@ -166,30 +166,30 @@ type noticeMsg struct { type noticeExpiredMsg int -func notify(text string) tea.Cmd { - return func() tea.Msg { return noticeMsg{text: text} } +func notify(text string) command { + return func() message { return noticeMsg{text: text} } } -func (m *mixer) waitSnapshot() tea.Cmd { +func (m *mixer) waitSnapshot() command { updated := m.client.Updated() - return func() tea.Msg { + return func() message { <-updated return snapshotMsg{} } } -func (m *mixer) waitMedia() tea.Cmd { +func (m *mixer) waitMedia() command { if m.media == nil { return nil } updated := m.media.Updated() - return func() tea.Msg { + return func() message { <-updated return mediaMsg{} } } -func (m *mixer) init() tea.Cmd { return tea.Batch(m.waitSnapshot(), m.waitMedia(), m.nextMeter()) } +func (m *mixer) init() []command { return []command{m.waitSnapshot(), m.waitMedia(), m.nextMeter()} } // findMedia matches playback streams to MPRIS players by process ID. func (m *mixer) findMedia() { @@ -233,7 +233,7 @@ func (m *mixer) setSize(width, height int) { m.scrollHelp(0) } -func (m *mixer) update(msg tea.Msg) tea.Cmd { +func (m *mixer) update(msg message) command { switch msg := msg.(type) { case snapshotMsg: m.snap = m.client.Snapshot() @@ -248,13 +248,11 @@ func (m *mixer) update(msg tea.Msg) tea.Cmd { case meterMsg: m.meterWaiting = false return m.startMetering() - case meterTickMsg: - return m.tickMetering() - case tea.FocusMsg: + case tui.FocusEvent: m.blurred = false m.watchMeters() return m.startMetering() - case tea.BlurMsg: + case tui.BlurEvent: m.blurred = true m.watchMeters() return m.startMetering() @@ -264,7 +262,7 @@ func (m *mixer) update(msg tea.Msg) tea.Cmd { seq := m.noticeSeq m.scroll() m.scrollHelp(0) - return tea.Tick(noticeTime, func(time.Time) tea.Msg { return noticeExpiredMsg(seq) }) + return after(noticeTime, noticeExpiredMsg(seq)) case noticeExpiredMsg: if int(msg) == m.noticeSeq { m.notice = "" @@ -656,7 +654,7 @@ func (m *mixer) pageItems() int { return max(1, m.listHeight()/m.itemHeight(it)) } -func (m *mixer) volumeTarget() (it item, channel int, cmd tea.Cmd) { +func (m *mixer) volumeTarget() (it item, channel int, cmd command) { it, i := m.focused() switch { case i < 0: @@ -675,7 +673,7 @@ func (m *mixer) volumeTarget() (it item, channel int, cmd tea.Cmd) { return it, channel, nil } -func (m *mixer) changeVolume(delta float64) tea.Cmd { +func (m *mixer) changeVolume(delta float64) command { it, channel, cmd := m.volumeTarget() if cmd != nil { return cmd @@ -684,7 +682,7 @@ func (m *mixer) changeVolume(delta float64) tea.Cmd { return nil } -func (m *mixer) setVolume100() tea.Cmd { +func (m *mixer) setVolume100() command { it, channel, cmd := m.volumeTarget() if cmd != nil { return cmd @@ -693,7 +691,7 @@ func (m *mixer) setVolume100() tea.Cmd { return nil } -func (m *mixer) toggleMute() tea.Cmd { +func (m *mixer) toggleMute() command { it, _, cmd := m.volumeTarget() if cmd != nil { return cmd @@ -702,7 +700,7 @@ func (m *mixer) toggleMute() tea.Cmd { return nil } -func (m *mixer) toggleLock() tea.Cmd { +func (m *mixer) toggleLock() command { it, i := m.focused() if i < 0 || it.channels() < 2 { return notify("Only items with more than one channel have a lock") @@ -713,7 +711,7 @@ func (m *mixer) toggleLock() tea.Cmd { return nil } -func (m *mixer) setDefault() tea.Cmd { +func (m *mixer) setDefault() command { it, i := m.focused() if i < 0 || it.node == nil || (it.node.Class != pw.Sink && it.node.Class != pw.Source) { return notify("Only output and input devices can be the default") @@ -722,7 +720,7 @@ func (m *mixer) setDefault() tea.Cmd { return nil } -func (m *mixer) openRouteMenu() tea.Cmd { +func (m *mixer) openRouteMenu() command { it, i := m.focused() if i < 0 || it.node == nil || len(it.node.Routes) == 0 { return notify("Only devices of sound cards have ports") @@ -741,7 +739,7 @@ func (m *mixer) openRouteMenu() tea.Cmd { return nil } -func (m *mixer) openProfileMenu() tea.Cmd { +func (m *mixer) openProfileMenu() command { it, i := m.focused() if i < 0 || it.card == nil { return notify("Profiles are on the Cards tab") @@ -777,7 +775,7 @@ func (m *mixer) setTab(t tab) { m.scroll() } -func (m *mixer) togglePlayPause() tea.Cmd { +func (m *mixer) togglePlayPause() command { it, i := m.focused() if i < 0 || it.node == nil || it.node.Class != pw.Playback { return notify("Only playback streams have media controls") @@ -787,7 +785,7 @@ func (m *mixer) togglePlayPause() tea.Cmd { } name := it.player.Name media := m.media - return func() tea.Msg { + return func() message { if err := media.PlayPause(name); err != nil { return noticeMsg{text: "Play/pause: " + err.Error(), err: true} } @@ -795,7 +793,7 @@ func (m *mixer) togglePlayPause() tea.Cmd { } } -func (m *mixer) portOrPlayPause() tea.Cmd { +func (m *mixer) portOrPlayPause() command { it, i := m.focused() if i >= 0 && it.node != nil && it.node.Class == pw.Playback { return m.togglePlayPause() @@ -804,7 +802,7 @@ func (m *mixer) portOrPlayPause() tea.Cmd { } // toggleSolo solos or unsolos the focused playback stream. -func (m *mixer) toggleSolo() tea.Cmd { +func (m *mixer) toggleSolo() command { it, i := m.focused() if i < 0 || it.node == nil || it.node.Class != pw.Playback || it.node.JACK { return notify("Only playback streams can be soloed") diff --git a/internal/pipmix/mixer_test.go b/internal/pipmix/mixer_test.go index e284b56..ab6c357 100644 --- a/internal/pipmix/mixer_test.go +++ b/internal/pipmix/mixer_test.go @@ -7,12 +7,11 @@ import ( "strings" "testing" - tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" "github.com/some-programs/pipmix/internal/mpris" "github.com/some-programs/pipmix/internal/pw" + "github.com/some-programs/pipmix/internal/tui" ) func stereo(v float64) []pw.Channel { @@ -219,11 +218,11 @@ func TestDefaultFirst(t *testing.T) { func TestQuitKeysAndLayers(t *testing.T) { m := testMixer() - isQuit := func(cmd tea.Cmd) bool { + isQuit := func(cmd command) bool { if cmd == nil { return false } - _, ok := cmd().(tea.QuitMsg) + _, ok := cmd().(quitMsg) return ok } m.handleKey("?") @@ -295,22 +294,22 @@ func TestMouse(t *testing.T) { // Rows: 0 tabs, then Player A at 1-2 (title, FL+FR folded), Player B // at 3-4. - click := func(x, y int, b tea.MouseButton) { - m.handleMouse(tea.MouseClickMsg{X: x, Y: y, Button: b}) + click := func(x, y int, b ansi.MouseButton) { + m.handleMouse(tui.MouseEvent{Kind: tui.MouseClick, X: x, Y: y, Button: b}) } - click(4, 3, tea.MouseLeft) + click(4, 3, tui.MouseLeft) if id := focusedID(&m); id != 11 { t.Fatalf("click on Player B's title: focus %d", id) } - click(barX+5, 2, tea.MouseLeft) + click(barX+5, 2, tui.MouseLeft) if id := focusedID(&m); id != 10 || m.drag == nil || m.drag.node != 10 || m.drag.channel != -1 { t.Fatalf("click on Player A's bar: focus %d, drag %+v", id, m.drag) } - m.handleMouse(tea.MouseMotionMsg{X: barX + 20, Y: 2, Button: tea.MouseLeft}) + m.handleMouse(tui.MouseEvent{Kind: tui.MouseMotion, X: barX + 20, Y: 2, Button: tui.MouseLeft}) if want := m.volumeAt(barX + 20); m.drag.last != want { t.Errorf("drag: last %v, want %v", m.drag.last, want) } - m.handleMouse(tea.MouseReleaseMsg{X: barX + 20, Y: 2, Button: tea.MouseLeft}) + m.handleMouse(tui.MouseEvent{Kind: tui.MouseRelease, X: barX + 20, Y: 2, Button: tui.MouseLeft}) if m.drag != nil { t.Error("release didn't end the drag") } @@ -326,16 +325,16 @@ func TestMouse(t *testing.T) { // A tab. spans := tabSpans() - click(spans[tabCards].start, 0, tea.MouseLeft) + click(spans[tabCards].start, 0, tui.MouseLeft) if m.tab != tabCards { t.Fatalf("click on the Cards tab: tab %d", m.tab) } // The profile line opens the menu; a click outside closes it. - click(5, 2, tea.MouseLeft) + click(5, 2, tui.MouseLeft) if m.menu == nil || m.menu.kind != menuProfile { t.Fatalf("click on the profile line: menu %+v", m.menu) } - click(0, m.height-1, tea.MouseLeft) + click(0, m.height-1, tui.MouseLeft) if m.menu != nil { t.Error("click outside didn't close the menu") } @@ -344,7 +343,7 @@ func TestMouse(t *testing.T) { func TestWheelPullsFocus(t *testing.T) { m := testMixer() m.setSize(60, 4) // three rows: room for one item of two lines - m.handleMouse(tea.MouseWheelMsg{Button: tea.MouseWheelDown}) + m.handleMouse(tui.MouseEvent{Kind: tui.MouseWheel, Button: tui.MouseWheelDown}) if id := focusedID(&m); id != 12 { t.Errorf("after scrolling 3 lines: focus %d, want 12, the only item fully on screen", id) } @@ -364,9 +363,9 @@ func TestFold(t *testing.T) { } return out } - raw := m.view() - if !strings.Contains(raw, boldStyle.Render("FL+FR")) || !strings.Contains(raw, boldStyle.Render(" 50")) { - t.Errorf("focused folded channel name or volume not bold:\n%s", raw) + g := drawGrid(&m) + if x, y, ok := find(g, "FL+FR 50"); !ok || g.At(x, y).Style != boldStyle || g.At(x+8, y).Style != boldStyle { + t.Errorf("focused folded channel name or volume not bold:\n%s", g) } if got := lines(); len(got) != 3 || !strings.HasPrefix(got[0], "█ FL+FR 50") { t.Fatalf("folded lines = %q", got) @@ -393,7 +392,7 @@ func TestFold(t *testing.T) { s = testSnapshot() m.snap = s m.refocus() - m.handleMouse(tea.MouseClickMsg{X: 4, Y: 4, Button: tea.MouseLeft}) + m.handleMouse(tui.MouseEvent{Kind: tui.MouseClick, X: 4, Y: 4, Button: tui.MouseLeft}) if id := focusedID(&m); id != 11 { t.Errorf("click on Player B's folded line: focus %d", id) } @@ -443,11 +442,11 @@ func TestTitleColumns(t *testing.T) { if !ok || end-start != ansi.StringWidth("Headphones ▾") || col(speakers, "Headphones") != start { t.Fatalf("port span %d-%d %v", start, end, ok) } - m.handleMouse(tea.MouseClickMsg{X: 8, Y: 1, Button: tea.MouseLeft}) + m.handleMouse(tui.MouseEvent{Kind: tui.MouseClick, X: 8, Y: 1, Button: tui.MouseLeft}) if m.menu != nil { t.Fatal("click on the title opened a menu") } - m.handleMouse(tea.MouseClickMsg{X: start, Y: 1, Button: tea.MouseLeft}) + m.handleMouse(tui.MouseEvent{Kind: tui.MouseClick, X: start, Y: 1, Button: tui.MouseLeft}) if m.menu == nil || m.menu.kind != menuRoute { t.Errorf("click on the port: menu %+v", m.menu) } @@ -510,12 +509,12 @@ func TestTypeStrip(t *testing.T) { pw.Node{ID: 40, Class: pw.Recording, Name: "rec", Title: "Recorder", Channels: stereo(1)}) m.snap = s m.refocus() - strip := func(c pw.Class) string { return classStripStyles[c].Render(typeStripBar) } - card := cardStripStyle.Render(typeStripBar) + strip := func(c pw.Class) tui.Style { return classStripStyles[c] } + card := cardStripStyle for _, tc := range []struct { tab tab id uint32 - strip string + strip tui.Style }{ {tabDefault, 20, strip(pw.Sink)}, {tabDefault, 10, strip(pw.Playback)}, @@ -534,19 +533,21 @@ func TestTypeStrip(t *testing.T) { found = true layout := m.tabLayout(tc.tab) for _, focused := range []bool{false, true} { - lines := m.renderItem(it, focused, layout) - if strings.Contains(lines[0], focusTitleStyle.Render(it.title())) != focused { - t.Errorf("tab %s, item %d, focused %v: title line %q, want the name bold and underlined only when focused", tabNames[tc.tab], tc.id, focused, lines[0]) + itemLines := m.itemLines(it) + g := tui.NewGrid(m.width, len(itemLines)) + for y, l := range itemLines { + m.drawLine(g, y, it, l, focused, layout) + } + x, y, ok := find(g, it.title()) + if titleFocused := ok && y == 0 && g.At(x, y).Style == focusTitleStyle; titleFocused != focused { + t.Errorf("tab %s, item %d, focused %v: title line %q, want the name bold and underlined only when focused", tabNames[tc.tab], tc.id, focused, g) } - for i, l := range lines { - if l == "" { + for i, l := range lines(g) { + if strings.TrimSpace(l) == "" { continue } - if !strings.HasPrefix(l, " "+tc.strip) { - t.Errorf("tab %s, item %d, focused %v, line %d: %q, want it to start %q", tabNames[tc.tab], tc.id, focused, i, l, " "+tc.strip) - } - if w := ansi.StringWidth(l); w != m.width { - t.Errorf("tab %s, item %d, line %d is %d wide, want %d", tabNames[tc.tab], tc.id, i, w, m.width) + if c := g.At(1, i); !strings.HasPrefix(l, " "+typeStripBar) || c.Style != tc.strip { + t.Errorf("tab %s, item %d, focused %v, line %d: %q in %+v, want it to start %q in %+v", tabNames[tc.tab], tc.id, focused, i, l, c.Style, " "+typeStripBar, tc.strip) } } } @@ -596,7 +597,7 @@ func TestJACKClient(t *testing.T) { } } for _, pt := range []struct{ x, y int }{{muteX, 7}, {barX + 2, 8}} { - cmd := m.click(tea.Mouse{X: pt.x, Y: pt.y, Button: tea.MouseLeft}) + cmd := m.click(tui.MouseEvent{X: pt.x, Y: pt.y, Button: tui.MouseLeft}) if cmd == nil { t.Fatalf("click at (%d,%d): no notice", pt.x, pt.y) } @@ -631,11 +632,11 @@ func TestMediaTitlesAndControls(t *testing.T) { t.Errorf("recording title %q", it.title()) } - raw := m.view() - if !strings.Contains(raw, focusStyle.Bold(true).Render(symPause)) { - t.Errorf("focused toolbar button should be cyan bold:\n%s", raw) + g := drawGrid(&m) + if st, ok := styleOf(g, symPause); !ok || st != (tui.Style{Fg: tui.Cyan, Attrs: tui.Bold}) { + t.Errorf("focused toolbar button should be cyan bold:\n%s", g) } - view := ansi.Strip(raw) + view := ansi.Strip(g.String()) if !strings.Contains(view, symSpeaker+" "+symPause) || !strings.Contains(view, "Player: Track 1") { t.Errorf("view with playing player: %q", view) } @@ -647,7 +648,7 @@ func TestMediaTitlesAndControls(t *testing.T) { } m.media = mpris.NewWatcher(nil) - if cmd := m.click(tea.Mouse{X: playX, Y: 1, Button: tea.MouseLeft}); cmd == nil { + if cmd := m.click(tui.MouseEvent{X: playX, Y: 1, Button: tui.MouseLeft}); cmd == nil { t.Fatal("click on play/pause button returned nil cmd") } diff --git a/internal/pipmix/mouse.go b/internal/pipmix/mouse.go index d2d1f6f..9c51810 100644 --- a/internal/pipmix/mouse.go +++ b/internal/pipmix/mouse.go @@ -2,28 +2,26 @@ package pipmix import ( "math" - "strings" - tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" + "github.com/some-programs/pipmix/internal/tui" ) const wheelRows = 3 -func (m *mixer) handleMouse(msg tea.MouseMsg) tea.Cmd { +func (m *mixer) handleMouse(ev tui.MouseEvent) command { if m.menu != nil { - return m.menuMouse(msg) - } - switch msg := msg.(type) { - case tea.MouseClickMsg: - return m.click(msg.Mouse()) - case tea.MouseMotionMsg: - m.dragTo(msg.Mouse()) - case tea.MouseReleaseMsg: + return m.menuMouse(ev) + } + switch ev.Kind { + case tui.MouseClick: + return m.click(ev) + case tui.MouseMotion: + m.dragTo(ev) + case tui.MouseRelease: m.drag = nil - case tea.MouseWheelMsg: + case tui.MouseWheel: delta := wheelRows - if msg.Button == tea.MouseWheelUp { + if ev.Button == tui.MouseWheelUp { delta = -delta } if m.help { @@ -35,8 +33,8 @@ func (m *mixer) handleMouse(msg tea.MouseMsg) tea.Cmd { return nil } -func (m *mixer) click(mouse tea.Mouse) tea.Cmd { - if mouse.Y == 0 && mouse.Button == tea.MouseLeft { +func (m *mixer) click(mouse tui.MouseEvent) command { + if mouse.Y == 0 && mouse.Button == tui.MouseLeft { for _, s := range tabSpans() { if mouse.X >= s.start && mouse.X < s.end { m.setTab(s.tab) @@ -54,7 +52,7 @@ func (m *mixer) click(mouse tea.Mouse) tea.Cmd { m.setFocus(items, i, line.channel) it := items[i] switch mouse.Button { - case tea.MouseMiddle: + case tui.MouseMiddle: switch line.kind { case lineChannel: if mouse.X < barX-2 || mouse.X >= barX+m.barWidth() { @@ -69,9 +67,9 @@ func (m *mixer) click(mouse tea.Mouse) tea.Cmd { } m.client.SetVolume(it.id, channel, 1.0, m.opts.limit) } - case tea.MouseRight: + case tui.MouseRight: return m.toggleMute() - case tea.MouseLeft: + case tui.MouseLeft: if onStreamMuteButton(it, line, mouse.X) { m.client.ToggleMute(it.id) return nil @@ -111,9 +109,9 @@ func (m *mixer) click(mouse tea.Mouse) tea.Cmd { return nil } -func (m *mixer) dragTo(mouse tea.Mouse) { +func (m *mixer) dragTo(mouse tui.MouseEvent) { d := m.drag - if d == nil || mouse.Button != tea.MouseLeft { + if d == nil || mouse.Button != tui.MouseLeft { return } if v := m.volumeAt(mouse.X); v != d.last { @@ -196,25 +194,22 @@ func (m *mixer) scrollBy(delta int) { func abs(n int) int { return max(n, -n) } -func (m *mixer) menuMouse(msg tea.MouseMsg) tea.Cmd { - switch msg := msg.(type) { - case tea.MouseClickMsg: - box, x, y := m.menuBox() - lines := strings.Split(box, "\n") - w := ansi.StringWidth(lines[0]) - mouse := msg.Mouse() - if mouse.X < x || mouse.X >= x+w || mouse.Y < y || mouse.Y >= y+len(lines) { +func (m *mixer) menuMouse(mouse tui.MouseEvent) command { + switch mouse.Kind { + case tui.MouseClick: + _, x, y, w, h := m.menuBox() + if mouse.X < x || mouse.X >= x+w || mouse.Y < y || mouse.Y >= y+h { m.menu = nil return nil } // Rows: the border, the title, then the items. first, n := m.menuRows() - if k := mouse.Y - y - 2; mouse.Button == tea.MouseLeft && k >= 0 && k < n && first+k < len(m.menu.items) { + if k := mouse.Y - y - 2; mouse.Button == tui.MouseLeft && k >= 0 && k < n && first+k < len(m.menu.items) { m.menu.cursor = first + k m.choose() } - case tea.MouseWheelMsg: - if msg.Button == tea.MouseWheelUp { + case tui.MouseWheel: + if mouse.Button == tui.MouseWheelUp { m.moveMenu(-1) } else { m.moveMenu(1) diff --git a/internal/pipmix/options_test.go b/internal/pipmix/options_test.go index 2cdc9d8..bc4e4dd 100644 --- a/internal/pipmix/options_test.go +++ b/internal/pipmix/options_test.go @@ -6,11 +6,11 @@ import ( "strings" "testing" - tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" "github.com/some-programs/pipmix/internal/pulse" "github.com/some-programs/pipmix/internal/pw" + "github.com/some-programs/pipmix/internal/tui" ) func parseOptions(args ...string) (options, error) { @@ -67,7 +67,7 @@ func TestMetersAlways(t *testing.T) { m := newMixer(pw.NewClient(nil), nil, pulse.NewMeter(nil, 0), quitKeys(), o) m.snap = meterSnapshot() m.setSize(60, 20) - m.update(tea.BlurMsg{}) + m.update(tui.BlurEvent{}) if got := m.meterTargets(); len(got) == 0 { t.Error("-meter.always: no targets while not focused") } @@ -114,8 +114,8 @@ func TestOptionsInUI(t *testing.T) { if strings.Contains(view, "click") { t.Errorf("help without the mouse has mouse actions:\n%s", view) } - if got := (app{mixer: m}).View().MouseMode; got != tea.MouseModeNone { - t.Errorf("-mouse.disable: mouse mode %v", got) + if got := terminalOptions(m.opts).Mouse; got { + t.Error("-mouse.disable: the terminal reports the mouse") } // A full fader is the limit. if k := knobCell(1, o.limit, 16); k != 15 { diff --git a/internal/pipmix/pipmix.go b/internal/pipmix/pipmix.go index a685bcd..59f75b6 100644 --- a/internal/pipmix/pipmix.go +++ b/internal/pipmix/pipmix.go @@ -13,8 +13,6 @@ import ( "path/filepath" "time" - tea "charm.land/bubbletea/v2" - "github.com/some-programs/pipmix/internal/mpris" "github.com/some-programs/pipmix/internal/pulse" "github.com/some-programs/pipmix/internal/pw" @@ -77,8 +75,8 @@ func Run(args []string) error { if debug.dump { return dump(ctx, os.Stdout, &dumpLog, fs, opts, client, media, meter) } - _, err = tea.NewProgram(app{mixer: newMixer(client, media, meter, quitKeys(), opts)}, tea.WithFPS(opts.fps)).Run() - return err + m := newMixer(client, media, meter, quitKeys(), opts) + return run(ctx, &m) } type debugFlags struct { @@ -126,43 +124,8 @@ func stateDir() (string, error) { return filepath.Join(home, ".local", "state"), nil } -type app struct { - mixer mixer -} - func quitKeys() section { return section{"Quit", []binding{ - {[]string{"q", "ctrl+c"}, "Quit", "", func(*mixer) tea.Cmd { return tea.Quit }}, + {[]string{"q", "ctrl+c"}, "Quit", "", func(*mixer) command { return quit }}, }} } - -func (a app) Init() tea.Cmd { return a.mixer.init() } - -func (a app) Update(msg tea.Msg) (tea.Model, tea.Cmd) { - var cmd tea.Cmd - switch msg := msg.(type) { - case tea.WindowSizeMsg: - a.mixer.setSize(msg.Width, msg.Height) - a.mixer.watchMeters() - case tea.KeyPressMsg: - cmd = a.mixer.handleKey(msg.String()) - a.mixer.watchMeters() - case tea.MouseMsg: - cmd = a.mixer.handleMouse(msg) - a.mixer.watchMeters() - default: - cmd = a.mixer.update(msg) - } - return a, cmd -} - -func (a app) View() tea.View { - var v tea.View - v.AltScreen = true - if a.mixer.opts.mouse { - v.MouseMode = tea.MouseModeCellMotion - } - v.ReportFocus = true - v.SetContent(a.mixer.view()) - return v -} diff --git a/internal/pipmix/view.go b/internal/pipmix/view.go index 0bad434..7262bc4 100644 --- a/internal/pipmix/view.go +++ b/internal/pipmix/view.go @@ -5,25 +5,25 @@ import ( "math" "strings" - "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" "github.com/some-programs/pipmix/internal/pw" + "github.com/some-programs/pipmix/internal/tui" ) var ( - tabStyle = lipgloss.NewStyle() - activeTabStyle = lipgloss.NewStyle().Reverse(true).Bold(true) - dimStyle = lipgloss.NewStyle().Foreground(lipgloss.BrightBlack) - boldStyle = lipgloss.NewStyle().Bold(true) - focusStyle = lipgloss.NewStyle().Foreground(lipgloss.Cyan) - focusTitleStyle = lipgloss.NewStyle().Bold(true).Underline(true) - defaultTagStyle = lipgloss.NewStyle().Foreground(lipgloss.Cyan) - errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Red).Bold(true) - barFullStyle = lipgloss.NewStyle().Foreground(lipgloss.Green) - barOverStyle = lipgloss.NewStyle().Foreground(lipgloss.Red) - menuCursorStyle = lipgloss.NewStyle().Reverse(true) - menuBoxStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 1) + plain = tui.Style{} + tabStyle = tui.Style{} + activeTabStyle = tui.Style{Attrs: tui.Reverse | tui.Bold} + dimStyle = tui.Style{Fg: tui.BrightBlack} + boldStyle = tui.Style{Attrs: tui.Bold} + focusStyle = tui.Style{Fg: tui.Cyan} + focusTitleStyle = tui.Style{Attrs: tui.Bold | tui.Underline} + defaultTagStyle = tui.Style{Fg: tui.Cyan} + errorStyle = tui.Style{Fg: tui.Red, Attrs: tui.Bold} + barFullStyle = tui.Style{Fg: tui.Green} + barOverStyle = tui.Style{Fg: tui.Red} + menuCursorStyle = tui.Style{Attrs: tui.Reverse} ) const ( @@ -39,7 +39,7 @@ func (m *mixer) innerWidth() int { return m.width - contentX - 2 } func (m *mixer) listHeight() int { h := m.height - 1 - if m.statusLine() != "" { + if m.status() != nil { h-- } return max(h, 0) @@ -158,79 +158,142 @@ func tabSpans() []tabSpan { return spans } -func (m *mixer) view() string { +// meterRow is a row of the screen that shows a meter. +type meterRow struct { + y int + it item + channel int +} + +// draw draws the whole screen into g, resizing it to the mixer, and notes +// the rows that show meters for [mixer.drawMeters]. +func (m *mixer) draw(g *tui.Grid) { + if w, h := g.Size(); w != m.width || h != m.height { + g.Resize(m.width, m.height) + } else { + g.Clear() + } + m.meterRows = m.meterRows[:0] if m.width <= 0 || m.height <= 0 { - return "" + return } - lines := []string{m.tabBar()} + m.drawTabBar(g) h := m.listHeight() - var list []string if m.help { - list = m.helpView(m.width, h) + m.drawHelp(g, h) } else { - layout := m.tabLayout(m.tab) - for i, it := range layout.items { - list = append(list, m.renderItem(it, i == layout.focus, layout)...) - } - if len(layout.items) == 0 && m.snap.Connected { - list = []string{dimStyle.Render(" Nothing here")} - } - off := min(m.offset[m.tab], max(len(list)-h, 0)) - list = list[off:] + m.drawList(g, h) } - list = list[:min(len(list), h)] - for len(list) < h { - list = append(list, "") + if status := m.status(); status != nil && m.height > 1 { + p := g.Pen(0, listTop+h, m.width) + for _, s := range status { + p.Text(s.text, s.style) + } } - lines = append(lines, list...) - if status := m.statusLine(); status != "" && m.height > 1 { - lines = append(lines, fit(status, m.width)) + if m.menu != nil { + m.drawMenu(g) } - content := strings.Join(lines, "\n") +} + +// drawMeters redraws the meters that the last [mixer.draw] drew, which +// must be the only change since. +func (m *mixer) drawMeters(g *tui.Grid) { if m.menu != nil { - box, x, y := m.menuBox() - content = overlay(content, box, x, y) + // The menu may cover meters. + m.draw(g) + return + } + w := m.barWidth() + for _, r := range m.meterRows { + p := g.Pen(barX, r.y, barX+w) + m.drawChannelBar(&p, r.it, r.channel) } - return content } -func (m *mixer) tabBar() string { - var b strings.Builder +// view draws the screen and returns it as lines. +func (m *mixer) view() string { + g := tui.NewGrid(m.width, m.height) + m.draw(g) + return g.String() +} + +func (m *mixer) drawTabBar(g *tui.Grid) { + p := g.Pen(0, 0, m.width) + p.AddAttrs(tui.Underline) for _, s := range tabSpans() { style := tabStyle if s.tab == m.tab { style = activeTabStyle } - b.WriteString(style.Render(tabNames[s.tab]) + strings.Repeat(" ", tabGap)) + p.Text(tabNames[s.tab], style) + p.Repeat(" ", tabGap, plain) } - return underlineRow(b.String(), m.width) + p.Pad(plain) } -func underlineRow(s string, width int) string { - const underline = "\x1b[4m" - s = fit(s, width) - for _, reset := range []string{"\x1b[m", "\x1b[0m"} { - s = strings.ReplaceAll(s, reset, reset+underline) +func (m *mixer) drawList(g *tui.Grid, h int) { + layout := m.tabLayout(m.tab) + if len(layout.items) == 0 { + if m.snap.Connected && h > 0 { + p := g.Pen(0, listTop, m.width) + p.Text(" Nothing here", dimStyle) + } + return + } + if m.width < contentX+2 { + return + } + lines := make([][]itemLine, len(layout.items)) + total := 0 + for i, it := range layout.items { + lines[i] = m.itemLines(it) + total += len(lines[i]) + } + y := listTop - min(m.offset[m.tab], max(total-h, 0)) + for i, it := range layout.items { + for _, l := range lines[i] { + if y >= listTop+h { + return + } + if y >= listTop { + m.drawLine(g, y, it, l, i == layout.focus, layout) + } + y++ + } } - return underline + s + ansi.ResetStyle } -func (m *mixer) statusLine() string { +type span struct { + text string + style tui.Style +} + +// status returns the status line, or nil if there is none. +func (m *mixer) status() []span { switch { case !m.snap.Connected && m.snap.Err != nil: - return errorStyle.Render(fmt.Sprintf("PipeWire: %v; reconnecting", m.snap.Err)) + return []span{{fmt.Sprintf("PipeWire: %v; reconnecting", m.snap.Err), errorStyle}} case !m.snap.Connected: - return "Connecting to PipeWire" + return []span{{"Connecting to PipeWire", plain}} case m.notice != "" && m.noticeErr: - return errorStyle.Render(m.notice) + return []span{{m.notice, errorStyle}} case m.soloID != 0 && m.notice != "": - return defaultTagStyle.Render("[SOLO] ") + m.soloTitle + " " + m.notice + return []span{{"[SOLO] ", defaultTagStyle}, {m.soloTitle + " " + m.notice, plain}} case m.soloID != 0: - return defaultTagStyle.Render("[SOLO] ") + m.soloTitle + return []span{{"[SOLO] ", defaultTagStyle}, {m.soloTitle, plain}} case m.notice != "": - return m.notice + return []span{{m.notice, plain}} } - return "" + return nil +} + +// statusLine returns the text of the status line. +func (m *mixer) statusLine() string { + var b strings.Builder + for _, s := range m.status() { + b.WriteString(s.text) + } + return b.String() } type tabLayout struct { @@ -269,64 +332,57 @@ func (l tabLayout) isGroupFocused(it item) bool { return l.items[l.focus].groupKey == it.groupKey } -func (m *mixer) renderItem(it item, focused bool, layout tabLayout) []string { - w := m.width - if w < contentX+2 { - return nil +// drawLine draws line l of item it on row y. +func (m *mixer) drawLine(g *tui.Grid, y int, it item, l itemLine, focused bool, layout tabLayout) { + if l.kind == lineBlank { + return } - inner := m.innerWidth() - gutter := " " + typeStrip(it) - line := func(s string) string { return gutter + " " + fit(s, inner) + " " } - cLine := func(s string) string { - if m.barWidth() > 0 { - return gutter + " " + s + " " + p := g.Pen(0, y, m.width) + p.Text(" ", plain) + p.Text(typeStripBar, typeStripStyle(it)) + p.Text(" ", plain) + c := p.Sub(m.innerWidth()) + switch l.kind { + case lineTitle: + m.drawTitle(&c, it, focused || layout.isGroupFocused(it), layout) + case lineChannel: + m.drawChannel(&c, y, it, l.channel, focused) + case lineNoVolume: + if it.node.JACK { + c.Repeat(" ", barX-contentX, plain) + c.Repeat(faderEmpty, m.barWidth(), dimStyle) + break } - return line(s) - } - var lines []string - for _, l := range m.itemLines(it) { - switch l.kind { - case lineBlank: - lines = append(lines, "") - case lineTitle: - groupFocused := focused || layout.isGroupFocused(it) - lines = append(lines, line(m.titleLine(it, groupFocused, inner, layout))) - case lineChannel: - lines = append(lines, cLine(m.channelLine(it, l.channel, focused))) - case lineNoVolume: - if it.node.JACK { - lines = append(lines, cLine(fixedBar(m.barWidth()))) - break - } - lines = append(lines, line(dimStyle.Render("volume not known yet"))) - case lineProfile: - desc := "off" - if it.card.Profile >= 0 { - desc = it.card.Profiles[it.card.Profile].Description - } - lines = append(lines, line(dimStyle.Render("Profile: ")+desc)) + c.Text("volume not known yet", dimStyle) + case lineProfile: + desc := "off" + if it.card.Profile >= 0 { + desc = it.card.Profiles[it.card.Profile].Description } + c.Text("Profile: ", dimStyle) + c.Text(desc, plain) } - return lines + c.Pad(plain) + p.Join(c) } const typeStripBar = "█" var ( - cardStripStyle = lipgloss.NewStyle().Foreground(lipgloss.White) - classStripStyles = [...]lipgloss.Style{ - pw.Playback: lipgloss.NewStyle().Foreground(lipgloss.Green), - pw.Recording: lipgloss.NewStyle().Foreground(lipgloss.Red), - pw.Sink: lipgloss.NewStyle().Foreground(lipgloss.Yellow), - pw.Source: lipgloss.NewStyle().Foreground(lipgloss.Magenta), + cardStripStyle = tui.Style{Fg: tui.White} + classStripStyles = [...]tui.Style{ + pw.Playback: {Fg: tui.Green}, + pw.Recording: {Fg: tui.Red}, + pw.Sink: {Fg: tui.Yellow}, + pw.Source: {Fg: tui.Magenta}, } ) -func typeStrip(it item) string { +func typeStripStyle(it item) tui.Style { if it.node == nil { - return cardStripStyle.Render(typeStripBar) + return cardStripStyle } - return classStripStyles[it.node.Class].Render(typeStripBar) + return classStripStyles[it.node.Class] } const ( @@ -387,70 +443,63 @@ func portText(it item) string { return port } -func tagsText(it item) string { - if it.node.Default { - return defaultTagStyle.Render(defaultTag) - } - return strings.Repeat(" ", ansi.StringWidth(defaultTag)) -} - const toolbarWidth = barX - contentX -func (m *mixer) toolbar(it item, focused bool, layout tabLayout) string { - if it.node == nil { - return "" - } - var b strings.Builder +func (m *mixer) drawToolbar(p *tui.Pen, it item, focused bool, layout tabLayout) { + c := p.Sub(toolbarWidth) muted := it.node.Mute if it.groupCount > 1 { muted = layout.isGroupMuted(it) } - b.WriteString(muteSymbol(muted, it.node.JACK, focused)) - if btn := playButton(it, focused); btn != "" { - b.WriteByte(' ') - b.WriteString(btn) + c.Text(muteSymbol(muted, it.node.JACK, focused)) + if btn, st := playButton(it, focused); btn != "" { + c.Text(" ", plain) + c.Text(btn, st) } - w := ansi.StringWidth(b.String()) - if w < toolbarWidth { - b.WriteString(strings.Repeat(" ", toolbarWidth-w)) - } - return b.String() + c.Pad(plain) + p.Join(c) } -func (m *mixer) titleLine(it item, focused bool, width int, layout tabLayout) string { +// drawTitle draws the title line of it into p, which spans the inner width. +func (m *mixer) drawTitle(p *tui.Pen, it item, focused bool, layout tabLayout) { title := it.title() if it.groupCount > 1 && it.groupTitle != "" { title = it.groupTitle } + titleStyle := plain if focused { - title = focusTitleStyle.Render(title) - } - tb := m.toolbar(it, focused, layout) - avail := width - if it.node != nil { - avail = max(0, width-toolbarWidth) + titleStyle = focusTitleStyle } if it.node == nil { - return tb + title + p.Text(title, titleStyle) + return } + m.drawToolbar(p, it, focused, layout) + avail := max(0, m.innerWidth()-toolbarWidth) tw := 0 titleW := avail - finalPortW := 0 + portW := 0 if it.node.Class == pw.Sink || it.node.Class == pw.Source { tw = m.tagsWidth() if avail < tw+2 { - return tb + title + p.Text(title, titleStyle) + return } - titleW, finalPortW = m.titleColumns(avail, layout.portWidth) + titleW, portW = m.titleColumns(avail, layout.portWidth) } - line := tb + fit(title, titleW) - if finalPortW > 0 { - line += " " + dimStyle.Render(fit(portText(it), finalPortW)) + p.Fit(title, titleW, titleStyle, plain) + if portW > 0 { + p.Text(" ", plain) + p.Fit(portText(it), portW, dimStyle, dimStyle) } if tw > 0 { - line += " " + tagsText(it) + p.Text(" ", plain) + if it.node.Default { + p.Text(defaultTag, defaultTagStyle) + } else { + p.Repeat(" ", tw, plain) + } } - return line } // portSpan returns the screen columns [start, end) of a device's port on @@ -481,37 +530,33 @@ const ( playWidth = 1 ) -var mutedButtonStyle = lipgloss.NewStyle().Foreground(lipgloss.Yellow) +var mutedButtonStyle = tui.Style{Fg: tui.Yellow} -func muteSymbol(muted, jack, focused bool) string { +func muteSymbol(muted, jack, focused bool) (string, tui.Style) { if muted && !jack { if focused { - return mutedButtonStyle.Bold(true).Render(symMuted) + return symMuted, tui.Style{Fg: mutedButtonStyle.Fg, Attrs: tui.Bold} } - return mutedButtonStyle.Render(symMuted) + return symMuted, mutedButtonStyle } if focused { - return focusStyle.Bold(true).Render(symSpeaker) + return symSpeaker, tui.Style{Fg: focusStyle.Fg, Attrs: tui.Bold} } - return symSpeaker -} - -func muteButton(n *pw.Node, focused bool) string { - return muteSymbol(n.Mute, n.JACK, focused) + return symSpeaker, plain } -func playButton(it item, focused bool) string { +func playButton(it item, focused bool) (string, tui.Style) { if it.player == nil { - return "" + return "", plain } sym := symPlay if it.player.Playing { sym = symPause } if focused { - return focusStyle.Bold(true).Render(sym) + return sym, tui.Style{Fg: focusStyle.Fg, Attrs: tui.Bold} } - return sym + return sym, plain } func onMuteButton(it item, line itemLine, x int) bool { @@ -533,32 +578,28 @@ func onStreamMuteButton(it item, line itemLine, x int) bool { x >= streamMuteX && x < streamMuteX+streamMuteWidth } -// channelLine renders a channel row (or folded row when i is -1). -func (m *mixer) channelLine(it item, i int, focused bool) string { +// drawChannel draws channel i of it (or its folded channels when i is -1) +// into p, which spans the inner width of row y. +func (m *mixer) drawChannel(p *tui.Pen, y int, it item, i int, focused bool) { n := it.node unlocked := m.isUnlocked(it) chanFocused := focused && (!unlocked || m.focus[m.tab].channel == i) var c pw.Channel - var nameStr string + var name string if i < 0 && len(n.Channels) > 1 { c = n.Channels[0] - nameStr = foldedName(n.Channels) + name = foldedName(n.Channels) } else { c = n.Channels[max(i, 0)] - nameStr = ansi.Truncate(c.Name, labelWidth, "…") - } - name := strings.Repeat(" ", max(0, labelWidth-ansi.StringWidth(nameStr))) + nameStr - vol := " " - if !n.JACK { - vol = fmt.Sprintf("%3d", percent(c.Volume)) + name = ansi.Truncate(c.Name, labelWidth, "…") } + labelStyle := plain if chanFocused { - name = boldStyle.Render(name) - vol = boldStyle.Render(vol) + labelStyle = boldStyle } - var prefix string + l := p.Sub(barX - contentX) if it.groupCount > 1 { if i < 0 || i == 0 { branch := "├" @@ -567,28 +608,34 @@ func (m *mixer) channelLine(it item, i int, focused bool) string { } else if it.groupLast { branch = "└" } - branchStr := dimStyle.Render(branch) + " " - spkStr := muteButton(n, focused) + " " - innerBracket := " " + l.Text(branch, dimStyle) + l.Text(" ", plain) + l.Text(muteSymbol(n.Mute, n.JACK, focused)) + l.Text(" ", plain) if len(n.Channels) > 1 && i >= 0 { - innerBracket = dimStyle.Render("┌") + " " + l.Text("┌", dimStyle) + l.Text(" ", plain) + } else { + l.Text(" ", plain) } - prefix = branchStr + spkStr + innerBracket } else { - stem := " " if !it.groupLast { - stem = dimStyle.Render("│") + " " + l.Text("│", dimStyle) + l.Text(" ", plain) + } else { + l.Text(" ", plain) } - spkSpace := " " - innerBracket := dimStyle.Render("├") + " " + l.Text(" ", plain) + bracket := "├" if i == len(n.Channels)-1 { - innerBracket = dimStyle.Render("└") + " " + bracket = "└" } - prefix = stem + spkSpace + innerBracket + l.Text(bracket, dimStyle) + l.Text(" ", plain) } } else { if i < 0 || len(n.Channels) <= 1 { - prefix = " " + l.Text(" ", plain) } else { bracket := "├" if i == 0 { @@ -596,15 +643,38 @@ func (m *mixer) channelLine(it item, i int, focused bool) string { } else if i == len(n.Channels)-1 { bracket = "└" } - prefix = " " + dimStyle.Render(bracket) + " " + l.Text(" ", plain) + l.Text(bracket, dimStyle) + l.Text(" ", plain) } } + l.Repeat(" ", labelWidth-ansi.StringWidth(name), labelStyle) + l.Text(name, labelStyle) + l.Text(" ", plain) + if n.JACK { + l.Text(" ", labelStyle) + } else { + l.Text(fmt.Sprintf("%3d", percent(c.Volume)), labelStyle) + } + l.Pad(plain) + p.Join(l) - label := prefix + name + " " + vol + " " + if m.barWidth() > 0 { + m.meterRows = append(m.meterRows, meterRow{y: y, it: it, channel: i}) + m.drawChannelBar(p, it, i) + } +} + +// drawChannelBar draws the fader or meter of channel i of it (or its folded +// channels when i is -1) into p, which spans the bar. +func (m *mixer) drawChannelBar(p *tui.Pen, it item, i int) { + n := it.node if n.JACK { - return label + meterBar(m.level(it, i), m.peak(it, i), m.barWidth(), m.opts.limit, m.look()) + drawMeterBar(p, m.level(it, i), m.peak(it, i), m.barWidth(), m.opts.limit, m.look()) + return } - return label + bar(c.Volume, m.level(it, i), m.peak(it, i), m.barWidth(), m.opts.limit, n.Mute, m.look()) + c := n.Channels[max(i, 0)] + drawBar(p, c.Volume, m.level(it, i), m.peak(it, i), m.barWidth(), m.opts.limit, n.Mute, m.look()) } const ( @@ -613,14 +683,29 @@ const ( faderEmpty = "░" ) -func fixedBar(width int) string { - return strings.Repeat(" ", barX-contentX) + dimStyle.Render(strings.Repeat(faderEmpty, max(width, 0))) +type barCell struct { + glyph string + style uint8 +} + +// drawCells draws cells into p, as runs of a glyph in one style. +func drawCells(p *tui.Pen, cells []barCell, styles []tui.Style) { + for i := 0; i < len(cells); { + j := i + 1 + for j < len(cells) && cells[j] == cells[i] { + j++ + } + p.Repeat(cells[i].glyph, j-i, styles[cells[i].style]) + i = j + } } -// meterBar renders a level meter of width cells without a volume fader. -func meterBar(level, peak float64, width int, limit float64, look meterLook) string { +var meterBarStyles = []tui.Style{barFullStyle, barOverStyle, brightFull, brightOver, dimStyle} + +// drawMeterBar draws a level meter of width cells without a volume fader. +func drawMeterBar(p *tui.Pen, level, peak float64, width int, limit float64, look meterLook) { if width <= 0 { - return "" + return } lit, pk := 0, 0 if look != meterOff { @@ -632,10 +717,10 @@ func meterBar(level, peak float64, width int, limit float64, look meterLook) str } } if lit == 0 && pk == 0 { - return dimStyle.Render(strings.Repeat(faderEmpty, width)) + p.Repeat(faderEmpty, width, dimStyle) + return } hundred := knobCell(1, limit, width) - styles := [...]lipgloss.Style{barFullStyle, barOverStyle, brightFull, brightOver, dimStyle} var cellBuf [256]barCell var cells []barCell if width <= len(cellBuf) { @@ -644,7 +729,7 @@ func meterBar(level, peak float64, width int, limit float64, look meterLook) str cells = make([]barCell, width) } for i := range cells { - over := 0 + var over uint8 if i > hundred { over = 1 } @@ -660,55 +745,34 @@ func meterBar(level, peak float64, width int, limit float64, look meterLook) str } cells[i] = c } - var b strings.Builder - b.Grow(width * 6) - for i := 0; i < len(cells); { - j := i + 1 - for j < len(cells) && cells[j] == cells[i] { - j++ - } - b.WriteString(styles[cells[i].style].Render(strings.Repeat(cells[i].glyph, j-i))) - i = j - } - return b.String() -} - -type barCell struct { - glyph string - style int + drawCells(p, cells, meterBarStyles) } var ( - emptyOverStyle = lipgloss.NewStyle().Foreground(lipgloss.Red).Faint(true) - brightFull = lipgloss.NewStyle().Foreground(lipgloss.BrightGreen) - brightOver = lipgloss.NewStyle().Foreground(lipgloss.BrightRed) + emptyOverStyle = tui.Style{Fg: tui.Red, Attrs: tui.Faint} + brightFull = tui.Style{Fg: tui.BrightGreen} + brightOver = tui.Style{Fg: tui.BrightRed} + barStyles = []tui.Style{barFullStyle, barOverStyle, brightFull, brightOver} ) -// bar renders a fader of width cells for volume v, level, and peak on [0, limit]. -func bar(v, level, peak float64, width int, limit float64, muted bool, look meterLook) string { +// drawBar draws a fader of width cells for volume v, level, and peak on +// [0, limit]. +func drawBar(p *tui.Pen, v, level, peak float64, width int, limit float64, muted bool, look meterLook) { if width <= 0 { - return "" + return } knob := knobCell(v, limit, width) hundred := knobCell(1, limit, width) - var b strings.Builder - b.Grow(width * 6) - run := func(s string, from, to int, style lipgloss.Style) { - if to > from { - b.WriteString(style.Render(strings.Repeat(s, to-from))) - } - } if muted { - run(faderFull, 0, knob, dimStyle) - run(faderKnob, knob, knob+1, dimStyle) - run(faderEmpty, knob+1, width, dimStyle) - return b.String() + p.Repeat(faderFull, knob, dimStyle) + p.Repeat(faderKnob, 1, dimStyle) + p.Repeat(faderEmpty, width-knob-1, dimStyle) + return } knobStyle := barFullStyle if knob > hundred { knobStyle = barOverStyle } - styles := [...]lipgloss.Style{barFullStyle, barOverStyle, brightFull, brightOver} lit, pk := 0, 0 if look != meterOff { if level > 0 { @@ -726,7 +790,7 @@ func bar(v, level, peak float64, width int, limit float64, muted bool, look mete cells = make([]barCell, knob) } for i := range cells { - over := 0 + var over uint8 if i > hundred { over = 1 } @@ -744,18 +808,10 @@ func bar(v, level, peak float64, width int, limit float64, muted bool, look mete } cells[i] = c } - for i := 0; i < len(cells); { - j := i + 1 - for j < len(cells) && cells[j] == cells[i] { - j++ - } - run(cells[i].glyph, i, j, styles[cells[i].style]) - i = j - } - run(faderKnob, knob, knob+1, knobStyle) - run(faderEmpty, knob+1, max(knob+1, hundred+1), dimStyle) - run(faderEmpty, max(knob+1, hundred+1), width, emptyOverStyle) - return b.String() + drawCells(p, cells, barStyles) + p.Repeat(faderKnob, 1, knobStyle) + p.Repeat(faderEmpty, max(knob+1, hundred+1)-(knob+1), dimStyle) + p.Repeat(faderEmpty, width-max(knob+1, hundred+1), emptyOverStyle) } func knobCell(v, limit float64, width int) int { @@ -770,49 +826,54 @@ func (m *mixer) menuRows() (first, n int) { return first, n } -func (m *mixer) menuBox() (box string, x, y int) { +// menuBox returns the width inside the menu's box and the box's position +// and size. +func (m *mixer) menuBox() (inner, x, y, w, h int) { mn := m.menu - width := ansi.StringWidth(mn.title) + inner = ansi.StringWidth(mn.title) for _, it := range mn.items { - width = max(width, ansi.StringWidth(it.label)+2) + inner = max(inner, ansi.StringWidth(it.label)+2) } - width = max(min(width, m.width-4), 1) + inner = max(min(inner, m.width-4), 1) first, n := m.menuRows() - lines := []string{boldStyle.Render(ansi.Truncate(mn.title, width, "…"))} - for i := first; i < min(first+n, len(mn.items)); i++ { + w, h = inner+4, min(first+n, len(mn.items))-first+3 + return inner, max((m.width-w)/2, 0), listTop + max(m.listHeight()-h, 0)/2, w, h +} + +// drawMenu draws the menu over the screen. +func (m *mixer) drawMenu(g *tui.Grid) { + mn := m.menu + inner, x, y, w, h := m.menuBox() + edge := func(row int, left, right string) { + p := g.Pen(x, y+row, x+w) + p.Text(left, plain) + p.Repeat("─", w-2, plain) + p.Text(right, plain) + } + row := func(row int, text string, st, pad tui.Style) { + p := g.Pen(x, y+row, x+w) + p.Text("│ ", plain) + p.Fit(text, inner, st, pad) + p.Text(" │", plain) + } + edge(0, "╭", "╮") + row(1, mn.title, boldStyle, plain) + first, _ := m.menuRows() + for r := 2; r < h-1; r++ { + i := first + r - 2 it := mn.items[i] mark := " " if it.active { mark = "● " } - label := fit(mark+it.label, width) + st := plain switch { case i == mn.cursor: - label = menuCursorStyle.Render(label) + st = menuCursorStyle case it.dim: - label = dimStyle.Render(label) - } - lines = append(lines, label) - } - box = menuBoxStyle.Render(strings.Join(lines, "\n")) - bw := ansi.StringWidth(strings.SplitN(box, "\n", 2)[0]) - bh := strings.Count(box, "\n") + 1 - return box, max((m.width-bw)/2, 0), listTop + max(m.listHeight()-bh, 0)/2 -} - -// overlay draws box over content with its top left corner at cell x, y. -func overlay(content, box string, x, y int) string { - lines := strings.Split(content, "\n") - x = max(0, x) - for i, b := range strings.Split(box, "\n") { - if y+i >= len(lines) { - break + st = dimStyle } - line := lines[y+i] - left := ansi.Truncate(line, x, "") - left += strings.Repeat(" ", max(0, x-ansi.StringWidth(left))) - right := ansi.Cut(line, x+ansi.StringWidth(b), ansi.StringWidth(line)) - lines[y+i] = left + ansi.ResetStyle + b + ansi.ResetStyle + right + row(r, mark+it.label, st, st) } - return strings.Join(lines, "\n") + edge(h-1, "╰", "╯") } diff --git a/internal/pipmix/view_test.go b/internal/pipmix/view_test.go new file mode 100644 index 0000000..75e9274 --- /dev/null +++ b/internal/pipmix/view_test.go @@ -0,0 +1,59 @@ +package pipmix + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" + + "github.com/some-programs/pipmix/internal/tui" +) + +// drawGrid draws m into a new grid. +func drawGrid(m *mixer) *tui.Grid { + g := tui.NewGrid(m.width, m.height) + m.draw(g) + return g +} + +// find returns the cell position of the first text on g. +func find(g *tui.Grid, text string) (x, y int, ok bool) { + w, h := g.Size() + for y := range h { + var row strings.Builder + var cols []int // the column of each byte of row + for x := range w { + c := g.At(x, y) + row.WriteString(c.Content) + for range len(c.Content) { + cols = append(cols, x) + } + } + if i := strings.Index(row.String(), text); i >= 0 { + return cols[i], y, true + } + } + return 0, 0, false +} + +// styleOf returns the style of the first cell of the first text on g. +func styleOf(g *tui.Grid, text string) (tui.Style, bool) { + x, y, ok := find(g, text) + if !ok { + return tui.Style{}, false + } + return g.At(x, y).Style, true +} + +// lines returns the rows of g as plain text. +func lines(g *tui.Grid) []string { + return strings.Split(ansi.Strip(g.String()), "\n") +} + +// penText returns the plain text that draw writes into a pen of width +// cells. +func penText(width int, draw func(p *tui.Pen)) string { + g := tui.NewGrid(width, 1) + p := g.Pen(0, 0, width) + draw(&p) + return strings.TrimRight(ansi.Strip(g.String()), " ") +} diff --git a/internal/tui/event.go b/internal/tui/event.go new file mode 100644 index 0000000..efa8b6f --- /dev/null +++ b/internal/tui/event.go @@ -0,0 +1,77 @@ +package tui + +import ( + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi" +) + +// Event is an input event from a [Terminal]: a [KeyEvent], [MouseEvent], +// [ResizeEvent], [FocusEvent] or [BlurEvent]. +type Event any + +// KeyEvent is a key press, named as in "a", "shift+tab", "ctrl+c", "pgup" +// or "space". +type KeyEvent string + +// MouseKind is what a mouse did. +type MouseKind uint8 + +// The kinds of mouse events. +const ( + MouseClick MouseKind = iota + MouseRelease + MouseMotion + MouseWheel +) + +// Mouse buttons. +const ( + MouseNone = ansi.MouseNone + MouseLeft = ansi.MouseLeft + MouseMiddle = ansi.MouseMiddle + MouseRight = ansi.MouseRight + MouseWheelUp = ansi.MouseWheelUp + MouseWheelDown = ansi.MouseWheelDown +) + +// MouseEvent is a mouse button press or release, motion while a button is +// held, or a wheel turn, at cell X, Y. +type MouseEvent struct { + Kind MouseKind + X, Y int + Button ansi.MouseButton +} + +// ResizeEvent reports the size of the terminal. +type ResizeEvent struct{ Width, Height int } + +// FocusEvent reports that the terminal gained focus. +type FocusEvent struct{} + +// BlurEvent reports that the terminal lost focus. +type BlurEvent struct{} + +// convert returns the event for an ultraviolet event, or nil if pipmix has +// no use for it. +func convert(ev uv.Event) Event { + mouse := func(kind MouseKind, m uv.Mouse) Event { + return MouseEvent{Kind: kind, X: m.X, Y: m.Y, Button: m.Button} + } + switch ev := ev.(type) { + case uv.KeyPressEvent: + return KeyEvent(ev.String()) + case uv.MouseClickEvent: + return mouse(MouseClick, uv.Mouse(ev)) + case uv.MouseReleaseEvent: + return mouse(MouseRelease, uv.Mouse(ev)) + case uv.MouseMotionEvent: + return mouse(MouseMotion, uv.Mouse(ev)) + case uv.MouseWheelEvent: + return mouse(MouseWheel, uv.Mouse(ev)) + case uv.FocusEvent: + return FocusEvent{} + case uv.BlurEvent: + return BlurEvent{} + } + return nil +} diff --git a/internal/tui/grid.go b/internal/tui/grid.go new file mode 100644 index 0000000..6083554 --- /dev/null +++ b/internal/tui/grid.go @@ -0,0 +1,114 @@ +package tui + +// Cell is one cell of a grid. A wide grapheme takes two cells: the left one +// holds it and has Width 2, and the right one is empty and has Width 0. +type Cell struct { + Content string + Width uint8 + Style Style +} + +// Blank is an empty cell in the default style. +var Blank = Cell{Content: " ", Width: 1} + +// Grid is a screen of cells. It remembers which rows changed since they +// were last flushed to a terminal. +type Grid struct { + w, h int + cells []Cell + dirty []bool +} + +// NewGrid returns a blank grid of w×h cells. +func NewGrid(w, h int) *Grid { + g := &Grid{} + g.Resize(w, h) + return g +} + +// Resize makes g a blank grid of w×h cells. +func (g *Grid) Resize(w, h int) { + w, h = max(w, 0), max(h, 0) + g.w, g.h = w, h + if cap(g.cells) >= w*h { + g.cells = g.cells[:w*h] + } else { + g.cells = make([]Cell, w*h) + } + if cap(g.dirty) >= h { + g.dirty = g.dirty[:h] + } else { + g.dirty = make([]bool, h) + } + g.Clear() +} + +// Size returns the width and height of g. +func (g *Grid) Size() (w, h int) { return g.w, g.h } + +// Clear blanks every cell. +func (g *Grid) Clear() { + for i := range g.cells { + g.cells[i] = Blank + } + for y := range g.dirty { + g.dirty[y] = true + } +} + +// At returns the cell at x, y. +func (g *Grid) At(x, y int) Cell { return g.cells[y*g.w+x] } + +func (g *Grid) row(y int) []Cell { return g.cells[y*g.w : (y+1)*g.w] } + +// set puts c at x, y, blanking what remains of wide cells it overwrites +// in part. c must fit in the row. +func (g *Grid) set(x, y int, c Cell) { + row := g.row(y) + if row[x].Width == 0 && x > 0 { + row[x-1] = Blank + } + if end := x + int(c.Width); row[end-1].Width == 2 && end < len(row) { + row[end] = Blank + } + row[x] = c + if c.Width == 2 { + row[x+1] = Cell{Style: c.Style} + } + g.dirty[y] = true +} + +// Pen returns a pen that writes row y from column x, clipping at column end. +func (g *Grid) Pen(x, y, end int) Pen { + if y < 0 || y >= g.h { + end = x + } + end = max(min(end, g.w), x) + return Pen{g: g, y: y, x: x, start: x, end: end, want: end} +} + +// String returns the rows of g as lines, with escape sequences for their +// styles. +func (g *Grid) String() string { + var b []byte + for y := range g.h { + if y > 0 { + b = append(b, '\n') + } + cur := Style{} + for _, c := range g.row(y) { + if c.Width == 0 { + continue + } + if c.Style != cur { + b = appendSGR(b, c.Style) + cur = c.Style + } + b = append(b, c.Content...) + } + if cur != (Style{}) { + b = append(b, "\x1b[m"...) + } + } + return string(b) +} diff --git a/internal/tui/pen.go b/internal/tui/pen.go new file mode 100644 index 0000000..6053b7d --- /dev/null +++ b/internal/tui/pen.go @@ -0,0 +1,129 @@ +package tui + +import "github.com/charmbracelet/x/ansi" + +// Ellipsis ends text that a pen clips. +const Ellipsis = "…" + +// Pen writes text along part of a grid row. Text that does not fit ends +// in an [Ellipsis], and the pen writes nothing more. +type Pen struct { + g *Grid + y int + x int // the next cell + start int // the first cell + end int // cells from here on are clipped + want int // where [Pen.Pad] pads to; past end if a parent pen clips + attrs Attr // added to every style + full bool // clipped; nothing more is written +} + +// X returns the column of the next cell p writes. +func (p *Pen) X() int { return p.x } + +// AddAttrs adds attrs to the style of everything p writes from now on. +func (p *Pen) AddAttrs(attrs Attr) { p.attrs |= attrs } + +// Text writes s in style st. Control characters and other graphemes of no +// width are dropped. +func (p *Pen) Text(s string, st Style) { + st.Attrs |= p.attrs + for len(s) > 0 && !p.full { + var cl string + var w int + if c := s[0]; c >= 0x20 && c < 0x7f && (len(s) == 1 || s[1] < 0x80) { + cl, w = s[:1], 1 + } else { + cl, w = ansi.FirstGraphemeCluster(s, ansi.GraphemeWidth) + w = min(w, 2) + } + s = s[len(cl):] + if w == 0 { + continue + } + if p.x+w > p.end { + p.clip(st) + return + } + p.g.set(p.x, p.y, Cell{Content: cl, Width: uint8(w), Style: st}) + p.x += w + } +} + +// Repeat writes n copies of the grapheme glyph in style st. +func (p *Pen) Repeat(glyph string, n int, st Style) { + if n <= 0 || p.full { + return + } + st.Attrs |= p.attrs + w := min(ansi.StringWidth(glyph), 2) + if w == 0 { + return + } + c := Cell{Content: glyph, Width: uint8(w), Style: st} + for range n { + if p.x+w > p.end { + p.clip(st) + return + } + p.g.set(p.x, p.y, c) + p.x += w + } +} + +// Pad writes spaces in style st up to the width of p. If a parent pen clips +// p, Pad clips there as text would. +func (p *Pen) Pad(st Style) { + st.Attrs |= p.attrs + c := Cell{Content: " ", Width: 1, Style: st} + for ; p.x < min(p.want, p.end); p.x++ { + p.g.set(p.x, p.y, c) + } + if p.want > p.end && !p.full { + p.clip(st) + } +} + +// Sub returns a pen for the next w cells of p, clipped where p clips. Hand +// it back to p with [Pen.Join] when done. +func (p *Pen) Sub(w int) Pen { + c := *p + c.start, c.want = p.x, p.x+max(w, 0) + c.end = min(c.want, p.end) + return c +} + +// Join continues p after sub, a pen from [Pen.Sub]. +func (p *Pen) Join(sub Pen) { + p.x = sub.x + if sub.full && sub.want > sub.end { + p.full = true + } +} + +// Fit writes s in style st into the next w cells, clipping it or padding it +// with spaces in style pad. +func (p *Pen) Fit(s string, w int, st, pad Style) { + c := p.Sub(w) + c.Text(s, st) + c.Pad(pad) + p.Join(c) +} + +// clip ends the text with an ellipsis in style st, taking back the last +// grapheme if the ellipsis does not fit after it. +func (p *Pen) clip(st Style) { + p.full = true + x := p.x + if x >= p.end { + x = p.end - 1 + if x > p.start && p.g.At(x, p.y).Width == 0 { + x-- + } + } + if x < p.start { + return + } + p.g.set(x, p.y, Cell{Content: Ellipsis, Width: 1, Style: st}) + p.x = x + 1 +} diff --git a/internal/tui/pen_test.go b/internal/tui/pen_test.go new file mode 100644 index 0000000..fa5c0c0 --- /dev/null +++ b/internal/tui/pen_test.go @@ -0,0 +1,66 @@ +package tui + +import ( + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" +) + +// oldFit is how pipmix fitted strings before it drew into grids. +func oldFit(s string, width int) string { + if width <= 0 { + return "" + } + s = ansi.Truncate(s, width, "…") + return s + strings.Repeat(" ", max(0, width-ansi.StringWidth(s))) +} + +func TestFitMatchesTruncate(t *testing.T) { + texts := []string{ + "", "a", "abc", "hello world", "日本語のテキスト", "a日b本c", "🔊 Speakers", "été", + "x🔇y", "Firefox: Some Track — Artist", "ab日", + } + for _, s := range texts { + for w := range 14 { + g := NewGrid(16, 1) + p := g.Pen(1, 0, 16) + p.Fit(s, w, Style{}, Style{}) + got := strings.TrimSuffix(ansi.Strip(g.String())[1:], strings.Repeat(" ", 15-w)) + if want := oldFit(s, w); got != want { + t.Errorf("Fit(%q, %d) = %q, want %q", s, w, got, want) + } + if p.X() != 1+w { + t.Errorf("Fit(%q, %d) ends at %d, want %d", s, w, p.X(), 1+w) + } + } + } +} + +func TestClippedSub(t *testing.T) { + // The parent clips a field that is wider than what is left of it: the + // padding is cut, so the text ends in an ellipsis as fit(a+fit(b)) did. + for w := range 12 { + g := NewGrid(20, 1) + p := g.Pen(0, 0, w) + p.Fit("🔊", 6, Style{}, Style{}) + p.Text("title", Style{}) + got := ansi.Truncate(ansi.Strip(g.String()), w, "") + if want := oldFit(oldFit("🔊", 6)+"title", w); got != want { + t.Errorf("width %d: %q, want %q", w, got, want) + } + } +} + +func TestWideOverwrite(t *testing.T) { + g := NewGrid(6, 1) + p := g.Pen(0, 0, 6) + p.Text("日本語", Style{}) + q := g.Pen(1, 0, 6) + q.Text("x", Style{}) + r := g.Pen(4, 0, 6) + r.Text("y", Style{}) + if got, want := g.String(), " x本y "; got != want { + t.Errorf("got %q, want %q", got, want) + } +} diff --git a/internal/tui/screen.go b/internal/tui/screen.go new file mode 100644 index 0000000..d260e77 --- /dev/null +++ b/internal/tui/screen.go @@ -0,0 +1,118 @@ +package tui + +import ( + "io" + "strconv" +) + +// maxGap is the most unchanged cells that a flush rewrites to save moving +// the cursor past them. +const maxGap = 4 + +// Screen shows grids on a terminal. It remembers what the terminal shows +// and writes only the cells that differ. +type Screen struct { + w io.Writer + front *Grid // what the terminal shows + buf []byte + style Style // the terminal's current style + cx, cy int // the cursor; cx is -1 when not known + reset bool // the next flush clears the terminal first +} + +// NewScreen returns a screen that writes to w. +func NewScreen(w io.Writer) *Screen { + return &Screen{w: w, front: NewGrid(0, 0), cx: -1, reset: true} +} + +// Redraw makes the next flush clear the terminal and draw every cell. +func (s *Screen) Redraw() { s.reset = true } + +// Flush updates the terminal to show g. It compares only the rows of g +// that changed since the last flush. +func (s *Screen) Flush(g *Grid) error { + // Synchronized output keeps the terminal from showing half a frame. + const syncStart, syncEnd = "\x1b[?2026h", "\x1b[?2026l" + s.buf = append(s.buf[:0], syncStart...) + if w, h := s.front.Size(); s.reset || w != g.w || h != g.h { + s.front.Resize(g.w, g.h) + s.buf = appendSGR(s.buf, Style{}) + s.buf = append(s.buf, "\x1b[H\x1b[2J"...) + s.style, s.cx, s.reset = Style{}, -1, false + for y := range g.dirty { + g.dirty[y] = true + } + } + for y, dirty := range g.dirty { + if dirty { + s.flushRow(g, y) + g.dirty[y] = false + } + } + if len(s.buf) == len(syncStart) { + return nil + } + s.buf = append(s.buf, syncEnd...) + _, err := s.w.Write(s.buf) + return err +} + +func (s *Screen) flushRow(g *Grid, y int) { + row, front := g.row(y), s.front.row(y) + for x := 0; x < len(row); { + if row[x] == front[x] { + x++ + continue + } + if row[x].Width == 0 && x > 0 { + x-- // Start at the left half of a wide cell. + } + for x < len(row) { + if row[x] == front[x] { + j := x + for j < len(row) && row[j] == front[j] { + j++ + } + if j == len(row) || j-x > maxGap { + x = j + break + } + } + x += s.writeCell(row, x, y) + } + } + copy(front, row) +} + +// writeCell writes the cell at x, y and returns how many cells it covers. +func (s *Screen) writeCell(row []Cell, x, y int) int { + c := row[x] + if c.Width == 0 { + // The right half of a wide cell written with its left half, or + // one left over from a wide cell that no longer fits. + if x == 0 || row[x-1].Width != 2 { + c = Cell{Content: " ", Width: 1, Style: c.Style} + } else { + return 1 + } + } + if s.cx != x || s.cy != y { + s.buf = append(s.buf, "\x1b["...) + s.buf = strconv.AppendInt(s.buf, int64(y+1), 10) + s.buf = append(s.buf, ';') + s.buf = strconv.AppendInt(s.buf, int64(x+1), 10) + s.buf = append(s.buf, 'H') + } + if c.Style != s.style { + s.buf = appendSGR(s.buf, c.Style) + s.style = c.Style + } + s.buf = append(s.buf, c.Content...) + s.cx, s.cy = x+int(c.Width), y + if c.Width == 2 { + // Terminals disagree on the width of some graphemes, so move to + // the next cell rather than trusting where this one ends. + s.cx = -1 + } + return int(c.Width) +} diff --git a/internal/tui/screen_test.go b/internal/tui/screen_test.go new file mode 100644 index 0000000..704fd8f --- /dev/null +++ b/internal/tui/screen_test.go @@ -0,0 +1,133 @@ +package tui + +import ( + "bytes" + "math/rand/v2" + "strconv" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" +) + +// vt is a terminal that knows only the sequences a Screen writes. +type vt struct { + g *Grid + x, y int + style Style + inSync bool +} + +func (t *vt) Write(p []byte) (int, error) { + s := string(p) + for len(s) > 0 { + if strings.HasPrefix(s, "\x1b[") { + end := strings.IndexAny(s[2:], "HJmhl") + 2 + params, final := s[2:end], s[end] + s = s[end+1:] + switch final { + case 'H': + t.x, t.y = 0, 0 + if params != "" { + row, col, _ := strings.Cut(params, ";") + t.y, _ = strconv.Atoi(row) + t.x, _ = strconv.Atoi(col) + t.y-- + t.x-- + } + case 'J': + t.g.Clear() + case 'h', 'l': + t.inSync = final == 'h' + case 'm': + t.style = Style{} + fields := strings.Split(params, ";") + for i := 0; i < len(fields); i++ { + n, _ := strconv.Atoi(fields[i]) + switch { + case n == 1: + t.style.Attrs |= Bold + case n == 2: + t.style.Attrs |= Faint + case n == 4: + t.style.Attrs |= Underline + case n == 7: + t.style.Attrs |= Reverse + case n >= 30 && n <= 37: + t.style.Fg = Color(n - 30 + 1) + case n >= 90 && n <= 97: + t.style.Fg = Color(n - 90 + 9) + case n == 58: + c, _ := strconv.Atoi(fields[i+2]) + t.style.UnderlineColor = Color(c + 1) + i += 2 + } + } + } + continue + } + cl, w := ansi.FirstGraphemeCluster(s, ansi.GraphemeWidth) + s = s[len(cl):] + t.g.set(t.x, t.y, Cell{Content: cl, Width: uint8(w), Style: t.style}) + t.x += w + } + return len(p), nil +} + +func TestScreenFlush(t *testing.T) { + r := rand.New(rand.NewPCG(1, 2)) + words := []string{"a", "hello", "日本", "🔊", "█", "▓▓", "x", " ", "é", "…"} + styles := []Style{{}, {Fg: Red}, {Fg: BrightGreen, Attrs: Bold}, {Attrs: Underline | Reverse}, {Attrs: Underline, UnderlineColor: BrightBlack}} + for _, size := range [][2]int{{1, 1}, {7, 3}, {30, 10}} { + term := &vt{g: NewGrid(size[0], size[1])} + s := NewScreen(term) + g := NewGrid(size[0], size[1]) + for frame := range 300 { + // Mostly small changes, as when meters move; sometimes a new + // screen. + if frame%50 == 0 { + g.Clear() + } + for range r.IntN(8) { + x, y := r.IntN(size[0]), r.IntN(size[1]) + p := g.Pen(x, y, x+r.IntN(size[0]-x+1)) + p.Text(words[r.IntN(len(words))], styles[r.IntN(len(styles))]) + } + if frame == 150 { + s.Redraw() + } + if err := s.Flush(g); err != nil { + t.Fatal(err) + } + if got, want := term.g.String(), g.String(); got != want { + t.Fatalf("%dx%d frame %d: terminal shows\n%s\nwant\n%s", size[0], size[1], frame, got, want) + } + if term.inSync { + t.Fatalf("frame %d left synchronized output on", frame) + } + } + } +} + +func TestScreenWritesOnlyChanges(t *testing.T) { + var out bytes.Buffer + s := NewScreen(&out) + g := NewGrid(40, 3) + p := g.Pen(0, 1, 40) + p.Text("volume ▓▓▓▓▓▓░░░░", Style{}) + if err := s.Flush(g); err != nil { + t.Fatal(err) + } + out.Reset() + if err := s.Flush(g); err != nil || out.Len() != 0 { + t.Fatalf("flush without changes wrote %q, %v", out.String(), err) + } + p = g.Pen(13, 1, 40) + p.Text("▓", Style{Fg: Green}) + if err := s.Flush(g); err != nil { + t.Fatal(err) + } + if want := "\x1b[?2026h\x1b[2;14H\x1b[0;32m▓\x1b[?2026l"; out.String() != want { + t.Errorf("one changed cell: wrote %q, want %q", out.String(), want) + } +} diff --git a/internal/tui/style.go b/internal/tui/style.go new file mode 100644 index 0000000..e742038 --- /dev/null +++ b/internal/tui/style.go @@ -0,0 +1,75 @@ +// Package tui draws text screens into cell grids and shows them on a +// terminal, writing only the cells that changed. +package tui + +import "strconv" + +// Color is one of the 16 basic terminal colors, or the terminal's default. +type Color uint8 + +// The basic colors. Their order follows the ANSI color numbers. +const ( + Default Color = iota + Black + Red + Green + Yellow + Blue + Magenta + Cyan + White + BrightBlack + BrightRed + BrightGreen + BrightYellow + BrightBlue + BrightMagenta + BrightCyan + BrightWhite +) + +// Attr is a set of text attributes. +type Attr uint8 + +// The text attributes. +const ( + Bold Attr = 1 << iota + Faint + Underline + Reverse +) + +// Style is how a cell looks. The zero Style is the terminal's default. +type Style struct { + Fg Color + Attrs Attr + UnderlineColor Color +} + +// appendSGR appends the escape sequence that sets the terminal to s from +// any style. +func appendSGR(b []byte, s Style) []byte { + b = append(b, "\x1b[0"...) + for _, a := range [...]struct { + attr Attr + code string + }{{Bold, ";1"}, {Faint, ";2"}, {Underline, ";4"}, {Reverse, ";7"}} { + if s.Attrs&a.attr != 0 { + b = append(b, a.code...) + } + } + switch c := int(s.Fg) - 1; { + case c < 0: + case c < 8: + b = append(b, ';') + b = strconv.AppendInt(b, int64(30+c), 10) + default: + b = append(b, ';') + b = strconv.AppendInt(b, int64(90+c-8), 10) + } + if s.UnderlineColor != Default { + b = append(b, ";58;5;"...) + b = strconv.AppendInt(b, int64(s.UnderlineColor-1), 10) + } + return append(b, 'm') +} diff --git a/internal/tui/term.go b/internal/tui/term.go new file mode 100644 index 0000000..2259683 --- /dev/null +++ b/internal/tui/term.go @@ -0,0 +1,154 @@ +package tui + +import ( + "context" + "errors" + "os" + "os/signal" + "sync" + "syscall" + "time" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/term" + "github.com/muesli/cancelreader" +) + +// Options are the terminal modes a [Terminal] sets. +type Options struct { + Mouse bool // report mouse buttons, wheel and motion while a button is held + Focus bool // report focus and blur +} + +// Terminal is the controlling terminal in raw mode, showing the alternate +// screen. Its input arrives as events. +type Terminal struct { + in, out *os.File + state *term.State + opts Options + reader cancelreader.CancelReader + cancel context.CancelFunc + events chan Event + winch chan os.Signal + done chan struct{} // closed when the input goroutine has returned + close sync.Once +} + +// Open sets up the terminal on standard input and output and starts +// reading its input. The first event is a [ResizeEvent]. Call +// [Terminal.Close] to restore the terminal. +func Open(opts Options) (*Terminal, error) { + in, out := os.Stdin, os.Stdout + if !term.IsTerminal(in.Fd()) || !term.IsTerminal(out.Fd()) { + return nil, errors.New("standard input and output must be a terminal") + } + state, err := term.MakeRaw(in.Fd()) + if err != nil { + return nil, err + } + setup := "\x1b[?1049h\x1b[?25l\x1b[?2004h" + if opts.Focus { + setup += "\x1b[?1004h" + } + if opts.Mouse { + setup += "\x1b[?1002h\x1b[?1006h" + } + if _, err := out.WriteString(setup); err != nil { + _ = term.Restore(in.Fd(), state) + return nil, err + } + reader, err := uv.NewCancelReader(in) + if err != nil { + _, _ = out.WriteString(teardown(opts)) + _ = term.Restore(in.Fd(), state) + return nil, err + } + ctx, cancel := context.WithCancel(context.Background()) + t := &Terminal{ + in: in, out: out, state: state, opts: opts, reader: reader, cancel: cancel, + events: make(chan Event, 64), + winch: make(chan os.Signal, 1), + done: make(chan struct{}), + } + if w, h, err := term.GetSize(out.Fd()); err == nil { + t.events <- ResizeEvent{w, h} + } + signal.Notify(t.winch, syscall.SIGWINCH) + go t.watchSize(ctx) + + raw := make(chan uv.Event) + go func() { + defer close(t.done) + _ = uv.NewTerminalReader(reader, os.Getenv("TERM")).StreamEvents(ctx, raw) + }() + go func() { + for { + select { + case <-ctx.Done(): + return + case ev := <-raw: + if e := convert(ev); e != nil { + t.send(ctx, e) + } + } + } + }() + return t, nil +} + +func (t *Terminal) send(ctx context.Context, e Event) { + select { + case t.events <- e: + case <-ctx.Done(): + } +} + +func (t *Terminal) watchSize(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case <-t.winch: + if w, h, err := term.GetSize(t.out.Fd()); err == nil { + t.send(ctx, ResizeEvent{w, h}) + } + } + } +} + +// Events returns the channel of input events. +func (t *Terminal) Events() <-chan Event { return t.events } + +// Write writes p to the terminal. +func (t *Terminal) Write(p []byte) (int, error) { return t.out.Write(p) } + +// Close stops reading input and restores the terminal as Open found it. +func (t *Terminal) Close() error { + var err error + t.close.Do(func() { + signal.Stop(t.winch) + t.reader.Cancel() + t.cancel() + select { + case <-t.done: + case <-time.After(500 * time.Millisecond): + // The read did not stop; give up on it. + } + _ = t.reader.Close() + _, err = t.out.WriteString(teardown(t.opts)) + err = errors.Join(err, term.Restore(t.in.Fd(), t.state)) + }) + return err +} + +// teardown returns what undoes the modes Open sets. +func teardown(opts Options) string { + s := "\x1b[0m" + if opts.Mouse { + s += "\x1b[?1006l\x1b[?1002l" + } + if opts.Focus { + s += "\x1b[?1004l" + } + return s + "\x1b[?2004l\x1b[?25h\x1b[?1049l" +}