gocui

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2020 License: BSD-3-Clause Imports: 7 Imported by: 0

README

GOCUI - Go Console User Interface

GoDoc

Minimalist Go package aimed at creating Console User Interfaces.

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 edition mode.
  • Easy to build reusable widgets, complex layouts...

Installation

Execute:

$ go get github.com/jroimartin/gocui

Documentation

Execute:

$ go doc github.com/jroimartin/gocui

Or visit godoc.org to read it online.

Example

package main

import (
	"fmt"
	"log"

	"github.com/jroimartin/gocui"
)

func main() {
	g, err := gocui.NewGui(gocui.OutputNormal)
	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 && 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); err != nil {
		if err != gocui.ErrUnknownView {
			return err
		}
		fmt.Fprintln(v, "Hello world!")
	}
	return nil
}

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

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.

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

Documentation

Overview

Help editor to Input cjk language.

Package gocui allows to create console user interfaces.

Create a new GUI:

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

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

if err := g.MainLoop(); err != nil && 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); err != nil {
	if 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); 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 edition 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 Attribute = Attribute(termbox.ColorDefault)
	ColorBlack             = Attribute(termbox.ColorBlack)
	ColorRed               = Attribute(termbox.ColorRed)
	ColorGreen             = Attribute(termbox.ColorGreen)
	ColorYellow            = Attribute(termbox.ColorYellow)
	ColorBlue              = Attribute(termbox.ColorBlue)
	ColorMagenta           = Attribute(termbox.ColorMagenta)
	ColorCyan              = Attribute(termbox.ColorCyan)
	ColorWhite             = Attribute(termbox.ColorWhite)
)

Color attributes.

View Source
const (
	AttrBold      Attribute = Attribute(termbox.AttrBold)
	AttrUnderline           = Attribute(termbox.AttrUnderline)
	AttrReverse             = Attribute(termbox.AttrReverse)
)

Text style attributes.

View Source
const (
	// OutputNormal provides 8-colors terminal mode.
	OutputNormal = OutputMode(termbox.OutputNormal)

	// Output256 provides 256-colors terminal mode.
	Output256 = OutputMode(termbox.Output256)
)
View Source
const (
	KeyF1         Key = Key(termbox.KeyF1)
	KeyF2             = Key(termbox.KeyF2)
	KeyF3             = Key(termbox.KeyF3)
	KeyF4             = Key(termbox.KeyF4)
	KeyF5             = Key(termbox.KeyF5)
	KeyF6             = Key(termbox.KeyF6)
	KeyF7             = Key(termbox.KeyF7)
	KeyF8             = Key(termbox.KeyF8)
	KeyF9             = Key(termbox.KeyF9)
	KeyF10            = Key(termbox.KeyF10)
	KeyF11            = Key(termbox.KeyF11)
	KeyF12            = Key(termbox.KeyF12)
	KeyInsert         = Key(termbox.KeyInsert)
	KeyDelete         = Key(termbox.KeyDelete)
	KeyHome           = Key(termbox.KeyHome)
	KeyEnd            = Key(termbox.KeyEnd)
	KeyPgup           = Key(termbox.KeyPgup)
	KeyPgdn           = Key(termbox.KeyPgdn)
	KeyArrowUp        = Key(termbox.KeyArrowUp)
	KeyArrowDown      = Key(termbox.KeyArrowDown)
	KeyArrowLeft      = Key(termbox.KeyArrowLeft)
	KeyArrowRight     = Key(termbox.KeyArrowRight)

	MouseLeft      = Key(termbox.MouseLeft)
	MouseMiddle    = Key(termbox.MouseMiddle)
	MouseRight     = Key(termbox.MouseRight)
	MouseRelease   = Key(termbox.MouseRelease)
	MouseWheelUp   = Key(termbox.MouseWheelUp)
	MouseWheelDown = Key(termbox.MouseWheelDown)
)

Special keys.

