vendor/github.com/charmbracelet/bubbletea/tea.go

816 lines · 20950 bytes

  1// Package tea provides a framework for building rich terminal user interfaces
  2// based on the paradigms of The Elm Architecture. It's well-suited for simple
  3// and complex terminal applications, either inline, full-window, or a mix of
  4// both. It's been battle-tested in several large projects and is
  5// production-ready.
  6//
  7// A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/master/tutorials
  8//
  9// Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/master/examples
 10package tea
 11
 12import (
 13	"context"
 14	"errors"
 15	"fmt"
 16	"io"
 17	"os"
 18	"os/signal"
 19	"runtime/debug"
 20	"sync"
 21	"sync/atomic"
 22	"syscall"
 23
 24	"github.com/charmbracelet/x/term"
 25	"github.com/muesli/cancelreader"
 26	"golang.org/x/sync/errgroup"
 27)
 28
 29// ErrProgramKilled is returned by [Program.Run] when the program gets killed.
 30var ErrProgramKilled = errors.New("program was killed")
 31
 32// ErrInterrupted is returned by [Program.Run] when the program get a SIGINT
 33// signal, or when it receives a [InterruptMsg].
 34var ErrInterrupted = errors.New("program was interrupted")
 35
 36// Msg contain data from the result of a IO operation. Msgs trigger the update
 37// function and, henceforth, the UI.
 38type Msg interface{}
 39
 40// Model contains the program's state as well as its core functions.
 41type Model interface {
 42	// Init is the first function that will be called. It returns an optional
 43	// initial command. To not perform an initial command return nil.
 44	Init() Cmd
 45
 46	// Update is called when a message is received. Use it to inspect messages
 47	// and, in response, update the model and/or send a command.
 48	Update(Msg) (Model, Cmd)
 49
 50	// View renders the program's UI, which is just a string. The view is
 51	// rendered after every Update.
 52	View() string
 53}
 54
 55// Cmd is an IO operation that returns a message when it's complete. If it's
 56// nil it's considered a no-op. Use it for things like HTTP requests, timers,
 57// saving and loading from disk, and so on.
 58//
 59// Note that there's almost never a reason to use a command to send a message
 60// to another part of your program. That can almost always be done in the
 61// update function.
 62type Cmd func() Msg
 63
 64type inputType int
 65
 66const (
 67	defaultInput inputType = iota
 68	ttyInput
 69	customInput
 70)
 71
 72// String implements the stringer interface for [inputType]. It is inteded to
 73// be used in testing.
 74func (i inputType) String() string {
 75	return [...]string{
 76		"default input",
 77		"tty input",
 78		"custom input",
 79	}[i]
 80}
 81
 82// Options to customize the program during its initialization. These are
 83// generally set with ProgramOptions.
 84//
 85// The options here are treated as bits.
 86type startupOptions int16
 87
 88func (s startupOptions) has(option startupOptions) bool {
 89	return s&option != 0
 90}
 91
 92const (
 93	withAltScreen startupOptions = 1 << iota
 94	withMouseCellMotion
 95	withMouseAllMotion
 96	withANSICompressor
 97	withoutSignalHandler
 98	// Catching panics is incredibly useful for restoring the terminal to a
 99	// usable state after a panic occurs. When this is set, Bubble Tea will
100	// recover from panics, print the stack trace, and disable raw mode. This
101	// feature is on by default.
102	withoutCatchPanics
103	withoutBracketedPaste
104	withReportFocus
105)
106
107// channelHandlers manages the series of channels returned by various processes.
108// It allows us to wait for those processes to terminate before exiting the
109// program.
110type channelHandlers []chan struct{}
111
112// Adds a channel to the list of handlers. We wait for all handlers to terminate
113// gracefully on shutdown.
114func (h *channelHandlers) add(ch chan struct{}) {
115	*h = append(*h, ch)
116}
117
118// shutdown waits for all handlers to terminate.
119func (h channelHandlers) shutdown() {
120	var wg sync.WaitGroup
121	for _, ch := range h {
122		wg.Add(1)
123		go func(ch chan struct{}) {
124			<-ch
125			wg.Done()
126		}(ch)
127	}
128	wg.Wait()
129}
130
131// Program is a terminal user interface.
132type Program struct {
133	initialModel Model
134
135	// handlers is a list of channels that need to be waited on before the
136	// program can exit.
137	handlers channelHandlers
138
139	// Configuration options that will set as the program is initializing,
140	// treated as bits. These options can be set via various ProgramOptions.
141	startupOptions startupOptions
142
143	// startupTitle is the title that will be set on the terminal when the
144	// program starts.
145	startupTitle string
146
147	inputType inputType
148
149	ctx    context.Context
150	cancel context.CancelFunc
151
152	msgs     chan Msg
153	errs     chan error
154	finished chan struct{}
155
156	// where to send output, this will usually be os.Stdout.
157	output io.Writer
158	// ttyOutput is null if output is not a TTY.
159	ttyOutput           term.File
160	previousOutputState *term.State
161	renderer            renderer
162
163	// the environment variables for the program, defaults to os.Environ().
164	environ []string
165
166	// where to read inputs from, this will usually be os.Stdin.
167	input io.Reader
168	// ttyInput is null if input is not a TTY.
169	ttyInput              term.File
170	previousTtyInputState *term.State
171	cancelReader          cancelreader.CancelReader
172	readLoopDone          chan struct{}
173
174	// was the altscreen active before releasing the terminal?
175	altScreenWasActive bool
176	ignoreSignals      uint32
177
178	bpWasActive bool // was the bracketed paste mode active before releasing the terminal?
179	reportFocus bool // was focus reporting active before releasing the terminal?
180
181	filter func(Model, Msg) Msg
182
183	// fps is the frames per second we should set on the renderer, if
184	// applicable,
185	fps int
186}
187
188// Quit is a special command that tells the Bubble Tea program to exit.
189func Quit() Msg {
190	return QuitMsg{}
191}
192
193// QuitMsg signals that the program should quit. You can send a [QuitMsg] with
194// [Quit].
195type QuitMsg struct{}
196
197// Suspend is a special command that tells the Bubble Tea program to suspend.
198func Suspend() Msg {
199	return SuspendMsg{}
200}
201
202// SuspendMsg signals the program should suspend.
203// This usually happens when ctrl+z is pressed on common programs, but since
204// bubbletea puts the terminal in raw mode, we need to handle it in a
205// per-program basis.
206//
207// You can send this message with [Suspend()].
208type SuspendMsg struct{}
209
210// ResumeMsg can be listen to to do something once a program is resumed back
211// from a suspend state.
212type ResumeMsg struct{}
213
214// InterruptMsg signals the program should suspend.
215// This usually happens when ctrl+c is pressed on common programs, but since
216// bubbletea puts the terminal in raw mode, we need to handle it in a
217// per-program basis.
218//
219// You can send this message with [Interrupt()].
220type InterruptMsg struct{}
221
222// Interrupt is a special command that tells the Bubble Tea program to
223// interrupt.
224func Interrupt() Msg {
225	return InterruptMsg{}
226}
227
228// NewProgram creates a new Program.
229func NewProgram(model Model, opts ...ProgramOption) *Program {
230	p := &Program{
231		initialModel: model,
232		msgs:         make(chan Msg),
233	}
234
235	// Apply all options to the program.
236	for _, opt := range opts {
237		opt(p)
238	}
239
240	// A context can be provided with a ProgramOption, but if none was provided
241	// we'll use the default background context.
242	if p.ctx == nil {
243		p.ctx = context.Background()
244	}
245	// Initialize context and teardown channel.
246	p.ctx, p.cancel = context.WithCancel(p.ctx)
247
248	// if no output was set, set it to stdout
249	if p.output == nil {
250		p.output = os.Stdout
251	}
252
253	// if no environment was set, set it to os.Environ()
254	if p.environ == nil {
255		p.environ = os.Environ()
256	}
257
258	return p
259}
260
261func (p *Program) handleSignals() chan struct{} {
262	ch := make(chan struct{})
263
264	// Listen for SIGINT and SIGTERM.
265	//
266	// In most cases ^C will not send an interrupt because the terminal will be
267	// in raw mode and ^C will be captured as a keystroke and sent along to
268	// Program.Update as a KeyMsg. When input is not a TTY, however, ^C will be
269	// caught here.
270	//
271	// SIGTERM is sent by unix utilities (like kill) to terminate a process.
272	go func() {
273		sig := make(chan os.Signal, 1)
274		signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
275		defer func() {
276			signal.Stop(sig)
277			close(ch)
278		}()
279
280		for {
281			select {
282			case <-p.ctx.Done():
283				return
284
285			case s := <-sig:
286				if atomic.LoadUint32(&p.ignoreSignals) == 0 {
287					switch s {
288					case syscall.SIGINT:
289						p.msgs <- InterruptMsg{}
290					default:
291						p.msgs <- QuitMsg{}
292					}
293					return
294				}
295			}
296		}
297	}()
298
299	return ch
300}
301
302// handleResize handles terminal resize events.
303func (p *Program) handleResize() chan struct{} {
304	ch := make(chan struct{})
305
306	if p.ttyOutput != nil {
307		// Get the initial terminal size and send it to the program.
308		go p.checkResize()
309
310		// Listen for window resizes.
311		go p.listenForResize(ch)
312	} else {
313		close(ch)
314	}
315
316	return ch
317}
318
319// handleCommands runs commands in a goroutine and sends the result to the
320// program's message channel.
321func (p *Program) handleCommands(cmds chan Cmd) chan struct{} {
322	ch := make(chan struct{})
323
324	go func() {
325		defer close(ch)
326
327		for {
328			select {
329			case <-p.ctx.Done():
330				return
331
332			case cmd := <-cmds:
333				if cmd == nil {
334					continue
335				}
336
337				// Don't wait on these goroutines, otherwise the shutdown
338				// latency would get too large as a Cmd can run for some time
339				// (e.g. tick commands that sleep for half a second). It's not
340				// possible to cancel them so we'll have to leak the goroutine
341				// until Cmd returns.
342				go func() {
343					// Recover from panics.
344					if !p.startupOptions.has(withoutCatchPanics) {
345						defer p.recoverFromPanic()
346					}
347
348					msg := cmd() // this can be long.
349					p.Send(msg)
350				}()
351			}
352		}
353	}()
354
355	return ch
356}
357
358func (p *Program) disableMouse() {
359	p.renderer.disableMouseCellMotion()
360	p.renderer.disableMouseAllMotion()
361	p.renderer.disableMouseSGRMode()
362}
363
364// eventLoop is the central message loop. It receives and handles the default
365// Bubble Tea messages, update the model and triggers redraws.
366func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
367	for {
368		select {
369		case <-p.ctx.Done():
370			return model, nil
371
372		case err := <-p.errs:
373			return model, err
374
375		case msg := <-p.msgs:
376			// Filter messages.
377			if p.filter != nil {
378				msg = p.filter(model, msg)
379			}
380			if msg == nil {
381				continue
382			}
383
384			// Handle special internal messages.
385			switch msg := msg.(type) {
386			case QuitMsg:
387				return model, nil
388
389			case InterruptMsg:
390				return model, ErrInterrupted
391
392			case SuspendMsg:
393				if suspendSupported {
394					p.suspend()
395				}
396
397			case clearScreenMsg:
398				p.renderer.clearScreen()
399
400			case enterAltScreenMsg:
401				p.renderer.enterAltScreen()
402
403			case exitAltScreenMsg:
404				p.renderer.exitAltScreen()
405
406			case enableMouseCellMotionMsg, enableMouseAllMotionMsg:
407				switch msg.(type) {
408				case enableMouseCellMotionMsg:
409					p.renderer.enableMouseCellMotion()
410				case enableMouseAllMotionMsg:
411					p.renderer.enableMouseAllMotion()
412				}
413				// mouse mode (1006) is a no-op if the terminal doesn't support it.
414				p.renderer.enableMouseSGRMode()
415
416			case disableMouseMsg:
417				p.disableMouse()
418
419			case showCursorMsg:
420				p.renderer.showCursor()
421
422			case hideCursorMsg:
423				p.renderer.hideCursor()
424
425			case enableBracketedPasteMsg:
426				p.renderer.enableBracketedPaste()
427
428			case disableBracketedPasteMsg:
429				p.renderer.disableBracketedPaste()
430
431			case enableReportFocusMsg:
432				p.renderer.enableReportFocus()
433
434			case disableReportFocusMsg:
435				p.renderer.disableReportFocus()
436
437			case execMsg:
438				// NB: this blocks.
439				p.exec(msg.cmd, msg.fn)
440
441			case BatchMsg:
442				for _, cmd := range msg {
443					cmds <- cmd
444				}
445				continue
446
447			case sequenceMsg:
448				go func() {
449					// Execute commands one at a time, in order.
450					for _, cmd := range msg {
451						if cmd == nil {
452							continue
453						}
454
455						msg := cmd()
456						if batchMsg, ok := msg.(BatchMsg); ok {
457							g, _ := errgroup.WithContext(p.ctx)
458							for _, cmd := range batchMsg {
459								cmd := cmd
460								g.Go(func() error {
461									p.Send(cmd())
462									return nil
463								})
464							}
465
466							//nolint:errcheck
467							g.Wait() // wait for all commands from batch msg to finish
468							continue
469						}
470
471						p.Send(msg)
472					}
473				}()
474
475			case setWindowTitleMsg:
476				p.SetWindowTitle(string(msg))
477
478			case windowSizeMsg:
479				go p.checkResize()
480			}
481
482			// Process internal messages for the renderer.
483			if r, ok := p.renderer.(*standardRenderer); ok {
484				r.handleMessages(msg)
485			}
486
487			var cmd Cmd
488			model, cmd = model.Update(msg) // run update
489			cmds <- cmd                    // process command (if any)
490			p.renderer.write(model.View()) // send view to renderer
491		}
492	}
493}
494
495// Run initializes the program and runs its event loops, blocking until it gets
496// terminated by either [Program.Quit], [Program.Kill], or its signal handler.
497// Returns the final model.
498func (p *Program) Run() (Model, error) {
499	p.handlers = channelHandlers{}
500	cmds := make(chan Cmd)
501	p.errs = make(chan error)
502	p.finished = make(chan struct{}, 1)
503
504	defer p.cancel()
505
506	switch p.inputType {
507	case defaultInput:
508		p.input = os.Stdin
509
510		// The user has not set a custom input, so we need to check whether or
511		// not standard input is a terminal. If it's not, we open a new TTY for
512		// input. This will allow things to "just work" in cases where data was
513		// piped in or redirected to the application.
514		//
515		// To disable input entirely pass nil to the [WithInput] program option.
516		f, isFile := p.input.(term.File)
517		if !isFile {
518			break
519		}
520		if term.IsTerminal(f.Fd()) {
521			break
522		}
523
524		f, err := openInputTTY()
525		if err != nil {
526			return p.initialModel, err
527		}
528		defer f.Close() //nolint:errcheck
529		p.input = f
530
531	case ttyInput:
532		// Open a new TTY, by request
533		f, err := openInputTTY()
534		if err != nil {
535			return p.initialModel, err
536		}
537		defer f.Close() //nolint:errcheck
538		p.input = f
539
540	case customInput:
541		// (There is nothing extra to do.)
542	}
543
544	// Handle signals.
545	if !p.startupOptions.has(withoutSignalHandler) {
546		p.handlers.add(p.handleSignals())
547	}
548
549	// Recover from panics.
550	if !p.startupOptions.has(withoutCatchPanics) {
551		defer p.recoverFromPanic()
552	}
553
554	// If no renderer is set use the standard one.
555	if p.renderer == nil {
556		p.renderer = newRenderer(p.output, p.startupOptions.has(withANSICompressor), p.fps)
557	}
558
559	// Check if output is a TTY before entering raw mode, hiding the cursor and
560	// so on.
561	if err := p.initTerminal(); err != nil {
562		return p.initialModel, err
563	}
564
565	// Honor program startup options.
566	if p.startupTitle != "" {
567		p.renderer.setWindowTitle(p.startupTitle)
568	}
569	if p.startupOptions&withAltScreen != 0 {
570		p.renderer.enterAltScreen()
571	}
572	if p.startupOptions&withoutBracketedPaste == 0 {
573		p.renderer.enableBracketedPaste()
574	}
575	if p.startupOptions&withMouseCellMotion != 0 {
576		p.renderer.enableMouseCellMotion()
577		p.renderer.enableMouseSGRMode()
578	} else if p.startupOptions&withMouseAllMotion != 0 {
579		p.renderer.enableMouseAllMotion()
580		p.renderer.enableMouseSGRMode()
581	}
582	if p.startupOptions&withReportFocus != 0 {
583		p.renderer.enableReportFocus()
584	}
585
586	// Start the renderer.
587	p.renderer.start()
588
589	// Initialize the program.
590	model := p.initialModel
591	if initCmd := model.Init(); initCmd != nil {
592		ch := make(chan struct{})
593		p.handlers.add(ch)
594
595		go func() {
596			defer close(ch)
597
598			select {
599			case cmds <- initCmd:
600			case <-p.ctx.Done():
601			}
602		}()
603	}
604
605	// Render the initial view.
606	p.renderer.write(model.View())
607
608	// Subscribe to user input.
609	if p.input != nil {
610		if err := p.initCancelReader(); err != nil {
611			return model, err
612		}
613	}
614
615	// Handle resize events.
616	p.handlers.add(p.handleResize())
617
618	// Process commands.
619	p.handlers.add(p.handleCommands(cmds))
620
621	// Run event loop, handle updates and draw.
622	model, err := p.eventLoop(model, cmds)
623	killed := p.ctx.Err() != nil || err != nil
624	if killed && err == nil {
625		err = fmt.Errorf("%w: %s", ErrProgramKilled, p.ctx.Err())
626	}
627	if err == nil {
628		// Ensure we rendered the final state of the model.
629		p.renderer.write(model.View())
630	}
631
632	// Restore terminal state.
633	p.shutdown(killed)
634
635	return model, err
636}
637
638// StartReturningModel initializes the program and runs its event loops,
639// blocking until it gets terminated by either [Program.Quit], [Program.Kill],
640// or its signal handler. Returns the final model.
641//
642// Deprecated: please use [Program.Run] instead.
643func (p *Program) StartReturningModel() (Model, error) {
644	return p.Run()
645}
646
647// Start initializes the program and runs its event loops, blocking until it
648// gets terminated by either [Program.Quit], [Program.Kill], or its signal
649// handler.
650//
651// Deprecated: please use [Program.Run] instead.
652func (p *Program) Start() error {
653	_, err := p.Run()
654	return err
655}
656
657// Send sends a message to the main update function, effectively allowing
658// messages to be injected from outside the program for interoperability
659// purposes.
660//
661// If the program hasn't started yet this will be a blocking operation.
662// If the program has already been terminated this will be a no-op, so it's safe
663// to send messages after the program has exited.
664func (p *Program) Send(msg Msg) {
665	select {
666	case <-p.ctx.Done():
667	case p.msgs <- msg:
668	}
669}
670
671// Quit is a convenience function for quitting Bubble Tea programs. Use it
672// when you need to shut down a Bubble Tea program from the outside.
673//
674// If you wish to quit from within a Bubble Tea program use the Quit command.
675//
676// If the program is not running this will be a no-op, so it's safe to call
677// if the program is unstarted or has already exited.
678func (p *Program) Quit() {
679	p.Send(Quit())
680}
681
682// Kill stops the program immediately and restores the former terminal state.
683// The final render that you would normally see when quitting will be skipped.
684// [program.Run] returns a [ErrProgramKilled] error.
685func (p *Program) Kill() {
686	p.shutdown(true)
687}
688
689// Wait waits/blocks until the underlying Program finished shutting down.
690func (p *Program) Wait() {
691	<-p.finished
692}
693
694// shutdown performs operations to free up resources and restore the terminal
695// to its original state.
696func (p *Program) shutdown(kill bool) {
697	p.cancel()
698
699	// Wait for all handlers to finish.
700	p.handlers.shutdown()
701
702	// Check if the cancel reader has been setup before waiting and closing.
703	if p.cancelReader != nil {
704		// Wait for input loop to finish.
705		if p.cancelReader.Cancel() {
706			if !kill {
707				p.waitForReadLoop()
708			}
709		}
710		_ = p.cancelReader.Close()
711	}
712
713	if p.renderer != nil {
714		if kill {
715			p.renderer.kill()
716		} else {
717			p.renderer.stop()
718		}
719	}
720
721	_ = p.restoreTerminalState()
722	if !kill {
723		p.finished <- struct{}{}
724	}
725}
726
727// recoverFromPanic recovers from a panic, prints the stack trace, and restores
728// the terminal to a usable state.
729func (p *Program) recoverFromPanic() {
730	if r := recover(); r != nil {
731		p.shutdown(true)
732		fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)
733		debug.PrintStack()
734	}
735}
736
737// ReleaseTerminal restores the original terminal state and cancels the input
738// reader. You can return control to the Program with RestoreTerminal.
739func (p *Program) ReleaseTerminal() error {
740	atomic.StoreUint32(&p.ignoreSignals, 1)
741	if p.cancelReader != nil {
742		p.cancelReader.Cancel()
743	}
744
745	p.waitForReadLoop()
746
747	if p.renderer != nil {
748		p.renderer.stop()
749		p.altScreenWasActive = p.renderer.altScreen()
750		p.bpWasActive = p.renderer.bracketedPasteActive()
751		p.reportFocus = p.renderer.reportFocus()
752	}
753
754	return p.restoreTerminalState()
755}
756
757// RestoreTerminal reinitializes the Program's input reader, restores the
758// terminal to the former state when the program was running, and repaints.
759// Use it to reinitialize a Program after running ReleaseTerminal.
760func (p *Program) RestoreTerminal() error {
761	atomic.StoreUint32(&p.ignoreSignals, 0)
762
763	if err := p.initTerminal(); err != nil {
764		return err
765	}
766	if err := p.initCancelReader(); err != nil {
767		return err
768	}
769	if p.altScreenWasActive {
770		p.renderer.enterAltScreen()
771	} else {
772		// entering alt screen already causes a repaint.
773		go p.Send(repaintMsg{})
774	}
775	if p.renderer != nil {
776		p.renderer.start()
777	}
778	if p.bpWasActive {
779		p.renderer.enableBracketedPaste()
780	}
781	if p.reportFocus {
782		p.renderer.enableReportFocus()
783	}
784
785	// If the output is a terminal, it may have been resized while another
786	// process was at the foreground, in which case we may not have received
787	// SIGWINCH. Detect any size change now and propagate the new size as
788	// needed.
789	go p.checkResize()
790
791	return nil
792}
793
794// Println prints above the Program. This output is unmanaged by the program
795// and will persist across renders by the Program.
796//
797// If the altscreen is active no output will be printed.
798func (p *Program) Println(args ...interface{}) {
799	p.msgs <- printLineMessage{
800		messageBody: fmt.Sprint(args...),
801	}
802}
803
804// Printf prints above the Program. It takes a format template followed by
805// values similar to fmt.Printf. This output is unmanaged by the program and
806// will persist across renders by the Program.
807//
808// Unlike fmt.Printf (but similar to log.Printf) the message will be print on
809// its own line.
810//
811// If the altscreen is active no output will be printed.
812func (p *Program) Printf(template string, args ...interface{}) {
813	p.msgs <- printLineMessage{
814		messageBody: fmt.Sprintf(template, args...),
815	}
816}