Skip to content
Myr

Add nil renderer and combination TUI-daemon program example

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

The Nil Renderer essentially disables the Bubble Tea renderer sending loggings and print statements to stdout. It can be enabled via the ProgramOption WithoutRenderer.

authored by Christian Rocha · committed by Christian Rocha · parent 2b8b95d · Browse files · 6 files+561 added−393 removed
This commit

State

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

Diff stats

6 files+561 added−393 removed

  • other:+561 added−393 removed

6 files+561 added−393 removed

added:examples/tui-daemon-combo/main.go+121 added
1package main23import (4 "flag"5 "fmt"6 "io/ioutil"7 "log"8 "math/rand"9 "os"10 "time"1112 "github.com/charmbracelet/bubbles/spinner"13 tea "github.com/charmbracelet/bubbletea"14 "github.com/mattn/go-isatty"15 "github.com/muesli/reflow/indent"16)1718func main() {19 rand.Seed(time.Now().UTC().UnixNano())2021 var (22 daemonMode bool23 showHelp bool24 opts []tea.ProgramOption25 )2627 flag.BoolVar(&daemonMode, "d", false, "run as a daemon")28 flag.BoolVar(&showHelp, "h", false, "show help")29 flag.Parse()3031 if showHelp {32 flag.Usage()33 os.Exit(0)34 }3536 if daemonMode || !isatty.IsTerminal(os.Stdout.Fd()) {37 // If we're in daemon mode don't render the TUI38 opts = []tea.ProgramOption{tea.WithoutRenderer()}39 } else {40 // If we're in TUI mode, discard log output41 log.SetOutput(ioutil.Discard)42 }4344 p := tea.NewProgram(newModel(), opts...)45 if err := p.Start(); err != nil {46 fmt.Println("Error starting Bubble Tea program:", err)47 os.Exit(1)48 }49}5051type model struct {52 spinner spinner.Model53 results []time.Duration54 quitting bool55}5657func newModel() model {58 const showLastResults = 55960 return model{61 spinner: spinner.NewModel(),62 results: make([]time.Duration, showLastResults),63 }64}6566func (m model) Init() tea.Cmd {67 log.Println("Starting work...")68 return tea.Batch(69 spinner.Tick,70 runPretendProcess,71 )72}7374func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {75 switch msg := msg.(type) {76 case tea.KeyMsg:77 m.quitting = true78 return m, tea.Quit79 case spinner.TickMsg:80 var cmd tea.Cmd81 m.spinner, cmd = m.spinner.Update(msg)82 return m, cmd83 case processFinishedMsg:84 d := time.Duration(msg)85 log.Printf("Finished job in %s", d)86 m.results = append(m.results[1:], d)87 return m, runPretendProcess88 default:89 return m, nil90 }91}9293func (m model) View() string {94 s := "\n" + m.spinner.View() + " Doing some work...\n\n"9596 for _, dur := range m.results {97 if dur == 0 {98 s += ".....................\n"99 } else {100 s += fmt.Sprintf("Job finished in %s\n", dur)101 }102 }103104 s += "\nPress any key to exit\n"105106 if m.quitting {107 s += "\n"108 }109110 return indent.String(s, 1)111}112113// processFinishedMsg is send when a pretend process completes.114type processFinishedMsg time.Duration115116// pretendProcess simulates a long-running process.117func runPretendProcess() tea.Msg {118 pause := time.Duration(rand.Int63n(899)+100) * time.Millisecond119 time.Sleep(pause)120 return processFinishedMsg(pause)121}
modified:examples/go.mod+1 added
6 unmodified lines
7 github.com/charmbracelet/bubbletea v0.12.48 github.com/charmbracelet/glamour v0.2.09 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf177610 github.com/lucasb-eyer/go-colorful v1.0.311 github.com/mattn/go-isatty v0.0.1212 github.com/mattn/go-runewidth v0.0.1013 github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df6814 github.com/muesli/termenv v0.7.415 golang.org/x/sys v0.0.0-20201026173827-119d4633e4d1 // indirect
3 unmodified lines
added:nil_renderer.go+9 added
1package tea23type nilRenderer struct{}45func (n nilRenderer) start() {}6func (n nilRenderer) stop() {}7func (n nilRenderer) write(v string) {}8func (n nilRenderer) altScreen() bool { return false }9func (n nilRenderer) setAltScreen(v bool) {}
modified:renderer.go+6 added-387 removed
1package tea23import (4 "bytes"5 "io"6 "strings"7 "sync"8 "time"910 "github.com/muesli/reflow/truncate"11)1213const (14 // defaultFramerate specifies the maximum interval at which we should15 // update the view.16 defaultFramerate = time.Second / 6017)1819// renderer is a timer-based renderer, updating the view at a given framerate20// to avoid overloading the terminal emulator.21//22// In cases where very high performance is needed the renderer can be told23// to exclude ranges of lines, allowing them to be written to directly.24type renderer struct {25 out io.Writer26 buf bytes.Buffer27 framerate time.Duration28 ticker *time.Ticker29 mtx *sync.Mutex30 done chan struct{}31 lastRender string32 linesRendered int3334 // essentially whether or not we're using the full size of the terminal35 altScreenActive bool3637 // renderer dimensions; usually the size of the window38 width int39 height int4041 // lines not to render42 ignoreLines map[int]struct{}3type renderer interface {4 start()5 stop()6 write(string)7 altScreen() bool8 setAltScreen(bool)9}4445// newRenderer creates a new renderer. Normally you'll want to initialize it46// with os.Stdout as the first argument.47func newRenderer(out io.Writer, mtx *sync.Mutex) *renderer {48 return &renderer{49 out: out,50 mtx: mtx,51 framerate: defaultFramerate,52 }53}5455// start starts the renderer.56func (r *renderer) start() {57 if r.ticker == nil {58 r.ticker = time.NewTicker(r.framerate)59 }60 r.done = make(chan struct{})61 go r.listen()62}6364// stop permanently halts the renderer.65func (r *renderer) stop() {66 r.flush()67 r.done <- struct{}{}68}6970// listen waits for ticks on the ticker, or a signal to stop the renderer.71func (r *renderer) listen() {72 for {73 select {74 case <-r.ticker.C:75 if r.ticker != nil {76 r.flush()77 }78 case <-r.done:79 r.mtx.Lock()80 r.ticker.Stop()81 r.ticker = nil82 r.mtx.Unlock()83 close(r.done)84 return85 }86 }87}8889// flush renders the buffer.90func (r *renderer) flush() {91 r.mtx.Lock()92 defer r.mtx.Unlock()9394 if r.buf.Len() == 0 || r.buf.String() == r.lastRender {95 // Nothing to do96 return97 }9899 out := new(bytes.Buffer)100101 // Clear any lines we painted in the last render.102 if r.linesRendered > 0 {103 for i := r.linesRendered - 1; i > 0; i-- {104 // Check if we should skip rendering for this line. Clearing the105 // line before painting is part of the standard rendering routine.106 if _, exists := r.ignoreLines[i]; !exists {107 clearLine(out)108 }109110 cursorUp(out)111 }112113 if _, exists := r.ignoreLines[0]; !exists {114 // We need to return to the start of the line here to properly115 // erase it. Going back the entire width of the terminal will116 // usually be farther than we need to go, but terminal emulators117 // will stop the cursor at the start of the line as a rule.118 //119 // We use this sequence in particular because it's part of the ANSI120 // standard (whereas others are proprietary to, say, VT100/VT52).121 // If cursor previous line (ESC[ + <n> + F) were better supported122 // we could use that above to eliminate this step.123 cursorBack(out, r.width)124 clearLine(out)125 }126 }127128 r.linesRendered = 0129 lines := strings.Split(r.buf.String(), "\n")130131 // Paint new lines132 for i := 0; i < len(lines); i++ {133 if _, exists := r.ignoreLines[r.linesRendered]; exists {134 cursorDown(out) // skip rendering for this line.135 } else {136 line := lines[i]137138 // Truncate lines wider than the width of the window to avoid139 // rendering troubles. If we don't have the width of the window140 // this will be ignored.141 //142 // Note that on Windows we can't get the width of the window143 // (signal SIGWINCH is not supported), so this will be ignored.144 if r.width > 0 {145 line = truncate.String(line, uint(r.width))146 }147148 _, _ = io.WriteString(out, line)149150 if i != len(lines)-1 {151 _, _ = io.WriteString(out, "\r\n")152 }153 }154 r.linesRendered++155 }156157 // Make sure the cursor is at the start of the last line to keep rendering158 // behavior consistent.159 if r.altScreenActive {160 // We need this case to fix a bug in macOS terminal. In other terminals161 // the below case seems to do the job regardless of whether or not we're162 // using the full terminal window.163 moveCursor(out, r.linesRendered, 0)164 } else {165 cursorBack(out, r.width)166 }167168 _, _ = r.out.Write(out.Bytes())169 r.lastRender = r.buf.String()170 r.buf.Reset()171}172173// write writes to the internal buffer. The buffer will be outputted via the174// ticker which calls flush().175func (r *renderer) write(s string) {176 r.mtx.Lock()177 defer r.mtx.Unlock()178 r.buf.Reset()179 _, _ = r.buf.WriteString(s)180}181182// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea183// renderer.184func (r *renderer) setIgnoredLines(from int, to int) {185 // Lock if we're going to be clearing some lines since we don't want186 // anything jacking our cursor.187 if r.linesRendered > 0 {188 r.mtx.Lock()189 defer r.mtx.Unlock()190 }191192 if r.ignoreLines == nil {193 r.ignoreLines = make(map[int]struct{})194 }195 for i := from; i < to; i++ {196 r.ignoreLines[i] = struct{}{}197 }198199 // Erase ignored lines200 if r.linesRendered > 0 {201 out := new(bytes.Buffer)202 for i := r.linesRendered - 1; i >= 0; i-- {203 if _, exists := r.ignoreLines[i]; exists {204 clearLine(out)205 }206 cursorUp(out)207 }208 moveCursor(out, r.linesRendered, 0) // put cursor back209 _, _ = r.out.Write(out.Bytes())210 }211}212213// clearIgnoredLines returns control of any ignored lines to the standard214// Bubble Tea renderer. That is, any lines previously set to be ignored can be215// rendered to again.216func (r *renderer) clearIgnoredLines() {217 r.ignoreLines = nil218}219220// insertTop effectively scrolls up. It inserts lines at the top of a given221// area designated to be a scrollable region, pushing everything else down.222// This is roughly how ncurses does it.223//224// To call this function use command ScrollUp().225//226// For this to work renderer.ignoreLines must be set to ignore the scrollable227// region since we are bypassing the normal Bubble Tea renderer here.228//229// Because this method relies on the terminal dimensions, it's only valid for230// full-window applications (generally those that use the alternate screen231// buffer).232//233// This method bypasses the normal rendering buffer and is philosophically234// different than the normal way we approach rendering in Bubble Tea. It's for235// use in high-performance rendering, such as a pager that could potentially236// be rendering very complicated ansi. In cases where the content is simpler237// standard Bubble Tea rendering should suffice.238func (r *renderer) insertTop(lines []string, topBoundary, bottomBoundary int) {239 r.mtx.Lock()240 defer r.mtx.Unlock()241242 b := new(bytes.Buffer)243244 changeScrollingRegion(b, topBoundary, bottomBoundary)245 moveCursor(b, topBoundary, 0)246 insertLine(b, len(lines))247 _, _ = io.WriteString(b, strings.Join(lines, "\r\n"))248 changeScrollingRegion(b, 0, r.height)249250 // Move cursor back to where the main rendering routine expects it to be251 moveCursor(b, r.linesRendered, 0)252253 _, _ = r.out.Write(b.Bytes())254}255256// insertBottom effectively scrolls down. It inserts lines at the bottom of257// a given area designated to be a scrollable region, pushing everything else258// up. This is roughly how ncurses does it.259//260// To call this function use the command ScrollDown().261//262// See note in insertTop() for caveats, how this function only makes sense for263// full-window applications, and how it differs from the normal way we do264// rendering in Bubble Tea.265func (r *renderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {266 r.mtx.Lock()267 defer r.mtx.Unlock()268269 b := new(bytes.Buffer)270271 changeScrollingRegion(b, topBoundary, bottomBoundary)272 moveCursor(b, bottomBoundary, 0)273 _, _ = io.WriteString(b, "\r\n"+strings.Join(lines, "\r\n"))274 changeScrollingRegion(b, 0, r.height)275276 // Move cursor back to where the main rendering routine expects it to be277 moveCursor(b, r.linesRendered, 0)278279 _, _ = r.out.Write(b.Bytes())280}281282// handleMessages handles internal messages for the renderer.283func (r *renderer) handleMessages(msg Msg) {284 switch msg := msg.(type) {285 case WindowSizeMsg:286 r.width = msg.Width287 r.height = msg.Height288289 case clearScrollAreaMsg:290 r.clearIgnoredLines()291292 // Force a repaint on the area where the scrollable stuff was in this293 // update cycle294 r.mtx.Lock()295 r.lastRender = ""296 r.mtx.Unlock()297298 case syncScrollAreaMsg:299 // Re-render scrolling area300 r.clearIgnoredLines()301 r.setIgnoredLines(msg.topBoundary, msg.bottomBoundary)302 r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)303304 // Force non-scrolling stuff to repaint in this update cycle305 r.mtx.Lock()306 r.lastRender = ""307 r.mtx.Unlock()308309 case scrollUpMsg:310 r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)311312 case scrollDownMsg:313 r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)314 }315}316317// HIGH-PERFORMANCE RENDERING STUFF318319type syncScrollAreaMsg struct {320 lines []string321 topBoundary int322 bottomBoundary int323}324325// SyncScrollArea performs a paint of the entire region designated to be the326// scrollable area. This is required to initialize the scrollable region and327// should also be called on resize (WindowSizeMsg).328//329// For high-performance, scroll-based rendering only.330func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {331 return func() Msg {332 return syncScrollAreaMsg{333 lines: lines,334 topBoundary: topBoundary,335 bottomBoundary: bottomBoundary,336 }337 }338}339340type clearScrollAreaMsg struct{}341342// ClearScrollArea deallocates the scrollable region and returns the control of343// those lines to the main rendering routine.344//345// For high-performance, scroll-based rendering only.346func ClearScrollArea() Msg {347 return clearScrollAreaMsg{}348}349350type scrollUpMsg struct {351 lines []string352 topBoundary int353 bottomBoundary int354}355356// ScrollUp adds lines to the top of the scrollable region, pushing existing357// lines below down. Lines that are pushed out the scrollable region disappear358// from view.359//360// For high-performance, scroll-based rendering only.361func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {362 return func() Msg {363 return scrollUpMsg{364 lines: newLines,365 topBoundary: topBoundary,366 bottomBoundary: bottomBoundary,367 }368 }369}370371type scrollDownMsg struct {372 lines []string373 topBoundary int374 bottomBoundary int375}376377// ScrollDown adds lines to the bottom of the scrollable region, pushing378// existing lines above up. Lines that are pushed out of the scrollable region379// disappear from view.380//381// For high-performance, scroll-based rendering only.382func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {383 return func() Msg {384 return scrollDownMsg{385 lines: newLines,386 topBoundary: topBoundary,387 bottomBoundary: bottomBoundary,388 }389 }390}
added:standard_renderer.go+398 added
1package tea23import (4 "bytes"5 "io"6 "strings"7 "sync"8 "time"910 "github.com/muesli/reflow/truncate"11)1213const (14 // defaultFramerate specifies the maximum interval at which we should15 // update the view.16 defaultFramerate = time.Second / 6017)1819// renderer is a timer-based renderer, updating the view at a given framerate20// to avoid overloading the terminal emulator.21//22// In cases where very high performance is needed the renderer can be told23// to exclude ranges of lines, allowing them to be written to directly.24type standardRenderer struct {25 out io.Writer26 buf bytes.Buffer27 framerate time.Duration28 ticker *time.Ticker29 mtx *sync.Mutex30 done chan struct{}31 lastRender string32 linesRendered int3334 // essentially whether or not we're using the full size of the terminal35 altScreenActive bool3637 // renderer dimensions; usually the size of the window38 width int39 height int4041 // lines not to render42 ignoreLines map[int]struct{}43}4445// newRenderer creates a new renderer. Normally you'll want to initialize it46// with os.Stdout as the first argument.47func newRenderer(out io.Writer, mtx *sync.Mutex) renderer {48 return &standardRenderer{49 out: out,50 mtx: mtx,51 framerate: defaultFramerate,52 }53}5455// start starts the renderer.56func (r *standardRenderer) start() {57 if r.ticker == nil {58 r.ticker = time.NewTicker(r.framerate)59 }60 r.done = make(chan struct{})61 go r.listen()62}6364// stop permanently halts the renderer.65func (r *standardRenderer) stop() {66 r.flush()67 r.done <- struct{}{}68}6970// listen waits for ticks on the ticker, or a signal to stop the renderer.71func (r *standardRenderer) listen() {72 for {73 select {74 case <-r.ticker.C:75 if r.ticker != nil {76 r.flush()77 }78 case <-r.done:79 r.mtx.Lock()80 r.ticker.Stop()81 r.ticker = nil82 r.mtx.Unlock()83 close(r.done)84 return85 }86 }87}8889// flush renders the buffer.90func (r *standardRenderer) flush() {91 if r.buf.Len() == 0 || r.buf.String() == r.lastRender {92 // Nothing to do93 return94 }9596 out := new(bytes.Buffer)9798 r.mtx.Lock()99 defer r.mtx.Unlock()100101 // Clear any lines we painted in the last render.102 if r.linesRendered > 0 {103 for i := r.linesRendered - 1; i > 0; i-- {104 // Check if we should skip rendering for this line. Clearing the105 // line before painting is part of the standard rendering routine.106 if _, exists := r.ignoreLines[i]; !exists {107 clearLine(out)108 }109110 cursorUp(out)111 }112113 if _, exists := r.ignoreLines[0]; !exists {114 // We need to return to the start of the line here to properly115 // erase it. Going back the entire width of the terminal will116 // usually be farther than we need to go, but terminal emulators117 // will stop the cursor at the start of the line as a rule.118 //119 // We use this sequence in particular because it's part of the ANSI120 // standard (whereas others are proprietary to, say, VT100/VT52).121 // If cursor previous line (ESC[ + <n> + F) were better supported122 // we could use that above to eliminate this step.123 cursorBack(out, r.width)124 clearLine(out)125 }126 }127128 r.linesRendered = 0129 lines := strings.Split(r.buf.String(), "\n")130131 // Paint new lines132 for i := 0; i < len(lines); i++ {133 if _, exists := r.ignoreLines[r.linesRendered]; exists {134 cursorDown(out) // skip rendering for this line.135 } else {136 line := lines[i]137138 // Truncate lines wider than the width of the window to avoid139 // rendering troubles. If we don't have the width of the window140 // this will be ignored.141 //142 // Note that on Windows we can't get the width of the window143 // (signal SIGWINCH is not supported), so this will be ignored.144 if r.width > 0 {145 line = truncate.String(line, uint(r.width))146 }147148 _, _ = io.WriteString(out, line)149150 if i != len(lines)-1 {151 _, _ = io.WriteString(out, "\r\n")152 }153 }154 r.linesRendered++155 }156157 // Make sure the cursor is at the start of the last line to keep rendering158 // behavior consistent.159 if r.altScreenActive {160 // We need this case to fix a bug in macOS terminal. In other terminals161 // the below case seems to do the job regardless of whether or not we're162 // using the full terminal window.163 moveCursor(out, r.linesRendered, 0)164 } else {165 cursorBack(out, r.width)166 }167168 _, _ = r.out.Write(out.Bytes())169 r.lastRender = r.buf.String()170 r.buf.Reset()171}172173// write writes to the internal buffer. The buffer will be outputted via the174// ticker which calls flush().175func (r *standardRenderer) write(s string) {176 r.mtx.Lock()177 defer r.mtx.Unlock()178 r.buf.Reset()179 _, _ = r.buf.WriteString(s)180}181182func (r *standardRenderer) altScreen() bool {183 return r.altScreenActive184}185186func (r *standardRenderer) setAltScreen(v bool) {187 r.altScreenActive = v188}189190// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea191// renderer.192func (r *standardRenderer) setIgnoredLines(from int, to int) {193 // Lock if we're going to be clearing some lines since we don't want194 // anything jacking our cursor.195 if r.linesRendered > 0 {196 r.mtx.Lock()197 defer r.mtx.Unlock()198 }199200 if r.ignoreLines == nil {201 r.ignoreLines = make(map[int]struct{})202 }203 for i := from; i < to; i++ {204 r.ignoreLines[i] = struct{}{}205 }206207 // Erase ignored lines208 if r.linesRendered > 0 {209 out := new(bytes.Buffer)210 for i := r.linesRendered - 1; i >= 0; i-- {211 if _, exists := r.ignoreLines[i]; exists {212 clearLine(out)213 }214 cursorUp(out)215 }216 moveCursor(out, r.linesRendered, 0) // put cursor back217 _, _ = r.out.Write(out.Bytes())218 }219}220221// clearIgnoredLines returns control of any ignored lines to the standard222// Bubble Tea renderer. That is, any lines previously set to be ignored can be223// rendered to again.224func (r *standardRenderer) clearIgnoredLines() {225 r.ignoreLines = nil226}227228// insertTop effectively scrolls up. It inserts lines at the top of a given229// area designated to be a scrollable region, pushing everything else down.230// This is roughly how ncurses does it.231//232// To call this function use command ScrollUp().233//234// For this to work renderer.ignoreLines must be set to ignore the scrollable235// region since we are bypassing the normal Bubble Tea renderer here.236//237// Because this method relies on the terminal dimensions, it's only valid for238// full-window applications (generally those that use the alternate screen239// buffer).240//241// This method bypasses the normal rendering buffer and is philosophically242// different than the normal way we approach rendering in Bubble Tea. It's for243// use in high-performance rendering, such as a pager that could potentially244// be rendering very complicated ansi. In cases where the content is simpler245// standard Bubble Tea rendering should suffice.246func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {247 r.mtx.Lock()248 defer r.mtx.Unlock()249250 b := new(bytes.Buffer)251252 changeScrollingRegion(b, topBoundary, bottomBoundary)253 moveCursor(b, topBoundary, 0)254 insertLine(b, len(lines))255 _, _ = io.WriteString(b, strings.Join(lines, "\r\n"))256 changeScrollingRegion(b, 0, r.height)257258 // Move cursor back to where the main rendering routine expects it to be259 moveCursor(b, r.linesRendered, 0)260261 _, _ = r.out.Write(b.Bytes())262}263264// insertBottom effectively scrolls down. It inserts lines at the bottom of265// a given area designated to be a scrollable region, pushing everything else266// up. This is roughly how ncurses does it.267//268// To call this function use the command ScrollDown().269//270// See note in insertTop() for caveats, how this function only makes sense for271// full-window applications, and how it differs from the normal way we do272// rendering in Bubble Tea.273func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {274 r.mtx.Lock()275 defer r.mtx.Unlock()276277 b := new(bytes.Buffer)278279 changeScrollingRegion(b, topBoundary, bottomBoundary)280 moveCursor(b, bottomBoundary, 0)281 _, _ = io.WriteString(b, "\r\n"+strings.Join(lines, "\r\n"))282 changeScrollingRegion(b, 0, r.height)283284 // Move cursor back to where the main rendering routine expects it to be285 moveCursor(b, r.linesRendered, 0)286287 _, _ = r.out.Write(b.Bytes())288}289290// handleMessages handles internal messages for the renderer.291func (r *standardRenderer) handleMessages(msg Msg) {292 switch msg := msg.(type) {293 case WindowSizeMsg:294 r.width = msg.Width295 r.height = msg.Height296297 case clearScrollAreaMsg:298 r.clearIgnoredLines()299300 // Force a repaint on the area where the scrollable stuff was in this301 // update cycle302 r.mtx.Lock()303 r.lastRender = ""304 r.mtx.Unlock()305306 case syncScrollAreaMsg:307 // Re-render scrolling area308 r.clearIgnoredLines()309 r.setIgnoredLines(msg.topBoundary, msg.bottomBoundary)310 r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)311312 // Force non-scrolling stuff to repaint in this update cycle313 r.mtx.Lock()314 r.lastRender = ""315 r.mtx.Unlock()316317 case scrollUpMsg:318 r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)319320 case scrollDownMsg:321 r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)322 }323}324325// HIGH-PERFORMANCE RENDERING STUFF326327type syncScrollAreaMsg struct {328 lines []string329 topBoundary int330 bottomBoundary int331}332333// SyncScrollArea performs a paint of the entire region designated to be the334// scrollable area. This is required to initialize the scrollable region and335// should also be called on resize (WindowSizeMsg).336//337// For high-performance, scroll-based rendering only.338func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {339 return func() Msg {340 return syncScrollAreaMsg{341 lines: lines,342 topBoundary: topBoundary,343 bottomBoundary: bottomBoundary,344 }345 }346}347348type clearScrollAreaMsg struct{}349350// ClearScrollArea deallocates the scrollable region and returns the control of351// those lines to the main rendering routine.352//353// For high-performance, scroll-based rendering only.354func ClearScrollArea() Msg {355 return clearScrollAreaMsg{}356}357358type scrollUpMsg struct {359 lines []string360 topBoundary int361 bottomBoundary int362}363364// ScrollUp adds lines to the top of the scrollable region, pushing existing365// lines below down. Lines that are pushed out the scrollable region disappear366// from view.367//368// For high-performance, scroll-based rendering only.369func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {370 return func() Msg {371 return scrollUpMsg{372 lines: newLines,373 topBoundary: topBoundary,374 bottomBoundary: bottomBoundary,375 }376 }377}378379type scrollDownMsg struct {380 lines []string381 topBoundary int382 bottomBoundary int383}384385// ScrollDown adds lines to the bottom of the scrollable region, pushing386// existing lines above up. Lines that are pushed out of the scrollable region387// disappear from view.388//389// For high-performance, scroll-based rendering only.390func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {391 return func() Msg {392 return scrollDownMsg{393 lines: newLines,394 topBoundary: topBoundary,395 bottomBoundary: bottomBoundary,396 }397 }398}
modified:tea.go+26 added-6 removed
96 unmodified lines
97 m.CatchPanics = false98 }99}100101// WithoutRenderer disables the renderer. When this is set output and log102// statements will be plainly sent to stdout (or another output if one is set)103// without any rendering and redrawing logic. In other words, printing and104// logging will behave the same way it would in a non-TUI commandline tool.105// This can be useful if you want to use the Bubble Tea framework for a non-TUI106// application, or to provide an additional non-TUI mode to your Bubble Tea107// programs. For example, your program could behave like a daemon if output is108// not a TTY.109func WithoutRenderer() ProgramOption {110 return func(m *Program) {111 m.renderer = &nilRenderer{}112 }113}114115// inputStatus indicates the current state of the input. By default, input is116// stdin, however we'll change this if input's not a TTY. The user can also set117// the input.118type inputStatus int
19 unmodified lines
138 mtx *sync.Mutex139140 output io.Writer // where to send output. this will usually be os.Stdout.141 input io.Reader // this will usually be os.Stdin.128 renderer *renderer142 renderer renderer143 altScreenActive bool144145 // CatchPanics is incredibly useful for restoring the terminal to a usable146 // state after a panic occurs. When this is set, Bubble Tea will recover
129 unmodified lines
276 }277 }()278 }279280 // If no renderer is set use the standard one.281 if p.renderer == nil {266 p.renderer = newRenderer(p.output, p.mtx)282 p.renderer = newRenderer(p.output, p.mtx)283 }284285 // Check if output is a TTY before entering raw mode, hiding the cursor and286 // so on.287 {
14 unmodified lines
302 }303304 // Start renderer305 p.renderer.start()289 p.renderer.altScreenActive = p.altScreenActive306 p.renderer.setAltScreen(p.altScreenActive)307308 // Render initial view309 p.renderer.write(model.View())310
70 unmodified lines
381 continue382 }383384 // Process internal messages for the renderer385 if r, ok := p.renderer.(*standardRenderer); ok {368 p.renderer.handleMessages(msg)386 r.handleMessages(msg)387 }388389 var cmd Cmd390 model, cmd = model.Update(msg) // run update391 cmds <- cmd // process command (if any)392 p.renderer.write(model.View()) // send view to renderer
10 unmodified lines
403 moveCursor(p.output, 0, 0)404405 p.altScreenActive = true406 if p.renderer != nil {387 p.renderer.altScreenActive = p.altScreenActive407 p.renderer.setAltScreen(p.altScreenActive)408 }409}410411// ExitAltScreen exits the alternate screen buffer.
3 unmodified lines
415 fmt.Fprintf(p.output, te.CSI+te.ExitAltScreenSeq)416417 p.altScreenActive = false418 if p.renderer != nil {399 p.renderer.altScreenActive = p.altScreenActive419 p.renderer.setAltScreen(p.altScreenActive)420 }421}422423// EnableMouseCellMotion enables mouse click, release, wheel and motion events
33 unmodified lines