gocui

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2022 License: BSD-3-Clause Imports: 17 Imported by: 156

README

GOCUI - Go Console User Interface

github actions Go Report Card GoDoc GitHub tag (latest SemVer)

Minimalist Go package aimed at creating Console User Interfaces. A community fork based on the amazing work of jroimartin For v0 to v1 mirgration help read: migrate-to-v1.md

Features

  • Minimalist API.
  • Views (the "windows" in the GUI) implement the interface io.ReadWriter.
  • Support for overlapping views.
  • The GUI can be modified at runtime (concurrent-safe).
  • Global and view-level keybindings.
  • Mouse support.
  • Colored text.
  • Customizable editing mode.
  • Easy to build reusable widgets, complex layouts...

About fork

This fork has many improvements over the original work from jroimartin.

  • Written ontop of TCell
  • Better wide character support
  • Support for 1 Line height views
  • Support for running in docker container
  • Better cursor handling
  • Customize frame colors
  • Improved code comments and quality
  • Many small improvements
  • Change Visibility of views
  • Requires Go 1.13 or newer

For information about this org see: awesome-gocui/about.

Installation

Execute:

$ go get github.com/awesome-gocui/gocui

Documentation

Execute:

$ go doc github.com/awesome-gocui/gocui

Or visit godoc.org to read it online.

Example

See the _example folder for more examples

package main

import (
	"fmt"
	"log"

	"github.com/awesome-gocui/gocui"
)

func main() {
	g, err := gocui.NewGui(gocui.OutputNormal, true)
	if err != nil {
		log.Panicln(err)
	}
	defer g.Close()

	g.SetManagerFunc(layout)

	if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
		log.Panicln(err)
	}

	if err := g.MainLoop(); err != nil && !errors.Is(err, gocui.ErrQuit) {
		log.Panicln(err)
	}
}

func layout(g *gocui.Gui) error {
	maxX, maxY := g.Size()
	if v, err := g.SetView("hello", maxX/2-7, maxY/2, maxX/2+7, maxY/2+2, 0); err != nil {
		if !errors.Is(err, gocui.ErrUnknownView) {
			return err
		}

		if _, err := g.SetCurrentView("hello"); err != nil {
			return err
		}

		fmt.Fprintln(v, "Hello world!")
	}

	return nil
}

func quit(g *gocui.Gui, v *gocui.View) error {
	return gocui.ErrQuit
}

Testing example

You can write simple tests for gocui which let you simulate keyboard and then validate the output drawn to the screen.

  1. Create an instance of gui with OutputSimulator set as the mode g, err := NewGui(OutputSimulator, true)
  2. Call GetTestingScreen to get a testingScreen instance.
  3. On this you can use SendKey to simulate input and GetViewContent to evaluate what is drawn.

Warning: Timing plays a part here, key bindings don't fire synchronously and drawing isn't instant. Here we used time.After to pause, gomega's asynchronous assertions are likely a better alternative for more complex tests.

Here is a simple example showing how this can be used to validate what a view shows and that a key binding is handled correctly:

func TestTestingScreenReturnsCorrectContent(t *testing.T) {
	// Track what happened in the view, we'll assert on these
	didCallCTRLC := false
	expectedViewContent := "Hello world!"
	viewName := "testView1"

	// Create a view specifying the "OutputSimulator" mode
	g, err := NewGui(OutputSimulator, true)
	if err != nil {
		log.Panicln(err)
	}
	g.SetManagerFunc(func(g *Gui) error {
		maxX, maxY := g.Size()
		if v, err := g.SetView(viewName, maxX/2-7, maxY/2, maxX/2+7, maxY/2+2, 0); err != nil {
			if !errors.Is(err, ErrUnknownView) {
				return err
			}

			if _, err := g.SetCurrentView(viewName); err != nil {
				return err
			}

			// Have the view draw "Hello world!"
			fmt.Fprintln(v, expectedViewContent)
		}

		return nil
	})

	// Create a key binding which sets "didCallCTRLC" when triggered
	exampleBindingToTest := func(g *Gui, v *View) error {
		didCallCTRLC = true
		return nil
	}
	if err := g.SetKeybinding("", KeyCtrlC, ModNone, exampleBindingToTest); err != nil {
		log.Panicln(err)
	}

	// Create a test screen and start gocui
	testingScreen := g.GetTestingScreen()
	cleanup := testingScreen.StartGui()
	defer cleanup()

	// Send a key to gocui
	testingScreen.SendKey(KeyCtrlC)

	// Wait for key to be processed
	<-time.After(time.Millisecond * 50)

	// Test that the keybinding fired and set "didCallCTRLC" to true
	if !didCallCTRLC {
		t.Error("Expect the simulator to invoke the key handler for CTRLC")
	}

	// Get the content from the testing screen
	actualContent, err := testingScreen.GetViewContent(viewName)
	if err != nil {
		t.Error(err)
	}

	// Test that it contains the "Hello World!" we thought the view should draw
	if strings.TrimSpace(actualContent) != expectedViewContent {
		t.Error(fmt.Printf("Expected view content to be: %q got: %q", expectedViewContent, actualContent))
	}
}

