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

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