View Source
const (
	KeyCtrlTilde      Key = Key(termbox.KeyCtrlTilde)
	KeyCtrl2              = Key(termbox.KeyCtrl2)
	KeyCtrlSpace          = Key(termbox.KeyCtrlSpace)
	KeyCtrlA              = Key(termbox.KeyCtrlA)
	KeyCtrlB              = Key(termbox.KeyCtrlB)
	KeyCtrlC              = Key(termbox.KeyCtrlC)
	KeyCtrlD              = Key(termbox.KeyCtrlD)
	KeyCtrlE              = Key(termbox.KeyCtrlE)
	KeyCtrlF              = Key(termbox.KeyCtrlF)
	KeyCtrlG              = Key(termbox.KeyCtrlG)
	KeyBackspace          = Key(termbox.KeyBackspace)
	KeyCtrlH              = Key(termbox.KeyCtrlH)
	KeyTab                = Key(termbox.KeyTab)
	KeyCtrlI              = Key(termbox.KeyCtrlI)
	KeyCtrlJ              = Key(termbox.KeyCtrlJ)
	KeyCtrlK              = Key(termbox.KeyCtrlK)
	KeyCtrlL              = Key(termbox.KeyCtrlL)
	KeyEnter              = Key(termbox.KeyEnter)
	KeyCtrlM              = Key(termbox.KeyCtrlM)
	KeyCtrlN              = Key(termbox.KeyCtrlN)
	KeyCtrlO              = Key(termbox.KeyCtrlO)
	KeyCtrlP              = Key(termbox.KeyCtrlP)
	KeyCtrlQ              = Key(termbox.KeyCtrlQ)
	KeyCtrlR              = Key(termbox.KeyCtrlR)
	KeyCtrlS              = Key(termbox.KeyCtrlS)
	KeyCtrlT              = Key(termbox.KeyCtrlT)
	KeyCtrlU              = Key(termbox.KeyCtrlU)
	KeyCtrlV              = Key(termbox.KeyCtrlV)
	KeyCtrlW              = Key(termbox.KeyCtrlW)
	KeyCtrlX              = Key(termbox.KeyCtrlX)
	KeyCtrlY              = Key(termbox.KeyCtrlY)
	KeyCtrlZ              = Key(termbox.KeyCtrlZ)
	KeyEsc                = Key(termbox.KeyEsc)
	KeyCtrlLsqBracket     = Key(termbox.KeyCtrlLsqBracket)
	KeyCtrl3              = Key(termbox.KeyCtrl3)
	KeyCtrl4              = Key(termbox.KeyCtrl4)
	KeyCtrlBackslash      = Key(termbox.KeyCtrlBackslash)
	KeyCtrl5              = Key(termbox.KeyCtrl5)
	KeyCtrlRsqBracket     = Key(termbox.KeyCtrlRsqBracket)
	KeyCtrl6              = Key(termbox.KeyCtrl6)
	KeyCtrl7              = Key(termbox.KeyCtrl7)
	KeyCtrlSlash          = Key(termbox.KeyCtrlSlash)
	KeyCtrlUnderscore     = Key(termbox.KeyCtrlUnderscore)
	KeySpace              = Key(termbox.KeySpace)
	KeyBackspace2         = Key(termbox.KeyBackspace2)
	KeyCtrl8              = Key(termbox.KeyCtrl8)
)

Keys combinations.

Variables

View Source
var (
	// ErrQuit is used to decide if the MainLoop finished successfully.
	ErrQuit = errors.New("quit")

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

Functions

This section is empty.

Types

type Attribute

type Attribute termbox.Attribute

Attribute represents a terminal attribute, like color, font style, etc. They can be combined using bitwise OR (|). Note that it is not possible to combine multiple color attributes.

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 Attribute

	// SelBgColor and SelFgColor allow to configure the background and
	// foreground colors of the frame of the current view.
	SelBgColor, SelFgColor 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
	// contains filtered or unexported fields
}

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

func NewGui

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

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

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) MainLoop

func (g *Gui) MainLoop() error

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

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.

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) (*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) 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) 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.

type Key

type Key termbox.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 termbox.Modifier

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

const (
	ModNone Modifier = Modifier(0)
	ModAlt           = Modifier(termbox.ModAlt)
)

Modifiers.

type OutputMode added in v0.4.0

type OutputMode termbox.OutputMode

OutputMode represents the terminal's output mode (8 or 256 colors).

type View

type View struct {

	// 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 edition 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

	// 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

	// If Mask is true, the View will display the mask instead of the real
	// content
	Mask rune
	// 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's internal buffer.

func (*View) Cursor

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

Cursor returns the cursor position 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) 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) 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) MoveCursor added in v0.2.0

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

MoveCursor moves the cursor taking into account the width of the line/view, displacing the origin if necessary.

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. It returns the number of bytes read into p. At EOF, err will be io.EOF. Calling Read() after Rewind() makes the cache to be refreshed with the contents of the view.

func (*View) ReadEditor added in v0.4.1

func (v *View) ReadEditor() []byte

ReadEditor Read byte array from editor 'v', delete the auto appended blank after CJK runes.

func (*View) Rewind added in v0.2.0

func (v *View) Rewind()

Rewind sets the offset for the next Read to 0, which also refresh the read cache.

func (*View) SetCursor

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

SetCursor sets the cursor position of the view at the given point, relative to the view. It checks if the position is valid.

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) 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) 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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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