Note: Under the covers this is using the tcell SimulationScreen.

Screenshots

r2cui

_examples/demo.go

_examples/dynamic.go

Projects using gocui

  • komanda-cli: IRC Client For Developers.
  • vuls: Agentless vulnerability scanner for Linux/FreeBSD.
  • wuzz: Interactive cli tool for HTTP inspection.
  • httplab: Interactive web server.
  • domainr: Tool that checks the availability of domains based on keywords.
  • gotime: Time tracker for projects and tasks.
  • claws: Interactive command line client for testing websockets.
  • terminews: Terminal based RSS reader.
  • diagram: Tool to convert ascii arts into hand drawn diagrams.
  • pody: CLI app to manage Pods in a Kubernetes cluster.
  • kubexp: Kubernetes client.
  • kcli: Tool for inspecting kafka topics/partitions/messages.
  • fac: git merge conflict resolver
  • jsonui: Interactive JSON explorer for your terminal.
  • cointop: Interactive terminal based UI application for tracking cryptocurrencies.
  • lazygit: simple terminal UI for git commands.
  • lazydocker: The lazier way to manage everything docker.

Note: if your project is not listed here, let us know! :)

Documentation

Overview

Package gocui allows to create console user interfaces.

Create a new GUI:

g, err := gocui.NewGui(gocui.OutputNormal, false)
if err != nil {
	// handle error
}
defer g.Close()

// Set GUI managers and key bindings
// ...

if err := g.MainLoop(); err != nil && !errors.Is(err, gocui.ErrQuit) {
	// handle error
}

Set GUI managers:

g.SetManager(mgr1, mgr2)

Managers are in charge of GUI's layout and can be used to build widgets. On each iteration of the GUI's main loop, the Layout function of each configured manager is executed. Managers are used to set-up and update the application's main views, being possible to freely change them during execution. Also, it is important to mention that a main loop iteration is executed on each reported event (key-press, mouse event, window resize, etc).

GUIs are composed by Views, you can think of it as buffers. Views implement the io.ReadWriter interface, so you can just write to them if you want to modify their content. The same is valid for reading.

Create and initialize a view with absolute coordinates:

if v, err := g.SetView("viewname", 2, 2, 22, 7, 0); err != nil {
	if !errors.Is(err, gocui.ErrUnknownView) {
		// handle error
	}
	fmt.Fprintln(v, "This is a new view")
	// ...
}

Views can also be created using relative coordinates:

maxX, maxY := g.Size()
if v, err := g.SetView("viewname", maxX/2-30, maxY/2, maxX/2+30, maxY/2+2, 0); err != nil {
	// ...
}

Configure keybindings:

if err := g.SetKeybinding("viewname", gocui.KeyEnter, gocui.ModNone, fcn); err != nil {
	// handle error
}

gocui implements full mouse support that can be enabled with:

g.Mouse = true

Mouse events are handled like any other keybinding:

if err := g.SetKeybinding("viewname", gocui.MouseLeft, gocui.ModNone, fcn); err != nil {
	// handle error
}

IMPORTANT: Views can only be created, destroyed or updated in three ways: from the Layout function within managers, from keybinding callbacks or via *Gui.Update(). The reason for this is that it allows gocui to be concurrent-safe. So, if you want to update your GUI from a goroutine, you must use *Gui.Update(). For example:

g.Update(func(g *gocui.Gui) error {
	v, err := g.View("viewname")
	if err != nil {
		// handle error
	}
	v.Clear()
	fmt.Fprintln(v, "Writing from different goroutines")
	return nil
})

By default, gocui provides a basic editing mode. This mode can be extended and customized creating a new Editor and assigning it to *View.Editor:

type Editor interface {
	Edit(v *View, key Key, ch rune, mod Modifier)
}

DefaultEditor can be taken as example to create your own custom Editor:

var DefaultEditor Editor = EditorFunc(simpleEditor)

func simpleEditor(v *View, key Key, ch rune, mod Modifier) {
	switch {
	case ch != 0 && mod == 0:
		v.EditWrite(ch)
	case key == KeySpace:
		v.EditWrite(' ')
	case key == KeyBackspace || key == KeyBackspace2:
		v.EditDelete(true)
	// ...
	}
}

Colored text:

Views allow to add colored text using ANSI colors. For example:

fmt.Fprintln(v, "\x1b[0;31mHello world")

For more information, see the examples in folder "_examples/".

Index

Constants

