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
Provenance
- Commit
b3f62af- Tree
44fdd42- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
2b8b95d
6 files changed+561 added−393 removed
added:examples/tui-daemon-combo/main.go+121 added
1+package main2+3+import (4+ "flag"5+ "fmt"6+ "io/ioutil"7+ "log"8+ "math/rand"9+ "os"10+ "time"11+12+ "github.com/charmbracelet/bubbles/spinner"13+ tea "github.com/charmbracelet/bubbletea"14+ "github.com/mattn/go-isatty"15+ "github.com/muesli/reflow/indent"16+)17+18+func main() {19+ rand.Seed(time.Now().UTC().UnixNano())20+21+ var (22+ daemonMode bool23+ showHelp bool24+ opts []tea.ProgramOption25+ )26+27+ flag.BoolVar(&daemonMode, "d", false, "run as a daemon")28+ flag.BoolVar(&showHelp, "h", false, "show help")29+ flag.Parse()30+31+ if showHelp {32+ flag.Usage()33+ os.Exit(0)34+ }35+36+ 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+ }43+44+ 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+}50+51+type model struct {52+ spinner spinner.Model53+ results []time.Duration54+ quitting bool55+}56+57+func newModel() model {58+ const showLastResults = 559+60+ return model{61+ spinner: spinner.NewModel(),62+ results: make([]time.Duration, showLastResults),63+ }64+}65+66+func (m model) Init() tea.Cmd {67+ log.Println("Starting work...")68+ return tea.Batch(69+ spinner.Tick,70+ runPretendProcess,71+ )72+}73+74+func (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+}92+93+func (m model) View() string {94+ s := "\n" + m.spinner.View() + " Doing some work...\n\n"95+96+ 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+ }103+104+ s += "\nPress any key to exit\n"105+106+ if m.quitting {107+ s += "\n"108+ }109+110+ return indent.String(s, 1)111+}112+113+// processFinishedMsg is send when a pretend process completes.114+type processFinishedMsg time.Duration115+116+// pretendProcess simulates a long-running process.117+func 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 lines7 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 // indirect3 unmodified linesadded:nil_renderer.go+9 added
1+package tea2+3+type nilRenderer struct{}4+5+func (n nilRenderer) start() {}6+func (n nilRenderer) stop() {}7+func (n nilRenderer) write(v string) {}8+func (n nilRenderer) altScreen() bool { return false }9+func (n nilRenderer) setAltScreen(v bool) {}modified:renderer.go+6 added-387 removed
1 package tea2 3-import (4- "bytes"5- "io"6- "strings"7- "sync"8- "time"9-10- "github.com/muesli/reflow/truncate"11-)12-13-const (14- // defaultFramerate specifies the maximum interval at which we should15- // update the view.16- defaultFramerate = time.Second / 6017-)18-19-// 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.24-type 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 int33-34- // essentially whether or not we're using the full size of the terminal35- altScreenActive bool36-37- // renderer dimensions; usually the size of the window38- width int39- height int40-41- // lines not to render42- ignoreLines map[int]struct{}3+type renderer interface {4+ start()5+ stop()6+ write(string)7+ altScreen() bool8+ setAltScreen(bool)9 }44-45-// newRenderer creates a new renderer. Normally you'll want to initialize it46-// with os.Stdout as the first argument.47-func newRenderer(out io.Writer, mtx *sync.Mutex) *renderer {48- return &renderer{49- out: out,50- mtx: mtx,51- framerate: defaultFramerate,52- }53-}54-55-// start starts the renderer.56-func (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-}63-64-// stop permanently halts the renderer.65-func (r *renderer) stop() {66- r.flush()67- r.done <- struct{}{}68-}69-70-// listen waits for ticks on the ticker, or a signal to stop the renderer.71-func (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-}88-89-// flush renders the buffer.90-func (r *renderer) flush() {91- r.mtx.Lock()92- defer r.mtx.Unlock()93-94- if r.buf.Len() == 0 || r.buf.String() == r.lastRender {95- // Nothing to do96- return97- }98-99- out := new(bytes.Buffer)100-101- // 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- }109-110- cursorUp(out)111- }112-113- 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- }127-128- r.linesRendered = 0129- lines := strings.Split(r.buf.String(), "\n")130-131- // 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]137-138- // 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- }147-148- _, _ = io.WriteString(out, line)149-150- if i != len(lines)-1 {151- _, _ = io.WriteString(out, "\r\n")152- }153- }154- r.linesRendered++155- }156-157- // 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- }167-168- _, _ = r.out.Write(out.Bytes())169- r.lastRender = r.buf.String()170- r.buf.Reset()171-}172-173-// write writes to the internal buffer. The buffer will be outputted via the174-// ticker which calls flush().175-func (r *renderer) write(s string) {176- r.mtx.Lock()177- defer r.mtx.Unlock()178- r.buf.Reset()179- _, _ = r.buf.WriteString(s)180-}181-182-// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea183-// renderer.184-func (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- }191-192- 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- }198-199- // 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-}212-213-// 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.216-func (r *renderer) clearIgnoredLines() {217- r.ignoreLines = nil218-}219-220-// 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.238-func (r *renderer) insertTop(lines []string, topBoundary, bottomBoundary int) {239- r.mtx.Lock()240- defer r.mtx.Unlock()241-242- b := new(bytes.Buffer)243-244- 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)249-250- // Move cursor back to where the main rendering routine expects it to be251- moveCursor(b, r.linesRendered, 0)252-253- _, _ = r.out.Write(b.Bytes())254-}255-256-// 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.265-func (r *renderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {266- r.mtx.Lock()267- defer r.mtx.Unlock()268-269- b := new(bytes.Buffer)270-271- 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)275-276- // Move cursor back to where the main rendering routine expects it to be277- moveCursor(b, r.linesRendered, 0)278-279- _, _ = r.out.Write(b.Bytes())280-}281-282-// handleMessages handles internal messages for the renderer.283-func (r *renderer) handleMessages(msg Msg) {284- switch msg := msg.(type) {285- case WindowSizeMsg:286- r.width = msg.Width287- r.height = msg.Height288-289- case clearScrollAreaMsg:290- r.clearIgnoredLines()291-292- // 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()297-298- 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)303-304- // Force non-scrolling stuff to repaint in this update cycle305- r.mtx.Lock()306- r.lastRender = ""307- r.mtx.Unlock()308-309- case scrollUpMsg:310- r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)311-312- case scrollDownMsg:313- r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)314- }315-}316-317-// HIGH-PERFORMANCE RENDERING STUFF318-319-type syncScrollAreaMsg struct {320- lines []string321- topBoundary int322- bottomBoundary int323-}324-325-// 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.330-func 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-}339-340-type clearScrollAreaMsg struct{}341-342-// 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.346-func ClearScrollArea() Msg {347- return clearScrollAreaMsg{}348-}349-350-type scrollUpMsg struct {351- lines []string352- topBoundary int353- bottomBoundary int354-}355-356-// 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.361-func 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-}370-371-type scrollDownMsg struct {372- lines []string373- topBoundary int374- bottomBoundary int375-}376-377-// 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.382-func 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
1+package tea2+3+import (4+ "bytes"5+ "io"6+ "strings"7+ "sync"8+ "time"9+10+ "github.com/muesli/reflow/truncate"11+)12+13+const (14+ // defaultFramerate specifies the maximum interval at which we should15+ // update the view.16+ defaultFramerate = time.Second / 6017+)18+19+// 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.24+type 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 int33+34+ // essentially whether or not we're using the full size of the terminal35+ altScreenActive bool36+37+ // renderer dimensions; usually the size of the window38+ width int39+ height int40+41+ // lines not to render42+ ignoreLines map[int]struct{}43+}44+45+// newRenderer creates a new renderer. Normally you'll want to initialize it46+// with os.Stdout as the first argument.47+func newRenderer(out io.Writer, mtx *sync.Mutex) renderer {48+ return &standardRenderer{49+ out: out,50+ mtx: mtx,51+ framerate: defaultFramerate,52+ }53+}54+55+// start starts the renderer.56+func (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+}63+64+// stop permanently halts the renderer.65+func (r *standardRenderer) stop() {66+ r.flush()67+ r.done <- struct{}{}68+}69+70+// listen waits for ticks on the ticker, or a signal to stop the renderer.71+func (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+}88+89+// flush renders the buffer.90+func (r *standardRenderer) flush() {91+ if r.buf.Len() == 0 || r.buf.String() == r.lastRender {92+ // Nothing to do93+ return94+ }95+96+ out := new(bytes.Buffer)97+98+ r.mtx.Lock()99+ defer r.mtx.Unlock()100+101+ // 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+ }109+110+ cursorUp(out)111+ }112+113+ 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+ }127+128+ r.linesRendered = 0129+ lines := strings.Split(r.buf.String(), "\n")130+131+ // 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]137+138+ // 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+ }147+148+ _, _ = io.WriteString(out, line)149+150+ if i != len(lines)-1 {151+ _, _ = io.WriteString(out, "\r\n")152+ }153+ }154+ r.linesRendered++155+ }156+157+ // 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+ }167+168+ _, _ = r.out.Write(out.Bytes())169+ r.lastRender = r.buf.String()170+ r.buf.Reset()171+}172+173+// write writes to the internal buffer. The buffer will be outputted via the174+// ticker which calls flush().175+func (r *standardRenderer) write(s string) {176+ r.mtx.Lock()177+ defer r.mtx.Unlock()178+ r.buf.Reset()179+ _, _ = r.buf.WriteString(s)180+}181+182+func (r *standardRenderer) altScreen() bool {183+ return r.altScreenActive184+}185+186+func (r *standardRenderer) setAltScreen(v bool) {187+ r.altScreenActive = v188+}189+190+// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea191+// renderer.192+func (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+ }199+200+ 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+ }206+207+ // 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+}220+221+// 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.224+func (r *standardRenderer) clearIgnoredLines() {225+ r.ignoreLines = nil226+}227+228+// 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.246+func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {247+ r.mtx.Lock()248+ defer r.mtx.Unlock()249+250+ b := new(bytes.Buffer)251+252+ 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)257+258+ // Move cursor back to where the main rendering routine expects it to be259+ moveCursor(b, r.linesRendered, 0)260+261+ _, _ = r.out.Write(b.Bytes())262+}263+264+// 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.273+func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {274+ r.mtx.Lock()275+ defer r.mtx.Unlock()276+277+ b := new(bytes.Buffer)278+279+ 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)283+284+ // Move cursor back to where the main rendering routine expects it to be285+ moveCursor(b, r.linesRendered, 0)286+287+ _, _ = r.out.Write(b.Bytes())288+}289+290+// handleMessages handles internal messages for the renderer.291+func (r *standardRenderer) handleMessages(msg Msg) {292+ switch msg := msg.(type) {293+ case WindowSizeMsg:294+ r.width = msg.Width295+ r.height = msg.Height296+297+ case clearScrollAreaMsg:298+ r.clearIgnoredLines()299+300+ // 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()305+306+ 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)311+312+ // Force non-scrolling stuff to repaint in this update cycle313+ r.mtx.Lock()314+ r.lastRender = ""315+ r.mtx.Unlock()316+317+ case scrollUpMsg:318+ r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)319+320+ case scrollDownMsg:321+ r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)322+ }323+}324+325+// HIGH-PERFORMANCE RENDERING STUFF326+327+type syncScrollAreaMsg struct {328+ lines []string329+ topBoundary int330+ bottomBoundary int331+}332+333+// 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.338+func 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+}347+348+type clearScrollAreaMsg struct{}349+350+// 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.354+func ClearScrollArea() Msg {355+ return clearScrollAreaMsg{}356+}357+358+type scrollUpMsg struct {359+ lines []string360+ topBoundary int361+ bottomBoundary int362+}363+364+// 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.369+func 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+}378+379+type scrollDownMsg struct {380+ lines []string381+ topBoundary int382+ bottomBoundary int383+}384+385+// 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.390+func 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 lines97 m.CatchPanics = false98 }99 }100 101+// 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.109+func WithoutRenderer() ProgramOption {110+ return func(m *Program) {111+ m.renderer = &nilRenderer{}112+ }113+}114+115 // 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.118 type inputStatus int19 unmodified lines138 mtx *sync.Mutex139 140 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 bool144 145 // CatchPanics is incredibly useful for restoring the terminal to a usable146 // state after a panic occurs. When this is set, Bubble Tea will recover129 unmodified lines276 }277 }()278 }279 280+ // 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+ }284 285 // Check if output is a TTY before entering raw mode, hiding the cursor and286 // so on.287 {14 unmodified lines302 }303 304 // Start renderer305 p.renderer.start()289- p.renderer.altScreenActive = p.altScreenActive306+ p.renderer.setAltScreen(p.altScreenActive)307 308 // Render initial view309 p.renderer.write(model.View())310 70 unmodified lines381 continue382 }383 384 // Process internal messages for the renderer385+ if r, ok := p.renderer.(*standardRenderer); ok {368- p.renderer.handleMessages(msg)386+ r.handleMessages(msg)387+ }388+389 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 renderer10 unmodified lines403 moveCursor(p.output, 0, 0)404 405 p.altScreenActive = true406 if p.renderer != nil {387- p.renderer.altScreenActive = p.altScreenActive407+ p.renderer.setAltScreen(p.altScreenActive)408 }409 }410 411 // ExitAltScreen exits the alternate screen buffer.3 unmodified lines415 fmt.Fprintf(p.output, te.CSI+te.ExitAltScreenSeq)416 417 p.altScreenActive = false418 if p.renderer != nil {399- p.renderer.altScreenActive = p.altScreenActive419+ p.renderer.setAltScreen(p.altScreenActive)420 }421 }422 423 // EnableMouseCellMotion enables mouse click, release, wheel and motion events33 unmodified lines