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 output, 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.
Note that support for non-UTF-8 locales (other than C) must be enabled by the application using RegisterEncoding() -- we don't have them all enabled by default to avoid bloating the application unnecessarily. (These days UTF-8 is good enough for almost everyone, and nobody should be using legacy locales anymore.) Also, actual glyphs for various code point will only be displayed if your terminal or emulator (or the font the emulator is using) supports them.
A rich set of keycodes is supported, with support for up to 65 function keys, and various other special keys.
Index ¶
- Constants
- Variables
- func GetEncoding(charset string) encoding.Encoding
- func LookupTerminfo(name string) (ti *terminfo.Terminfo, e error)
- func RegisterEncoding(charset string, enc encoding.Encoding)
- func SetEncodingFallback(fb EncodingFallback)
- type AttrMask
- type ButtonMask
- type CellBuffer
- func (cb *CellBuffer) Dirty(x, y int) bool
- func (cb *CellBuffer) Fill(r rune, style Style)
- func (cb *CellBuffer) GetContent(x, y int) (rune, []rune, Style, int)
- func (cb *CellBuffer) Invalidate()
- func (cb *CellBuffer) Resize(w, h int)
- func (cb *CellBuffer) SetContent(x int, y int, mainc rune, combc []rune, style Style)
- func (cb *CellBuffer) SetDirty(x, y int, dirty bool)
- func (cb *CellBuffer) Size() (int, int)
- type Color
- type CursorStyle
- type EncodingFallback
- type Event
- type EventError
- type EventHandler
- type EventInterrupt
- type EventKey
- type EventMouse
- type EventPaste
- type EventResize
- type EventTime
- type Key
- type ModMask
- type MouseFlags
- type Screen
- type SimCell
- type SimulationScreen
- type Style
- func (s Style) Attributes(attrs AttrMask) Style
- func (s Style) Background(c Color) Style
- func (s Style) Blink(on bool) Style
- func (s Style) Bold(on bool) Style
- func (s Style) Decompose() (fg Color, bg Color, attr AttrMask)
- func (s Style) Dim(on bool) Style
- func (s Style) Foreground(c Color) Style
- func (s Style) Italic(on bool) Style
- func (s Style) Normal() Style
- func (s Style) Reverse(on bool) Style
- func (s Style) StrikeThrough(on bool) Style
- func (s Style) Underline(on bool) Style
- func (s Style) Url(url string) Style
- func (s Style) UrlId(id string) Style
- type Tty
Constants ¶
const ( ColorBlack = ColorValid + iota ColorMaroon ColorGreen ColorOlive ColorPurple ColorTeal ColorSilver ColorGray ColorRed ColorLime ColorYellow ColorBlue ColorFuchsia ColorAqua ColorWhite Color16 Color17 Color18 Color19 Color20 Color21 Color22 Color23 Color24 Color25 Color26 Color27 Color28 Color29 Color30 Color31 Color32 Color33 Color34 Color35 Color36 Color37 Color38 Color39 Color40 Color41 Color42 Color43 Color44 Color45 Color46 Color47 Color48 Color49 Color50 Color51 Color52 Color53 Color54 Color55 Color56 Color57 Color58 Color59 Color60 Color61 Color62 Color63 Color64 Color65 Color66 Color67 Color68 Color69 Color70 Color71 Color72 Color73 Color74 Color75 Color76 Color77 Color78 Color79 Color80 Color81 Color82 Color83 Color84 Color85 Color86 Color87 Color88 Color89 Color90 Color91 Color92 Color93 Color94 Color95 Color96 Color97 Color98 Color99 Color100 Color101 Color102 Color103 Color104 Color105 Color106 Color107 Color108 Color109 Color110 Color111 Color112 Color113 Color114 Color115 Color116 Color117 Color118 Color119 Color120 Color121 Color122 Color123 Color124 Color125 Color126 Color127 Color128 Color129 Color130 Color131 Color132 Color133 Color134 Color135 Color136 Color137 Color138 Color139 Color140 Color141 Color142 Color143 Color144 Color145 Color146 Color147 Color148 Color149 Color150 Color151 Color152 Color153 Color154 Color155 Color156 Color157 Color158 Color159 Color160 Color161 Color162 Color163 Color164 Color165 Color166 Color167 Color168 Color169 Color170 Color171 Color172 Color173 Color174 Color175 Color176 Color177 Color178 Color179 Color180 Color181 Color182 Color183 Color184 Color185 Color186 Color187 Color188 Color189 Color190 Color191 Color192 Color193 Color194 Color195 Color196 Color197 Color198 Color199 Color200 Color201 Color202 Color203 Color204 Color205 Color206 Color207 Color208 Color209 Color210 Color211 Color212 Color213 Color214 Color215 Color216 Color217 Color218 Color219 Color220 Color221 Color222 Color223 Color224 Color225 Color226 Color227 Color228 Color229 Color230 Color231 Color232 Color233 Color234 Color235 Color236 Color237 Color238 Color239 Color240 Color241 Color242 Color243 Color244 Color245 Color246 Color247 Color248 Color249 Color250 Color251 Color252 Color253 Color254 Color255 ColorAliceBlue ColorAntiqueWhite ColorAquaMarine ColorAzure ColorBeige ColorBisque ColorBlanchedAlmond ColorBlueViolet ColorBrown ColorBurlyWood ColorCadetBlue ColorChartreuse ColorChocolate ColorCoral ColorCornflowerBlue ColorCornsilk ColorCrimson ColorDarkBlue ColorDarkCyan ColorDarkGoldenrod ColorDarkGray ColorDarkGreen ColorDarkKhaki ColorDarkMagenta ColorDarkOliveGreen ColorDarkOrange ColorDarkOrchid ColorDarkRed ColorDarkSalmon ColorDarkSeaGreen ColorDarkSlateBlue ColorDarkSlateGray ColorDarkTurquoise ColorDarkViolet ColorDeepPink ColorDeepSkyBlue ColorDimGray ColorDodgerBlue ColorFireBrick ColorFloralWhite ColorForestGreen ColorGainsboro ColorGhostWhite ColorGold ColorGoldenrod ColorGreenYellow ColorHoneydew ColorHotPink ColorIndianRed ColorIndigo ColorIvory ColorKhaki ColorLavender ColorLavenderBlush ColorLawnGreen ColorLemonChiffon ColorLightBlue ColorLightCoral ColorLightCyan ColorLightGoldenrodYellow ColorLightGray ColorLightGreen ColorLightPink ColorLightSalmon ColorLightSeaGreen ColorLightSkyBlue ColorLightSlateGray ColorLightSteelBlue ColorLightYellow ColorLimeGreen ColorLinen ColorMediumAquamarine ColorMediumBlue ColorMediumOrchid ColorMediumPurple ColorMediumSeaGreen ColorMediumSlateBlue ColorMediumSpringGreen ColorMediumTurquoise ColorMediumVioletRed ColorMidnightBlue ColorMintCream ColorMistyRose ColorMoccasin ColorOldLace ColorOliveDrab ColorOrange ColorOrangeRed ColorOrchid ColorPaleGoldenrod ColorPaleGreen ColorPaleTurquoise ColorPaleVioletRed ColorPapayaWhip ColorPeachPuff ColorPeru ColorPink ColorPlum ColorPowderBlue ColorRebeccaPurple ColorRosyBrown ColorRoyalBlue ColorSaddleBrown ColorSalmon ColorSandyBrown ColorSeaGreen ColorSeashell ColorSienna ColorSkyblue ColorSlateBlue ColorSlateGray ColorSnow ColorSpringGreen ColorSteelBlue ColorTan ColorThistle ColorTomato ColorTurquoise ColorViolet ColorWheat ColorWhiteSmoke ColorYellowGreen )
Note that the order of these options is important -- it follows the definitions used by ECMA and XTerm. Hence any further named colors must begin at a value not less than 256.
const ( ColorGrey = ColorGray ColorDimGrey = ColorDimGray ColorDarkGrey = ColorDarkGray ColorDarkSlateGrey = ColorDarkSlateGray ColorLightGrey = ColorLightGray ColorLightSlateGrey = ColorLightSlateGray ColorSlateGrey = ColorSlateGray )
These are aliases for the color gray, because some of us spell it as grey.
const ( // EncodingFallbackFail behavior causes GetEncoding to fail // when it cannot find an encoding. EncodingFallbackFail = iota // EncodingFallbackASCII behaviore causes GetEncoding to fall back // to a 7-bit ASCII encoding, if no other encoding can be found. EncodingFallbackASCII // EncodingFallbackUTF8 behavior causes GetEncoding to assume // UTF8 can pass unmodified upon failure. Note that this behavior // is not recommended, unless you are sure your terminal can cope // with real UTF8 sequences. EncodingFallbackUTF8 )
const ( KeyBackspace = KeyBS KeyTab = KeyTAB KeyEsc = KeyESC KeyEscape = KeyESC KeyEnter = KeyCR KeyBackspace2 = KeyDEL )
These keys are aliases for other names.
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 = '│' )
The names of these constants are chosen to match Terminfo names, modulo case, and changing the prefix from ACS_ to Rune. These are the runes we provide extra special handling for, with ASCII fallbacks for terminals that lack them.
const ( MouseButtonEvents = MouseFlags(1) // Click events only MouseDragEvents = MouseFlags(2) // Click-drag events (includes button events) MouseMotionEvents = MouseFlags(4) // All mouse events (includes click and drag events) )
const ( CursorStyleDefault = CursorStyle(iota) // The default CursorStyleBlinkingBlock CursorStyleSteadyBlock CursorStyleBlinkingUnderline CursorStyleSteadyUnderline CursorStyleBlinkingBar CursorStyleSteadyBar )
const ( // ColorReset is used to indicate that the color should use the // vanilla terminal colors. (Basically go back to the defaults.) ColorReset = ColorSpecial | iota )
Special colors.
Variables ¶
var ( // ErrTermNotFound indicates that a suitable terminal entry could // not be found. This can result from either not having TERM set, // or from the TERM failing to support certain minimal functionality, // in particular absolute cursor addressability (the cup capability) // is required. For example, legacy "adm3" lacks this capability, // whereas the slightly newer "adm3a" supports it. This failure // occurs most often with "dumb". ErrTermNotFound = terminfo.ErrTermNotFound // ErrNoScreen indicates that no suitable screen could be found. // This may result from attempting to run on a platform where there // is no support for either termios or console I/O (such as nacl), // or from running in an environment where there is no access to // a suitable console/terminal device. (For example, running on // without a controlling TTY or with no /dev/tty on POSIX platforms.) ErrNoScreen = errors.New("no suitable screen available") // ErrNoCharset indicates that the locale environment the // program is not supported by the program, because no suitable // encoding was found for it. This problem never occurs if // the environment is UTF-8 or UTF-16. ErrNoCharset = errors.New("character set not supported") // ErrEventQFull indicates that the event queue is full, and // cannot accept more events. ErrEventQFull = errors.New("event queue full") )
var ColorNames = map[string]Color{}/* 146 elements not displayed */
ColorNames holds the written names of colors. Useful to present a list of recognized named colors.
var ColorValues = map[Color]int32{}/* 379 elements not displayed */
ColorValues maps color constants to their RGB values.
var KeyNames = map[Key]string{}/* 118 elements not displayed */
KeyNames holds the written names of special keys. Useful to echo back a key name, or to look up a key from a string value.
var RuneFallbacks = map[rune]string{ RuneSterling: "f", RuneDArrow: "v", RuneLArrow: "<", RuneRArrow: ">", RuneUArrow: "^", RuneBullet: "o", 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: "|", }
RuneFallbacks is the default map of fallback strings that will be used to replace a rune when no other more appropriate transformation is available, and the rune cannot be displayed directly.
New entries may be added to this map over time, as it becomes clear that such is desirable. Characters that represent either letters or numbers should not be added to this list unless it is certain that the meaning will still convey unambiguously.
As an example, it would be appropriate to add an ASCII mapping for the full width form of the letter 'A', but it would not be appropriate to do so a glyph representing the country China.
Programs that desire richer fallbacks may register additional ones, or change or even remove these mappings with Screen.RegisterRuneFallback Screen.UnregisterRuneFallback methods.
Note that Unicode is presumed to be able to display all glyphs. This is a pretty poor assumption, but there is no easy way to figure out which glyphs are supported in a given font. Hence, some care in selecting the characters you support in your application is still appropriate.
Functions ¶
func GetEncoding ¶
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 LookupTerminfo ¶
LookupTerminfo attempts to find a definition for the named $TERM falling back to attempting to parse the output from infocmp.
func RegisterEncoding ¶
RegisterEncoding may be called by the application to register an encoding. The presence of additional encodings will facilitate application usage with terminal environments where the I/O subsystem does not support Unicode.
Windows systems use Unicode natively, and do not need any of the encoding subsystem when using Windows Console screens.
Please see the Go documentation for golang.org/x/text/encoding -- most of the common ones exist already as stock variables. For example, ISO8859-15 can be registered using the following code:
import "golang.org/x/text/encoding/charmap" ... RegisterEncoding("ISO8859-15", charmap.ISO8859_15)
Aliases can be registered as well, for example "8859-15" could be an alias for "ISO8859-15".
For POSIX systems, the tcell package will check the environment variables LC_ALL, LC_CTYPE, and LANG (in that order) to determine the character set. These are expected to have the following pattern:
$language[.$codeset[@$variant]
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.)
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.
func SetEncodingFallback ¶
func SetEncodingFallback(fb EncodingFallback)
SetEncodingFallback changes the behavior of GetEncoding when a suitable encoding is not found. The default is EncodingFallbackFail, which causes GetEncoding to simply return nil.
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.
type ButtonMask ¶
type ButtonMask int16
ButtonMask is a mask of mouse buttons and wheel events. Mouse button presses are normally delivered as both press and release events. Mouse wheel events are normally just single impulse events. Windows supports up to eight separate buttons plus all four wheel directions, but XTerm can only support mouse buttons 1-3 and wheel up/down. Its not unheard of for terminals to support only one or two buttons (think Macs). Old terminals, and true emulations (such as vt100) won't support mice at all, of course.
const ( Button1 ButtonMask = 1 << iota // Usually the left (primary) mouse button. Button2 // Usually the right (secondary) mouse button. Button3 // Usually the middle mouse button. Button4 // Often a side button (thumb/next). Button5 // Often a side button (thumb/prev). Button6 Button7 Button8 WheelUp // Wheel motion up/away from user. WheelDown // Wheel motion down/towards user. WheelLeft // Wheel motion to left. WheelRight // Wheel motion to right. ButtonNone ButtonMask = 0 // No button or wheel events. ButtonPrimary = Button1 ButtonSecondary = Button2 ButtonMiddle = Button3 )
These are the actual button values. Note that tcell version 1.x reversed buttons two and three on *nix based terminals. We use button 1 as the primary, and button 2 as the secondary, and button 3 (which is often missing) as the middle.
type CellBuffer ¶
type CellBuffer struct {
// contains filtered or unexported fields
}
CellBuffer represents a two dimensional array of character cells. This is primarily intended for use by Screen implementors; it contains much of the common code they need. To create one, just declare a variable of its type; no explicit initialization is necessary.
CellBuffer is not thread safe.
func (*CellBuffer) Dirty ¶
func (cb *CellBuffer) Dirty(x, y int) bool
Dirty checks if a character at the given location needs an to be refreshed on the physical display. This returns true if the cell content is different since the last time it was marked clean.
func (*CellBuffer) Fill ¶
func (cb *CellBuffer) Fill(r rune, style Style)
Fill fills the entire cell buffer array with the specified character and style. Normally choose ' ' to clear the screen. This API doesn't support combining characters, or characters with a width larger than one.
func (*CellBuffer) GetContent ¶
GetContent returns the contents of a character cell, including the primary rune, any combining character runes (which will usually be nil), the style, and the display width in cells. (The width can be either 1, normally, or 2 for East Asian full-width characters.)
func (*CellBuffer) Invalidate ¶
func (cb *CellBuffer) Invalidate()
Invalidate marks all characters within the buffer as dirty.
func (*CellBuffer) Resize ¶
func (cb *CellBuffer) Resize(w, h int)
Resize is used to resize the cells array, with different dimensions, while preserving the original contents. The cells will be invalidated so that they can be redrawn.
func (*CellBuffer) SetContent ¶
SetContent sets the contents (primary rune, combining runes, and style) for a cell at a given location.
func (*CellBuffer) SetDirty ¶
func (cb *CellBuffer) SetDirty(x, y int, dirty bool)
SetDirty is normally used to indicate that a cell has been displayed (in which case dirty is false), or to manually force a cell to be marked dirty.
func (*CellBuffer) Size ¶
func (cb *CellBuffer) Size() (int, int)
Size returns the (width, height) in cells of the buffer.
type Color ¶
type Color uint64
Color represents a color. The low numeric values are the same as used by ECMA-48, and beyond that XTerm. A 24-bit RGB value may be used by adding in the ColorIsRGB flag. For Color names we use the W3C approved color names.
We use a 64-bit integer to allow future expansion if we want to add an 8-bit alpha, while still leaving us some room for extra options.
Note that on various terminals colors may be approximated however, or not supported at all. If no suitable representation for a color is known, the library will simply not set any color, deferring to whatever default attributes the terminal uses.
const ( // ColorDefault is used to leave the Color unchanged from whatever // system or terminal default may exist. It's also the zero value. ColorDefault Color = 0 // ColorValid is used to indicate the color value is actually // valid (initialized). This is useful to permit the zero value // to be treated as the default. ColorValid Color = 1 << 32 // ColorIsRGB is used to indicate that the numeric value is not // a known color constant, but rather an RGB value. The lower // order 3 bytes are RGB. ColorIsRGB Color = 1 << 33 // ColorSpecial is a flag used to indicate that the values have // special meaning, and live outside of the color space(s). ColorSpecial Color = 1 << 34 )
func FindColor ¶
FindColor attempts to find a given color, or the best match possible for it, from the palette given. This is an expensive operation, so results should be cached by the caller.
func FromImageColor ¶
FromImageColor converts an image/color.Color into tcell.Color. The alpha value is dropped, so it should be tracked separately if it is needed.
func GetColor ¶
GetColor creates a Color from a color name (W3C name). A hex value may be supplied as a string in the format "#ffffff".
func NewHexColor ¶
NewHexColor returns a color using the given 24-bit RGB value.
func NewRGBColor ¶
NewRGBColor returns a new color with the given red, green, and blue values. Each value must be represented in the range 0-255.
func PaletteColor ¶
PaletteColor creates a color based on the palette index.
func (Color) Hex ¶
Hex returns the color's hexadecimal RGB 24-bit value with each component consisting of a single byte, ala R << 16 | G << 8 | B. If the color is unknown or unset, -1 is returned.
func (Color) RGB ¶
RGB returns the red, green, and blue components of the color, with each component represented as a value 0-255. In the event that the color cannot be broken up (not set usually), -1 is returned for each value.
type CursorStyle ¶
type CursorStyle int
CursorStyle represents a given cursor style, which can include the shape and whether the cursor blinks or is solid. Support for changing this is not universal.
type EncodingFallback ¶
type EncodingFallback int
EncodingFallback describes how the system behavees when the locale requires a character set that we do not support. The system always supports UTF-8 and US-ASCII. On Windows consoles, UTF-16LE is also supported automatically. Other character sets must be added using the RegisterEncoding API. (A large group of nearly all of them can be added using the RegisterAll function in the encoding sub package.)
type EventError ¶
type EventError struct {
// contains filtered or unexported fields
}
An EventError is an event representing some sort of error, and carries an error payload.
func NewEventError ¶
func NewEventError(err error) *EventError
NewEventError creates an ErrorEvent with the given error payload.
func (*EventError) When ¶
func (ev *EventError) When() time.Time
When returns the time when the event was created.
type EventHandler ¶
EventHandler is anything that handles events. If the handler has consumed the event, it should return true. False otherwise.
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
NewEventInterrupt creates an EventInterrupt with the given payload.
func (*EventInterrupt) Data ¶
func (ev *EventInterrupt) Data() interface{}
Data is used to obtain the opaque event payload.
func (*EventInterrupt) When ¶
func (ev *EventInterrupt) When() time.Time
When returns the time when this event was created.
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 ¶
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 ¶
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) Modifiers ¶
Modifiers 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 ¶
Name returns a printable value or the key stroke. This can be used when printing the event, for example.
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. On some terminals only the initiating press and terminating release event will be delivered.
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 some cannot report motion events unless a button is pressed.
Applications can inspect the time between events to resolve double or triple clicks.
func NewEventMouse ¶
func NewEventMouse(x, y int, btn ButtonMask, mod ModMask, motion bool) *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
Buttons returns the list of buttons that were pressed or wheel motions.
func (*EventMouse) HasMotion ¶
func (ev *EventMouse) HasMotion() bool
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
When returns the time when this EventMouse was created.
type EventPaste ¶
type EventPaste struct {
// contains filtered or unexported fields
}
EventPaste is used to mark the start and end of a bracketed paste. An event with .Start() true will be sent to mark the start. Then a number of keys will be sent to indicate that the content is pasted in. At the end, an event with .Start() false will be sent.
func NewEventPaste ¶
func NewEventPaste(start bool) *EventPaste
NewEventPaste returns a new EventPaste.
func (*EventPaste) End ¶
func (ev *EventPaste) End() bool
End returns true if this is the end of a paste.
func (*EventPaste) Start ¶
func (ev *EventPaste) Start() bool
Start returns true if this is the start of a paste.
func (*EventPaste) When ¶
func (ev *EventPaste) When() time.Time
When returns the time when this EventPaste was created.
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
NewEventResize creates an EventResize with the new updated window size, which is given in character cells.
func (*EventResize) Size ¶
func (ev *EventResize) Size() (int, int)
Size returns the new window size as width, height in character cells.
func (*EventResize) When ¶
func (ev *EventResize) When() time.Time
When returns the time when the Event was created.
type EventTime ¶
type EventTime struct {
// contains filtered or unexported fields
}
EventTime is a simple base event class, suitable for easy reuse. It can be used to deliver actual timer events as well.
func (*EventTime) SetEventNow ¶
func (e *EventTime) SetEventNow()
SetEventNow sets the time of occurrence for the event to the current time.
func (*EventTime) SetEventTime ¶
SetEventTime sets the time of occurrence for the event.
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 )
This is the list of named keys. KeyRune is special however, in that it is a place holder key indicating that a printable character was sent. The actual value of the rune will be transported in the Rune of the associated EventKey.
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 )
These are the control keys. Note that they overlap with other keys, perhaps. For example, KeyCtrlH is the same as KeyBackspace.
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 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.
These are the modifiers keys that can be sent either with a key press, or a mouse event. Note that as of now, due to the confusion associated with Meta, and the lack of support for it on many/most platforms, the current implementations never use it. Instead, they use ModAlt, even for events that could possibly have been distinguished from ModAlt.
type MouseFlags ¶
type MouseFlags int
MouseFlags are options to modify the handling of mouse events. Actual events can be ORed together.
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() // Fill fills the screen with the given character and style. Fill(rune, Style) // SetCell is an older API, and will be removed. Please use // SetContent instead; SetCell is implemented in terms of SetContent. SetCell(x int, y int, style Style, ch ...rune) // GetContent returns the contents at the given location. If the // coordinates are out of range, then the values will be 0, nil, // StyleDefault. Note that the contents returned are logical contents // and may not actually be what is displayed, but rather are what will // be displayed if Show() or Sync() is called. The width is the width // in screen cells; most often this will be 1, but some East Asian // characters require two cells. GetContent(x, y int) (primary rune, combining []rune, style Style, width int) // SetContent sets the contents of the given cell location. If // the coordinates are out of range, then the operation is ignored. // // The first rune is the primary non-zero width rune. The array // that follows is a possible list of combining characters to append, // and will usually be nil (no combining characters.) // // The results are not displayed until Show() or Sync() is called. // // Note that wide (East Asian full width) runes occupy two cells, // and attempts to place character at next cell to the right will have // undefined effects. Wide runes that are printed in the // last column will be replaced with a single width space on output. SetContent(x int, y int, primary rune, combining []rune, style Style) // 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. It's an alias for // ShowCursor(-1, -1).sim HideCursor() // SetCursorStyle is used to set the cursor style. If the style // is not supported (or cursor styles are not supported at all), // then this will have no effect. SetCursorStyle(CursorStyle) // Size returns the screen size as width, height. This changes in // response to a call to Clear or Flush. Size() (width, height int) // ChannelEvents is an infinite loop that waits for an event and // channels it into the user provided channel ch. Closing the // quit channel and calling the Fini method are cancellation // signals. When a cancellation signal is received the method // returns after closing ch. // // This method should be used as a goroutine. // // NOTE: PollEvent should not be called while this method is running. ChannelEvents(ch chan<- Event, quit <-chan struct{}) // 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 // HasPendingEvent returns true if PollEvent would return an event // without blocking. If the screen is stopped and PollEvent would // return nil, then the return value from this function is unspecified. // The purpose of this function is to allow multiple events to be collected // at once, to minimize screen redraws. HasPendingEvent() bool // PostEvent tries to post an event into the event stream. This // can fail if the event queue is full. In that case, the event // is dropped, and ErrEventQFull is returned. PostEvent(ev Event) error // Deprecated: PostEventWait is unsafe, and will be removed // in the future. // // PostEventWait is like PostEvent, but if the queue is full, it // blocks until there is space in the queue, making delivery // reliable. However, it is VERY important that this function // never be called from within whatever event loop is polling // with PollEvent(), otherwise a deadlock may arise. // // For this reason, when using this function, the use of a // Goroutine is recommended to ensure no deadlock can occur. PostEventWait(ev Event) // EnableMouse enables the mouse. (If your terminal supports it.) // If no flags are specified, then all events are reported, if the // terminal supports them. EnableMouse(...MouseFlags) // DisableMouse disables the mouse. DisableMouse() // EnablePaste enables bracketed paste mode, if supported. EnablePaste() // DisablePaste disables bracketed paste mode. DisablePaste() // HasMouse returns true if the terminal (apparently) supports a // mouse. Note that the return value of true doesn't guarantee that // a mouse/pointing device is present; a false return definitely // indicates no mouse support is available. HasMouse() bool // 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 makes all the content changes made using SetContent() visible // on the 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/output // 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 // RegisterRuneFallback adds a fallback for runes that are not // part of the character set -- for example one could register // o as a fallback for ø. This should be done cautiously for // characters that might be displayed ordinarily in language // specific text -- characters that could change the meaning of // written text would be dangerous. The intention here is to // facilitate fallback characters in pseudo-graphical applications. // // If the terminal has fallbacks already in place via an alternate // character set, those are used in preference. Also, standard // fallbacks for graphical characters in the alternate character set // terminfo string are registered implicitly. // // The display string should be the same width as original rune. // This makes it possible to register two character replacements // for full width East Asian characters, for example. // // It is recommended that replacement strings consist only of // 7-bit ASCII, since other characters may not display everywhere. RegisterRuneFallback(r rune, subst string) // UnregisterRuneFallback unmaps a replacement. It will unmap // the implicit ASCII replacements for alternate characters as well. // When an unmapped char needs to be displayed, but no suitable // glyph is available, '?' is emitted instead. It is not possible // to "disable" the use of alternate characters that are supported // by your terminal except by changing the terminal database. UnregisterRuneFallback(r rune) // CanDisplay returns true if the given rune can be displayed on // this screen. Note that this is a best-guess effort -- whether // your fonts support the character or not may be questionable. // Mostly this is for folks who work outside of Unicode. // // If checkFallbacks is true, then if any (possibly imperfect) // fallbacks are registered, this will return true. This will // also return true if the terminal can replace the glyph with // one that is visually indistinguishable from the one requested. CanDisplay(r rune, checkFallbacks bool) bool // Resize does nothing, since it's generally not possible to // ask a screen to resize, but it allows the Screen to implement // the View interface. Resize(int, int, int, int) // HasKey returns true if the keyboard is believed to have the // key. In some cases a keyboard may have keys with this name // but no support for them, while in others a key may be reported // as supported but not actually be usable (such as some emulators // that hijack certain keys). Its best not to depend to strictly // on this function, but it can be used for hinting when building // menus, displayed hot-keys, etc. Note that KeyRune (literal // runes) is always true. HasKey(Key) bool // Suspend pauses input and output processing. It also restores the // terminal settings to what they were when the application started. // This can be used to, for example, run a sub-shell. Suspend() error // Resume resumes after Suspend(). Resume() error // Beep attempts to sound an OS-dependent audible alert and returns an error // when unsuccessful. Beep() error // SetSize attempts to resize the window. It also invalidates the cells and // calls the resize function. Note that if the window size is changed, it will // not be restored upon application exit. // // Many terminals cannot support this. Perversely, the "modern" Windows Terminal // does not support application-initiated resizing, whereas the legacy terminal does. // Also, some emulators can support this but may have it disabled by default. SetSize(int, int) }
Screen represents the physical (or emulated) screen. This can be a terminal window or a physical console. Platforms implement this differently.
func NewConsoleScreen ¶
NewConsoleScreen returns a console based screen. This platform doesn't have support for any, so it returns nil and a suitable error.
func NewTerminfoScreen ¶
NewTerminfoScreen returns a Screen that uses the stock TTY interface and POSIX terminal control, 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.
func NewTerminfoScreenFromTty ¶
NewTerminfoScreenFromTty returns a Screen using a custom Tty implementation. If the passed in tty is nil, then a reasonable default (typically /dev/tty) is presumed, at least on UNIX hosts. (Windows hosts will typically fail this call altogether.)
func NewTerminfoScreenFromTtyTerminfo ¶
NewTerminfoScreenFromTtyTerminfo returns a Screen using a custom Tty implementation and custom terminfo specification. If the passed in tty is nil, then a reasonable default (typically /dev/tty) is presumed, at least on UNIX hosts. (Windows hosts will typically fail this call altogether.) If passed terminfo is nil, then TERM environment variable is queried for terminal specification.
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) // 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 SetSize() // 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 struct {
// contains filtered or unexported fields
}
Style represents a complete text style, including both foreground color, background color, and additional attributes such as "bold" or "underline".
Note that not all terminals can display all colors or attributes, and many might have specific incompatibilities between specific attributes and color combinations.
To use Style, just declare a variable of its type.
var StyleDefault Style
StyleDefault represents a default style, based upon the context. It is the zero value.
func (Style) Attributes ¶
Attributes returns a new style based on s, with its attributes set as specified.
func (Style) Background ¶
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 (Style) Blink ¶
Blink returns a new style based on s, with the blink attribute set as requested.
func (Style) Decompose ¶
Decompose breaks a style up, returning the foreground, background, and other attributes. The URL if set is not included.
func (Style) Foreground ¶
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) Italic ¶
Italic returns a new style based on s, with the italic attribute set as requested.
func (Style) Reverse ¶
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) StrikeThrough ¶
StrikeThrough sets strikethrough mode.
func (Style) Underline ¶
Underline returns a new style based on s, with the underline attribute set as requested.
func (Style) Url ¶ added in v0.4.0
Url returns a style with the Url set. If the provided Url is not empty, and the terminal supports it, text will typically be marked up as a clickable link to that Url. If the Url is empty, then this mode is turned off.
func (Style) UrlId ¶ added in v0.4.0
UrlId returns a style with the UrlId set. If the provided UrlId is not empty, any marked up Url with this style will be given the UrlId also. If the terminal supports it, any text with the same UrlId will be grouped as if it were one Url, even if it spans multiple lines.
type Tty ¶
type Tty interface { // Start is used to activate the Tty for use. Upon return the terminal should be // in raw mode, non-blocking, etc. The implementation should take care of saving // any state that is required so that it may be restored when Stop is called. Start() error // Stop is used to stop using this Tty instance. This may be a suspend, so that other // terminal based applications can run in the foreground. Implementations should // restore any state collected at Start(), and return to ordinary blocking mode, etc. // Drain is called first to drain the input. Once this is called, no more Read // or Write calls will be made until Start is called again. Stop() error // Drain is called before Stop, and ensures that the reader will wake up appropriately // if it was blocked. This workaround is required for /dev/tty on certain UNIX systems // to ensure that Read() does not block forever. This typically arranges for the tty driver // to send data immediately (e.g. VMIN and VTIME both set zero) and sets a deadline on input. // Implementations may reasonably make this a no-op. There will still be control sequences // emitted between the time this is called, and when Stop is called. Drain() error // NotifyResize is used register a callback when the tty thinks the dimensions have // changed. The standard UNIX implementation links this to a handler for SIGWINCH. // If the supplied callback is nil, then any handler should be unregistered. NotifyResize(cb func()) // WindowSize is called to determine the terminal dimensions. This might be determined // by an ioctl or other means. WindowSize() (width int, height int, err error) io.ReadWriteCloser }
Tty is an abstraction of a tty (traditionally "teletype"). This allows applications to provide for alternate backends, as there are situations where the traditional /dev/tty does not work, or where more flexible handling is required. This interface is for use with the terminfo-style based API. It extends the io.ReadWriter API. It is reasonable that the implementation might choose to use different underlying files for the Reader and Writer sides of this API, as part of it's internal implementation.
func NewDevTtyFromDev ¶
NewDevTtyFromDev opens a tty device given a path. This can be useful to bind to other nodes.
func NewStdIoTty ¶
NewStdioTty opens a tty using standard input/output.
Source Files ¶
- attr.go
- cell.go
- charset_unix.go
- color.go
- colorfit.go
- console_stub.go
- doc.go
- encoding.go
- errors.go
- event.go
- interrupt.go
- key.go
- mouse.go
- nonblock_unix.go
- paste.go
- resize.go
- runes.go
- screen.go
- simulation.go
- stdin_unix.go
- style.go
- terms_default.go
- terms_dynamic.go
- tscreen.go
- tscreen_unix.go
- tty.go
- tty_unix.go
Directories ¶
Path | Synopsis |
---|---|
Package termbox is a compatibility layer to allow tcell to emulate the github.com/nsf/termbox package.
|
Package termbox is a compatibility layer to allow tcell to emulate the github.com/nsf/termbox package. |
base
Package base contains the base terminal descriptions that are likely to be needed by any stock application.
|
Package base contains the base terminal descriptions that are likely to be needed by any stock application. |
extended
Package extended contains an extended set of terminal descriptions.
|
Package extended contains an extended set of terminal descriptions. |