View Source
const (
	// ColorDefault is used to leave the Color unchanged from whatever system or teminal default may exist.
	ColorDefault = Attribute(tcell.ColorDefault)

	// AttrIsValidColor 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.
	AttrIsValidColor = Attribute(tcell.ColorValid)

	// AttrIsRGBColor is used to indicate that the Attribute value is RGB value of color.
	// The lower order 3 bytes are RGB.
	// (It's not a color in basic ANSI range 256).
	AttrIsRGBColor = Attribute(tcell.ColorIsRGB)

	// AttrColorBits is a mask where color is located in Attribute
	AttrColorBits = 0xffffffffff // roughly 5 bytes, tcell uses 4 bytes and half-byte as a special flags for color (rest is reserved for future)

	// AttrStyleBits is a mask where character attributes (e.g.: bold, italic, underline) are located in Attribute
	AttrStyleBits = 0xffffff0000000000 // remaining 3 bytes in the 8 bytes Attribute (tcell is not using it, so we should be fine)
)
View Source
const (
	KeyF1         Key = Key(tcell.KeyF1)
	KeyF2             = Key(tcell.KeyF2)
	KeyF3             = Key(tcell.KeyF3)
	KeyF4             = Key(tcell.KeyF4)
	KeyF5             = Key(tcell.KeyF5)
	KeyF6             = Key(tcell.KeyF6)
	KeyF7             = Key(tcell.KeyF7)
	KeyF8             = Key(tcell.KeyF8)
	KeyF9             = Key(tcell.KeyF9)
	KeyF10            = Key(tcell.KeyF10)
	KeyF11            = Key(tcell.KeyF11)
	KeyF12            = Key(tcell.KeyF12)
	KeyInsert         = Key(tcell.KeyInsert)
	KeyDelete         = Key(tcell.KeyDelete)
	KeyHome           = Key(tcell.KeyHome)
	KeyEnd            = Key(tcell.KeyEnd)
	KeyPgdn           = Key(tcell.KeyPgDn)
	KeyPgup           = Key(tcell.KeyPgUp)
	KeyArrowUp        = Key(tcell.KeyUp)
	KeyArrowDown      = Key(tcell.KeyDown)
	KeyArrowLeft      = Key(tcell.KeyLeft)
	KeyArrowRight     = Key(tcell.KeyRight)
)

Special keys.

View Source
const (
	KeyCtrlTilde      = Key(tcell.KeyF64) // arbitrary assignment
	KeyCtrlSpace      = Key(tcell.KeyCtrlSpace)
	KeyCtrlA          = Key(tcell.KeyCtrlA)
	KeyCtrlB          = Key(tcell.KeyCtrlB)
	KeyCtrlC          = Key(tcell.KeyCtrlC)
	KeyCtrlD          = Key(tcell.KeyCtrlD)
	KeyCtrlE          = Key(tcell.KeyCtrlE)
	KeyCtrlF          = Key(tcell.KeyCtrlF)
	KeyCtrlG          = Key(tcell.KeyCtrlG)
	KeyBackspace      = Key(tcell.KeyBackspace)
	KeyCtrlH          = Key(tcell.KeyCtrlH)
	KeyTab            = Key(tcell.KeyTab)
	KeyBacktab        = Key(tcell.KeyBacktab)
	KeyCtrlI          = Key(tcell.KeyCtrlI)
	KeyCtrlJ          = Key(tcell.KeyCtrlJ)
	KeyCtrlK          = Key(tcell.KeyCtrlK)
	KeyCtrlL          = Key(tcell.KeyCtrlL)
	KeyEnter          = Key(tcell.KeyEnter)
	KeyCtrlM          = Key(tcell.KeyCtrlM)
	KeyCtrlN          = Key(tcell.KeyCtrlN)
	KeyCtrlO          = Key(tcell.KeyCtrlO)
	KeyCtrlP          = Key(tcell.KeyCtrlP)
	KeyCtrlQ          = Key(tcell.KeyCtrlQ)
	KeyCtrlR          = Key(tcell.KeyCtrlR)
	KeyCtrlS          = Key(tcell.KeyCtrlS)
	KeyCtrlT          = Key(tcell.KeyCtrlT)
	KeyCtrlU          = Key(tcell.KeyCtrlU)
	KeyCtrlV          = Key(tcell.KeyCtrlV)
	KeyCtrlW          = Key(tcell.KeyCtrlW)
	KeyCtrlX          = Key(tcell.KeyCtrlX)
	KeyCtrlY          = Key(tcell.KeyCtrlY)
	KeyCtrlZ          = Key(tcell.KeyCtrlZ)
	KeyEsc            = Key(tcell.KeyEscape)
	KeyCtrlUnderscore = Key(tcell.KeyCtrlUnderscore)
	KeySpace          = Key(32)
	KeyBackspace2     = Key(tcell.KeyBackspace2)
	KeyCtrl8          = Key(tcell.KeyBackspace2) // same key as in termbox-go

	MouseLeft         = Key(tcell.KeyF63) // arbitrary assignments
	MouseRight        = Key(tcell.KeyF62)
	MouseMiddle       = Key(tcell.KeyF61)
	MouseRelease      = Key(tcell.KeyF60)
	MouseWheelUp      = Key(tcell.KeyF59)
	MouseWheelDown    = Key(tcell.KeyF58)
	MouseWheelLeft    = Key(tcell.KeyF57)
	MouseWheelRight   = Key(tcell.KeyF56)
	KeyCtrl2          = Key(tcell.KeyNUL) // termbox defines theses
	KeyCtrl3          = Key(tcell.KeyEscape)
	KeyCtrl4          = Key(tcell.KeyCtrlBackslash)
	KeyCtrl5          = Key(tcell.KeyCtrlRightSq)
	KeyCtrl6          = Key(tcell.KeyCtrlCarat)
	KeyCtrl7          = Key(tcell.KeyCtrlUnderscore)
	KeyCtrlSlash      = Key(tcell.KeyCtrlUnderscore)
	KeyCtrlRsqBracket = Key(tcell.KeyCtrlRightSq)
	KeyCtrlBackslash  = Key(tcell.KeyCtrlBackslash)
	KeyCtrlLsqBracket = Key(tcell.KeyCtrlLeftSq)
)

