tty.go
This file
Path
tty.go
176 lines · 3.9 KiB · Go
Last changed by
fix(tty): fall back to default dimensions when terminal size is 0x0 (#1836)adam maguedbefore adoption96d69d2
History of this fileTake it
1package tea23import (4 "fmt"5 "os"6 "strconv"7 "time"89 uv "github.com/charmbracelet/ultraviolet"10 "github.com/charmbracelet/x/term"11)1213func (p *Program) suspend() {14 if err := p.releaseTerminal(true); err != nil {15 // If we can't release input, abort.16 return17 }1819 suspendProcess()2021 _ = p.RestoreTerminal()22 go p.Send(ResumeMsg{})23}2425func (p *Program) initTerminal() error {26 if p.disableRenderer {27 return nil28 }29 return p.initInput()30}3132// restoreTerminalState restores the terminal to the state prior to running the33// Bubble Tea program.34func (p *Program) restoreTerminalState() error {35 // Flush queued commands.36 _ = p.flush()3738 return p.restoreInput()39}4041// restoreInput restores the tty input to its original state.42func (p *Program) restoreInput() error {43 if p.ttyInput != nil && p.previousTtyInputState != nil {44 if err := term.Restore(p.ttyInput.Fd(), p.previousTtyInputState); err != nil {45 return fmt.Errorf("bubbletea: error restoring console: %w", err)46 }47 }48 if p.ttyOutput != nil && p.previousOutputState != nil {49 if err := term.Restore(p.ttyOutput.Fd(), p.previousOutputState); err != nil {50 return fmt.Errorf("bubbletea: error restoring console: %w", err)51 }52 }53 return nil54}5556// initInputReader (re)commences reading inputs.57func (p *Program) initInputReader(cancel bool) error {58 if cancel && p.cancelReader != nil {59 p.cancelReader.Cancel()60 p.waitForReadLoop()61 }6263 term := p.environ.Getenv("TERM")6465 // Initialize the input reader.66 // This need to be done after the terminal has been initialized and set to67 // raw mode.6869 var err error70 p.cancelReader, err = uv.NewCancelReader(p.input)71 if err != nil {72 return fmt.Errorf("bubbletea: could not create cancelable reader: %w", err)73 }7475 drv := uv.NewTerminalReader(p.cancelReader, term)76 drv.SetLogger(p.logger)77 p.inputScanner = drv78 p.readLoopDone = make(chan struct{})7980 go p.readLoop()8182 return nil83}8485func (p *Program) readLoop() {86 defer close(p.readLoopDone)8788 if err := p.inputScanner.StreamEvents(p.ctx, p.msgs); err != nil {89 select {90 case <-p.ctx.Done():91 return92 case p.errs <- err:93 }94 }95}9697// waitForReadLoop waits for the cancelReader to finish its read loop.98func (p *Program) waitForReadLoop() {99 select {100 case <-p.readLoopDone:101 case <-time.After(500 * time.Millisecond): //nolint:mnd102 // The read loop hangs, which means the input103 // cancelReader's cancel function has returned true even104 // though it was not able to cancel the read.105 }106}107108const (109 defaultWidth = 80110 defaultHeight = 24111)112113// fallbackDimensions returns width and height, falling back to COLUMNS/LINES114// environment variables or 80x24 defaults when dimensions are non-positive.115func (p *Program) fallbackDimensions(width, height int) (int, int) {116 if width <= 0 {117 var cols string118 if p != nil && p.environ != nil {119 cols = p.environ.Getenv("COLUMNS")120 } else {121 cols = os.Getenv("COLUMNS")122 }123 if c, err := strconv.Atoi(cols); err == nil && c > 0 {124 width = c125 } else {126 width = defaultWidth127 }128 }129 if height <= 0 {130 var lines string131 if p != nil && p.environ != nil {132 lines = p.environ.Getenv("LINES")133 } else {134 lines = os.Getenv("LINES")135 }136 if l, err := strconv.Atoi(lines); err == nil && l > 0 {137 height = l138 } else {139 height = defaultHeight140 }141 }142 return width, height143}144145// checkResize detects the current size of the output and informs the program146// via a WindowSizeMsg.147func (p *Program) checkResize() {148 if p.ttyOutput == nil {149 // can't query window size150 return151 }152153 w, h, err := term.GetSize(p.ttyOutput.Fd())154 if err != nil {155 select {156 case <-p.ctx.Done():157 case p.errs <- err:158 }159160 return161 }162163 w, h = p.fallbackDimensions(w, h)164165 p.width, p.height = w, h166 p.Send(WindowSizeMsg{Width: w, Height: h})167}168169// OpenTTY opens the running terminal's TTY for reading and writing.170func OpenTTY() (*os.File, *os.File, error) {171 in, out, err := uv.OpenTTY()172 if err != nil {173 return nil, nil, fmt.Errorf("bubbletea: could not open TTY: %w", err)174 }175 return in, out, nil176}