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
Provenance
- Commit
683473c- Tree
af9a2a1- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
da86f9a
3 files changed+250 added−26 removed
modified:renderer.go+151 added-19 removed
1 unmodified line2 3 import (4 "bytes"5 "io"6+ "strings"7 "sync"8 "time"8-9- "github.com/muesli/termenv"9 )10 11 const (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 = "␢"20-12 // defaultFramerate specifies the maximum interval at which we should13 // update the view.14 defaultFramerate = time.Second / 6015 )16 17+// RendererIgnoreLinesMsg tells the renderer to skip rendering for the given18+// range of lines.19+type IgnoreLinesMsg struct {20+ from int21+ to int22+}23+24+// 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.27+func IgnoreLines(from int, to int) IgnoreLinesMsg {28+ return IgnoreLinesMsg{from: from, to: to}29+}30+31+// ClearIgnoredLinesMsg has the renderer allows the renderer to commence rendering32+// any lines previously set to be ignored.33+type ClearIgnoredLinesMsg struct{}34+35+// RendererIgnoreLines is a command that sets a range of lines to be ignored36+// by the renderer.37+func ClearIgnoredLines(from int, to int) ClearIgnoredLinesMsg {38+ return ClearIgnoredLinesMsg{}39+}40+41+// ScrollDownMsg is experiemental. There are no guarantees about it persisting42+// in a future API. It's exposed for high performance scrolling.43+type ScrollUpMsg struct {44+ newLines []string45+ topBoundary int46+ bottomBoundary int47+}48+49+// ScrollDownMsg is experiemental. There are no guarantees about it persisting50+// in a future API. It's exposed for high performance scrolling.51+type ScrollDownMsg struct {52+ newLines []string53+ topBoundary int54+ bottomBoundary int55+}56+57 // renderer is a timer-based renderer, updating the view at a given framerate58 // to avoid overloading the terminal emulator.59 type renderer struct {60 out io.Writer3 unmodified lines64 mtx sync.Mutex65 done chan struct{}66 lastRender string67 linesRendered int68+69+ // renderer size; usually the size of the window70+ width int71+ height int72+73+ // lines not to render74+ ignoreLines map[int]struct{}75 }76 77+// newRenderer creates a new renderer. Normally you'll want to initialize it78+// with os.Stdout as the argument.79 func newRenderer(out io.Writer) *renderer {80 return &renderer{81 out: out,82 framerate: defaultFramerate,83 }84 }85 86+// start starts the renderer.87 func (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 }94 95+// stop permanently halts the renderer.96 func (r *renderer) stop() {97 r.flush()98 r.done <- struct{}{}99 }15 unmodified lines115 }116 }117 }118 119+// flush renders the buffer.120 func (r *renderer) flush() {121 if r.buf.Len() == 0 || r.buf.String() == r.lastRender {122 // Nothing to do123 return2 unmodified lines126 // 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-runewidth4 unmodified lines139 //140 // Because of the way this would complicate the renderer, this may not be141 // the place to do that.142 143+ out := new(bytes.Buffer)144+145 r.mtx.Lock()146 defer r.mtx.Unlock()147 148 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 = 0161 108- 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 lines175 r.lastRender = r.buf.String()176 r.buf.Reset()177 }178 179+// write writes to the internal buffer. The buffer will be outputted via the180+// ticker which calls flush().123-func (w *renderer) write(s string) {124- w.mtx.Lock()125- defer w.mtx.Unlock()126- w.buf.Reset()127- w.buf.WriteString(s)181+func (r *renderer) write(s string) {182+ r.mtx.Lock()183+ defer r.mtx.Unlock()184+ r.buf.Reset()185+ _, _ = r.buf.WriteString(s)186 }187+188+// setIngoredLines speicifies lines not to be touched by the standard Bubble Tea189+// renderer.190+func (r *renderer) setIgnoredLines(from int, to int) {191+ for i := from; i < to; i++ {192+ r.ignoreLines[i] = struct{}{}193+ }194+}195+196+// 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.199+func (r *renderer) clearIgnoredLines() {200+ r.ignoreLines = make(map[int]struct{})201+}202+203+// 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.219+func (r *renderer) insertTop(lines []string, topBoundary, bottomBoundary int) {220+ r.mtx.Lock()221+ defer r.mtx.Unlock()222+223+ b := new(bytes.Buffer)224+225+ 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)232+233+ r.out.Write(b.Bytes())234+}235+236+// 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.246+func (r *renderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {247+ r.mtx.Lock()248+ defer r.mtx.Unlock()249+250+ b := new(bytes.Buffer)251+252+ 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)258+259+ r.out.Write(b.Bytes())260+}added:screen.go+40 added
1+package tea2+3+import (4+ "fmt"5+ "io"6+7+ te "github.com/muesli/termenv"8+)9+10+func clearLine(w io.Writer) {11+ fmt.Fprintf(w, te.CSI+te.EraseLineSeq, 2)12+}13+14+func cursorUp(w io.Writer) {15+ fmt.Fprintf(w, te.CSI+te.CursorUpSeq, 1)16+}17+18+func cursorDown(w io.Writer) {19+ fmt.Fprintf(w, te.CSI+te.CursorDownSeq, 1)20+}21+22+func insertLine(w io.Writer, numLines int) {23+ fmt.Fprintf(w, te.CSI+"%dL", numLines)24+}25+26+func moveCursor(w io.Writer, row, col int) {27+ fmt.Fprintf(w, te.CSI+te.CursorPositionSeq, row, col)28+}29+30+func saveCursorPosition(w io.Writer) {31+ fmt.Fprint(w, te.CSI+"s")32+}33+34+func restoreCursorPosition(w io.Writer) {35+ fmt.Fprint(w, te.CSI+"u")36+}37+38+func 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
1 package tea2 3 import (4 "os"5+ "os/signal"6+ "syscall"7 8 "github.com/muesli/termenv"9+ "golang.org/x/crypto/ssh/terminal"10 )11 12 // 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 lines60 // batchMsg is the internal message used to perform a bunch of commands. You61 // can send a batchMsg with Batch.62 type batchMsg []Cmd63 64+// WindowSizeMsg is used to report on the terminal size. It's fired once initially65+// and then on every terminal resize.66+type WindowSizeMsg struct {67+ width int68+ height int69+}70+71 // NewProgram creates a new Program.72 func NewProgram(init Init, update Update, view View) *Program {73 return &Program{74 init: init,4 unmodified lines79 80 // Start initializes the program.81 func (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{})89+90+ output *os.File = os.Stdout91+ mrRenderer = newRenderer(output)92 )93 94 err := initTerminal()95 if err != nil {25 unmodified lines121 msgs <- KeyMsg(msg)122 }123 }()124 125+ // 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+ }()133+134+ // 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+ }()147+148 // Process commands149 go func() {150 for {151 select {23 unmodified lines175 close(done)176 return nil177 }178 179+ // 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+ }185+186+ // Handle messages telling the renderer to ignore ranges of lines187+ if ignore, ok := msg.(IgnoreLinesMsg); ok {188+ mrRenderer.setIgnoredLines(ignore.from, ignore.to)189+ }190+191+ // Handle messages telling the renderer to stop ignoring lines192+ if _, ok := msg.(IgnoreLinesMsg); ok {193+ mrRenderer.clearIgnoredLines()194+ }195+196 // Process batch commands197 if batchedCmds, ok := msg.(batchMsg); ok {198 for _, cmd := range batchedCmds {199 cmds <- cmd22 unmodified lines