Keys combinations.

View Source
const (
	ModNone Modifier = Modifier(0)
	ModAlt           = Modifier(tcell.ModAlt)

	// ModShift only makes sense on keys that are not characters like the
	// arrow keys and any mouse keys
	// Character keys will instead be triggerd as their translated variant.
	ModShift     = Modifier(tcell.ModShift)
	ModMouseCtrl = Modifier(tcell.ModCtrl)
)

Modifiers.

View Source
const (
	TOP    = 1 // view is overlapping at top edge
	BOTTOM = 2 // view is overlapping at bottom edge
	LEFT   = 4 // view is overlapping at left edge
	RIGHT  = 8 // view is overlapping at right edge
)

Constants for overlapping edges

AttrAll represents all the text effect attributes turned on

Variables

View Source
var (
	// ErrAlreadyBlacklisted is returned when the keybinding is already blacklisted.
	ErrAlreadyBlacklisted = errors.New("keybind already blacklisted")

	// ErrBlacklisted is returned when the keybinding being parsed / used is blacklisted.
	ErrBlacklisted = errors.New("keybind blacklisted")

	// ErrNotBlacklisted is returned when a keybinding being whitelisted is not blacklisted.
	ErrNotBlacklisted = errors.New("keybind not blacklisted")

	// ErrNoSuchKeybind is returned when the keybinding being parsed does not exist.
	ErrNoSuchKeybind = errors.New("no such keybind")

	// ErrUnknownView allows to assert if a View must be initialized.
	ErrUnknownView = errors.New("unknown view")

	// ErrQuit is used to decide if the MainLoop finished successfully.
	ErrQuit = errors.New("quit")
)
View Source
var (
	// ErrInvalidPoint is returned when client passed invalid coordinates of a cell.
	// Most likely client has passed negative coordinates of a cell.
	ErrInvalidPoint = errors.New("invalid point")
)

Functions

func Loader added in v0.5.0

func Loader() cell

Loader can show a loading animation

func MustParseAll added in v1.0.0

func MustParseAll(input []string) map[interface{}]Modifier

MustParseAll takes an array of strings and returns a map of all keybindings. It will panic if any error occured.

func ParseAll added in v1.0.0

func ParseAll(input []string) (map[interface{}]Modifier, error)

ParseAll takes an array of strings and returns a map of all keybindings.

func Resume added in v1.0.0

func Resume() error

Resume re-initializes the tcell screen, intended to be used after "Suspend" has been called

func Suspend added in v1.0.0

func Suspend()

Suspend closes the tcell screen allowing other terminal apps to run

Types

type Attribute

type Attribute uint64

Attribute affects the presentation of characters, such as color, boldness, etc.

const (
	ColorBlack Attribute = AttrIsValidColor + iota
	ColorRed
	ColorGreen
	ColorYellow
	ColorBlue
	ColorMagenta
	ColorCyan
	ColorWhite
)

Color attributes. These colors are compatible with tcell.Color type and can be expanded like:

g.FgColor := gocui.Attribute(tcell.ColorLime)
const (
	AttrBold Attribute = 1 << (40 + iota)
	AttrBlink
	AttrReverse
	AttrUnderline
	AttrDim
	AttrItalic
	AttrStrikeThrough
	AttrNone Attribute = 0 // Just normal text.
)

Attributes are not colors, but effects (e.g.: bold, dim) which affect the display of text. They can be combined.

func Get256Color added in v1.0.0

func Get256Color(color int32) Attribute

Get256Color creates Attribute which stores ANSI color (0-255)

func GetColor added in v1.0.0

func GetColor(color string) Attribute

GetColor creates a Color from a color name (W3C name). A hex value may be supplied as a string in the format "#ffffff".

func GetRGBColor added in v1.0.0

func GetRGBColor(color int32) Attribute

GetRGBColor creates Attribute which stores RGB color. Color is passed as 24bit RGB value, where R << 16 | G << 8 | B

func NewRGBColor added in v1.0.0

func NewRGBColor(r, g, b int32) Attribute

NewRGBColor creates Attribute which stores RGB color.

func (Attribute) Hex added in v1.0.0

func (a Attribute) Hex() int32

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.

This function produce the same output as `tcell.Hex()` with additional support for `termbox-go` colors (to 256).

func (Attribute) IsValidColor added in v1.0.0

func (a Attribute) IsValidColor() bool

IsValidColor indicates if the Attribute is a valid color value (has been set).

func (Attribute) RGB added in v1.0.0

func (a Attribute) RGB() (int32, int32, int32)

