tea.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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
  10. package tea
  11. import (
  12. "context"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "os"
  17. "os/signal"
  18. "runtime/debug"
  19. "sync"
  20. "sync/atomic"
  21. "syscall"
  22. "github.com/containerd/console"
  23. isatty "github.com/mattn/go-isatty"
  24. "github.com/muesli/cancelreader"
  25. "github.com/muesli/termenv"
  26. "golang.org/x/sync/errgroup"
  27. )
  28. // ErrProgramKilled is returned by [Program.Run] when the program got killed.
  29. var ErrProgramKilled = errors.New("program was killed")
  30. // Msg contain data from the result of a IO operation. Msgs trigger the update
  31. // function and, henceforth, the UI.
  32. type Msg interface{}
  33. // Model contains the program's state as well as its core functions.
  34. type Model interface {
  35. // Init is the first function that will be called. It returns an optional
  36. // initial command. To not perform an initial command return nil.
  37. Init() Cmd
  38. // Update is called when a message is received. Use it to inspect messages
  39. // and, in response, update the model and/or send a command.
  40. Update(Msg) (Model, Cmd)
  41. // View renders the program's UI, which is just a string. The view is
  42. // rendered after every Update.
  43. View() string
  44. }
  45. // Cmd is an IO operation that returns a message when it's complete. If it's
  46. // nil it's considered a no-op. Use it for things like HTTP requests, timers,
  47. // saving and loading from disk, and so on.
  48. //
  49. // Note that there's almost never a reason to use a command to send a message
  50. // to another part of your program. That can almost always be done in the
  51. // update function.
  52. type Cmd func() Msg
  53. type inputType int
  54. const (
  55. defaultInput inputType = iota
  56. ttyInput
  57. customInput
  58. )
  59. // String implements the stringer interface for [inputType]. It is inteded to
  60. // be used in testing.
  61. func (i inputType) String() string {
  62. return [...]string{
  63. "default input",
  64. "tty input",
  65. "custom input",
  66. }[i]
  67. }
  68. // Options to customize the program during its initialization. These are
  69. // generally set with ProgramOptions.
  70. //
  71. // The options here are treated as bits.
  72. type startupOptions byte
  73. func (s startupOptions) has(option startupOptions) bool {
  74. return s&option != 0
  75. }
  76. const (
  77. withAltScreen startupOptions = 1 << iota
  78. withMouseCellMotion
  79. withMouseAllMotion
  80. withANSICompressor
  81. withoutSignalHandler
  82. // Catching panics is incredibly useful for restoring the terminal to a
  83. // usable state after a panic occurs. When this is set, Bubble Tea will
  84. // recover from panics, print the stack trace, and disable raw mode. This
  85. // feature is on by default.
  86. withoutCatchPanics
  87. )
  88. // handlers manages series of channels returned by various processes. It allows
  89. // us to wait for those processes to terminate before exiting the program.
  90. type handlers []chan struct{}
  91. // Adds a channel to the list of handlers. We wait for all handlers to terminate
  92. // gracefully on shutdown.
  93. func (h *handlers) add(ch chan struct{}) {
  94. *h = append(*h, ch)
  95. }
  96. // shutdown waits for all handlers to terminate.
  97. func (h handlers) shutdown() {
  98. var wg sync.WaitGroup
  99. for _, ch := range h {
  100. wg.Add(1)
  101. go func(ch chan struct{}) {
  102. <-ch
  103. wg.Done()
  104. }(ch)
  105. }
  106. wg.Wait()
  107. }
  108. // Program is a terminal user interface.
  109. type Program struct {
  110. initialModel Model
  111. // Configuration options that will set as the program is initializing,
  112. // treated as bits. These options can be set via various ProgramOptions.
  113. startupOptions startupOptions
  114. inputType inputType
  115. ctx context.Context
  116. cancel context.CancelFunc
  117. msgs chan Msg
  118. errs chan error
  119. finished chan struct{}
  120. // where to send output, this will usually be os.Stdout.
  121. output *termenv.Output
  122. restoreOutput func() error
  123. renderer renderer
  124. // where to read inputs from, this will usually be os.Stdin.
  125. input io.Reader
  126. cancelReader cancelreader.CancelReader
  127. readLoopDone chan struct{}
  128. console console.Console
  129. // was the altscreen active before releasing the terminal?
  130. altScreenWasActive bool
  131. ignoreSignals uint32
  132. // Stores the original reference to stdin for cases where input is not a
  133. // TTY on windows and we've automatically opened CONIN$ to receive input.
  134. // When the program exits this will be restored.
  135. //
  136. // Lint ignore note: the linter will find false positive on unix systems
  137. // as this value only comes into play on Windows, hence the ignore comment
  138. // below.
  139. windowsStdin *os.File //nolint:golint,structcheck,unused
  140. filter func(Model, Msg) Msg
  141. // fps is the frames per second we should set on the renderer, if
  142. // applicable,
  143. fps int
  144. }
  145. // Quit is a special command that tells the Bubble Tea program to exit.
  146. func Quit() Msg {
  147. return QuitMsg{}
  148. }
  149. // QuitMsg signals that the program should quit. You can send a QuitMsg with
  150. // Quit.
  151. type QuitMsg struct{}
  152. // NewProgram creates a new Program.
  153. func NewProgram(model Model, opts ...ProgramOption) *Program {
  154. p := &Program{
  155. initialModel: model,
  156. msgs: make(chan Msg),
  157. }
  158. // Apply all options to the program.
  159. for _, opt := range opts {
  160. opt(p)
  161. }
  162. // A context can be provided with a ProgramOption, but if none was provided
  163. // we'll use the default background context.
  164. if p.ctx == nil {
  165. p.ctx = context.Background()
  166. }
  167. // Initialize context and teardown channel.
  168. p.ctx, p.cancel = context.WithCancel(p.ctx)
  169. // if no output was set, set it to stdout
  170. if p.output == nil {
  171. p.output = termenv.DefaultOutput()
  172. // cache detected color values
  173. termenv.WithColorCache(true)(p.output)
  174. }
  175. p.restoreOutput, _ = termenv.EnableVirtualTerminalProcessing(p.output)
  176. return p
  177. }
  178. func (p *Program) handleSignals() chan struct{} {
  179. ch := make(chan struct{})
  180. // Listen for SIGINT and SIGTERM.
  181. //
  182. // In most cases ^C will not send an interrupt because the terminal will be
  183. // in raw mode and ^C will be captured as a keystroke and sent along to
  184. // Program.Update as a KeyMsg. When input is not a TTY, however, ^C will be
  185. // caught here.
  186. //
  187. // SIGTERM is sent by unix utilities (like kill) to terminate a process.
  188. go func() {
  189. sig := make(chan os.Signal, 1)
  190. signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
  191. defer func() {
  192. signal.Stop(sig)
  193. close(ch)
  194. }()
  195. for {
  196. select {
  197. case <-p.ctx.Done():
  198. return
  199. case <-sig:
  200. if atomic.LoadUint32(&p.ignoreSignals) == 0 {
  201. p.msgs <- QuitMsg{}
  202. return
  203. }
  204. }
  205. }
  206. }()
  207. return ch
  208. }
  209. // handleResize handles terminal resize events.
  210. func (p *Program) handleResize() chan struct{} {
  211. ch := make(chan struct{})
  212. if f, ok := p.output.TTY().(*os.File); ok && isatty.IsTerminal(f.Fd()) {
  213. // Get the initial terminal size and send it to the program.
  214. go p.checkResize()
  215. // Listen for window resizes.
  216. go p.listenForResize(ch)
  217. } else {
  218. close(ch)
  219. }
  220. return ch
  221. }
  222. // handleCommands runs commands in a goroutine and sends the result to the
  223. // program's message channel.
  224. func (p *Program) handleCommands(cmds chan Cmd) chan struct{} {
  225. ch := make(chan struct{})
  226. go func() {
  227. defer close(ch)
  228. for {
  229. select {
  230. case <-p.ctx.Done():
  231. return
  232. case cmd := <-cmds:
  233. if cmd == nil {
  234. continue
  235. }
  236. // Don't wait on these goroutines, otherwise the shutdown
  237. // latency would get too large as a Cmd can run for some time
  238. // (e.g. tick commands that sleep for half a second). It's not
  239. // possible to cancel them so we'll have to leak the goroutine
  240. // until Cmd returns.
  241. go func() {
  242. msg := cmd() // this can be long.
  243. p.Send(msg)
  244. }()
  245. }
  246. }
  247. }()
  248. return ch
  249. }
  250. func (p *Program) disableMouse() {
  251. p.renderer.disableMouseCellMotion()
  252. p.renderer.disableMouseAllMotion()
  253. p.renderer.disableMouseSGRMode()
  254. }
  255. // eventLoop is the central message loop. It receives and handles the default
  256. // Bubble Tea messages, update the model and triggers redraws.
  257. func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
  258. for {
  259. select {
  260. case <-p.ctx.Done():
  261. return model, nil
  262. case err := <-p.errs:
  263. return model, err
  264. case msg := <-p.msgs:
  265. // Filter messages.
  266. if p.filter != nil {
  267. msg = p.filter(model, msg)
  268. }
  269. if msg == nil {
  270. continue
  271. }
  272. // Handle special internal messages.
  273. switch msg := msg.(type) {
  274. case QuitMsg:
  275. return model, nil
  276. case clearScreenMsg:
  277. p.renderer.clearScreen()
  278. case enterAltScreenMsg:
  279. p.renderer.enterAltScreen()
  280. case exitAltScreenMsg:
  281. p.renderer.exitAltScreen()
  282. case enableMouseCellMotionMsg, enableMouseAllMotionMsg:
  283. switch msg.(type) {
  284. case enableMouseCellMotionMsg:
  285. p.renderer.enableMouseCellMotion()
  286. case enableMouseAllMotionMsg:
  287. p.renderer.enableMouseAllMotion()
  288. }
  289. // mouse mode (1006) is a no-op if the terminal doesn't support it.
  290. p.renderer.enableMouseSGRMode()
  291. case disableMouseMsg:
  292. p.disableMouse()
  293. case showCursorMsg:
  294. p.renderer.showCursor()
  295. case hideCursorMsg:
  296. p.renderer.hideCursor()
  297. case execMsg:
  298. // NB: this blocks.
  299. p.exec(msg.cmd, msg.fn)
  300. case BatchMsg:
  301. for _, cmd := range msg {
  302. cmds <- cmd
  303. }
  304. continue
  305. case sequenceMsg:
  306. go func() {
  307. // Execute commands one at a time, in order.
  308. for _, cmd := range msg {
  309. if cmd == nil {
  310. continue
  311. }
  312. msg := cmd()
  313. if batchMsg, ok := msg.(BatchMsg); ok {
  314. g, _ := errgroup.WithContext(p.ctx)
  315. for _, cmd := range batchMsg {
  316. cmd := cmd
  317. g.Go(func() error {
  318. p.Send(cmd())
  319. return nil
  320. })
  321. }
  322. //nolint:errcheck
  323. g.Wait() // wait for all commands from batch msg to finish
  324. continue
  325. }
  326. p.Send(msg)
  327. }
  328. }()
  329. case setWindowTitleMsg:
  330. p.SetWindowTitle(string(msg))
  331. }
  332. // Process internal messages for the renderer.
  333. if r, ok := p.renderer.(*standardRenderer); ok {
  334. r.handleMessages(msg)
  335. }
  336. var cmd Cmd
  337. model, cmd = model.Update(msg) // run update
  338. cmds <- cmd // process command (if any)
  339. p.renderer.write(model.View()) // send view to renderer
  340. }
  341. }
  342. }
  343. // Run initializes the program and runs its event loops, blocking until it gets
  344. // terminated by either [Program.Quit], [Program.Kill], or its signal handler.
  345. // Returns the final model.
  346. func (p *Program) Run() (Model, error) {
  347. handlers := handlers{}
  348. cmds := make(chan Cmd)
  349. p.errs = make(chan error)
  350. p.finished = make(chan struct{}, 1)
  351. defer p.cancel()
  352. switch p.inputType {
  353. case defaultInput:
  354. p.input = os.Stdin
  355. // The user has not set a custom input, so we need to check whether or
  356. // not standard input is a terminal. If it's not, we open a new TTY for
  357. // input. This will allow things to "just work" in cases where data was
  358. // piped in or redirected to the application.
  359. //
  360. // To disable input entirely pass nil to the [WithInput] program option.
  361. f, isFile := p.input.(*os.File)
  362. if !isFile {
  363. break
  364. }
  365. if isatty.IsTerminal(f.Fd()) {
  366. break
  367. }
  368. f, err := openInputTTY()
  369. if err != nil {
  370. return p.initialModel, err
  371. }
  372. defer f.Close() //nolint:errcheck
  373. p.input = f
  374. case ttyInput:
  375. // Open a new TTY, by request
  376. f, err := openInputTTY()
  377. if err != nil {
  378. return p.initialModel, err
  379. }
  380. defer f.Close() //nolint:errcheck
  381. p.input = f
  382. case customInput:
  383. // (There is nothing extra to do.)
  384. }
  385. // Handle signals.
  386. if !p.startupOptions.has(withoutSignalHandler) {
  387. handlers.add(p.handleSignals())
  388. }
  389. // Recover from panics.
  390. if !p.startupOptions.has(withoutCatchPanics) {
  391. defer func() {
  392. if r := recover(); r != nil {
  393. p.shutdown(true)
  394. fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)
  395. debug.PrintStack()
  396. return
  397. }
  398. }()
  399. }
  400. // If no renderer is set use the standard one.
  401. if p.renderer == nil {
  402. p.renderer = newRenderer(p.output, p.startupOptions.has(withANSICompressor), p.fps)
  403. }
  404. // Check if output is a TTY before entering raw mode, hiding the cursor and
  405. // so on.
  406. if err := p.initTerminal(); err != nil {
  407. return p.initialModel, err
  408. }
  409. // Honor program startup options.
  410. if p.startupOptions&withAltScreen != 0 {
  411. p.renderer.enterAltScreen()
  412. }
  413. if p.startupOptions&withMouseCellMotion != 0 {
  414. p.renderer.enableMouseCellMotion()
  415. p.renderer.enableMouseSGRMode()
  416. } else if p.startupOptions&withMouseAllMotion != 0 {
  417. p.renderer.enableMouseAllMotion()
  418. p.renderer.enableMouseSGRMode()
  419. }
  420. // Initialize the program.
  421. model := p.initialModel
  422. if initCmd := model.Init(); initCmd != nil {
  423. ch := make(chan struct{})
  424. handlers.add(ch)
  425. go func() {
  426. defer close(ch)
  427. select {
  428. case cmds <- initCmd:
  429. case <-p.ctx.Done():
  430. }
  431. }()
  432. }
  433. // Start the renderer.
  434. p.renderer.start()
  435. // Render the initial view.
  436. p.renderer.write(model.View())
  437. // Subscribe to user input.
  438. if p.input != nil {
  439. if err := p.initCancelReader(); err != nil {
  440. return model, err
  441. }
  442. }
  443. // Handle resize events.
  444. handlers.add(p.handleResize())
  445. // Process commands.
  446. handlers.add(p.handleCommands(cmds))
  447. // Run event loop, handle updates and draw.
  448. model, err := p.eventLoop(model, cmds)
  449. killed := p.ctx.Err() != nil
  450. if killed {
  451. err = ErrProgramKilled
  452. } else {
  453. // Ensure we rendered the final state of the model.
  454. p.renderer.write(model.View())
  455. }
  456. // Tear down.
  457. p.cancel()
  458. // Check if the cancel reader has been setup before waiting and closing.
  459. if p.cancelReader != nil {
  460. // Wait for input loop to finish.
  461. if p.cancelReader.Cancel() {
  462. p.waitForReadLoop()
  463. }
  464. _ = p.cancelReader.Close()
  465. }
  466. // Wait for all handlers to finish.
  467. handlers.shutdown()
  468. // Restore terminal state.
  469. p.shutdown(killed)
  470. return model, err
  471. }
  472. // StartReturningModel initializes the program and runs its event loops,
  473. // blocking until it gets terminated by either [Program.Quit], [Program.Kill],
  474. // or its signal handler. Returns the final model.
  475. //
  476. // Deprecated: please use [Program.Run] instead.
  477. func (p *Program) StartReturningModel() (Model, error) {
  478. return p.Run()
  479. }
  480. // Start initializes the program and runs its event loops, blocking until it
  481. // gets terminated by either [Program.Quit], [Program.Kill], or its signal
  482. // handler.
  483. //
  484. // Deprecated: please use [Program.Run] instead.
  485. func (p *Program) Start() error {
  486. _, err := p.Run()
  487. return err
  488. }
  489. // Send sends a message to the main update function, effectively allowing
  490. // messages to be injected from outside the program for interoperability
  491. // purposes.
  492. //
  493. // If the program hasn't started yet this will be a blocking operation.
  494. // If the program has already been terminated this will be a no-op, so it's safe
  495. // to send messages after the program has exited.
  496. func (p *Program) Send(msg Msg) {
  497. select {
  498. case <-p.ctx.Done():
  499. case p.msgs <- msg:
  500. }
  501. }
  502. // Quit is a convenience function for quitting Bubble Tea programs. Use it
  503. // when you need to shut down a Bubble Tea program from the outside.
  504. //
  505. // If you wish to quit from within a Bubble Tea program use the Quit command.
  506. //
  507. // If the program is not running this will be a no-op, so it's safe to call
  508. // if the program is unstarted or has already exited.
  509. func (p *Program) Quit() {
  510. p.Send(Quit())
  511. }
  512. // Kill stops the program immediately and restores the former terminal state.
  513. // The final render that you would normally see when quitting will be skipped.
  514. // [program.Run] returns a [ErrProgramKilled] error.
  515. func (p *Program) Kill() {
  516. p.cancel()
  517. }
  518. // Wait waits/blocks until the underlying Program finished shutting down.
  519. func (p *Program) Wait() {
  520. <-p.finished
  521. }
  522. // shutdown performs operations to free up resources and restore the terminal
  523. // to its original state.
  524. func (p *Program) shutdown(kill bool) {
  525. if p.renderer != nil {
  526. if kill {
  527. p.renderer.kill()
  528. } else {
  529. p.renderer.stop()
  530. }
  531. }
  532. _ = p.restoreTerminalState()
  533. if p.restoreOutput != nil {
  534. _ = p.restoreOutput()
  535. }
  536. p.finished <- struct{}{}
  537. }
  538. // ReleaseTerminal restores the original terminal state and cancels the input
  539. // reader. You can return control to the Program with RestoreTerminal.
  540. func (p *Program) ReleaseTerminal() error {
  541. atomic.StoreUint32(&p.ignoreSignals, 1)
  542. p.cancelReader.Cancel()
  543. p.waitForReadLoop()
  544. if p.renderer != nil {
  545. p.renderer.stop()
  546. }
  547. p.altScreenWasActive = p.renderer.altScreen()
  548. return p.restoreTerminalState()
  549. }
  550. // RestoreTerminal reinitializes the Program's input reader, restores the
  551. // terminal to the former state when the program was running, and repaints.
  552. // Use it to reinitialize a Program after running ReleaseTerminal.
  553. func (p *Program) RestoreTerminal() error {
  554. atomic.StoreUint32(&p.ignoreSignals, 0)
  555. if err := p.initTerminal(); err != nil {
  556. return err
  557. }
  558. if err := p.initCancelReader(); err != nil {
  559. return err
  560. }
  561. if p.altScreenWasActive {
  562. p.renderer.enterAltScreen()
  563. } else {
  564. // entering alt screen already causes a repaint.
  565. go p.Send(repaintMsg{})
  566. }
  567. if p.renderer != nil {
  568. p.renderer.start()
  569. }
  570. // If the output is a terminal, it may have been resized while another
  571. // process was at the foreground, in which case we may not have received
  572. // SIGWINCH. Detect any size change now and propagate the new size as
  573. // needed.
  574. go p.checkResize()
  575. return nil
  576. }
  577. // Println prints above the Program. This output is unmanaged by the program
  578. // and will persist across renders by the Program.
  579. //
  580. // If the altscreen is active no output will be printed.
  581. func (p *Program) Println(args ...interface{}) {
  582. p.msgs <- printLineMessage{
  583. messageBody: fmt.Sprint(args...),
  584. }
  585. }
  586. // Printf prints above the Program. It takes a format template followed by
  587. // values similar to fmt.Printf. This output is unmanaged by the program and
  588. // will persist across renders by the Program.
  589. //
  590. // Unlike fmt.Printf (but similar to log.Printf) the message will be print on
  591. // its own line.
  592. //
  593. // If the altscreen is active no output will be printed.
  594. func (p *Program) Printf(template string, args ...interface{}) {
  595. p.msgs <- printLineMessage{
  596. messageBody: fmt.Sprintf(template, args...),
  597. }
  598. }