package uvimport ()// DefaultBufferSize is the default size of the input buffer used for reading// terminal events.constDefaultBufferSize = 4096// DefaultEventTimeout is the default duration to wait for input events before// timing out.constDefaultEventTimeout = 100 * time.Millisecond// Options represents options for creating a new [Terminal].typeOptionsstruct {// BufferSize is the size of the input buffer used for reading terminal // events. If zero, [DefaultBufferSize] is used.BufferSizeint// EventTimeout is the duration to wait for input events before timing out. // If zero, a default of 100 milliseconds is used.EventTimeouttime.Duration// LegacyKeyEncoding represents any legacy key encoding ambiguities. By // default, the terminal will use its preferred key encoding settings.LegacyKeyEncodingLegacyKeyEncoding// LookupKeys whether to use a lookup table for common key sequences. If // true, the terminal will use a lookup table to quickly identify common // key sequences, reducing the need for more complex decoding logic. This // can improve performance for common key sequences at the cost of // increased memory usage. // // This is enabled by default.LookupKeysbool// UseTerminfoKeys whether to use terminfo databases key definitions to // build up the keys lookup table. If true, the terminal will use terminfo // databases key definitions to build up the keys lookup table, which can // provide more accurate key mappings for legacy non-xterm like terminals. // // This won't take effect if [TerminalOptions.LookupKeys] is false, since // the lookup table won't be used. // // This is disabled by default.UseTerminfoKeysbool// Logger is an optional logger for tracing terminal I/O operations. // If nil, no logging is performed.LoggerLogger}// DefaultOptions returns the default [Terminal] options.func () *Options {return &Options{BufferSize: DefaultBufferSize,EventTimeout: DefaultEventTimeout,LookupKeys: true, }}// Terminal represents an interactive terminal application.typeTerminalstruct {conConsoleopts *Optionsscr *TerminalScreenprpollReaderbuf []byteevcchanEventerrgerrgroup.Groupwinchchanos.Signaldonecchanstruct{}}// DefaultTerminal creates a new [Terminal] instance using the default standard// console and the given options. Options can be nil to use the default// options.//// This is a convenience function for creating a terminal that uses the// standard input and output file descriptors.func () *Terminal {returnNewTerminal(nil, nil)}// ControllingTerminal creates a new [Terminal] instance using the controlling// terminal's input and output file descriptors.// Options can be nil to use the default options.//// This is a convenience function for creating a terminal that uses the// controlling TTY of the current process.func () (*Terminal, error) { , := ControllingConsole()if != nil {returnnil, }returnNewTerminal(, nil), nil}// NewTerminal creates a new [Terminal] instance with the given console and// options.// Options can be nil to use the default options.func ( Console, *Options) *Terminal { := &Terminal{}if == nil { = DefaultConsole() }if == nil { = DefaultOptions() }if .BufferSize <= 0 { .BufferSize = DefaultBufferSize }if .EventTimeout <= 0 { .EventTimeout = DefaultEventTimeout } .con = .opts = .scr = NewTerminalScreen(.con.Writer(), .con.Environ()) .buf = make([]byte, .BufferSize)// These channels never close during the terminal's lifetime. .evc = make(chanEvent) .winch = make(chanos.Signal, 1) // buffered to avoid missing signalsif .Logger != nil { .scr.rend.SetLogger(.Logger) }return}// GetSize returns the current size of the terminal in characters and pixels.func ( *Terminal) () (, int, error) { , , := .con.GetSize()if != nil {return0, 0, fmt.Errorf("getting terminal size: %w", ) }returnint(), int(), nil}// GetWinsize returns the current size of the terminal as a [Winsize] struct.// This includes both character dimensions (columns and rows) and pixel// dimensions (xpixel and ypixel).//// Note that this only returns the pixel dimensions on Unix-like systems that// support the TIOCGWINSZ ioctl. On other platforms, the pixel dimensions may// be zero or not available.func ( *Terminal) () (*Winsize, error) { , := .con.GetWinsize()if != nil {returnnil, fmt.Errorf("getting terminal winsize: %w", ) }return , nil}// Screen returns the terminal's screen.func ( *Terminal) () *TerminalScreen {return .scr}// Events returns the terminal's event channel.func ( *Terminal) () <-chanEvent {return .evc}// Start starts the terminal application event loop. This is a non-blocking// call. Use [Terminal.Wait] to wait for the terminal to exit.func ( *Terminal) () error { , := .con.MakeRaw()if != nil {returnfmt.Errorf("failed to set terminal to raw mode: %w", ) } := newEventScanner() .lookup = .opts.LookupKeysif .lookup { .table = buildKeysTable(.opts.LegacyKeyEncoding, .con.Getenv("TERM"), .opts.UseTerminfoKeys) }if .opts.Logger != nil { .setLogger(.opts.Logger) } := make(chan []byte) .donec = make(chanstruct{}) .pr, = newPollReader(.con.Reader())if != nil {returnfmt.Errorf("failed to create poll reader: %w", ) }// input loop .errg.Go(func() error {for { , := .pr.Read(.buf)if != nil {returnfmt.Errorf("reading terminal input: %w", ) }select {case<- .buf[:]:case<-.donec:returnnil } } })// event loop := func( []byte, bool) int { , := .scanEvents(, )for , := range { .handleEvent() .SendEvent() }return } .errg.Go(func() error {var []byte := time.NewTimer(.opts.EventTimeout) := time.Now().Add(.opts.EventTimeout)for {select {case<-.donec:returnnilcase<-.C: := len() > 0 && time.Now().After() := (, )if > 0 { = [min(, len()):] }iflen() > 0 { .Reset(.opts.EventTimeout) }case := <-: = append(, ...) := (, false) = time.Now().Add(.opts.EventTimeout) .Stop()if > 0 { = [min(, len()):] }iflen() > 0 { .Reset(.opts.EventTimeout) } } } }) := func() error { , := .con.GetWinsize()if != nil {returnfmt.Errorf("getting terminal size: %w", ) }if .Col > 0 && .Row > 0 { .SendEvent(WindowSizeEvent{Width: int(.Col),Height: int(.Row), }) }if .Xpixel > 0 && .Ypixel > 0 { .SendEvent(PixelSizeEvent{Width: int(.Xpixel),Height: int(.Ypixel), }) }returnnil }// winch handlerNotifyWinch(.winch) .errg.Go(func() error {for {select {case<-.donec:returnnilcase<-.winch:if := (); != nil {return } } } })// init window size .errg.Go(func() error {if := (); != nil {return }returnnil })// Restore any previous screen state. .scr.Restore()// Query whether the terminal supports Unicode core mode (DEC mode 2027) so // we can negotiate grapheme-cluster width. The response is handled in the // event loop. .scr.requestGraphemeWidth()if := .scr.Flush(); != nil {returnfmt.Errorf("failed to flush terminal screen: %w", ) }returnnil}// handleEvent reacts to internal events before they are forwarded to the// application. It negotiates Unicode core mode (DEC mode 2027): when the// terminal reports the mode is in a settable or active state, it enables// grapheme-cluster width so wide-glyph measurement matches the terminal. The// event is still forwarded to the application.//// The mode is only enabled for settable/active states (mode set, reset but// settable, or permanently set). It is explicitly not enabled when the mode is// not recognized or permanently reset, since those terminals cannot honor it.// Enabling goes through the screen's locked write path so it cannot race with// the application's Render/Flush.func ( *Terminal) ( Event) {if , := .(ModeReportEvent); {if .Mode == ansi.ModeUnicodeCore && (.Value.IsSet() || .Value == ansi.ModeReset) { .scr.enableGraphemeWidth() } }}// Wait waits for the terminal event loop to exit and returns any error that// occurred.func ( *Terminal) () error {if := .errg.Wait(); != nil {returnfmt.Errorf("terminal event loop error: %w", ) }returnnil}// Stop stops the terminal event loop. It is safe to call Stop without a// prior [Terminal.Start], and safe to call Stop multiple times in a row.// After Stop returns, [Terminal.Start] may be called again to resume.func ( *Terminal) () error {if .donec != nil {select {case<-.donec:// Already closed.default:close(.donec) } }if .winch != nil {signal.Stop(.winch) }if .pr != nil { .pr.Cancel() _ = .pr.Close() .pr = nil } .scr.Reset()if := .scr.Flush(); != nil { _ = .con.Restore()returnfmt.Errorf("failed to flush terminal screen: %w", ) }if := .con.Restore(); != nil {returnfmt.Errorf("failed to restore terminal state: %w", ) }returnnil}// SendEvent sends an event to the terminal's event channel.//// This can be used to inject custom events into the terminal's event loop,// such as timer events, signals, or application-specific events.func ( *Terminal) ( Event) {select {case .evc<- :case<-.donec: }}// Write writes data directly to the terminal's console output.//// This is a low-level operation that bypasses the terminal screen buffering// and writes directly to the console output handler, usually [os.Stdout] or// the controlling TTY.func ( *Terminal) ( []byte) ( int, error) {return .con.Write()}// Read reads data from the terminal's console input.//// This is a low-level operation that bypasses the terminal event processing// and reads directly from the console input handler, usually [os.Stdin] or the// controlling TTY. Use this method with caution, as it may interfere with the// terminal's event loop and screen management.func ( *Terminal) ( []byte) ( int, error) {return .con.Read()}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)