RGB returns the red, green, and blue components of the color, with each component represented as a value 0-255. If the color is unknown or unset, -1 is returned for each component.

This function produce the same output as `tcell.RGB()` with additional support for `termbox-go` colors (to 256).

type Editor added in v0.2.0

type Editor interface {
	Edit(v *View, key Key, ch rune, mod Modifier)
}

Editor interface must be satisfied by gocui editors.

var DefaultEditor Editor = EditorFunc(simpleEditor)

DefaultEditor is the default editor.

type EditorFunc added in v0.2.0

type EditorFunc func(v *View, key Key, ch rune, mod Modifier)

The EditorFunc type is an adapter to allow the use of ordinary functions as Editors. If f is a function with the appropriate signature, EditorFunc(f) is an Editor object that calls f.

func (EditorFunc) Edit added in v0.2.0

func (f EditorFunc) Edit(v *View, key Key, ch rune, mod Modifier)

Edit calls f(v, key, ch, mod)

type Gui

type Gui struct {

	// BgColor and FgColor allow to configure the background and foreground
	// colors of the GUI.
	BgColor, FgColor, FrameColor Attribute

	// SelBgColor and SelFgColor allow to configure the background and
	// foreground colors of the frame of the current view.
	SelBgColor, SelFgColor, SelFrameColor Attribute

	// If Highlight is true, Sel{Bg,Fg}Colors will be used to draw the
	// frame of the current view.
	Highlight bool

	// If Cursor is true then the cursor is enabled.
	Cursor bool

	// If Mouse is true then mouse events will be enabled.
	Mouse bool

	// If InputEsc is true, when ESC sequence is in the buffer and it doesn't
	// match any known sequence, ESC means KeyEsc.
	InputEsc bool

	// If ASCII is true then use ASCII instead of unicode to draw the
	// interface. Using ASCII is more portable.
	ASCII bool

	// SupportOverlaps is true when we allow for view edges to overlap with other
	// view edges
	SupportOverlaps bool
	// contains filtered or unexported fields
}

Gui represents the whole User Interface, including the views, layouts and keybindings.

func NewGui

func NewGui(mode OutputMode, supportOverlaps bool) (*Gui, error)

NewGui returns a new Gui object with a given output mode.

func (*Gui) BlacklistKeybinding added in v1.0.0

func (g *Gui) BlacklistKeybinding(k Key) error

BlackListKeybinding adds a keybinding to the blacklist

func (*Gui) Close

func (g *Gui) Close()

Close finalizes the library. It should be called after a successful initialization and when gocui is not needed anymore.

func (*Gui) CurrentView

func (g *Gui) CurrentView() *View

CurrentView returns the currently focused view, or nil if no view owns the focus.

func (*Gui) DeleteKeybinding added in v0.3.0

func (g *Gui) DeleteKeybinding(viewname string, key interface{}, mod Modifier) error

DeleteKeybinding deletes a keybinding.

func (*Gui) DeleteKeybindings added in v0.3.0

func (g *Gui) DeleteKeybindings(viewname string)

DeleteKeybindings deletes all keybindings of view.

func (*Gui) DeleteView

func (g *Gui) DeleteView(name string) error

DeleteView deletes a view by name.

func (*Gui) GetTestingScreen added in v1.0.0

func (g *Gui) GetTestingScreen() TestingScreen

Creates an instance of TestingScreen for the current Gui

func (*Gui) MainLoop

func (g *Gui) MainLoop() error

MainLoop runs the main loop until an error is returned. A successful finish should return ErrQuit.

func (*Gui) MousePosition added in v1.1.0

func (g *Gui) MousePosition() (x, y int)

MousePosition returns the last position of the mouse. If no mouse event was triggered yet MousePosition will return -1, -1.

func (*Gui) Rune

func (g *Gui) Rune(x, y int) (rune, error)

Rune returns the rune contained in the cell at the given position. It checks if the position is valid.

func (*Gui) SetCurrentView

func (g *Gui) SetCurrentView(name string) (*View, error)

SetCurrentView gives the focus to a given view.

func (*Gui) SetKeybinding

func (g *Gui) SetKeybinding(viewname string, key interface{}, mod Modifier, handler func(*Gui, *View) error) error

SetKeybinding creates a new keybinding. If viewname equals to "" (empty string) then the keybinding will apply to all views. key must be a rune or a Key.

When mouse keys are used (MouseLeft, MouseRight, ...), modifier might not work correctly. It behaves differently on different platforms. Somewhere it doesn't register Alt key press, on others it might report Ctrl as Alt. It's not consistent and therefore it's not recommended to use with mouse keys.

func (*Gui) SetManager added in v0.4.0

func (g *Gui) SetManager(managers ...Manager)

SetManager sets the given GUI managers. It deletes all views and keybindings.

func (*Gui) SetManagerFunc added in v0.4.0

func (g *Gui) SetManagerFunc(manager func(*Gui) error)

SetManagerFunc sets the given manager function. It deletes all views and keybindings.

func (*Gui) SetRune

func (g *Gui) SetRune(x, y int, ch rune, fgColor, bgColor Attribute) error

