terminal

package module
v0.27.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2024 License: Apache-2.0 Imports: 16 Imported by: 4

README

terminal

Fortio's terminal has 2 distinct components and a number of utilities built on the second one.

Readline style terminal and more vs Low level ansipixels terminal control and drawing:

fortio.org/terminal

Go Reference

fortio.org/terminal is a readline style library. It handles prompts, edit (like Ctrl-A for beginning of line etc...), navigating through history using arrow keys, loading and saving history from file, etc... It works on everywhere go does (including macOS, Windows (using Terminal app), Linux).

See example/main.go for a rather complete example/demo.

See the godoc above for details.

The grol command line repl and others use this.

The implementations currently is a wrapper fully encapsulating (our fork of) x/term, i.e. fortio.org/term and new features like the interrupts handling (filters Ctrl-C ahead of term' reads)

fortio.org/terminal/ansipixels

Go Reference

A much lower level library that allow direct control of both the input and the output of the terminal, including mouse tracking, clicks, drag events and modifiers, mousewheel decoding/querying and many functions to emit the corresponding ANSI escape codes (colors, cursor positioning etc).

FPS

The tagged release of ansipixels also includes a standalone binary, fps, that uses that package to test your terminal frames per second capabilities. See the source fps/fps.go

You can get the binary from releases

Or just run

CGO_ENABLED=0 go install fortio.org/terminal/fps@latest  # to install or just
CGO_ENABLED=0 go run fortio.org/terminal/fps@latest  # to run without install

or even

docker run -ti fortio/fps # but that's obviously slower

or

brew install fortio/tap/fps

Use the -image flag to pass a different image to load as background. Or use -i and fps is now just a terminal image viewer (in addition to keys, you can now zoom using the mousewheel, click to move the image - see ? for help).

Pass an optional maxfps as argument.

E.g fps -image my.jpg 60 will run at 60 fps with my.jpg as background.

After hitting any key to start the measurement, you can also resize the window at any time and fps will render with the new size. Use q to stop.

fps screenshot

Image viewer screenshot:

fps image viewer

Detailed statistics are saved in a JSON files and can be visualized or compared by running fortio report

fps fortio histogram

Hot (!) off the press a new -fire mode for fps (with space to toggle on/off and i to turn off the text):

FPS Fire mode
Usage

Additional flags/command help:

fps 0.27.0 usage:
        fps [flags] [maxfps] or fps -i imagefiles...
or 1 of the special arguments
        fps {help|envhelp|version|buildinfo}
flags:
  -color
        If your terminal supports color, this will load image in (216) colors instead of monochrome
  -fire
        Show fire animation instead of RGB around the image
  -gray
        Convert the image to grayscale
  -i    Arguments are now images files to show, no FPS test (hit any key to continue)
  -image string
        Image file to display in monochrome in the background instead of the default one
  -n number of frames
        Start immediately an FPS test with the specified number of frames (default is interactive)
  -nobox
        Don't draw the box around the image, make the image full screen instead of 1 pixel less on all sides
  -nojson
        Don't output json file with results that otherwise get produced and can be visualized with fortio report
  -nomouse
        Disable mouse tracking
  -truecolor
        If your terminal supports truecolor, this will load image in truecolor (24bits) instead of monochrome (default true)

Game of life

See life/ for a classic Conway's game of life black and white demo (with resizing, mouse edits, etc... supported).

Same installation as above, just replace fps by life.

life screenshot

Brick

Play an old time favorite, or watch replays of saved games... or even let the computer play!

See the options below.

brick screenshot

brick 0.20.0 usage:
	brick [flags]
or 1 of the special arguments
	brick {help|envhelp|version|buildinfo}
flags:
  -autoplay
    	Computer plays mode
  -fps float
    	Frames per second (default 30)
  -lives int
    	Number of lives - 0 is infinite (default 3)
  -nodeath
    	No death mode
  -nosave
    	Don't save the game as JSON (default is to save)
  -replay game
    	Replay a game from a JSON file
  -seed seed
    	Random number generator seed, default (0) is time based

Like for the others, to try if you have go:

go run fortio.org/terminal/brick@latest

or pick a binary from the releases

Nocolor

nocolor is a very simple unix style filter (source code, uses ansipixels.AnsiClean): it removes all ansi codes from the input stream and writes the filtered version, color free, to stdout.

To install if you have go:

go install fortio.org/terminal/nocolor@latest
# then
somethingProducingColors | nocolor

Or on a mac

brew install fortio/tap/nocolor

Or pick a binary from the releases

Documentation

Overview

Library to interact with ansi/v100 style terminals.

Index

Constants

View Source
const CtrlC = 3 // Control-C is ascii 3 (C is 3rd letter of the alphabet)
View Source
const DefaultHistoryCapacity = term.DefaultHistoryEntries

DefaultHistoryCapacity is the default number of entries in the history (99).

View Source
const IsUnix = true

Variables

View Source
var (
	ErrUserInterrupt = NewErrInterrupted("terminal interrupted by user")
	ErrStopped       = NewErrInterrupted("interrupt reader stopped") // not really an error more of a marker.
	ErrSignal        = NewErrInterrupted("signal received")
)

Functions

func ReadWithTimeout added in v0.17.0

func ReadWithTimeout(fd int, tv *unix.Timeval, buf []byte) (int, error)

func SleepWithContext added in v0.8.0

func SleepWithContext(ctx context.Context, duration time.Duration) error

func TimeoutToTimeval added in v0.8.1

func TimeoutToTimeval(timeout time.Duration) *unix.Timeval

Types

type AutoCompleteCallback

type AutoCompleteCallback func(t *Terminal, line string, pos int, key rune) (newLine string, newPos int, ok bool)

AutoCompleteCallback is called with "this" terminal as first argument so AutoCompleteCallback can use t.Out etc. (compared to the original x/term callback).

type InterruptReader added in v0.8.0

type InterruptReader struct {
	// contains filtered or unexported fields
}

func NewInterruptReader added in v0.8.0

func NewInterruptReader(reader *os.File, bufSize int) *InterruptReader

NewInterruptReader creates a new interrupt reader. it needs to be Start()ed to start reading from the underlying reader and intercept Ctrl-C and listen for interrupt signals.

func (*InterruptReader) Read added in v0.8.0

func (ir *InterruptReader) Read(p []byte) (int, error)

Implement io.Reader interface.

func (*InterruptReader) Start added in v0.8.0

Start or restart (after a cancel/interrupt) the interrupt reader.

func (*InterruptReader) Stop added in v0.9.0

func (ir *InterruptReader) Stop()

type InterruptedError added in v0.8.1

type InterruptedError struct {
	DetailedReason string
	OriginalError  error
}

func NewErrInterrupted added in v0.8.1

func NewErrInterrupted(reason string) InterruptedError

func NewErrInterruptedWithErr added in v0.8.1

func NewErrInterruptedWithErr(reason string, err error) InterruptedError

func (InterruptedError) Error added in v0.8.1

func (e InterruptedError) Error() string

func (InterruptedError) Unwrap added in v0.8.1

func (e InterruptedError) Unwrap() error

type Terminal

type Terminal struct {
	// Use this for any output to the screen/console so the required \r are added in raw mode
	// the prompt and command edit is refresh as needed when input comes in.
	Out io.Writer
	// Cancellable context after Open(). Use it to cancel the terminal reading or check for done.
	Context context.Context //nolint:containedctx // To avoid Open() returning 4 values.
	Cancel  context.CancelFunc
	// contains filtered or unexported fields
}

func Open

func Open(ctx context.Context) (t *Terminal, err error)

Open opens stdin as a terminal, do `defer terminal.Close()` to restore the terminal to its original state upon exit. fortio.org/log (and thus stdlib "log") will be redirected to the terminal in a manner that preserves the prompt. New cancellable context is returned, use it to cancel the terminal reading or check for done for control-c or signal.

func (*Terminal) AddToHistory added in v0.4.0

func (t *Terminal) AddToHistory(commands ...string)

AddToHistory add commands to the history.

func (*Terminal) AutoHistory added in v0.5.0

func (t *Terminal) AutoHistory() bool

AutoHistory returns the current auto history setting.

func (*Terminal) Close

func (t *Terminal) Close() error

Close restores the terminal to its original state. Must be called at exit to avoid leaving the terminal in raw mode. Safe to call multiple times. Will save the history to the history file if one was set using [SetHistoryFile] and the capacity is > 0.

func (*Terminal) History added in v0.4.0

func (t *Terminal) History() []string

History returns the current history state.

func (*Terminal) IsTerminal

func (t *Terminal) IsTerminal() bool

func (*Terminal) NewHistory added in v0.4.0

func (t *Terminal) NewHistory(capacity int)

NewHistory creates/resets the history to a new one with the given capacity. Using 0 as capacity will disable history reading and writing but not change the underlying history state from it's DefaultHistoryCapacity.

func (*Terminal) ReadLine

func (t *Terminal) ReadLine() (string, error)

ReadLine reads a line from the terminal using the setup prompt and history and edit capabilities. Returns the line and an error if any. io.EOF is returned when the user presses Control-D. ErrInterrupted is returned when the user presses Control-C or a signal is received.

func (*Terminal) ReplaceLatest added in v0.5.0

func (t *Terminal) ReplaceLatest(command string) string

ReplaceLatest replaces the current history with the given commands, returns the previous value.

func (*Terminal) ResetInterrupts added in v0.8.0

func (t *Terminal) ResetInterrupts(ctx context.Context) (context.Context, context.CancelFunc)

If you want to reset and restart after an interrupt, call this.

func (*Terminal) Resume added in v0.9.0

func (*Terminal) SetAutoCompleteCallback

func (t *Terminal) SetAutoCompleteCallback(f AutoCompleteCallback)

SetAutoCompleteCallback sets the callback called for each key press. Can be used to implement auto completion. See example/main.go for an example.

func (*Terminal) SetAutoHistory added in v0.5.0

func (t *Terminal) SetAutoHistory(enabled bool)

SetAutoHistory enables/disables auto history (default is enabled).

func (*Terminal) SetHistoryFile

func (t *Terminal) SetHistoryFile(f string) error

Sets up a file to load and save history from/to. File is being read when this is called. If no error is returned, the file will also be automatically updated on Close().

func (*Terminal) SetPrompt

func (t *Terminal) SetPrompt(s string)

Sets or change the prompt.

func (*Terminal) Suspend added in v0.9.0

func (t *Terminal) Suspend()

Temporarily suspend/resume of the terminal back to normal (for example to run a sub process). use defer t.Resume() after calling Suspend() to put the terminal back in raw mode.

type TimeoutReader added in v0.8.1

type TimeoutReader struct {
	// contains filtered or unexported fields
}

func NewTimeoutReader added in v0.17.0

func NewTimeoutReader(stream *os.File, timeout time.Duration) *TimeoutReader

func (*TimeoutReader) ChangeTimeout added in v0.17.0

func (tr *TimeoutReader) ChangeTimeout(timeout time.Duration)

func (*TimeoutReader) Read added in v0.17.0

func (tr *TimeoutReader) Read(buf []byte) (int, error)

Directories

Path Synopsis
ansipixel provides terminal drawing and key reading abilities.
ansipixel provides terminal drawing and key reading abilities.
* A more interesting/real example is https://github.com/grol-io/grol * but this demonstrates most of the features of the terminal package.
* A more interesting/real example is https://github.com/grol-io/grol * but this demonstrates most of the features of the terminal package.
nocolor is a simple utility to filter out all Ansi (color, cursor movement, etc...) sequences from stdin to stdout.
nocolor is a simple utility to filter out all Ansi (color, cursor movement, etc...) sequences from stdin to stdout.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL