termbox

package module
Version: v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2021 License: MIT Imports: 17 Imported by: 1,202

README

Go Reference Build

IMPORTANT

This library is somewhat not maintained anymore. But I'm glad that it did what I wanted the most. It moved people away from "ncurses" mindset and these days we see both re-implementations of termbox API in various languages and even possibly better libs with similar API design. If you're looking for a Go lib that provides terminal-based user interface facilities, I've heard that gdamore/tcell is good (never used it myself). Also for more complicated interfaces and/or computer games I recommend you to consider using HTML-based UI. Having said that, termbox still somewhat works. In fact I'm writing this line of text right now in godit (which is a text editor written using termbox-go). So, be aware. Good luck and have a nice day.

Termbox

Termbox is a library that provides a minimalistic API which allows the programmer to write text-based user interfaces. The library is crossplatform and has both terminal-based implementations on *nix operating systems and a winapi console based implementation for windows operating systems. The basic idea is an abstraction of the greatest common subset of features available on all major terminals and other terminal-like APIs in a minimalistic fashion. Small API means it is easy to implement, test, maintain and learn it, that's what makes the termbox a distinct library in its area.

Installation

Install and update this go package with go get -u github.com/nsf/termbox-go

Examples

For examples of what can be done take a look at various examples in the _demos directory. You can try them with go run: go run _demos/keyboard.go

There are also some interesting projects using termbox-go:

  • godit is an emacsish lightweight text editor written using termbox.
  • gotetris is an implementation of Tetris.
  • sokoban-go is an implementation of sokoban game.
  • hecate is a hex editor designed by Satan.
  • httopd is top for httpd logs.
  • mop is stock market tracker for hackers.
  • termui is a terminal dashboard.
  • termloop is a terminal game engine.
  • xterm-color-chart is a XTerm 256 color chart.
  • gocui is a minimalist Go library aimed at creating console user interfaces.
  • dry is an interactive cli to manage Docker containers.
  • pxl displays images in the terminal.
  • snake-game is an implementation of the Snake game.
  • gone is a CLI pomodoro® timer.
  • Spoof.go controllable movement spoofing from the cli.
  • rat lets you compose shell commands to build terminal applications.
  • httplab An interactive web server.
  • wot Wait time during command is completed.
  • 2048-go is 2048 in Go.
  • jv helps you view JSON on the command-line.
  • pinger helps you to monitor numerous hosts using ICMP ECHO_REQUEST.
  • vixl44 lets you create pixel art inside your terminal using vim movements.
  • zterm is a typing game inspired by http://zty.pe/.
  • gotypist is a fun touch-typing tutor following Steve Yegge's method.
  • cointop is an interactive terminal based UI application for tracking cryptocurrencies.
  • pexpo is a terminal sending ping tool written in Go.
  • jid is an interactive JSON drill down tool using filtering queries like jq.
  • nonograminGo is a nonogram (aka. picross) in Go.
  • tower-of-go is a tiny maze game that runs on the terminal.

Documentation

Overview

termbox is a library for creating cross-platform text-based interfaces

Index

Constants

This section is empty.

Variables

View Source
var (
	IsInit bool = false
)

To know if termbox has been initialized or not

Functions

func AttributeToRGB added in v1.1.0

func AttributeToRGB(attr Attribute) (uint8, uint8, uint8)

AttributeToRGB converts an Attribute to the underlying rgb triplet. This is only useful if termbox is in Full RGB mode and the specified attribute is also an attribute with r, g, b specified

func Clear

func Clear(fg, bg Attribute) error

Clears the internal back buffer.

func Close

func Close()

Finalizes termbox library, should be called after successful initialization when termbox's functionality isn't required anymore.

func Flush

func Flush() error

Synchronizes the internal back buffer with the terminal.

func HideCursor

func HideCursor()

The shortcut for SetCursor(-1, -1).

func Init

func Init() error

Initializes termbox library. This function should be called before any other functions. After successful initialization, the library must be finalized using 'Close' function.

Example usage:

err := termbox.Init()
if err != nil {
        panic(err)
}
defer termbox.Close()

func Interrupt

func Interrupt()

Interrupt an in-progress call to PollEvent by causing it to return EventInterrupt. Note that this function will block until the PollEvent function has successfully been interrupted.

func SetBg added in v1.1.0

func SetBg(x, y int, bg Attribute)

Changes cell's background attributes in the internal back buffer at the specified position.

func SetCell

func SetCell(x, y int, ch rune, fg, bg Attribute)

Changes cell's parameters in the internal back buffer at the specified position.

func SetChar added in v1.1.0

func SetChar(x, y int, ch rune)

Changes cell's character (rune) in the internal back buffer at the specified position.

func SetCursor

func SetCursor(x, y int)

Sets the position of the cursor. See also HideCursor().

func SetFg added in v1.1.0

func SetFg(x, y int, fg Attribute)

Changes cell's foreground attributes in the internal back buffer at the specified position.