SetRune writes a rune at the given point, relative to the top-left corner of the terminal. It checks if the position is valid and applies the given colors.

func (*Gui) SetView

func (g *Gui) SetView(name string, x0, y0, x1, y1 int, overlaps byte) (*View, error)

SetView creates a new view with its top-left corner at (x0, y0) and the bottom-right one at (x1, y1). If a view with the same name already exists, its dimensions are updated; otherwise, the error ErrUnknownView is returned, which allows to assert if the View must be initialized. It checks if the position is valid.

func (*Gui) SetViewBeneath added in v1.0.0

func (g *Gui) SetViewBeneath(name string, aboveViewName string, height int) (*View, error)

SetViewBeneath sets a view stacked beneath another view

func (*Gui) SetViewOnBottom added in v0.4.0

func (g *Gui) SetViewOnBottom(name string) (*View, error)

SetViewOnBottom sets the given view on bottom of the existing ones.

func (*Gui) SetViewOnTop added in v0.3.0

func (g *Gui) SetViewOnTop(name string) (*View, error)

SetViewOnTop sets the given view on top of the existing ones.

func (*Gui) Size

func (g *Gui) Size() (x, y int)

Size returns the terminal's size.

func (*Gui) Update added in v0.4.0

func (g *Gui) Update(f func(*Gui) error)

Update executes the passed function. This method can be called safely from a goroutine in order to update the GUI. It is important to note that the passed function won't be executed immediately, instead it will be added to the user events queue. Given that Update spawns a goroutine, the order in which the user events will be handled is not guaranteed.

func (*Gui) UpdateAsync added in v1.0.0

func (g *Gui) UpdateAsync(f func(*Gui) error)

UpdateAsync is a version of Update that does not spawn a go routine, it can be a bit more efficient in cases where Update is called many times like when tailing a file. In general you should use Update()

func (*Gui) View

func (g *Gui) View(name string) (*View, error)

View returns a pointer to the view with the given name, or error ErrUnknownView if a view with that name does not exist.

func (*Gui) ViewByPosition added in v0.2.0

func (g *Gui) ViewByPosition(x, y int) (*View, error)

ViewByPosition returns a pointer to a view matching the given position, or error ErrUnknownView if a view in that position does not exist.

func (*Gui) ViewPosition added in v0.2.0

func (g *Gui) ViewPosition(name string) (x0, y0, x1, y1 int, err error)

ViewPosition returns the coordinates of the view with the given name, or error ErrUnknownView if a view with that name does not exist.

func (*Gui) Views added in v0.4.0

func (g *Gui) Views() []*View

Views returns all the views in the GUI.

func (*Gui) WhitelistKeybinding added in v1.0.0

func (g *Gui) WhitelistKeybinding(k Key) error

WhiteListKeybinding removes a keybinding from the blacklist

type Key

type Key tcell.Key

Key represents special keys or keys combinations.

type Manager added in v0.4.0

type Manager interface {
	// Layout is called every time the GUI is redrawn, it must contain the
	// base views and its initializations.
	Layout(*Gui) error
}

A Manager is in charge of GUI's layout and can be used to build widgets.

type ManagerFunc added in v0.4.0

type ManagerFunc func(*Gui) error

The ManagerFunc type is an adapter to allow the use of ordinary functions as Managers. If f is a function with the appropriate signature, ManagerFunc(f) is an Manager object that calls f.

func (ManagerFunc) Layout added in v0.4.0

func (f ManagerFunc) Layout(g *Gui) error

Layout calls f(g)

type Modifier

type Modifier tcell.ModMask

Modifier allows to define special keys combinations. They can be used in combination with Keys or Runes when a new keybinding is defined.

func MustParse added in v1.0.0

func MustParse(input string) (interface{}, Modifier)

MustParse takes the input string and returns a Key / rune and a Modifier. It will panic if any error occured.

func Parse added in v1.0.0

func Parse(input string) (interface{}, Modifier, error)

Parse takes the input string and extracts the keybinding. Returns a Key / rune, a Modifier and an error.

type OutputMode added in v0.4.0

type OutputMode int

OutputMode represents an output mode, which determines how colors are used.

const (
	// OutputNormal provides 8-colors terminal mode.
	OutputNormal OutputMode = iota

	// Output256 provides 256-colors terminal mode.
	Output256

	// Output216 provides 216 ansi color terminal mode.
	Output216

	// OutputGrayscale provides greyscale terminal mode.
	OutputGrayscale

	// OutputTrue provides 24bit color terminal mode.
	// This mode is recommended even if your terminal doesn't support
	// such mode. The colors are represented exactly as you
	// write them (no clamping or truncating). `tcell` should take care
	// of what your terminal can do.
	OutputTrue

	// OutputSimulator uses a simulated screen allowing testing with simulated
	// input and the option to retrieve the current conent
	// See: SendKeyToSimulatedScreen, GetContentOfSimulatedScreen
	OutputSimulator
)

type TestingScreen added in v1.0.0

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

TestingScreen is used to create tests using a simulated screen

func (*TestingScreen) GetViewContent added in v1.0.0

