-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtea.go
More file actions
1418 lines (1214 loc) Β· 38.9 KB
/
tea.go
File metadata and controls
1418 lines (1214 loc) Β· 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package tea provides a framework for building rich terminal user interfaces
// based on the paradigms of The Elm Architecture. It's well-suited for simple
// and complex terminal applications, either inline, full-window, or a mix of
// both. It's been battle-tested in several large projects and is
// production-ready.
//
// A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/master/tutorials
//
// Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/master/examples
package tea
import (
"bytes"
"context"
"errors"
"fmt"
"image/color"
"io"
"log"
"os"
"os/signal"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/charmbracelet/colorprofile"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
"github.com/muesli/cancelreader"
)
// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.
var ErrProgramPanic = errors.New("program experienced a panic")
// ErrProgramKilled is returned by [Program.Run] when the program gets killed.
var ErrProgramKilled = errors.New("program was killed")
// ErrInterrupted is returned by [Program.Run] when the program get a SIGINT
// signal, or when it receives a [InterruptMsg].
var ErrInterrupted = errors.New("program was interrupted")
// Msg contain data from the result of a IO operation. Msgs trigger the update
// function and, henceforth, the UI.
type Msg = uv.Event
// Model contains the program's state as well as its core functions.
type Model interface {
// Init is the first function that will be called. It returns an optional
// initial command. To not perform an initial command return nil.
Init() Cmd
// Update is called when a message is received. Use it to inspect messages
// and, in response, update the model and/or send a command.
Update(Msg) (Model, Cmd)
// View renders the program's UI, which can be a string or a [Layer]. The
// view is rendered after every Update.
View() View
}
// NewView is a helper function to create a new [View] with the given styled
// string. A styled string represents text with styles and hyperlinks encoded
// as ANSI escape codes.
//
// Example:
//
// ```go
// v := tea.NewView("Hello, World!")
// ```
func NewView(s string) View {
var view View
view.SetContent(s)
return view
}
// View represents a terminal view that can be composed of multiple layers.
// It can also contain a cursor that will be rendered on top of the layers.
type View struct {
// Content is the screen content of the view. It holds styled strings that
// will be rendered to the terminal when the view is rendered.
//
// A styled string represents text with styles and hyperlinks encoded as
// ANSI escape codes.
//
// Example:
//
// ```go
// v := tea.NewView("Hello, World!")
// ```
Content string
// OnMouse is an optional mouse message handler that can be used to
// intercept mouse messages that depends on view content from last render.
// It can be useful for implementing view-specific behavior without
// breaking the unidirectional data flow of Bubble Tea.
//
// Example:
//
// ```go
// content := "Hello, World!"
// v := tea.NewView(content)
// v.OnMouse = func(msg tea.MouseMsg) tea.Cmd {
// return func() tea.Msg {
// m := msg.Mouse()
// // Check if the mouse is within the bounds of "World!"
// start := strings.Index(content, "World!")
// end := start + len("World!")
// if m.Y == 0 && m.X >= start && m.X < end {
// // Mouse is over "World!"
// return MyCustomMsg{
// MouseMsg: msg,
// }
// }
// }
// }
// return nil
// }
// return v
// ```
OnMouse func(msg MouseMsg) Cmd
// Cursor represents the cursor position, style, and visibility on the
// screen. When not nil, the cursor will be shown at the specified
// position.
Cursor *Cursor
// BackgroundColor when not nil, sets the terminal background color. Use
// nil to reset to the terminal's default background color.
BackgroundColor color.Color
// ForegroundColor when not nil, sets the terminal foreground color. Use
// nil to reset to the terminal's default foreground color.
ForegroundColor color.Color
// WindowTitle sets the terminal window title. Support depends on the
// terminal.
WindowTitle string
// ProgressBar when not nil, shows a progress bar in the terminal's
// progress bar section. Support depends on the terminal.
ProgressBar *ProgressBar
// AltScreen puts the program in the alternate screen buffer
// (i.e. the program goes into full window mode). Note that the altscreen will
// be automatically exited when the program quits.
//
// Example:
//
// func (m model) View() tea.View {
// v := tea.NewView("Hello, World!")
// v.AltScreen = true
// return v
// }
//
AltScreen bool
// ReportFocus enables reporting when the terminal gains and loses focus.
// When this is enabled [FocusMsg] and [BlurMsg] messages will be sent to
// your Update method.
//
// Note that while most terminals and multiplexers support focus reporting,
// some do not. Also note that tmux needs to be configured to report focus
// events.
ReportFocus bool
// DisableBracketedPasteMode disables bracketed paste mode for this view.
DisableBracketedPasteMode bool
// MouseMode sets the mouse mode for this view. It can be one of
// [MouseModeNone], [MouseModeCellMotion], or [MouseModeAllMotion].
MouseMode MouseMode
// KeyboardEnhancements describes what keyboard enhancement features Bubble
// Tea should request from the terminal.
//
// Bubble Tea supports requesting the following keyboard enhancement features:
// - ReportEventTypes: requests the terminal to report key repeat and
// release events.
//
// If the terminal supports any of these features, your program will
// receive a [KeyboardEnhancementsMsg] that indicates which features are
// available.
KeyboardEnhancements KeyboardEnhancements
}
// KeyboardEnhancements describes the requested keyboard enhancement features.
// If the terminal supports any of them, it will respond with a
// [KeyboardEnhancementsMsg] that indicates which features are supported.
// KeyboardEnhancements defines different keyboard enhancement features that
// can be requested from the terminal.
// KeyboardEnhancements defines different keyboard enhancement features that
// can be requested from the terminal.
//
// By default, Bubble Tea requests basic key disambiguation features from the
// terminal. If the terminal supports keyboard enhancements, or any of its
// additional features, it will respond with a [KeyboardEnhancementsMsg] that
// indicates which features are supported.
//
// Example:
//
// ```go
// func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// switch msg := msg.(type) {
// case tea.KeyboardEnhancementsMsg:
// // We have basic key disambiguation support.
// // We can handle "shift+enter", "ctrl+i", etc.
// m.keyboardEnhancements = msg
// if msg.ReportEventTypes {
// // Even better! We can now handle key repeat and release events.
// }
// case tea.KeyPressMsg:
// switch msg.String() {
// case "shift+enter":
// // Handle shift+enter
// // This would not be possible without keyboard enhancements.
// case "ctrl+j":
// // Handle ctrl+j
// }
// case tea.KeyReleaseMsg:
// // Whoa! A key was released!
// }
//
// return m, nil
// }
//
// func (m model) View() tea.View {
// v := tea.NewView("Press some keys!")
// // Request reporting key repeat and release events.
// v.KeyboardEnhancements.ReportEventTypes = true
// return v
// }
// ```
type KeyboardEnhancements struct {
// ReportEventTypes requests the terminal to report key repeat and release
// events.
// If supported, your program will receive [KeyReleaseMsg]s and
// [KeyPressMsg] with the [Key.IsRepeat] field set indicating that this is
// a it's part of a key repeat sequence.
ReportEventTypes bool
}
// SetContent is a helper method to set the content of a [View] with a styled
// string. A styled string represents text with styles and hyperlinks encoded
// as ANSI escape codes.
//
// Example:
//
// ```go
// var v tea.View
// v.SetContent("Hello, World!")
// ```
func (v *View) SetContent(s string) {
v.Content = s
}
// MouseMode represents the mouse mode of a view.
type MouseMode int
const (
// MouseModeNone disables mouse events.
MouseModeNone MouseMode = iota
// MouseModeCellMotion enables mouse click, release, and wheel events.
// Mouse movement events are also captured if a mouse button is pressed
// (i.e., drag events). Cell motion mode is better supported than all
// motion mode.
//
// This will try to enable the mouse in extended mode (SGR), if that is not
// supported by the terminal it will fall back to normal mode (X10).
MouseModeCellMotion
// MouseModeAllMotion enables all mouse events, including click, release,
// wheel, and movement events. You will receive mouse movement events even
// when no buttons are pressed.
//
// This will try to enable the mouse in extended mode (SGR), if that is not
// supported by the terminal it will fall back to normal mode (X10).
MouseModeAllMotion
)
// ProgressBarState represents the state of the progress bar.
type ProgressBarState int
// Progress bar states.
const (
ProgressBarNone ProgressBarState = iota
ProgressBarDefault
ProgressBarError
ProgressBarIndeterminate
ProgressBarWarning
)
// String return a human-readable value for the given [ProgressBarState].
func (s ProgressBarState) String() string {
return [...]string{
"None",
"Default",
"Error",
"Indeterminate",
"Warning",
}[s]
}
// ProgressBar represents the terminal progress bar.
//
// Support depends on the terminal.
//
// See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences
type ProgressBar struct {
// State is the current state of the progress bar. It can be one of
// [ProgressBarNone], [ProgressBarDefault], [ProgressBarError],
// [ProgressBarIndeterminate], and [ProgressBarWarn].
State ProgressBarState
// Value is the current value of the progress bar. It should be between
// 0 and 100.
Value int
}
// NewProgressBar returns a new progress bar with the given state and value.
// The value is ignored if the state is [ProgressBarNone] or
// [ProgressBarIndeterminate].
func NewProgressBar(state ProgressBarState, value int) *ProgressBar {
return &ProgressBar{
State: state,
Value: min(max(value, 0), 100),
}
}
// Cursor represents a cursor on the terminal screen.
type Cursor struct {
// Position is a [Position] that determines the cursor's position on the
// screen relative to the top left corner of the frame.
Position
// Color is a [color.Color] that determines the cursor's color.
Color color.Color
// Shape is a [CursorShape] that determines the cursor's shape.
Shape CursorShape
// Blink is a boolean that determines whether the cursor should blink.
Blink bool
}
// NewCursor returns a new cursor with the default settings and the given
// position.
func NewCursor(x, y int) *Cursor {
return &Cursor{
Position: Position{X: x, Y: y},
Color: nil,
Shape: CursorBlock,
Blink: true,
}
}
// Cmd is an IO operation that returns a message when it's complete. If it's
// nil it's considered a no-op. Use it for things like HTTP requests, timers,
// saving and loading from disk, and so on.
//
// Note that there's almost never a reason to use a command to send a message
// to another part of your program. That can almost always be done in the
// update function.
type Cmd func() Msg
// channelHandlers manages the series of channels returned by various processes.
// It allows us to wait for those processes to terminate before exiting the
// program.
type channelHandlers struct {
handlers []chan struct{}
mu sync.RWMutex
}
// Adds a channel to the list of handlers. We wait for all handlers to terminate
// gracefully on shutdown.
func (h *channelHandlers) add(ch chan struct{}) {
h.mu.Lock()
h.handlers = append(h.handlers, ch)
h.mu.Unlock()
}
// shutdown waits for all handlers to terminate.
func (h *channelHandlers) shutdown() {
var wg sync.WaitGroup
h.mu.RLock()
defer h.mu.RUnlock()
for _, ch := range h.handlers {
wg.Add(1)
go func(ch chan struct{}) {
<-ch
wg.Done()
}(ch)
}
wg.Wait()
}
// Program is a terminal user interface.
type Program struct {
// disableInput disables all input. This is useful for programs that
// don't need input, like a progress bar or a spinner.
disableInput bool
// disableSignalHandler disables the signal handler that Bubble Tea sets up
// for Programs. This is useful if you want to handle signals yourself.
disableSignalHandler bool
// disableCatchPanics disables the panic catching that Bubble Tea does by
// default. If panic catching is disabled the terminal will be in a fairly
// unusable state after a panic because Bubble Tea will not perform its usual
// cleanup on exit.
disableCatchPanics bool
// filter supplies an event filter that will be invoked before Bubble Tea
// processes a tea.Msg. The event filter can return any tea.Msg which will
// then get handled by Bubble Tea instead of the original event. If the
// event filter returns nil, the event will be ignored and Bubble Tea will
// not process it.
//
// As an example, this could be used to prevent a program from shutting
// down if there are unsaved changes.
//
// Example:
//
// func filter(m tea.Model, msg tea.Msg) tea.Msg {
// if _, ok := msg.(tea.QuitMsg); !ok {
// return msg
// }
//
// model := m.(myModel)
// if model.hasChanges {
// return nil
// }
//
// return msg
// }
//
// p := tea.NewProgram(Model{});
// p.filter = filter
//
// if _,err := p.Run(context.Background()); err != nil {
// fmt.Println("Error running program:", err)
// os.Exit(1)
// }
filter func(Model, Msg) Msg
// fps sets a custom maximum fps at which the renderer should run. If less
// than 1, the default value of 60 will be used. If over 120, the fps will
// be capped at 120.
fps int
// initialModel is the initial model for the program and is the only
// required field when creating a new program.
initialModel Model
// disableRenderer prevents the program from rendering to the terminal.
// This can be useful for running daemon-like programs that don't require a
// UI but still want to take advantage of Bubble Tea's architecture.
disableRenderer bool
// handlers is a list of channels that need to be waited on before the
// program can exit.
handlers channelHandlers
// ctx is the programs's internal context for signalling internal teardown.
// It is built and derived from the externalCtx in NewProgram().
ctx context.Context
cancel context.CancelFunc
// externalCtx is a context that was passed in via WithContext, otherwise defaulting
// to ctx.Background() (in case it was not), the internal context is derived from it.
externalCtx context.Context
msgs chan Msg
errs chan error
finished chan struct{}
shutdownOnce sync.Once
profile *colorprofile.Profile // the terminal color profile
// where to send output, this will usually be os.Stdout.
output io.Writer
outputBuf bytes.Buffer // buffer used to queue commands to be sent to the output
// ttyOutput is null if output is not a TTY.
ttyOutput term.File
previousOutputState *term.State
renderer renderer
// the environment variables for the program, defaults to os.Environ().
environ uv.Environ
// the program's logger for debugging.
logger uv.Logger
// where to read inputs from, this will usually be os.Stdin.
input io.Reader
// ttyInput is null if input is not a TTY.
ttyInput term.File
previousTtyInputState *term.State
cancelReader cancelreader.CancelReader
inputScanner *uv.TerminalReader
readLoopDone chan struct{}
// modes keeps track of terminal modes that have been enabled or disabled.
ignoreSignals uint32
// ticker is the ticker that will be used to write to the renderer.
ticker *time.Ticker
// once is used to stop the renderer.
once sync.Once
// rendererDone is used to stop the renderer.
rendererDone chan struct{}
// Initial window size. Mainly used for testing.
width, height int
// whether to use hard tabs to optimize cursor movements
useHardTabs bool
// whether to use backspace to optimize cursor movements
useBackspace bool
mu sync.Mutex
}
// Quit is a special command that tells the Bubble Tea program to exit.
func Quit() Msg {
return QuitMsg{}
}
// QuitMsg signals that the program should quit. You can send a [QuitMsg] with
// [Quit].
type QuitMsg struct{}
// Suspend is a special command that tells the Bubble Tea program to suspend.
func Suspend() Msg {
return SuspendMsg{}
}
// SuspendMsg signals the program should suspend.
// This usually happens when ctrl+z is pressed on common programs, but since
// bubbletea puts the terminal in raw mode, we need to handle it in a
// per-program basis.
//
// You can send this message with [Suspend()].
type SuspendMsg struct{}
// ResumeMsg can be listen to do something once a program is resumed back
// from a suspend state.
type ResumeMsg struct{}
// InterruptMsg signals the program should suspend.
// This usually happens when ctrl+c is pressed on common programs, but since
// bubbletea puts the terminal in raw mode, we need to handle it in a
// per-program basis.
//
// You can send this message with [Interrupt()].
type InterruptMsg struct{}
// Interrupt is a special command that tells the Bubble Tea program to
// interrupt.
func Interrupt() Msg {
return InterruptMsg{}
}
// NewProgram creates a new [Program].
func NewProgram(model Model, opts ...ProgramOption) *Program {
p := &Program{
initialModel: model,
msgs: make(chan Msg),
errs: make(chan error, 1),
rendererDone: make(chan struct{}),
}
// Apply all options to the program.
for _, opt := range opts {
opt(p)
}
// A context can be provided with a ProgramOption, but if none was provided
// we'll use the default background context.
if p.externalCtx == nil {
p.externalCtx = context.Background()
}
// Initialize context and teardown channel.
p.ctx, p.cancel = context.WithCancel(p.externalCtx)
// if no output was set, set it to stdout
if p.output == nil {
p.output = os.Stdout
}
// if no environment was set, set it to os.Environ()
if p.environ == nil {
p.environ = os.Environ()
}
if p.fps < 1 {
p.fps = defaultFPS
} else if p.fps > maxFPS {
p.fps = maxFPS
}
tracePath, traceOk := os.LookupEnv("TEA_TRACE")
if traceOk && len(tracePath) > 0 {
// We have a trace filepath.
if f, err := os.OpenFile(tracePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600); err == nil {
p.logger = log.New(f, "bubbletea: ", log.LstdFlags|log.Lshortfile)
}
}
return p
}
func (p *Program) handleSignals() chan struct{} {
ch := make(chan struct{})
// Listen for SIGINT and SIGTERM.
//
// In most cases ^C will not send an interrupt because the terminal will be
// in raw mode and ^C will be captured as a keystroke and sent along to
// Program.Update as a KeyMsg. When input is not a TTY, however, ^C will be
// caught here.
//
// SIGTERM is sent by unix utilities (like kill) to terminate a process.
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
defer func() {
signal.Stop(sig)
close(ch)
}()
for {
select {
case <-p.ctx.Done():
return
case s := <-sig:
if atomic.LoadUint32(&p.ignoreSignals) == 0 {
switch s {
case syscall.SIGINT:
p.msgs <- InterruptMsg{}
default:
p.msgs <- QuitMsg{}
}
return
}
}
}
}()
return ch
}
// handleResize handles terminal resize events.
func (p *Program) handleResize() chan struct{} {
ch := make(chan struct{})
if p.ttyOutput != nil {
// Listen for window resizes.
go p.listenForResize(ch)
} else {
close(ch)
}
return ch
}
// handleCommands runs commands in a goroutine and sends the result to the
// program's message channel.
func (p *Program) handleCommands(cmds chan Cmd) chan struct{} {
ch := make(chan struct{})
go func() {
defer close(ch)
for {
select {
case <-p.ctx.Done():
return
case cmd := <-cmds:
if cmd == nil {
continue
}
// Don't wait on these goroutines, otherwise the shutdown
// latency would get too large as a Cmd can run for some time
// (e.g. tick commands that sleep for half a second). It's not
// possible to cancel them so we'll have to leak the goroutine
// until Cmd returns.
go func() {
// Recover from panics.
if !p.disableCatchPanics {
defer func() {
if r := recover(); r != nil {
p.recoverFromPanic(r)
}
}()
}
msg := cmd() // this can be long.
p.Send(msg)
}()
}
}
}()
return ch
}
// eventLoop is the central message loop. It receives and handles the default
// Bubble Tea messages, update the model and triggers redraws.
func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
for {
select {
case <-p.ctx.Done():
return model, nil
case err := <-p.errs:
return model, err
case msg := <-p.msgs:
msg = p.translateInputEvent(msg)
// Filter messages.
if p.filter != nil {
msg = p.filter(model, msg)
}
if msg == nil {
continue
}
// Handle special internal messages.
switch msg := msg.(type) {
case QuitMsg:
return model, nil
case InterruptMsg:
return model, ErrInterrupted
case SuspendMsg:
if suspendSupported {
p.suspend()
}
case CapabilityMsg:
switch msg.Content {
case "RGB", "Tc":
if *p.profile != colorprofile.TrueColor {
tc := colorprofile.TrueColor
p.profile = &tc
go p.Send(ColorProfileMsg{*p.profile})
}
}
case ModeReportMsg:
switch msg.Mode {
case ansi.ModeSynchronizedOutput:
if msg.Value == ansi.ModeReset {
// The terminal supports synchronized output and it's
// currently disabled, so we can enable it on the renderer.
p.renderer.setSyncdUpdates(true)
}
case ansi.ModeUnicodeCore:
if msg.Value == ansi.ModeReset || msg.Value == ansi.ModeSet || msg.Value == ansi.ModePermanentlySet {
p.renderer.setWidthMethod(ansi.GraphemeWidth)
}
}
case MouseMsg:
switch msg.(type) {
case MouseClickMsg, MouseReleaseMsg, MouseWheelMsg, MouseMotionMsg:
// Only send mouse messages to the renderer if they are an
// actual mouse event.
if cmd := p.renderer.onMouse(msg); cmd != nil {
go p.Send(cmd())
}
}
case readClipboardMsg:
p.execute(ansi.RequestSystemClipboard)
case setClipboardMsg:
p.execute(ansi.SetSystemClipboard(string(msg)))
case readPrimaryClipboardMsg:
p.execute(ansi.RequestPrimaryClipboard)
case setPrimaryClipboardMsg:
p.execute(ansi.SetPrimaryClipboard(string(msg)))
case backgroundColorMsg:
p.execute(ansi.RequestBackgroundColor)
case foregroundColorMsg:
p.execute(ansi.RequestForegroundColor)
case cursorColorMsg:
p.execute(ansi.RequestCursorColor)
case execMsg:
// NB: this blocks.
p.exec(msg.cmd, msg.fn)
case terminalVersion:
p.execute(ansi.RequestNameVersion)
case requestCapabilityMsg:
p.execute(ansi.RequestTermcap(string(msg)))
case BatchMsg:
go p.execBatchMsg(msg)
continue
case sequenceMsg:
go p.execSequenceMsg(msg)
continue
case WindowSizeMsg:
p.renderer.resize(msg.Width, msg.Height)
case windowSizeMsg:
go p.checkResize()
case requestCursorPosMsg:
p.execute(ansi.RequestCursorPositionReport)
case RawMsg:
p.execute(fmt.Sprint(msg.Msg))
case printLineMessage:
p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec
case clearScreenMsg:
p.renderer.clearScreen()
case ColorProfileMsg:
p.renderer.setColorProfile(msg.Profile)
}
var cmd Cmd
model, cmd = model.Update(msg) // run update
select {
case <-p.ctx.Done():
return model, nil
case cmds <- cmd: // process command (if any)
}
p.render(model) // render view
}
}
}
// render renders the given view to the renderer.
func (p *Program) render(model Model) {
if p.renderer != nil {
p.renderer.render(model.View()) // send view to renderer
}
}
func (p *Program) execSequenceMsg(msg sequenceMsg) {
if !p.disableCatchPanics {
defer func() {
if r := recover(); r != nil {
p.recoverFromGoPanic(r)
}
}()
}
// Execute commands one at a time, in order.
for _, cmd := range msg {
if cmd == nil {
continue
}
msg := cmd()
switch msg := msg.(type) {
case BatchMsg:
p.execBatchMsg(msg)
case sequenceMsg:
p.execSequenceMsg(msg)
default:
p.Send(msg)
}
}
}
func (p *Program) execBatchMsg(msg BatchMsg) {
if !p.disableCatchPanics {
defer func() {
if r := recover(); r != nil {
p.recoverFromGoPanic(r)
}
}()
}
// Execute commands one at a time.
var wg sync.WaitGroup
for _, cmd := range msg {
if cmd == nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
if !p.disableCatchPanics {
defer func() {
if r := recover(); r != nil {
p.recoverFromGoPanic(r)
}
}()
}
msg := cmd()
switch msg := msg.(type) {
case BatchMsg:
p.execBatchMsg(msg)
case sequenceMsg:
p.execSequenceMsg(msg)
default:
p.Send(msg)
}
}()
}
wg.Wait() // wait for all commands from batch msg to finish
}
// shouldQuerySynchronizedOutput determines whether the terminal should be
// queried for various capabilities.
//
// This function checks for terminals that are known to support mode 2026,
// while excluding SSH sessions which may be unreliable, unless it's a
// known-good terminal like Windows Terminal.
//
// The function returns true for:
// - Terminals without TERM_PROGRAM set and not in SSH sessions
// - Windows Terminal (WT_SESSION is set)
// - Terminals with TERM_PROGRAM set (except Apple Terminal) and not in SSH sessions
// - Specific terminal types: ghostty, wezterm, alacritty, kitty, rio
func shouldQuerySynchronizedOutput(environ uv.Environ) bool {
termType := environ.Getenv("TERM")
termProg, okTermProg := environ.LookupEnv("TERM_PROGRAM")
_, okSSHTTY := environ.LookupEnv("SSH_TTY")
_, okWTSession := environ.LookupEnv("WT_SESSION")
return (!okTermProg && !okSSHTTY) ||
okWTSession ||
(okTermProg && !strings.Contains(termProg, "Apple") && !okSSHTTY) ||
strings.Contains(termType, "ghostty") ||
strings.Contains(termType, "wezterm") ||
strings.Contains(termType, "alacritty") ||
strings.Contains(termType, "kitty") ||
strings.Contains(termType, "rio")
}
// Run initializes the program and runs its event loops, blocking until it gets
// terminated by either [Program.Quit], [Program.Kill], or its signal handler.
// Returns the final model.
func (p *Program) Run() (returnModel Model, returnErr error) {
if p.initialModel == nil {
return nil, errors.New("bubbletea: InitialModel cannot be nil")
}
// Initialize context and teardown channel.
p.handlers = channelHandlers{}
cmds := make(chan Cmd)
p.finished = make(chan struct{})
defer func() {
close(p.finished)
}()
defer p.cancel()
if p.disableInput {
p.input = nil
} else if p.input == nil {
p.input = os.Stdin
if !term.IsTerminal(os.Stdin.Fd()) {
ttyIn, _, err := OpenTTY()
if err != nil {
return p.initialModel, fmt.Errorf("bubbletea: error opening TTY: %w", err)
}
p.input = ttyIn
}
}