tea.go 17 KB

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