func (t *TestingScreen) GetViewContent(viewName string) (string, error)

GetViewContent gets the current conent of a view from the simulated screen

func (*TestingScreen) SendKey added in v1.0.0

func (t *TestingScreen) SendKey(key Key)

SendsKey sends a key to gocui

func (*TestingScreen) SendKeySync added in v1.1.0

func (t *TestingScreen) SendKeySync(key Key)

SendsKeySync sends a key to gocui and wait until MainLoop process it.

func (*TestingScreen) SendStringAsKeys added in v1.0.0

func (t *TestingScreen) SendStringAsKeys(input string)

SendStringAsKeys sends a string of text to gocui

func (*TestingScreen) StartGui added in v1.0.0

func (t *TestingScreen) StartGui() func()

StartGui starts the Gui using the test screen it returns a func which stops the Gui to cleanup after your test finishes:

cleanup := testingScreen.StartGui() defer cleanup()

func (*TestingScreen) WaitSync added in v1.1.0

func (t *TestingScreen) WaitSync()

WaitSync sends time event to gocui and awaits notification that it was received.

Notification is sent from gocui at the end of MainLoop, so after this function returns, user has confirmation that all the keys sent to gocui before time event were processed.

type View

type View struct {

	// Visible specifies whether the view is visible.
	Visible bool

	// BgColor and FgColor allow to configure the background and foreground
	// colors of the View.
	BgColor, FgColor Attribute

	// SelBgColor and SelFgColor are used to configure the background and
	// foreground colors of the selected line, when it is highlighted.
	SelBgColor, SelFgColor Attribute

	// If Editable is true, keystrokes will be added to the view's internal
	// buffer at the cursor position.
	Editable bool

	// Editor allows to define the editor that manages the editing mode,
	// including keybindings or cursor behaviour. DefaultEditor is used by
	// default.
	Editor Editor

	// Overwrite enables or disables the overwrite mode of the view.
	Overwrite bool

	// If Highlight is true, Sel{Bg,Fg}Colors will be used
	// for the line under the cursor position.
	Highlight bool

	// If Frame is true, a border will be drawn around the view.
	Frame bool

	// FrameColor allow to configure the color of the Frame when it is not highlighted.
	FrameColor Attribute

	// FrameRunes allows to define custom runes for the frame edges.
	// The rune slice can be defined with 3 different lengths.
	// If slice doesn't match these lengths, default runes will be used instead of missing one.
	//
	// 2 runes with only horizontal and vertical edges.
	//  []rune{'─', '│'}
	//  []rune{'═','║'}
	// 6 runes with horizontal, vertical edges and top-left, top-right, bottom-left, bottom-right cornes.
	//  []rune{'─', '│', '┌', '┐', '└', '┘'}
	//  []rune{'═','║','╔','╗','╚','╝'}
	// 11 runes which can be used with `gocui.Gui.SupportOverlaps` property.
	//  []rune{'─', '│', '┌', '┐', '└', '┘', '├', '┤', '┬', '┴', '┼'}
	//  []rune{'═','║','╔','╗','╚','╝','╠','╣','╦','╩','╬'}
	FrameRunes []rune

	// If Wrap is true, the content that is written to this View is
	// automatically wrapped when it is longer than its width. If true the
	// view's x-origin will be ignored.
	Wrap bool

	// If Autoscroll is true, the View will automatically scroll down when the
	// text overflows. If true the view's y-origin will be ignored.
	Autoscroll bool

	// If Frame is true, Title allows to configure a title for the view.
	Title string

	// TitleColor allow to configure the color of title and subtitle for the view.
	TitleColor Attribute

	// If Frame is true, Subtitle allows to configure a subtitle for the view.
	Subtitle string

	// If Mask is true, the View will display the mask instead of the real
	// content
	Mask rune

	// Overlaps describes which edges are overlapping with another view's edges
	Overlaps byte

	// If HasLoader is true, the message will be appended with a spinning loader animation
	HasLoader bool

	// KeybindOnEdit should be set to true when you want to execute keybindings even when the view is editable
	// (this is usually not the case)
	KeybindOnEdit bool
	// contains filtered or unexported fields
}

A View is a window. It maintains its own internal buffer and cursor position.

func (*View) Buffer added in v0.2.0

func (v *View) Buffer() string

Buffer returns a string with the contents of the view's internal buffer.

func (*View) BufferLines added in v0.4.0

func (v *View) BufferLines() []string

BufferLines returns the lines in the view's internal buffer.

func (*View) Clear

func (v *View) Clear()

Clear empties the view and resets the view offsets, cursor position, read offsets and write offsets

func (*View) Cursor

func (v *View) Cursor() (x, y int)

Cursor returns the cursor position of the view.

func (*View) Dimensions added in v0.5.0

func (v *View) Dimensions() (int, int, int, int)

Dimensions returns the dimensions of the View

func (*View) EditDelete added in v0.2.0

func (v *View) EditDelete(back bool)

EditDelete deletes a rune at the cursor position. back determines the direction.

func (*View) EditDeleteToStartOfLine added in v1.0.0

func (v *View) EditDeleteToStartOfLine()

