tcell

package module
v0.0.0-...-d89f0da Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2015 License: Apache-2.0 Imports: 18 Imported by: 0

README

tcell

Linux Status Windows Status GitHub License Issues Gitter GoDoc

Tcell is a work in progress (Gamma). Please use with caution; interfaces may change in before final release. That said, our confidence in Tcell's stability is increasing. If you would like to use it in your own application, it is recommended that you drop a message to garrett@damore.org before commitment.

Package tcell provides a cell based view for text terminals, like xterm. It was inspired by termbox, but differs from termbox in some important ways. It also adds substantial functionality beyond termbox.

Pure Go Terminfo Database

First, it includes a full parser and expander for terminfo capability strings, so that it can avoid hard coding escape strings for formatting. It also favors portability, and includes support for all POSIX systems, at the slight expense of needing cgo support for terminal initializations. (This may be corrected when Go provides standard support for terminal handling via termio ioctls on all POSIX platforms.) The database itself, while built using CGO, as well as the parser for it, is implemented in Pure Go.

The database is also flexible & extensibel, and can modified by either running a program to build the database, or hand editing of simple JSON files.

More Portable

Tcell is portable to a wider variety of systems. It relies on standard POSIX supported function calls (on POSIX platforms) for setting terminal modes, which leads to improved support for a broader array of platforms. This does come at the cost of requiring your code to be able to use CGO, but we believe that the vastly improved portability justifies this requirement. Note that the functions called are part of the standard C library, so there shouldn't be any additional external requirements beyond that required for every POSIX program.

No async IO

Termbox code is able to operate without requiring SIGIO signals, or asynchronous I/O, and can instead use standard Go file objects and Go routines. This means it should be safe, especially for use with programs that use exec, or otherwise need to manipulate the tty streams. This model is also much closer to idiomatic Go, leading to fewer surprises.

Richer Unicode & non-Unicode support

Tcell includes enhanced support for Unicode, include wide characters and combining characters, provided your terminal can support them. Note that Windows terminals generally don't support the full Unicode repertoire.

It will also convert to and from Unicode locales, so that the program can work with UTF-8 internally, and get reasonable output in other locales. We try hard to convert to native characters on both input and output, and on output we even make use of the alternate character set to facilitate drawing certain characters.

More Function Keys

It also has richer support for a larger number of special keys that some terminals can send.

Better color handling

Tcell will respect your terminal's color space as specified within your terminfo entries, so that for example attempts to emit color sequences on VT100 terminals won't result in unintended consequences.

In Windows mode, we support 16 colors, underline, bold, dim, and reverse, instead of just termbox's 8 colors with reverse. (Note that there is some conflation with bold/dim and colors.)

Tcell maps 16 colors down to 8, for Terminals that need it. (The upper 8 colors are just brighter versions of the lower 8.)

Better mouse support

It supports enhanced mouse tracking mode, so your application can receive regular mouse motion events, and wheel events, if your terminal supports it.

Why not just patch termbox-go?

I started this project originally by submitting patches to the author of go-termbox, but due to some fundamental differences of opinion, I thought it might be simpler just to start from scratch. At this point, Tcell has far exceeded the capabilities of termbox.

Termbox compatibility

A compatibility layer for termbox is provided in the compat directory. To use it, try importing "github.com/gdamore/tcell/termbox" instead. Most termbox-go programs will probably work without further modification.

Working With Unicode

Internally Tcell uses UTF-8, just like Go. However, it understands how to convert to and from other character sets, using the capabilities of the golang.org/x/text/encoding packages. Your application must supply them, as the full set of the most common ones bloats the program by about 2MB. If you're lazy, and want them all anyway, see the tcell/encoding sub package.

Wide & Combining Characters

The Setcell() API takes a sequence of runes; exactly least one of them should be a non-zero width. Combining runes may follow. If any of the runes is a wide (East Asian) rune occupying two cells, then the library will skip output from the following cell, but care must be taken in the application to avoid explicitly attempting to set content in the next cell, otherwise the results are undefined. (Normally the wide character will not be displayed.)

Experience has shown that the vanilla Windows 8 console application does not support any of these characters properly, but at least some options like ConEmu do support Wide characters at least.

Colors

We assume the ANSI/XTerm color model, including the 256 color map that XTerm uses when it supports 256 colors. The terminfo guidance will be honored, with respect to the number of colors supported. Also, only terminals which expose ANSI style setaf and setab will support color; if you have a color terminal that only has setf and setb, please let me know; it wouldn't be hard to add that if there is need.

Performance

Reasonable attempts have been made to minimize sending data to terminals, avoiding repeated sequences or drawing the same cell on refresh updates.

Terminfo

(Not relevent for Windows users.)

The Terminfo implementation operates with two forms of database. The first is the database.go file, which contains a number of real database entries that are compiled into the program directly. This should minimize calling out to database file searches.

The second is a JSON file, that contains the same information, which can be located either by the $TCELLDB environment file, or is located in the Go source directory.

These files (both the Go database.go and the database.json) file can be generated using the mkinfo.go program. If you need to regnerate the entire set for some reason, run the mkdatabase.sh file. The generation uses the terminfo routines on the system to populate the data files.