func Size

func Size() (width int, height int)

Returns the size of the internal back buffer (which is mostly the same as terminal's window size in characters). But it doesn't always match the size of the terminal window, after the terminal size has changed, the internal back buffer will get in sync only after Clear or Flush function calls.

func Sync

func Sync() error

Sync comes handy when something causes desync between termbox's understanding of a terminal buffer and the reality. Such as a third party process. Sync forces a complete resync between the termbox and a terminal, it may not be visually pretty though.

Types

type Attribute

type Attribute uint64
const (
	ColorDefault Attribute = iota
	ColorBlack
	ColorRed
	ColorGreen
	ColorYellow
	ColorBlue
	ColorMagenta
	ColorCyan
	ColorWhite
	ColorDarkGray
	ColorLightRed
	ColorLightGreen
	ColorLightYellow
	ColorLightBlue
	ColorLightMagenta
	ColorLightCyan
	ColorLightGray
)

Cell colors, you can combine a color with multiple attributes using bitwise OR ('|').

const (
	AttrBold Attribute = 1 << (iota + 9)
	AttrBlink
	AttrHidden
	AttrDim
	AttrUnderline
	AttrCursive
	AttrReverse
)

Cell attributes, it is possible to use multiple attributes by combining them using bitwise OR ('|'). Although, colors cannot be combined. But you can combine attributes and a single color.

It's worth mentioning that some platforms don't support certain attributes. For example windows console doesn't support AttrUnderline. And on some terminals applying AttrBold to background may result in blinking text. Use them with caution and test your code on various terminals.

func RGBToAttribute added in v1.1.0

func RGBToAttribute(r uint8, g uint8, b uint8) Attribute

RGBToAttribute is used to convert an rgb triplet into a termbox attribute. This attribute can only be applied when termbox is in Full RGB mode, otherwise it'll be ignored and no color will be drawn. R, G, B have to be in the range of 0 and 255.

type Cell

type Cell struct {
	Ch rune
	Fg Attribute
	Bg Attribute
}

A cell, single conceptual entity on the screen. The screen is basically a 2d array of cells. 'Ch' is a unicode character, 'Fg' and 'Bg' are foreground and background attributes respectively.

func CellBuffer

func CellBuffer() []Cell

Returns a slice into the termbox's back buffer. You can get its dimensions using 'Size' function. The slice remains valid as long as no 'Clear' or 'Flush' function calls were made after call to this function.

func GetCell added in v1.1.0

func GetCell(x, y int) Cell

Returns the specified cell from the internal back buffer.

type Event

type Event struct {
	Type   EventType // one of Event* constants
	Mod    Modifier  // one of Mod* constants or 0
	Key    Key       // one of Key* constants, invalid if 'Ch' is not 0
	Ch     rune      // a unicode character
	Width  int       // width of the screen
	Height int       // height of the screen
	Err    error     // error in case if input failed
	MouseX int       // x coord of mouse
	MouseY int       // y coord of mouse
	N      int       // number of bytes written when getting a raw event
}

This type represents a termbox event. The 'Mod', 'Key' and 'Ch' fields are valid if 'Type' is EventKey. The 'Width' and 'Height' fields are valid if 'Type' is EventResize. The 'Err' field is valid if 'Type' is EventError.

func ParseEvent

func ParseEvent(data []byte) Event

After getting a raw event from PollRawEvent function call, you can parse it again into an ordinary one using termbox logic. That is parse an event as termbox would do it. Returned event in addition to usual Event struct fields sets N field to the amount of bytes used within 'data' slice. If the length of 'data' slice is zero or event cannot be parsed for some other reason, the function will return a special event type: EventNone.

IMPORTANT: EventNone may contain a non-zero N, which means you should skip these bytes, because termbox cannot recognize them.

NOTE: This API is experimental and may change in future.

func PollEvent

func PollEvent() Event

Wait for an event and return it. This is a blocking function call.

func PollRawEvent

func PollRawEvent(data []byte) Event

Wait for an event and return it. This is a blocking function call. Instead of EventKey and EventMouse it returns EventRaw events. Raw event is written into `data` slice and Event's N field is set to the amount of bytes written. The minimum required length of the 'data' slice is 1. This requirement may vary on different platforms.

NOTE: This API is experimental and may change in future.

type EventType

type EventType uint8
const (
	EventKey EventType = iota
	EventResize
	EventMouse
	EventError
	EventInterrupt
	EventRaw
	EventNone
)

Event type. See Event.Type field.

type InputMode

type InputMode int
const (
	InputEsc InputMode = 1 << iota
	InputAlt
	InputMouse
	InputCurrent InputMode = 0
)

Input mode. See SetInputMode function.

func SetInputMode

func SetInputMode(mode InputMode) InputMode

Sets termbox input mode. Termbox has two input modes:

1. Esc input mode. When ESC sequence is in the buffer and it doesn't match any known sequence. ESC means KeyEsc. This is the default input mode.

2. Alt input mode. When ESC sequence is in the buffer and it doesn't match any known sequence. ESC enables ModAlt modifier for the next keyboard event.

Both input modes can be OR'ed with Mouse mode. Setting Mouse mode bit up will enable mouse button press/release and drag events.

If 'mode' is InputCurrent, returns the current input mode. See also Input* constants.

type Key

type Key uint16
const (
	KeyF1 Key = 0xFFFF - iota
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyInsert
	KeyDelete
	KeyHome
	KeyEnd
	KeyPgup
	KeyPgdn
	KeyArrowUp
	KeyArrowDown
	KeyArrowLeft
	KeyArrowRight

	MouseLeft
	MouseMiddle
	MouseRight
	MouseRelease
	MouseWheelUp
	MouseWheelDown
)

Key constants, see Event.Key field.

const (
	KeyCtrlTilde      Key = 0x00
	KeyCtrl2          Key = 0x00
	KeyCtrlSpace      Key = 0x00
	KeyCtrlA          Key = 0x01
	KeyCtrlB          Key = 0x02
	KeyCtrlC          Key = 0x03
	KeyCtrlD          Key = 0x04
	KeyCtrlE          Key = 0x05
	KeyCtrlF          Key = 0x06
	KeyCtrlG          Key = 0x07
	KeyBackspace      Key = 0x08
	KeyCtrlH          Key = 0x08
	KeyTab            Key = 0x09
	KeyCtrlI          Key = 0x09
	KeyCtrlJ          Key = 0x0A
	KeyCtrlK          Key = 0x0B
	KeyCtrlL          Key = 0x0C
	KeyEnter          Key = 0x0D
	KeyCtrlM          Key = 0x0D
	KeyCtrlN          Key = 0x0E
	KeyCtrlO          Key = 0x0F
	KeyCtrlP          Key = 0x10
	KeyCtrlQ          Key = 0x11
	KeyCtrlR          Key = 0x12
	KeyCtrlS          Key = 0x13
	KeyCtrlT          Key = 0x14
	KeyCtrlU          Key = 0x15
	KeyCtrlV          Key = 0x16
	KeyCtrlW          Key = 0x17
	KeyCtrlX          Key = 0x18
	KeyCtrlY          Key = 0x19
	KeyCtrlZ          Key = 0x1A
	KeyEsc            Key = 0x1B
	KeyCtrlLsqBracket Key = 0x1B
	KeyCtrl3          Key = 0x1B
	KeyCtrl4          Key = 0x1C
	KeyCtrlBackslash  Key = 0x1C
	KeyCtrl5          Key = 0x1D
	KeyCtrlRsqBracket Key = 0x1D
	KeyCtrl6          Key = 0x1E
	KeyCtrl7          Key = 0x1F
	KeyCtrlSlash      Key = 0x1F
	KeyCtrlUnderscore Key = 0x1F
	KeySpace          Key = 0x20
	KeyBackspace2     Key = 0x7F
	KeyCtrl8          Key = 0x7F
)

type Modifier

type Modifier uint8
const (
	ModAlt Modifier = 1 << iota
	ModMotion
)

Alt modifier constant, see Event.Mod field and SetInputMode function.

type OutputMode

type OutputMode int
const (
	OutputCurrent OutputMode = iota
	OutputNormal
	Output256
	Output216
	OutputGrayscale
	OutputRGB
)

Output mode. See SetOutputMode function.

func SetOutputMode

func SetOutputMode(mode OutputMode) OutputMode

Sets the termbox output mode. Termbox has four output options:

1. OutputNormal => [1..8]

This mode provides 8 different colors:
    black, red, green, yellow, blue, magenta, cyan, white
Shortcut: ColorBlack, ColorRed, ...
Attributes: AttrBold, AttrUnderline, AttrReverse

Example usage:
    SetCell(x, y, '@', ColorBlack | AttrBold, ColorRed);

2. Output256 => [1..256]

In this mode you can leverage the 256 terminal mode:
0x01 - 0x08: the 8 colors as in OutputNormal
0x09 - 0x10: Color* | AttrBold
0x11 - 0xe8: 216 different colors
0xe9 - 0x1ff: 24 different shades of grey

Example usage:
    SetCell(x, y, '@', 184, 240);
    SetCell(x, y, '@', 0xb8, 0xf0);

3. Output216 => [1..216]

This mode supports the 3rd range of the 256 mode only.
But you don't need to provide an offset.

4. OutputGrayscale => [1..26]

This mode supports the 4th range of the 256 mode
and black and white colors from 3th range of the 256 mode
But you don't need to provide an offset.

In all modes, 0x00 represents the default color.

`go run _demos/output.go` to see its impact on your terminal.

If 'mode' is OutputCurrent, it returns the current output mode.

Note that this may return a different OutputMode than the one requested, as the requested mode may not be available on the target platform.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL