Skip to content
Myr

Blind pass at adding high performance scrolling into the renderer

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent da86f9a · Browse files · 3 files+250 added−26 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+250 added−26 removed

  • other:+250 added−26 removed

3 files+250 added−26 removed

modified:renderer.go+151 added-19 removed
1 unmodified line
23import (4 "bytes"5 "io"6 "strings"7 "sync"8 "time"89 "github.com/muesli/termenv"9)1011const (13 // BlankSymbol, in this case, is used to signal to the renderer to skip14 // over a given cell and not perform any rendering on it. The const is15 // literally the Unicode "BLANK SYMBOL" (U+2422).16 //17 // This character becomes useful when handing of portions of the screen to18 // a separate renderer.19 BlankSymbol = "␢"2012 // defaultFramerate specifies the maximum interval at which we should13 // update the view.14 defaultFramerate = time.Second / 6015)1617// RendererIgnoreLinesMsg tells the renderer to skip rendering for the given18// range of lines.19type IgnoreLinesMsg struct {20 from int21 to int22}2324// IgnoreLines is a command that sets a range of lines to be ignored25// by the renderer. The general use case here is that those lines would be26// rendered separately for performance reasons.27func IgnoreLines(from int, to int) IgnoreLinesMsg {28 return IgnoreLinesMsg{from: from, to: to}29}3031// ClearIgnoredLinesMsg has the renderer allows the renderer to commence rendering32// any lines previously set to be ignored.33type ClearIgnoredLinesMsg struct{}3435// RendererIgnoreLines is a command that sets a range of lines to be ignored36// by the renderer.37func ClearIgnoredLines(from int, to int) ClearIgnoredLinesMsg {38 return ClearIgnoredLinesMsg{}39}4041// ScrollDownMsg is experiemental. There are no guarantees about it persisting42// in a future API. It's exposed for high performance scrolling.43type ScrollUpMsg struct {44 newLines []string45 topBoundary int46 bottomBoundary int47}4849// ScrollDownMsg is experiemental. There are no guarantees about it persisting50// in a future API. It's exposed for high performance scrolling.51type ScrollDownMsg struct {52 newLines []string53 topBoundary int54 bottomBoundary int55}5657// renderer is a timer-based renderer, updating the view at a given framerate58// to avoid overloading the terminal emulator.59type renderer struct {60 out io.Writer
3 unmodified lines
64 mtx sync.Mutex65 done chan struct{}66 lastRender string67 linesRendered int6869 // renderer size; usually the size of the window70 width int71 height int7273 // lines not to render74 ignoreLines map[int]struct{}75}7677// newRenderer creates a new renderer. Normally you'll want to initialize it78// with os.Stdout as the argument.79func newRenderer(out io.Writer) *renderer {80 return &renderer{81 out: out,82 framerate: defaultFramerate,83 }84}8586// start starts the renderer.87func (r *renderer) start() {88 if r.ticker == nil {89 r.ticker = time.NewTicker(r.framerate)90 }91 r.done = make(chan struct{})92 go r.listen()93}9495// stop permanently halts the renderer.96func (r *renderer) stop() {97 r.flush()98 r.done <- struct{}{}99}
15 unmodified lines
115 }116 }117}118119// flush renders the buffer.120func (r *renderer) flush() {121 if r.buf.Len() == 0 || r.buf.String() == r.lastRender {122 // Nothing to do123 return
2 unmodified lines
126 // We have an opportunity here to limit the rendering to the terminal width127 // and height, but this would mean a few things:128 //129 // 1) We'd need to maintain the terminal dimensions internally and listen87 // for window size changes.130 // for window size changes. [done]131 //132 // 2) We'd need to measure the width of lines, accounting for multi-cell133 // rune widths, commonly found in Chinese, Japanese, Korean, emojis and so134 // on. We'd use something like go-runewidth
4 unmodified lines
139 //140 // Because of the way this would complicate the renderer, this may not be141 // the place to do that.142143 out := new(bytes.Buffer)144145 r.mtx.Lock()146 defer r.mtx.Unlock()147148 if r.linesRendered > 0 {104 termenv.ClearLines(r.linesRendered)149 // Clear the lines we painted in the last render.150 for i := r.linesRendered; i >= 0; i++ {151 // Check and see if we should skip rendering for this line. That152 // includes clearing the line, which we normally do before a153 // render.154 if _, exists := r.ignoreLines[i]; !exists {155 clearLine(out)156 }157 cursorUp(out)158 }159 }160 r.linesRendered = 0161108 var out bytes.Buffer162 for _, b := range r.buf.Bytes() {110 if b == '\n' {163 if _, exists := r.ignoreLines[r.linesRendered]; !exists {164 cursorDown(out) // skip rendering for this line.165 r.linesRendered++166 } else if b == '\n' {167 out.Write([]byte("\r\n"))168 r.linesRendered++169 } else {170 _, _ = out.Write([]byte{b})171 }172 }
2 unmodified lines
175 r.lastRender = r.buf.String()176 r.buf.Reset()177}178179// write writes to the internal buffer. The buffer will be outputted via the180// ticker which calls flush().123func (w *renderer) write(s string) {124 w.mtx.Lock()125 defer w.mtx.Unlock()126 w.buf.Reset()127 w.buf.WriteString(s)181func (r *renderer) write(s string) {182 r.mtx.Lock()183 defer r.mtx.Unlock()184 r.buf.Reset()185 _, _ = r.buf.WriteString(s)186}187188// setIngoredLines speicifies lines not to be touched by the standard Bubble Tea189// renderer.190func (r *renderer) setIgnoredLines(from int, to int) {191 for i := from; i < to; i++ {192 r.ignoreLines[i] = struct{}{}193 }194}195196// clearIgnoredLines sets all lines to be rendered by the standard Bubble197// Tea renderer. Any lines previously set to be ignored can be rendered to198// again.199func (r *renderer) clearIgnoredLines() {200 r.ignoreLines = make(map[int]struct{})201}202203// insertTop effectively scrolls up. It inserts lines at the top of a given204// area designated to be a scrollable region, pushing everything else down.205// This is roughly how ncurses does it.206//207// For this to work renderer.ignoreLines must be set to ignore the scrollable208// region since we are bypassing the normal Bubble Tea renderer here.209//210// Because this method relies on the terminal dimensions, it's only valid for211// full-window applications (generally those that use the alternate screen212// buffer).213//214// This method bypasses the normal rendering buffer and is philisophically215// different than the normal way we approach rendering in Bubble Tea. It's for216// use in high-performance rendering, such as a pager that could potentially217// be rendering very complicated ansi. In cases where the content is simpler218// standard Bubble Tea rendering should suffice.219func (r *renderer) insertTop(lines []string, topBoundary, bottomBoundary int) {220 r.mtx.Lock()221 defer r.mtx.Unlock()222223 b := new(bytes.Buffer)224225 saveCursorPosition(b)226 changeScrollingRegion(b, topBoundary, bottomBoundary)227 moveCursor(b, topBoundary, 0)228 insertLine(b, len(lines))229 _, _ = io.WriteString(b, "\r\n"+strings.Join(lines, "\r\n"))230 changeScrollingRegion(b, 0, r.height)231 restoreCursorPosition(b)232233 r.out.Write(b.Bytes())234}235236// insertBottom effectively scrolls down. It inserts lines at the bottom of237// a given area designated to be a scrollable region, pushing everything else238// up. This is roughly how ncurses does it.239//240// For this to work renderer.ignoreLines must be set to ignore the scrollable241// region since we are bypassing the normal Bubble Tea renderer here.242//243// See note in insertTop() on how this function only makes sense for244// full-window applications and how it differs from the noraml way we do245// rendering in Bubble Tea.246func (r *renderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {247 r.mtx.Lock()248 defer r.mtx.Unlock()249250 b := new(bytes.Buffer)251252 saveCursorPosition(b)253 changeScrollingRegion(b, topBoundary, bottomBoundary)254 moveCursor(b, topBoundary, 0)255 _, _ = io.WriteString(b, "\r\n"+strings.Join(lines, "\r\n"))256 changeScrollingRegion(b, 0, r.height)257 restoreCursorPosition(b)258259 r.out.Write(b.Bytes())260}
added:screen.go+40 added
1package tea23import (4 "fmt"5 "io"67 te "github.com/muesli/termenv"8)910func clearLine(w io.Writer) {11 fmt.Fprintf(w, te.CSI+te.EraseLineSeq, 2)12}1314func cursorUp(w io.Writer) {15 fmt.Fprintf(w, te.CSI+te.CursorUpSeq, 1)16}1718func cursorDown(w io.Writer) {19 fmt.Fprintf(w, te.CSI+te.CursorDownSeq, 1)20}2122func insertLine(w io.Writer, numLines int) {23 fmt.Fprintf(w, te.CSI+"%dL", numLines)24}2526func moveCursor(w io.Writer, row, col int) {27 fmt.Fprintf(w, te.CSI+te.CursorPositionSeq, row, col)28}2930func saveCursorPosition(w io.Writer) {31 fmt.Fprint(w, te.CSI+"s")32}3334func restoreCursorPosition(w io.Writer) {35 fmt.Fprint(w, te.CSI+"u")36}3738func changeScrollingRegion(w io.Writer, top, bottom int) {39 fmt.Fprintf(w, te.CSI+"%d;%dr", top, bottom)40}
modified:tea.go+59 added-7 removed
1package tea23import (4 "os"5 "os/signal"6 "syscall"78 "github.com/muesli/termenv"9 "golang.org/x/crypto/ssh/terminal"10)1112// Msg represents an action and is usually the result of an IO operation. It's13// triggers the Update function, and henceforth, the UI.
46 unmodified lines
60// batchMsg is the internal message used to perform a bunch of commands. You61// can send a batchMsg with Batch.62type batchMsg []Cmd6364// WindowSizeMsg is used to report on the terminal size. It's fired once initially65// and then on every terminal resize.66type WindowSizeMsg struct {67 width int68 height int69}7071// NewProgram creates a new Program.72func NewProgram(init Init, update Update, view View) *Program {73 return &Program{74 init: init,
4 unmodified lines
7980// Start initializes the program.81func (p *Program) Start() error {82 var (73 model Model74 cmd Cmd75 cmds = make(chan Cmd)76 msgs = make(chan Msg)77 errs = make(chan error)78 done = make(chan struct{})79 mrRenderer = newRenderer(os.Stdout)83 model Model84 cmd Cmd85 cmds = make(chan Cmd)86 msgs = make(chan Msg)87 errs = make(chan error)88 done = make(chan struct{})8990 output *os.File = os.Stdout91 mrRenderer = newRenderer(output)92 )9394 err := initTerminal()95 if err != nil {
25 unmodified lines
121 msgs <- KeyMsg(msg)122 }123 }()124125 // Get initial terminal size126 go func() {127 w, h, err := terminal.GetSize(int(output.Fd()))128 if err != nil {129 errs <- err130 }131 msgs <- WindowSizeMsg{w, h}132 }()133134 // Listen for window resizes135 go func() {136 sig := make(chan os.Signal)137 signal.Notify(sig, syscall.SIGWINCH)138 for {139 <-sig140 w, h, err := terminal.GetSize(int(output.Fd()))141 if err != nil {142 errs <- err143 }144 msgs <- WindowSizeMsg{w, h}145 }146 }()147148 // Process commands149 go func() {150 for {151 select {
23 unmodified lines
175 close(done)176 return nil177 }178179 // Report resizes to the renderer. This only matters if we're doing180 // higher performance scroll-based rendering.181 if size, ok := msg.(WindowSizeMsg); ok {182 mrRenderer.width = size.width183 mrRenderer.height = size.height184 }185186 // Handle messages telling the renderer to ignore ranges of lines187 if ignore, ok := msg.(IgnoreLinesMsg); ok {188 mrRenderer.setIgnoredLines(ignore.from, ignore.to)189 }190191 // Handle messages telling the renderer to stop ignoring lines192 if _, ok := msg.(IgnoreLinesMsg); ok {193 mrRenderer.clearIgnoredLines()194 }195196 // Process batch commands197 if batchedCmds, ok := msg.(batchMsg); ok {198 for _, cmd := range batchedCmds {199 cmds <- cmd
22 unmodified lines