The mkinfo.go program can also be used to generate specific database entries for named terminals, in case your favorite terminal is missing. (If you find that this is the case, please let me know and I'll try to add it!)

Tcell requires that the terminal support the 'cup' mode of cursor addressing. Terminals without absolute cursor addressability are not supported. This is unlikely to be a problem; such terminals have not been mass produced since the early 1970s.

Mouse Support

Mouse support is detected via the "kmous" terminfo variable, however, enablement/disablement and decoding mouse events is done using hard coded sequences based on the XTerm X11 model. As of this writing all popular terminals with mouse tracking support this model. (Full terminfo support is not possible as terminfo sequences are not defined.)

On Windows, the mouse works normally.

Mouse wheel buttons on various terminals are known to work, but the support in terminal emulators, as well as support for various buttons and live mouse tracking, varies widely. As a particular datum, MacOS X Terminal does not support Mouse events at all (as of MacOS 10.10, aka Yosemite.) The excellent iTerm application is fully supported, as is vanilla XTerm.

Mouse tracking with live tracking also varies widely. Current XTerm implementations, as well as current Screen and iTerm2, and Windows consoles, all support this quite nicely. On other platforms you might find that only mouse click and release events are reported, with no intervening motion events. It really depends on your terminal.

Testablity

There is a SimulationScreen, that can be used to simulate a real screen for automated testing. The supplied tests do this. The simulation contains event delivery, screen resizing support, and capabilities to inject events and examine "physical" screen contents.

Platforms

On POSIX systems, a POSIX termios implementation with /dev/tty is required. It also requires functional cgo to run. As of this writing, Cgo is available on all POSIX Go 1.5 platforms.

Windows console mode applications are supported. Unfortunately mintty and other cygwin style applications are not supported.

Modern console applications like ConEmu support all the good features (resize, mouse tracking, etc.)

I haven't figured out how to cleanly resolve the dichotomy between cygwin style termios and the Windows Console API; it seems that perhaps nobody else has either. If anyone has suggestions, let me know! Really, if you're using a Windows application, you should use the native Windows console or a fully compatible consule implementation. We expect that Windows 10 ships with a less crippled implementation than prior releases -- we haven't tested that, lacking Windows 10 ourselves.

The nacl and plan9 platforms won't work, but compilation stubs are supplied for folks that want to include parts of this in software targetting those platforms. The test screens will work, but as we don't know how to allocate a real screen object on those platforms, NewScreen() will fail.

Documentation

Overview

Package tcell provides a lower-level, portable API for building programs that interact with terminals or consoles. It works with both common (and many uncommon!) terminals or terminal emulators, and Windows console implementations.

It provides support for up to 256 colors, text attributes, and box drawing elements. A database of terminals built from a real terminfo database is provided, along with code to generate new database entries.

Tcell offers very rich support for mice, dependent upon the terminal of course. (Windows, XTerm, and iTerm 2 are known to work very well.)

If the environment is not Unicode by default, such as an ISO8859 based locale or GB18030, Tcell can convert input and outupt, so that your terminal can operate in whatever locale is most convenient, while the application program can just assume "everything is UTF-8". Reasonable defaults are used for updating characters to something suitable for display. Unicode box drawing characters will be converted to use the alternate character set of your terminal, if native conversions are not available. If no ACS is available, then some ASCII fallbacks will be used.

A rich set of keycodes is supported, with support for up to 65 function keys, and various other special keys.

Index

Constants

View Source
const (
	KeyBackspace  = KeyBS
	KeyTab        = KeyTAB
	KeyEsc        = KeyESC
	KeyEscape     = KeyESC
	KeyEnter      = KeyCR
	KeySpace      = KeySP
	KeyBackspace2 = KeyDEL // This is delete back, not forward
)
View Source
const (
	RuneSterling = '£'
	RuneDArrow   = '↓'
	RuneLArrow   = '←'
	RuneRArrow   = '→'
	RuneUArrow   = '↑'
	RuneBullet   = '·'
	RuneBoard    = '░'
	RuneCkBoard  = '▒'
	RuneDegree   = '°'
	RuneDiamond  = '◆'
	RuneGEqual   = '≥'
	RunePi       = 'π'
	RuneHLine    = '─'
	RuneLantern  = '§'
	RunePlus     = '┼'
	RuneLEqual   = '≤'
	RuneLLCorner = '└'
	RuneLRCorner = '┘'
	RuneNEqual   = '≠'
	RunePlMinus  = '±'
	RuneS1       = '⎺'
	RuneS3       = '⎻'
	RuneS7       = '⎼'
	RuneS9       = '⎽'
	RuneBlock    = '█'
	RuneTTee     = '┬'
	RuneRTee     = '┤'
	RuneLTee     = '├'
	RuneBTee     = '┴'
	RuneULCorner = '┌'
	RuneURCorner = '┐'
	RuneVLine    = '│'
)

Variables

View Source
var (
	ErrNoDatabase   = errors.New("terminal database not found")
	ErrTermNotFound = errors.New("terminal entry not found")
)

Functions

func AddTerminfo

func AddTerminfo(t *Terminfo)

AddTerminfo can be called to register a new Terminfo entry.

func ClearCells

func ClearCells(c []Cell, style Style)

ClearCells clears the entire set of cells, making them all whitespace with the provided attribute.

func GetEncoding

func GetEncoding(name string) encoding.Encoding

GetEncoding is used by Screen implementors who want to locate an encoding for the given character set name. Note that this will return nil for either the Unicode (UTF-8) or ASCII encodings, since we don't use encodings for them but instead have our own native methods.

func InvalidateCells

func InvalidateCells(c []Cell)

InvalidateCells marks all cells in the array dirty.

func RegisterEncoding

func RegisterEncoding(name string, enc encoding.Encoding)

We extract only the $codeset part, which will usually be something like UTF-8 or ISO8859-15 or KOI8-R. Note that if the locale is either "POSIX" or "C", then we assume US-ASCII (the POSIX 'portable character set' and assume all other characters are somehow invalid.)

On Windows systems, the Console is assumed to be UTF-16LE. As we communicate with the console subsystem using UTF-16LE, no conversions are necessary. So none of this is required for Windows systems.

Modern POSIX systems and terminal emulators may use UTF-8, and for those systems, this API is also unnecessary. For example, Darwin (MacOS X) and modern Linux running modern xterm generally will out of the box without any of this. Use of UTF-8 is recommended when possible, as it saves quite a lot processing overhead.

Note that some encodings are quite large (for example GB18030 which is a superset of Unicode) and so the application size can be expected ot increase quite a bit as each encoding is added. The East Asian encodings have been seen to add 100-200K per encoding to the application size.

Types

type AttrMask

type AttrMask int

AttrMask represents a mask of text attributes, apart from color. Note that support for attributes may vary widely across terminals.

const (
	AttrBold AttrMask = 1 << iota
	AttrBlink
	AttrReverse
	AttrUnderline
	AttrDim

	// AttrNone is just normal text.
	AttrNone AttrMask = 0
)

type ButtonMask

type ButtonMask int16

BtnMask is a mask of mouse buttons.

const (
	// Button1 is usually the left mouse button.
	Button1 ButtonMask = 1 << iota
	// Button2 is usually the middle mouse button, for three button mice.
	Button2
	// Button3 is usually the right mouse button on 2 or 3 button mice.
	Button3
	Button4
	Button5
	Button6
	Button7
	Button8
	// WheelUp indicates the wheel being moved up, away from the user.
	WheelUp
	// WheelDown indicates the wheel being moved down, towards the user.
	WheelDown
	WheelLeft
	WheelRight
)
const ButtonNone ButtonMask = 0

type Cell

type Cell struct {
	Ch    []rune
	Dirty bool
	Width uint8
	Style Style
}

Cell represents a single character cell. This is primarily intended for use by Screen implementors.

func ResizeCells

func ResizeCells(oldc []Cell, oldw, oldh, neww, newh int) []Cell

ResizeCells is used to create a new cells array, with different dimensions, while preserving the original contents. The returned array may be the same as the original, if we can reuse it. Hence, the old array should no longer be used by the caller after this call. The cells will be marked dirty so that they can be redrawn.

func (*Cell) PutChar

func (c *Cell) PutChar(ch rune)

PutChar writes a single rune into the cells location. The rune should be a a normal (not combining) printable character.

func (*Cell) PutChars

func (c *Cell) PutChars(ch []rune)

PutChars is a handy way to write runes to the Cell, without changing its style. The first rune should be a printable non-zero width value, and subsequent values may be combining marks.

func (*Cell) PutStyle

func (c *Cell) PutStyle(style Style)

PutStyle changes the style of the given Cell, without altering the character content.

func (*Cell) SetCell

func (c *Cell) SetCell(ch []rune, style Style)

SetCell writes the contents into the cell. It ensures that at most one nonzero width rune is present in the Ch array (and if any zero width runes are present without a non-zero one, then a space is inserted), and updates the Dirty bit if the contents are different than they were.

type Color

type Color int16

Color represents a color. Colors numeric values are taken from the XTerm 256 color map, except that they are offset by one, to allow 0 to indicate the default (unset) color.

const (
	// ColorDefault is used to leave the Color unchanged from whatever
	// system or teminal default may exist.
	ColorDefault Color = iota
	ColorBlack
	ColorRed
	ColorGreen
	ColorYellow
	ColorBlue
	ColorMagenta
	ColorCyan
	ColorWhite
	ColorGrey
	ColorBrightRed
	ColorBrightGreen
	ColorBrightYellow
	ColorBrightBlue
	ColorBrightMagenta
	ColorBrightCyan
	ColorBrightWhite
)

type Event

type Event interface {
	// When reports the time when the event was generated.
	When() time.Time
}

Event is a generic interface used for passing around Events. Concrete types follow.

type EventError

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

func NewEventError

func NewEventError(err error) *EventError

func (*EventError) Error

func (ev *EventError) Error() string

func (*EventError) When

func (ev *EventError) When() time.Time

type EventInterrupt

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

EventInterrupt is a generic wakeup event. Its can be used to to request a redraw. It can carry an arbitrary payload, as well.

func NewEventInterrupt

func NewEventInterrupt(data interface{}) *EventInterrupt

func (*EventInterrupt) Data

func (ev *EventInterrupt) Data() interface{}

func (*EventInterrupt) When

func (ev *EventInterrupt) When() time.Time

type EventKey

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

EventKey represents a key press. Usually this is a key press followed by a key release, but since terminal programs don't have a way to report key release events, we usually get just one event. If a key is held down then the terminal may synthesize repeated key presses at some predefined rate. We have no control over that, nor visibility into it.

In some cases, we can have a modifier key, such as ModAlt, that can be generated with a key press. (This usually is represented by having the high bit set, or in some cases, by sending an ESC prior to the rune.)

If the value of Key() is KeyRune, then the actual key value will be available with the Rune() method. This will be the case for most keys. In most situations, the modifiers will not be set. For example, if the rune is 'A', this will be reported without the ModShift bit set, since really can't tell if the Shift key was pressed (it might have been CAPSLOCK, or a terminal that only can send capitals, or keyboard with separate capital letters from lower case letters).

Generally, terminal applications have far less visibility into keyboard activity than graphical applications. Hence, they should avoid depending overly much on availability of modifiers, or the availability of any specific keys.

func NewEventKey

func NewEventKey(k Key, ch rune, mod ModMask) *EventKey

NewEventKey attempts to create a suitable event. It parses the various ASCII control sequences if KeyRune is passed for Key, but if the caller has more precise information it should set that specifically. Callers that aren't sure about modifier state (most) should just pass ModNone.

func (*EventKey) Key

func (ev *EventKey) Key() Key

Key returns a virtual key code. We use this to identify specific key codes, such as KeyEnter, etc. Most control and function keys are reported with unique Key values. Normal alphanumeric and punctuation keys will generally return KeyRune here; the specific key can be further decoded using the Rune() function.

func (*EventKey) Mod

func (ev *EventKey) Mod() ModMask

ModMask returns the modifiers that were present with the key press. Note that not all platforms and terminals support this equally well, and some cases we will not not know for sure. Hence, applications should avoid using this in most circumstances.

func (*EventKey) Name

func (ev *EventKey) Name() string

Name returns a printable value or the key stroke. This can be used when printing the event, for example.

func (*EventKey) Rune

func (ev *EventKey) Rune() rune

Rune returns the rune corresponding to the key press, if it makes sense. The result is only defined if the value of Key() is KeyRune.

func (*EventKey) When

func (*EventKey) When() time.Time

When returns the time when this Event was created, which should closely match the time when the key was pressed.

type EventMouse

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

EventMouse is a mouse event. It is sent on either mouse up or mouse down events. It is also sent on mouse motion events - if the terminal supports it. We make every effort to ensure that mouse release events are delivered. Hence, click drag can be identified by a motion event with the mouse down, without any intervening button release.

Mouse wheel events, when reported, may appear on their own as individual impulses; that is, there will normally not be a release event delivered for mouse wheel movements.

Most terminals cannot report the state of more than one button at a time -- and many cannot report motion events. (Windows consoles, modern XTerm, and modern emulators like iTerm2, are known to support this well, though.)

Applications can inspect the time between events to figure out double clicks and such.

func NewEventMouse

func NewEventMouse(x, y int, btn ButtonMask, mod ModMask) *EventMouse

NewEventMouse is used to create a new mouse event. Applications shouldn't need to use this; its mostly for screen implementors.

func (*EventMouse) Buttons

func (ev *EventMouse) Buttons() ButtonMask

ButtonMask returns the list of buttons that were pressed.

func (*EventMouse) Modifiers

func (ev *EventMouse) Modifiers() ModMask

Modifiers returns a list of keyboard modifiers that were pressed with the mouse button(s).

func (*EventMouse) Position

func (ev *EventMouse) Position() (int, int)

Position returns the mouse position in character cells. The origin 0, 0 is at the upper left corner.

func (*EventMouse) When

func (ev *EventMouse) When() time.Time

type EventResize

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

EventResize is sent when the window size changes.

func NewEventResize

func NewEventResize(width, height int) *EventResize

func (*EventResize) Size

func (ev *EventResize) Size() (int, int)

func (*EventResize) When

func (ev *EventResize) When() time.Time

type Key

type Key int16

Key is a generic value for representing keys, and especially special keys (function keys, cursor movement keys, etc.) For normal keys, like ASCII letters, we use KeyRune, and then expect the application to inspect the Rune() member of the EventKey.

const (
	KeyRune Key = iota + 256
	KeyUp
	KeyDown
	KeyRight
	KeyLeft
	KeyUpLeft
	KeyUpRight
	KeyDownLeft
	KeyDownRight
	KeyCenter
	KeyPgUp
	KeyPgDn
	KeyHome
	KeyEnd
	KeyInsert
	KeyDelete
	KeyHelp
	KeyExit
	KeyClear
	KeyCancel
	KeyPrint
	KeyPause
	KeyBacktab
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyF13
	KeyF14
	KeyF15
	KeyF16
	KeyF17
	KeyF18
	KeyF19
	KeyF20
	KeyF21
	KeyF22
	KeyF23
	KeyF24
	KeyF25
	KeyF26
	KeyF27
	KeyF28
	KeyF29
	KeyF30
	KeyF31
	KeyF32
	KeyF33
	KeyF34
	KeyF35
	KeyF36
	KeyF37
	KeyF38
	KeyF39
	KeyF40
	KeyF41
	KeyF42
	KeyF43
	KeyF44
	KeyF45
	KeyF46
	KeyF47
	KeyF48
	KeyF49
	KeyF50
	KeyF51
	KeyF52
	KeyF53
	KeyF54
	KeyF55
	KeyF56
	KeyF57
	KeyF58
	KeyF59
	KeyF60
	KeyF61
	KeyF62
	KeyF63
	KeyF64
)
const (
	KeyCtrlSpace Key = iota
	KeyCtrlA
	KeyCtrlB
	KeyCtrlC
	KeyCtrlD
	KeyCtrlE
	KeyCtrlF
	KeyCtrlG
	KeyCtrlH
	KeyCtrlI
	KeyCtrlJ
	KeyCtrlK
	KeyCtrlL
	KeyCtrlM
	KeyCtrlN
	KeyCtrlO
	KeyCtrlP
	KeyCtrlQ
	KeyCtrlR
	KeyCtrlS
	KeyCtrlT
	KeyCtrlU
	KeyCtrlV
	KeyCtrlW
	KeyCtrlX
	KeyCtrlY
	KeyCtrlZ
	KeyCtrlLeftSq // Escape
	KeyCtrlBackslash
	KeyCtrlRightSq
	KeyCtrlCarat
	KeyCtrlUnderscore
)
const (
	KeyNUL Key = iota
	KeySOH
	KeySTX
	KeyETX
	KeyEOT
	KeyENQ
	KeyACK
	KeyBEL
	KeyBS
	KeyTAB
	KeyLF
	KeyVT
	KeyFF
	KeyCR
	KeySO
	KeySI
	KeyDLE
	KeyDC1
	KeyDC2
	KeyDC3
	KeyDC4
	KeyNAK
	KeySYN
	KeyETB
	KeyCAN
	KeyEM
	KeySUB
	KeyESC
	KeyFS
	KeyGS
	KeyRS
	KeyUS
	KeySP
	KeyDEL Key = 0x7F
)

These are the defined ASCII values for key codes. They generally match with KeyCtrl values.

type ModMask

type ModMask int16

ModMask is a mask of modifier keys. Note that it will not always be possible to report modifier keys.

const (
	ModShift ModMask = 1 << iota
	ModCtrl
	ModAlt
	ModMeta
)
const ModNone ModMask = 0

type Screen

type Screen interface {
	// Init initializes the screen for use.
	Init() error

	// Fini finalizes the screen also releasing resources.
	Fini()

	// Clear erases the screen.  The contents of any screen buffers
	// will also be cleared.  This has the logical effect of
	// filling the screen with spaces, using the global default style.
	Clear()

	// SetCell sets the cell at the given location.
	// The ch list contains at most one rune of width > 0, and the
	// runes with zero width (combining marks) must follow the first
	// non-zero width character.  (If only combining marks are present,
	// a space character will be filled in.)
	//
	// Note that double wide runes occupy two cells, and attempts to
	// place a character at the immediately adjacent cell will have
	// undefined effects.  Double wide runes that are printed in the
	// last column will be replaced with a single width space on output.
	//
	// SetCell may change the cursor location.  Callers should explictly
	// save and restore cursor state if neccesary.  The cursor visibility
	// is not affected, so callers probably should hide the cursor when
	// calling this.
	//
	// Note that the results will not be visible until either Show() or
	// Sync() are called.
	SetCell(x int, y int, style Style, ch ...rune)

	// PutCell stores the contents of the given cell at the given location.
	// The Dirty flag on the stored cell is set to true if the contents
	// do not match.
	PutCell(x, y int, cell *Cell)

	// GetCell returns the contents of the given cell.  If the coordinates
	// are out of range, then nil will be returned for the rune array.
	// This will also be the case if no content has been written to that
	// location.  Note that the returned Cell object is a copy, and
	// modifications made will not change the display.
	GetCell(x, y int) *Cell

	// SetStyle sets the default style to use when clearing the screen
	// or when StyleDefault is specified.  If it is also StyleDefault,
	// then whatever system/terminal default is relevant will be used.
	SetStyle(style Style)

	// ShowCursor is used to display the cursor at a given location.
	// If the coordinates -1, -1 are given or are otherwise outside the
	// dimensions of the screen, the cursor will be hidden.
	ShowCursor(x int, y int)

	// HideCursor is used to hide the cursor.  Its an alias for
	// ShowCursor(-1, -1).
	HideCursor()

	// Size returns the screen size as width, height.  This changes in
	// response to a call to Clear or Flush.
	Size() (int, int)

	// PollEvent waits for events to arrive.  Main application loops
	// must spin on this to prevent the application from stalling.
	// Furthermore, this will return nil if the Screen is finalized.
	PollEvent() Event

	// PostEvent posts an event into the event stream.
	PostEvent(Event)

	// EnableMouse enables the mouse.  (If your terminal supports it.)
	EnableMouse()

	// DisableMouse disables the mouse.
	DisableMouse()

	// Colors returns the number of colors.  All colors are assumed to
	// use the ANSI color map.  If a terminal is monochrome, it will
	// return 0.
	Colors() int

	// Show takes any output that was deferred due to buffering, and
	// flushes it to the physical display.  It does so in the most
	// efficient and least visually disruptive manner possible.
	Show()

	// Sync works like Show(), but it updates every visible cell on the
	// physical display, assuming that it is not synchronized with any
	// internal model.  This may be both expensive and visually jarring,
	// so it should only be used when believed to actually be necessary.
	// Typically this is called as a result of a user-requested redraw
	// (e.g. to clear up on screen corruption caused by some other program),
	// or during a resize event.
	Sync()

	// CharacterSet() returns information about the character set.
	// This isn't the full locale, but it does give us the input/ouput
	// character set.  Note that this is just for diagnostic purposes,
	// we normally translate input/output to/from UTF-8, regardless of
	// what the user's environment is.
	CharacterSet() string
}

Screen represents the physical (or emulated) screen. This can be a terminal window or a physical console. Platforms implement this differerently.

func NewConsoleScreen

func NewConsoleScreen() (Screen, error)

func NewScreen

func NewScreen() (Screen, error)

NewScreen returns a default Screen suitable for the user's terminal environment.

func NewTerminfoScreen

func NewTerminfoScreen() (Screen, error)

NewTerminfoScreen returns a Screen that uses the stock TTY interface and POSIX termios, combined with a terminfo description taken from the $TERM environment variable. It returns an error if the terminal is not supported for any reason.

For terminals that do not support dynamic resize events, the $LINES $COLUMNS environment variables can be set to the actual window size, otherwise defaults taken from the terminal database are used.

type SimCell

type SimCell struct {
	// Bytes is the actual character bytes.  Normally this is
	// rune data, but it could be be data in another encoding system.
	Bytes []byte

	// Style is the style used to display the data.
	Style Style

	// Runes is the list of runes, unadulterated, in UTF-8.
	Runes []rune
}

SimCell represents a simulated screen cell. The purpose of this is to track on screen content.

type SimulationScreen

type SimulationScreen interface {
	// InjectKeyBytes injects a stream of bytes corresponding to
	// the native encoding (see charset).  It turns true if the entire
	// set of bytes were processed and delivered as KeyEvents, false
	// if any bytes were not fully understood.  Any bytes that are not
	// fully converted are discarded.
	InjectKeyBytes(buf []byte) bool

	// InjectKey injects a key event.  The rune is a UTF-8 rune, post
	// any translation.
	InjectKey(key Key, r rune, mod ModMask)

	// InjectMouse injects a mouse event.
	InjectMouse(x, y int, buttons ButtonMask, mod ModMask)

	// Resize resizes the underlying physical screen.  It also causes
	// a resize event to be injected during the next Show() or Sync().
	// A new physical contents array will be allocated (with data from
	// the old copied), so any prior value obtained with GetContents
	// won't be used anymore
	Resize(width, height int)

	// GetContents returns screen contents as an array of
	// cells, along with the physical width & height.   Note that the
	// physical contents will be used until the next time Resize()
	// is called.
	GetContents() (cells []SimCell, width int, height int)

	// GetCursor returns the cursor details.
	GetCursor() (x int, y int, visible bool)

	Screen
}

SimulationScreen represents a screen simulation. This is intended to be a superset of normal Screens, but also adds some important interfaces for testing.

func NewSimulationScreen

func NewSimulationScreen(charset string) SimulationScreen

NewSimulationScreen returns a SimulationScreen. Note that SimulationScreen is also a Screen.

type Style

type Style int64

Style represents a complete text style, including both foreground and background color. We encode it in a 64-bit int for efficiency. The coding is (MSB): <16b rsvd><16b attr><16b fgcolor><16b bgcolor>. This gives 16bit color options, if it ever becomes truly necessary. However, applications must not rely on this encoding.

Note that not all terminals can display all colors or attributes, and many might have specific incompatibilities between specific attributes and color combinations.

const StyleDefault Style = 0

func NewStyle

func NewStyle() Style

func (Style) Background

func (s Style) Background(c Color) Style

Background returns a new style based on s, with the background color set as requested. ColorDefault can be used to select the global default.

func (s Style) Blink(on bool) Style

Blink returns a new style based on s, with the blink attribute set as requested.

func (Style) Bold

func (s Style) Bold(on bool) Style

Bold returns a new style based on s, with the bold attribute set as requested.

func (Style) Decompose

func (s Style) Decompose() (fg Color, bg Color, attr AttrMask)

Decompose breaks a style up, returning the foreground, background, and other attributes.

func (Style) Dim

func (s Style) Dim(on bool) Style

Dim returns a new style based on s, with the dim attribute set as requested.

func (Style) Foreground

func (s Style) Foreground(c Color) Style

Foreground returns a new style based on s, with the foreground color set as requested. ColorDefault can be used to select the global default.

func (Style) Normal

func (s Style) Normal() Style

Normal returns the style with all attributes disabled.

func (Style) Reverse

func (s Style) Reverse(on bool) Style

Reverse returns a new style based on s, with the reverse attribute set as requested. (Reverse usually changes the foreground and background colors.)

func (Style) Underline

func (s Style) Underline(on bool) Style

Reverse returns a new style based on s, with the underline attribute set as requested.

type Terminfo

type Terminfo struct {
	Name         string   `json:"name"`
	Aliases      []string `json:"aliases,omitempty"`
	Columns      int      `json:"cols,omitempty"`   // cols
	Lines        int      `json:"lines,omitempty"`  // lines
	Colors       int      `json:"colors,omitempty"` // colors
	Bell         string   `json:"bell,omitempty"`   // bell
	Clear        string   `json:"clear,omitempty"`  // clear
	EnterCA      string   `json:"smcup,omitempty"`  // smcup
	ExitCA       string   `json:"rmcup,omitempty"`  // rmcup
	ShowCursor   string   `json:"cnorm,omitempty"`  // cnorm
	HideCursor   string   `json:"civis,omitempty"`  // civis
	AttrOff      string   `json:"sgr0,omitempty"`   // sgr0
	Underline    string   `json:"smul,omitempty"`   // smul
	Bold         string   `json:"bold,omitempty"`   // bold
	Blink        string   `json:"blink,omitempty"`  // blink
	Reverse      string   `json:"rev,omitempty"`    // rev
	Dim          string   `json:"dim,omitempty"`    // dim
	EnterKeypad  string   `json:"smkx,omitempty"`   // smkx
	ExitKeypad   string   `json:"rmkx,omitempty"`   // rmkx
	SetFg        string   `json:"setaf,omitempty"`  // setaf
	SetBg        string   `json:"setbg,omitempty"`  // setab
	SetCursor    string   `json:"cup,omitempty"`    // cup
	CursorBack1  string   `json:"cub1,omitempty"`   // cub1
	CursorUp1    string   `json:"cuu1,omitempty"`   // cuu1
	PadChar      string   `json:"pad,omitempty"`    // pad
	KeyBackspace string   `json:"kbs,omitempty"`    // kbs
	KeyF1        string   `json:"kf1,omitempty"`    // kf1
	KeyF2        string   `json:"kf2,omitempty"`    // kf2
	KeyF3        string   `json:"kf3,omitempty"`    // kf3
	KeyF4        string   `json:"kf4,omitempty"`    // kf4
	KeyF5        string   `json:"kf5,omitempty"`    // kf5
	KeyF6        string   `json:"kf6,omitempty"`    // kf6
	KeyF7        string   `json:"kf7,omitempty"`    // kf7
	KeyF8        string   `json:"kf8,omitempty"`    // kf8
	KeyF9        string   `json:"kf9,omitempty"`    // kf9
	KeyF10       string   `json:"kf10,omitempty"`   // kf10
	KeyF11       string   `json:"kf11,omitempty"`   // kf11
	KeyF12       string   `json:"kf12,omitempty"`   // kf12
	KeyF13       string   `json:"kf13,omitempty"`   // kf13
	KeyF14       string   `json:"kf14,omitempty"`   // kf14
	KeyF15       string   `json:"kf15,omitempty"`   // kf15
	KeyF16       string   `json:"kf16,omitempty"`   // kf16
	KeyF17       string   `json:"kf17,omitempty"`   // kf17
	KeyF18       string   `json:"kf18,omitempty"`   // kf18
	KeyF19       string   `json:"kf19,omitempty"`   // kf19
	KeyF20       string   `json:"kf20,omitempty"`   // kf20
	KeyF21       string   `json:"kf21,omitempty"`   // kf21
	KeyF22       string   `json:"kf22,omitempty"`   // kf22
	KeyF23       string   `json:"kf23,omitempty"`   // kf23
	KeyF24       string   `json:"kf24,omitempty"`   // kf24
	KeyF25       string   `json:"kf25,omitempty"`   // kf25
	KeyF26       string   `json:"kf26,omitempty"`   // kf26
	KeyF27       string   `json:"kf27,omitempty"`   // kf27
	KeyF28       string   `json:"kf28,omitempty"`   // kf28
	KeyF29       string   `json:"kf29,omitempty"`   // kf29
	KeyF30       string   `json:"kf30,omitempty"`   // kf30
	KeyF31       string   `json:"kf31,omitempty"`   // kf31
	KeyF32       string   `json:"kf32,omitempty"`   // kf32
	KeyF33       string   `json:"kf33,omitempty"`   // kf33
	KeyF34       string   `json:"kf34,omitempty"`   // kf34
	KeyF35       string   `json:"kf35,omitempty"`   // kf35
	KeyF36       string   `json:"kf36,omitempty"`   // kf36
	KeyF37       string   `json:"kf37,omitempty"`   // kf37
	KeyF38       string   `json:"kf38,omitempty"`   // kf38
	KeyF39       string   `json:"kf39,omitempty"`   // kf39
	KeyF40       string   `json:"kf40,omitempty"`   // kf40
	KeyF41       string   `json:"kf41,omitempty"`   // kf41
	KeyF42       string   `json:"kf42,omitempty"`   // kf42
	KeyF43       string   `json:"kf43,omitempty"`   // kf43
	KeyF44       string   `json:"kf44,omitempty"`   // kf44
	KeyF45       string   `json:"kf45,omitempty"`   // kf45
	KeyF46       string   `json:"kf46,omitempty"`   // kf46
	KeyF47       string   `json:"kf47,omitempty"`   // kf47
	KeyF48       string   `json:"kf48,omitempty"`   // kf48
	KeyF49       string   `json:"kf49,omitempty"`   // kf49
	KeyF50       string   `json:"kf50,omitempty"`   // kf50
	KeyF51       string   `json:"kf51,omitempty"`   // kf51
	KeyF52       string   `json:"kf52,omitempty"`   // kf52
	KeyF53       string   `json:"kf53,omitempty"`   // kf53
	KeyF54       string   `json:"kf54,omitempty"`   // kf54
	KeyF55       string   `json:"kf55,omitempty"`   // kf55
	KeyF56       string   `json:"kf56,omitempty"`   // kf56
	KeyF57       string   `json:"kf57,omitempty"`   // kf57
	KeyF58       string   `json:"kf58,omitempty"`   // kf58
	KeyF59       string   `json:"kf59,omitempty"`   // kf59
	KeyF60       string   `json:"kf60,omitempty"`   // kf60
	KeyF61       string   `json:"kf61,omitempty"`   // kf61
	KeyF62       string   `json:"kf62,omitempty"`   // kf62
	KeyF63       string   `json:"kf63,omitempty"`   // kf63
	KeyF64       string   `json:"kf64,omitempty"`   // kf64
	KeyInsert    string   `json:"kich,omitempty"`   // kich1
	KeyDelete    string   `json:"kdch,omitempty"`   // kdch1
	KeyHome      string   `json:"khome,omitempty"`  // khome
	KeyEnd       string   `json:"kend,omitempty"`   // kend
	KeyHelp      string   `json:"khlp,omitempty"`   // khlp
	KeyPgUp      string   `json:"kpp,omitempty"`    // kpp
	KeyPgDn      string   `json:"knp,omitempty"`    // knp
	KeyUp        string   `json:"kcuu1,omitempty"`  // kcuu1
	KeyDown      string   `json:"kcud1,omitempty"`  // kcud1
	KeyLeft      string   `json:"kcub1,omitempty"`  // kcub1
	KeyRight     string   `json:"kcuf1,omitempty"`  // kcuf1
	KeyBacktab   string   `json:"kcbt,omitempty"`   // kcbt
	KeyExit      string   `json:"kext,omitempty"`   // kext
	KeyClear     string   `json:"kclr,omitempty"`   // kclr
	KeyPrint     string   `json:"kprt,omitempty"`   // kprt
	KeyCancel    string   `json:"kcan,omitempty"`   // kcan
	Mouse        string   `json:"kmous,omitempty"`  // kmous
	MouseMode    string   `json:"XM,omitempty"`     // XM
	AltChars     string   `json:"acsc,omitempty"`   // acsc
	EnterAcs     string   `json:"smacs,omitempty"`  // smacs
	ExitAcs      string   `json:"rmacs,omitempty"`  // rmacs
}

Terminfo represents a terminfo entry. Note that we use friendly names in Go, but when we write out JSON, we use the same names as terminfo. The name, aliases and smous, rmous fields do not come from terminfo directly.

func LookupTerminfo

func LookupTerminfo(name string) (*Terminfo, error)

LookupTerminfo attemps to find a definition for the named $TERM. It first looks in the builtin database, which should cover just about everyone. If it can't find one there, then it will attempt to read one from the JSON file located in either $TCELLDB, or in this package's source directory. (XXX: Perhaps move that to $HOME/.tcelldb or somesuch instead? What about somewhere in /etc?)

func (*Terminfo) TColor

func (t *Terminfo) TColor(fg, bg Color) string

Color returns a string corresponding to the given foreground and background colors. Either fg or bg can be set to -1 to elide.

func (*Terminfo) TGoto

func (t *Terminfo) TGoto(col, row int) string

TGoto returns a string suitable for addressing the cursor at the given row and column. The origin 0, 0 is in the upper left corner of the screen.

func (*Terminfo) TParm

func (t *Terminfo) TParm(s string, p ...int) string

TParm takes a terminfo parameterized string, such as setaf or cup, and evaluates the string, and returns the result with the parameter applied.

func (*Terminfo) TPuts

func (t *Terminfo) TPuts(w io.Writer, s string, baud int)

Directories

Path Synopsis
boxes just displays random colored boxes on your terminal screen.
boxes just displays random colored boxes on your terminal screen.
Package termbox is a compatibility layer to allow tcells to emulate the github.com/nsf/termbox package.
Package termbox is a compatibility layer to allow tcells to emulate the github.com/nsf/termbox package.

Jump to

Keyboard shortcuts

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