EditDeleteToStartOfLine is the equivalent of pressing ctrl+U in your terminal, it deletes to the start of the line. Or if you are already at the start of the line, it deletes the newline character

func (*View) EditGotoToEndOfLine added in v1.0.0

func (v *View) EditGotoToEndOfLine()

EditGotoToEndOfLine takes you to the end of the line

func (*View) EditGotoToStartOfLine added in v1.0.0

func (v *View) EditGotoToStartOfLine()

EditGotoToStartOfLine takes you to the start of the current line

func (*View) EditNewLine added in v0.2.0

func (v *View) EditNewLine()

EditNewLine inserts a new line under the cursor.

func (*View) EditWrite added in v0.2.0

func (v *View) EditWrite(ch rune)

EditWrite writes a rune at the cursor position.

func (*View) IsTainted added in v1.0.0

func (v *View) IsTainted() bool

IsTainted tells us if the view is tainted

func (*View) Line

func (v *View) Line(y int) (string, error)

Line returns a string with the line of the view's internal buffer at the position corresponding to the point (x, y).

func (*View) LinesHeight added in v0.5.0

func (v *View) LinesHeight() int

LinesHeight is the count of view lines (i.e. lines excluding wrapping)

func (*View) MoveCursor added in v0.2.0

func (v *View) MoveCursor(dx, dy int)

MoveCursor mores the cursor relative from it's current possition

func (*View) Name

func (v *View) Name() string

Name returns the name of the view.

func (*View) Origin

func (v *View) Origin() (x, y int)

Origin returns the origin position of the view.

func (*View) Read added in v0.2.0

func (v *View) Read(p []byte) (n int, err error)

Read reads data into p from the current reading position set by SetReadPos. It returns the number of bytes read into p. At EOF, err will be io.EOF.

func (*View) ReadPos added in v0.6.0

func (v *View) ReadPos() (x, y int)

ReadPos returns the current read position of the view's internal buffer.

func (*View) Rewind added in v0.2.0

func (v *View) Rewind()

Rewind sets read and write pos to (0, 0).

func (*View) SetCursor

func (v *View) SetCursor(x, y int) error

SetCursor tries sets the cursor position of the view at the given point If the x or y are outside of the buffer this function will place the cursor on the nearest buffer location

Rules:

y >= 0
x >= 0

func (*View) SetCursorUnrestricted added in v1.0.0

func (v *View) SetCursorUnrestricted(x, y int) error

SetCursorUnrestricted sets the cursor position of the view at the given point This does NOT check if the x and y location are available in the buffer

Rules:

y >= 0
x >= 0

func (*View) SetHighlight added in v0.6.0

func (v *View) SetHighlight(y int, on bool) error

SetHighlight toggles highlighting of separate lines, for custom lists or multiple selection in views.

func (*View) SetLine added in v0.6.0

func (v *View) SetLine(y int, text string) error

SetLine changes the contents of an existing line.

func (*View) SetOrigin

func (v *View) SetOrigin(x, y int) error

SetOrigin sets the origin position of the view's internal buffer, so the buffer starts to be printed from this point, which means that it is linked with the origin point of view. It can be used to implement Horizontal and Vertical scrolling with just incrementing or decrementing ox and oy.

func (*View) SetReadPos added in v0.6.0

func (v *View) SetReadPos(x, y int) error

SetReadPos sets the read position of the view's internal buffer. So the next Read call would read from the specified position.

func (*View) SetWritePos added in v0.6.0

func (v *View) SetWritePos(x, y int) error

SetWritePos sets the write position of the view's internal buffer. So the next Write call would write directly to the specified position.

func (*View) Size

func (v *View) Size() (x, y int)

Size returns the number of visible columns and rows in the View.

func (*View) ViewBuffer added in v0.2.0

func (v *View) ViewBuffer() string

ViewBuffer returns a string with the contents of the view's buffer that is shown to the user.

func (*View) ViewBufferLines added in v0.4.0

func (v *View) ViewBufferLines() []string

ViewBufferLines returns the lines in the view's internal buffer that is shown to the user.

func (*View) ViewLinesHeight added in v1.0.0

func (v *View) ViewLinesHeight() int

ViewLinesHeight is the count of view lines (i.e. lines including wrapping)

func (*View) Word

func (v *View) Word(x, y int) (string, error)

Word returns a string with the word of the view's internal buffer at the position corresponding to the point (x, y).

func (*View) Write

func (v *View) Write(p []byte) (n int, err error)

Write appends a byte slice into the view's internal buffer. Because View implements the io.Writer interface, it can be passed as parameter of functions like fmt.Fprintf, fmt.Fprintln, io.Copy, etc. Clear must be called to clear the view's buffer.

func (*View) WritePos added in v0.6.0

func (v *View) WritePos() (x, y int)

WritePos returns the current write position of the view's internal buffer.

func (*View) WriteRunes added in v0.6.0

func (v *View) WriteRunes(p []rune)

func (*View) WriteString added in v0.6.0

func (v *View) WriteString(s string)

Directories

Path Synopsis
_examples module

Jump to

Keyboard shortcuts

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