clui

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2018 License: MIT Imports: 15 Imported by: 0

README

CLUI

Command Line User Interface (Console UI inspired by TurboVision) with built-in theme support. Please see screenshots of working examples at the end of the README.

Installation

go get -u github.com/VladimirMarkelov/clui

Current version

The current version is 0.6.2. Please see details in changelog.

Applications that uses the library

Documentation

  • Introduction
  • Getting started
  • Layout manager
  • Basic standrd control methods and properties
  • About Windows
  • Predefined hotkeys

The list of available controls

  • Window (Main control container - with maximize, window order and other window features)
  • Label (Horizontal and Vertical with basic color control tags)
  • Button (Simple push button control)
  • EditField (One line text edit control with basic clipboard control)
  • ListBox (string list control with vertical scroll)
  • TextView (ListBox-alike control with vertical and horizontal scroll, and wordwrap mode)
  • ProgressBar (Vertical and horizontal. The latter one supports custom text over control)
  • Frame (A decorative control that can be a container for other controls as well)
  • CheckBox (Simple check box)
  • Radio (Simple radio button. Useless alone - should be used along with RadioGroup)
  • RadioGroup (Non-visual control to manage a group of a few RadioButtons)
  • ConfirmationDialog (modal View to ask a user confirmation, button titles are custom)
  • SelectDialog (modal View to ask a user to select an item from the list - list can be ListBox or RadioGroup)
  • BarChart (Horizontal bar chart without scroll)
  • SparkChart (Show tabular data as a bar graph)
  • GridView (Table to show structured data - only virtual and readonly mode with scroll support)

Screenshots

The main demo (theme changing and radio group control)

Main Demo

The screencast of demo:

Library Demo

The library is in the very beginning but it can be used to create working utilities: below is the example of my Dilbert comix downloader:

Dilbert Downloader

Documentation

Overview

Package clui is an UI library to create simple interactive console applications. Inspired by Borland TurboVision.

The library includes a set of simple but useful controls to create a multi-Windows application with mouse support easily. Available at this moment controls:

  • EditField is one line edit text control
  • Label is static control to output single- or multi-line texts. The control supports multicolor output with tags
  • Frame is a border decoration and container
  • ListBox is a control to display a set of items with scrollbar
  • CheckBox is a control to allow to choose between 2 or 3 choices
  • RadioGroup is a control to select one item of the available
  • ProgressBar is a control to show some task progress
  • Button is push button control
  • Dialogs for a user to confirm something or to choose an item
  • more controls to come later

* Drag-n-drop with mouse is not supported due to limitations of some terminals.

Built-in theme support feature. Change the control look instantly without restarting the application

Predefined hotkeys(hardcoded). One touch combinations:

  • TAB to select the next control in the current View
  • Alt+PgDn, Alt+PgUp to select next or previous control in the current View, respectively. Hotkeys added because it is not possible to catch TAB contol with Shift or Ctrl modifier
  • Space to click a Button, CheckBox or RadioGroup if the control is active
  • Ctrl+R to clear the EditField
  • Arrows, Home, and End to move cursor inside EditField and ListBox

Sequences:

At first one should press a sequence start combination:
    Ctrl+W to execute any View related command
    Ctrl+P to begin changing View position
    Ctrl+S to begin changing View size
    Ctrl+Q is used only to quit application - press Ctrl+Q twice
And the next pressed key is considered as a subcomand:
    Ctrl+S and Ctrl+P processes only arrows. These commands supports
        multi-press - while one presses the same arrow after Ctrl+*, he/she
        does not need to press Ctrl+P or Ctrl+S before pressing each arrow
    Ctrl+W allow to:
        Ctrl+H moves the View to the bottom of View stack and activates a
            View below the View
        Ctrl+M maximizes or restores the current View
        Ctrl+C closes the current View. If it is the only View the application
            closes

Index

Constants

View Source
const (
	// ElemPrintable - the item is a rune
	ElemPrintable = iota
	// ElemBackColor - the item sets new background color
	ElemBackColor
	// ElemTextColor - the item sets new text color
	ElemTextColor
	// ElemLineBreak - line break
	ElemLineBreak
	// ElemEndOfText - the string parsing has complited
	ElemEndOfText
)

TextElementType values

View Source
const (
	// Fixed means 'never change size of the object when its parent resizes'
	Fixed int = 0
	// AutoSize is used only in constructors. It means that the constructor
	// should either calculate the size of an object, e.g. for Label it is its text
	// length, or use default intial values
	AutoSize int = -1
	// KeepSize is used as a placeholder when you want to change only one
	// value and keep other ones untouched. Used in SetSize and SetConstraints
	// methods only
	// Example: control.SetConstraint(10, KeepValue) changes only minimal width
	// of the control and do not change the current minimal control height
	KeepValue int = -1
)
View Source
const (
	ColorDefault     = term.ColorDefault
	ColorBlack       = term.ColorBlack
	ColorRed         = term.ColorRed
	ColorGreen       = term.ColorGreen
	ColorYellow      = term.ColorYellow
	ColorBlue        = term.ColorBlue
	ColorMagenta     = term.ColorMagenta
	ColorCyan        = term.ColorCyan
	ColorWhite       = term.ColorWhite
	ColorBlackBold   = term.ColorBlack | term.AttrBold
	ColorRedBold     = term.ColorRed | term.AttrBold
	ColorGreenBold   = term.ColorGreen | term.AttrBold
	ColorYellowBold  = term.ColorYellow | term.AttrBold
	ColorBlueBold    = term.ColorBlue | term.AttrBold
	ColorMagentaBold = term.ColorMagenta | term.AttrBold
	ColorCyanBold    = term.ColorCyan | term.AttrBold
	ColorWhiteBold   = term.ColorWhite | term.AttrBold
)

Color predefined values

View Source
const (
	// ButtonDefault - no button
	ButtonDefault ViewButton = 0
	// ButtonClose - button to close View
	ButtonClose = 1 << 0
	// ButtonBottom -  move Window to bottom of the View stack
	ButtonBottom = 1 << 1
	// ButtonMaximaize - maximize and restore View
	ButtonMaximize = 1 << 2
)

VeiwButton values - list of buttons available for using in View title

View Source
const (
	Horizontal = iota
	Vertical
)

Output direction Used for Label text output direction and for Radio items distribution, and for container controls

View Source
const (
	ObjSingleBorder = "SingleBorder"
	ObjDoubleBorder = "DoubleBorder"
	ObjEdit         = "Edit"
	ObjScrollBar    = "ScrollBar"
	ObjViewButtons  = "ViewButtons"
	ObjCheckBox     = "CheckBox"
	ObjRadio        = "Radio"
	ObjProgressBar  = "ProgressBar"
	ObjBarChart     = "BarChart"
	ObjSparkChart   = "SparkChart"
	ObjTableView    = "TableView"
)

Available object identifiers that can be used in themes

View Source
const (
	// Window back and fore colors (inner area & border)
	ColorViewBack = "ViewBack"
	ColorViewText = "ViewText"

	// general colors
	ColorBack         = "Back"
	ColorText         = "Text"
	ColorDisabledText = "GrayText"
	ColorDisabledBack = "GrayBack"

	// editable & listbox-like controls
	ColorEditBack       = "EditBack"
	ColorEditText       = "EditText"
	ColorEditActiveBack = "EditActiveBack"
	ColorEditActiveText = "EditActiveText"
	ColorSelectionText  = "SelectionText"
	ColorSelectionBack  = "SelectionBack"

	// button control
	ColorButtonBack         = "ButtonBack"
	ColorButtonText         = "ButtonText"
	ColorButtonActiveBack   = "ButtonActiveBack"
	ColorButtonActiveText   = "ButtonActiveText"
	ColorButtonShadow       = "ButtonShadowBack"
	ColorButtonDisabledBack = "ButtonDisabledBack"
	ColorButtonDisabledText = "ButtonDisabledText"

	// scroll control
	ColorScrollText = "ScrollText"
	ColorScrollBack = "ScrollBack"
	ColorThumbText  = "ThumbText"
	ColorThumbBack  = "ThumbBack"

	// window-like controls (button, radiogroup...)
	ColorControlText         = "ControlText"
	ColorControlBack         = "ControlBack"
	ColorControlActiveBack   = "ControlActiveBack"
	ColorControlActiveText   = "ControlActiveText"
	ColorControlDisabledBack = "ControlDisabledBack"
	ColorControlDisabledText = "ControlDisabledText"
	ColorControlShadow       = "ControlShadowBack"

	// progressbar colors
	ColorProgressBack       = "ProgressBack"
	ColorProgressText       = "ProgressText"
	ColorProgressActiveBack = "ProgressActiveBack"
	ColorProgressActiveText = "ProgressActiveText"
	ColorProgressTitleText  = "ProgressTitle"

	// barchart colors
	ColorBarChartBack = "BarChartBack"
	ColorBarChartText = "BarChartText"

	// sparkchart colors
	ColorSparkChartBack    = "SparkChartBack"
	ColorSparkChartText    = "SparkChartText"
	ColorSparkChartBarBack = "SparkChartBarBack"
	ColorSparkChartBarText = "SparkChartBarText"
	ColorSparkChartMaxBack = "SparkChartMaxBack"
	ColorSparkChartMaxText = "SparkChartMaxText"

	// tableview colors
	ColorTableText           = "TableText"
	ColorTableBack           = "TableBack"
	ColorTableSelectedText   = "TableSelectedText"
	ColorTableSelectedBack   = "TableSelectedBack"
	ColorTableActiveCellText = "TableActiveCellText"
	ColorTableActiveCellBack = "TableActiveCellBack"
	ColorTableLineText       = "TableLineText"
	ColorTableHeaderText     = "TableHeaderText"
	ColorTableHeaderBack     = "TableHeaderBack"
)

Available color identifiers that can be used in themes

View Source
const (
	// a key pressed
	EventKey EventType = iota
	// an object or console size changed. X and Y are new width and height
	EventResize
	// Mouse button clicked. X and Y are coordinates of mouse click
	EventMouse
	// Something bad happened
	EventError
	EventInterrupt
	EventRaw
	EventNone

	// Asks an object to redraw. A library can ask a control to redraw and control can send the event to its parent to ask for total repaint, e.g, button sends redraw event after to its parent it depressed after a while to imitate real button
	EventRedraw = iota + 100
	// an object that receives the event should close and destroys itself
	EventClose
	// Notify an object when it is activated or deactivated. X determines whether the object is activated or deactivated(0 - deactivated, 1 - activated)
	EventActivate
	// An object changes its position. X and Y are new coordinates of the object
	EventMove

	/*
	   control events
	*/
	// Content of a control changed. E.g, EditField text changed, selected item of ListBox changed etc
	// X defines how the content was changed: 0 - by pressing any key, 1 - by clicking mouse. This is used by compound controls, e.g, child ListBox of ComboBox should change its parent EditField text when a user selects a new item an ListBox with arrow keys and the ListBox should be closed if a user clicks on ListBox item
	EventChanged
	// Button event - button was clicked
	EventClick
	// dialog closed
	EventDialogClose
	// Close application
	EventQuit
	// Close top window - or application is there is only one window
	EventCloseWindow
)

EventType is event that window or control may process Note: Do not change events from EventKey to EventNone - they correspond to the same named events in termbox library

View Source
const (
	// DialogClosed - a user clicked close button on the dialog title
	DialogClosed = -1
	// DialogAlive - a user does not close the dialog yet, exit code is unavailable
	DialogAlive = 0
	// DialogButton1 - a user clicked the first button in the dialog (by default, it is 'Yes' or 'OK')
	DialogButton1 = 1
	// DialogButton2 - a user clicked the second button in the dialog
	DialogButton2 = 2
	// DialogButton3 - a user clicked the third button in the dialog
	DialogButton3 = 3
)

ConfirmationDialog and SelectDialog exit codes

Variables

View Source
var (
	ButtonsOK          = []string{"OK"}
	ButtonsYesNo       = []string{"Yes", "No"}
	ButtonsYesNoCancel = []string{"Yes", "No", "Cancel"}
)

Predefined sets of the buttons for ConfirmationDialog and SelectDialog

Functions

func ActivateControl

func ActivateControl(parent, control Control) bool

ActivateControl makes control active and disables all other children of the parent. Returns true if control was found and activated

func AlignColorizedText

func AlignColorizedText(str string, width int, align Align) (int, string)

AlignColorizedText does the same as AlignText does but it preserves the color of the letters by adding correct color tags to the line beginning. Note: function is ineffective and a bit slow - do not use it everywhere

func AlignText

func AlignText(str string, width int, align Align) (shift int, out string)

AlignText calculates the initial position of the text output depending on str length and available width. The str is truncated in case of its lenght greater than width. Function returns shift that should be added to original label position before output instead of padding the string with spaces. The reason is to make possible to draw a label aligned but with transparent beginning and ending. If you do not need transparency you can add spaces manually using the returned shift value

func BackColor

func BackColor() term.Attribute

func ClipRect

func ClipRect() (x int, y int, w int, h int)

ClipRect returns the current clipping rectangle

func ColorToString

func ColorToString(attr term.Attribute) string

ColorToString returns string representation of the attribute

func CurrentTheme

func CurrentTheme() string

CurrentTheme returns name of the current theme

func CutText

func CutText(str string, maxWidth int) string

CutText makes a text no longer than maxWidth

func DeactivateControls

func DeactivateControls(parent Control)

DeactivateControls makes all children of parent inactive

func DeinitLibrary

func DeinitLibrary()

Close closes console management and makes a console cursor visible

func DrawFrame

func DrawFrame(x, y, w, h int, border BorderStyle)

DrawFrame paints the frame without changing area inside it

func DrawHorizontalLine

func DrawHorizontalLine(x, y, w int, r rune)

DrawHorizontalLine draws the part of the horizontal line that is inside current clipping rectangle

func DrawRawText

func DrawRawText(x, y int, text string)

DrawRawText draws the part of text that is inside the current clipping rectangle. DrawRawText always paints string as is - no color changes. If you want to draw string with color changing commands included then use DrawText function

func DrawRawTextVertical

func DrawRawTextVertical(x, y int, text string)

DrawRawTextVertical draws the part of text that is inside the current clipping rectangle. DrawRawTextVertical always paints string as is - no color changes. If you want to draw string with color changing commands included then use DrawTextVertical function

func DrawScrollBar

func DrawScrollBar(x, y, w, h, pos int)

DrawScrollBar displays a scrollbar. pos is the position of the thumb. The function detects direction of the scrollbar automatically: if w is greater than h then it draws horizontal scrollbar and vertical otherwise

func DrawText

func DrawText(x, y int, text string)

DrawText draws the part of text that is inside the current clipping rectangle. DrawText always paints colorized string. If you want to draw raw string then use DrawRawText function

func DrawTextVertical

func DrawTextVertical(x, y int, text string)

DrawTextVertical draws the part of text that is inside the current clipping rectangle. DrawTextVertical always paints colorized string. If you want to draw raw string then use DrawRawTextVertical function

func DrawVerticalLine

func DrawVerticalLine(x, y, h int, r rune)

DrawVerticalLine draws the part of the vertical line that is inside current clipping rectangle

func Ellipsize

func Ellipsize(str string, maxWidth int) string

Ellipsize truncates text to maxWidth by replacing a substring in the middle with ellipsis and keeping the beginning and ending of the string untouched. If maxWidth is less than 5 then no ellipsis is added, the text is just truncated from the right.

func FillRect

func FillRect(x, y, w, h int, r rune)

FillRect paints the area with r character using the current colors

func Flush

func Flush()

Flush makes termbox to draw everything to screen

func GrabEvents

func GrabEvents(c Control)

GrabEvents makes control c as the exclusive event reciever. After calling this function the control will recieve all mouse and keyboard events even if it is not active or mouse is outside it. Useful to implement dragging or alike stuff

func InClipRect

func InClipRect(x, y int) bool

InClipRect returns true if x and y position is inside current clipping rectangle

func InitLibrary

func InitLibrary() bool

func InitLogger

func InitLogger()

func IsDeadKey

func IsDeadKey(key term.Key) bool

IsDeadKey returns true if the pressed key is the first key in the key sequence understood by composer. Dead key is never sent to any control

func IsMouseClickEvent

func IsMouseClickEvent(ev Event) bool

IsMouseClickEvent returns if a user action can be treated as mouse click.

func ItemByThumbPosition

func ItemByThumbPosition(position, itemCount, length int) int

ItemByThumbPosition calculates item number by scrollbar thumb position. Position - thumb position inside scrollbar, itemCount - total number of items, lenght - lenght or heigth of scrollbar. Return -1 if it is not possible to calculate: e.g, itemCount equals zero

func Logger

func Logger() *log.Logger

func MainLoop

func MainLoop()

MainLoop starts the main application event loop

func PopAttributes

func PopAttributes()

PopAttributes restores saved with PushAttributes colors. Function does nothing if there is no saved colors

func PopClip

func PopClip()

PopClip restores saved with PushClip clipping window

func ProcessEvent

func ProcessEvent(ev Event)

func PushAttributes

func PushAttributes()

PushAttributes saves the current back and fore colors. Useful when used with PopAttributes: you can save colors then change them to anything you like and as the final step just restore original colors

func PushClip

func PushClip()

PushClip saves the current clipping window

func PutChar

func PutChar(x, y int, r rune) bool

PutChar sets value for the Canvas cell: rune and its colors. Returns result of operation: e.g, if the symbol position is outside Canvas the operation fails and the function returns false

func PutEvent

func PutEvent(ev Event)

PutEvent send event to a Composer directly. Used by Views to ask for repainting or for quitting the application

func RealColor

func RealColor(clr term.Attribute, id string) term.Attribute

RealColor returns attribute that should be applied to an object. By default all attributes equal ColorDefault and the real color should be retrieved from the current theme. Attribute selection work this way: if color is not ColorDefault, it is returned as is, otherwise the function tries to load color from the theme. clr - current object color id - color ID in theme

func RefreshScreen

func RefreshScreen()

Repaints everything on the screen

func ReleaseEvents

func ReleaseEvents()

ReleaseEvents stops a control being exclusive evetn reciever and backs all to normal event processing

func ReloadTheme

func ReloadTheme(name string)

ReloadTheme refresh cache entry for the theme with new data loaded from file. Use it to apply theme changes on the fly without resetting manager or restarting application

func Reset

func Reset()

Reset reinitializes canvas: set clipping rectangle to the whole terminal window, clears clip and color saved data, sets colors to default ones

func ScreenSize

func ScreenSize() (width int, height int)

Size returns current Canvas size

func SendEventToChild

func SendEventToChild(parent Control, ev Event) bool

SendEventToChild tries to find a child control that should recieve the evetn For mouse click events it looks for a control at coordinates of event, makes it active, and then sends the event to it. If it is not mouse click event then it looks for the first active child and sends the event to it if it is not nil

func SetBackColor

func SetBackColor(clr term.Attribute)

SetBackColor changes current background color

func SetClipRect

func SetClipRect(x, y, w, h int)

SetClipRect defines a new clipping rect. Maybe useful with PopClip and PushClip functions

func SetCurrentTheme

func SetCurrentTheme(name string) bool

SetCurrentTheme changes the current theme. Returns false if changing failed - e.g, theme does not exist

func SetCursorPos

func SetCursorPos(x int, y int)

SetCursorPos sets text caret position. Used by controls like EditField

func SetScreenSize

func SetScreenSize(width int, height int)

SetSize sets the new Canvas size. If new size does not equal old size then Canvas is recreated and cleared with default colors. Both Canvas width and height must be greater than 2

func SetTextColor

func SetTextColor(clr term.Attribute)

SetTextColor changes current text color

func SetThemePath

func SetThemePath(path string)

SetThemePath changes the directory that contains themes. If new path does not equal old one, theme list reloads

func SliceColorized

func SliceColorized(str string, start, end int) string

SliceColorized returns a slice of text with correct color tags. start and end are real printable rune indices

func Stop

func Stop()

Stop sends termination event to Composer. Composer should stop console management and quit application

func StringToColor

func StringToColor(str string) term.Attribute

StringToColor returns attribute by its string description. Description is the list of attributes separated with spaces, plus or pipe symbols. You can use 8 base colors: black, white, red, green, blue, magenta, yellow, cyan and a few modifiers: bold or bright, underline or underlined, reverse Note: some terminals do not support all modifiers, e.g, Windows one understands only bold/bright - it makes the color brighter with the modidierA Examples: "red bold", "green+underline+bold"

func Symbol

func Symbol(x, y int) (term.Cell, bool)

Symbol returns the character and its attributes by its coordinates

func SysColor

func SysColor(color string) term.Attribute

SysColor returns attribute by its id for the current theme. The method panics if theme loop is detected - check if parent attribute is correct

func SysObject

func SysObject(object string) string

SysObject returns object look by its id for the current theme. E.g, border lines for frame or arrows for scrollbar. The method panics if theme loop is detected - check if parent attribute is correct

func TextColor

func TextColor() term.Attribute

func TextExtent

func TextExtent(text string) (int, int)

TextExtent calculates the width and the height of the text

func ThemeNames

func ThemeNames() []string

ThemeNames returns the list of short theme names (file names)

func ThemePath

func ThemePath() string

ThemePath returns the current directory with theme inside it

func ThemeReset

func ThemeReset()

Reset removes all loaded themes from cache and reinitialize the default theme

func ThumbPosition

func ThumbPosition(itemNo, itemCount, length int) int

ThumbPosition returns a scrollbar thumb position depending on currently active item(itemNo), total number of items (itemCount), and length/height of the scrollbar(length) including arrows. Returns position in interval of (1..lenght-2) or -1 if the thumb is not visible

func UnColorizeText

func UnColorizeText(str string) string

UnColorizeText removes all color-related tags from the string. Tags to remove: <(f|t|b|c):.*>

Types

type Align

type Align int

Align is text align: left, right and center

const (
	AlignLeft Align = iota
	AlignRight
	AlignCenter
)

Alignment constants

type BarChart

type BarChart struct {
	BaseControl
	// contains filtered or unexported fields
}

BarChart is a chart that represents grouped data with rectangular bars. It can be monochrome - defaut behavior. One can assign individual color to each bar and even use custom drawn bars to display multicolored bars depending on bar value. All bars have the same width: either constant BarSize - in case of AutoSize is false, or automatically calculated but cannot be less than BarSize. Bars that do not fit the chart area are not displayed. BarChart displays vertical axis with values on the chart left if ValueWidth greater than 0, horizontal axis with bar titles if ShowTitles is true (to enable displaying marks on horizontal axis, set ShowMarks to true), and chart legend on the right if LegendWidth is greater than 3. If LegendWidth is greater than half of the chart it is not displayed. The same is applied to ValueWidth

func CreateBarChart

func CreateBarChart(parent Control, w, h int, scale int) *BarChart

NewBarChart creates a new bar chart. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. w and h - are minimal size of the control. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*BarChart) AddData

func (b *BarChart) AddData(val BarData)

AddData appends a new bar to a chart

func (*BarChart) AutoSize

func (b *BarChart) AutoSize() bool

AutoSize returns whether automatic bar width calculation is on. If AutoSize is false then all bars have width BarWidth. If AutoSize is true then bar width is the maximum of three values: BarWidth, calculated width that makes all bars fit the bar chart area, and 1

func (*BarChart) BarGap

func (b *BarChart) BarGap() int32

Gap returns width of visual gap between two adjacent bars

func (*BarChart) ClearData

func (b *BarChart) ClearData()

ClearData removes all bar from chart

func (*BarChart) Draw

func (b *BarChart) Draw()

Repaint draws the control on its View surface

func (*BarChart) LegendWidth

func (b *BarChart) LegendWidth() int32

LegendWidth returns width of chart legend displayed at the right side of the chart. Set it to 0 to disable legend

func (*BarChart) MinBarWidth

func (b *BarChart) MinBarWidth() int32

MinBarWidth returns current minimal bar width

func (*BarChart) OnDrawCell

func (b *BarChart) OnDrawCell(fn func(*BarDataCell))

OnDrawCell sets callback that allows to draw multicolored bars. BarChart sends the current attrubutes and rune that it is going to use to display as well as the current value of the bar. A user can change the values of BarDataCell depending on some external data or calculations - only changing colors and rune makes sense. Changing anything else does not affect the chart

func (*BarChart) SetAutoSize

func (b *BarChart) SetAutoSize(auto bool)

SetAutoSize enables or disables automatic bar width calculation

func (*BarChart) SetBarGap

func (b *BarChart) SetBarGap(gap int32)

SetGap sets the space width between two adjacent bars

func (*BarChart) SetData

func (b *BarChart) SetData(data []BarData)

SetData assign a new bar list to a chart

func (*BarChart) SetLegendWidth

func (b *BarChart) SetLegendWidth(width int32)

SetLegendWidth sets new legend panel width

func (*BarChart) SetMinBarWidth

func (b *BarChart) SetMinBarWidth(size int32)

SetMinBarWidth changes the minimal bar width

func (*BarChart) SetShowMarks

func (b *BarChart) SetShowMarks(show bool)

SetShowMarks turns on and off marks under horizontal axis

func (*BarChart) SetShowTitles

func (b *BarChart) SetShowTitles(show bool)

SetShowTitles turns on and off horizontal axis and bar titles

func (*BarChart) SetValueWidth

func (b *BarChart) SetValueWidth(width int32)

SetValueWidth changes width of the value panel on the left

func (*BarChart) ShowMarks

func (b *BarChart) ShowMarks() bool

ShowMarks returns if horizontal axis has mark under each bar. To show marks, ShowTitles must be enabled.

func (*BarChart) ShowTitles

func (b *BarChart) ShowTitles() bool

ShowTitles returns if chart displays horizontal axis and bar titles under it

func (*BarChart) ValueWidth

func (b *BarChart) ValueWidth() int32

ValueWidth returns the width of the area at the left of chart used to draw values. Set it to 0 to turn off the value panel

type BarData

type BarData struct {
	Value float64
	Title string
	Fg    term.Attribute
	Bg    term.Attribute
	Ch    rune
}

BarData is info about one bar in the chart. Every bar can be customized by setting its own colors and rune to draw the bar. Use ColorDefault for Fg and Bg, and 0 for Ch to draw with BarChart defaults

type BarDataCell

type BarDataCell struct {
	// Title of the bar
	Item string
	// order number of the bar
	ID int
	// value of the bar that is currently drawn
	Value float64
	// maximum value of the bar
	BarMax float64
	// value of the highest bar
	TotalMax float64
	// Default attributes and rune to draw the bar
	Fg term.Attribute
	Bg term.Attribute
	Ch rune
}

BarDataCell is used in callback to user to draw with customized colors and runes

type BaseControl

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

BaseControl is a base for all visible controls. Every new control must inherit it or implement the same set of methods

func (*BaseControl) Active

func (c *BaseControl) Active() bool

func (*BaseControl) ActiveColors

func (c *BaseControl) ActiveColors() (term.Attribute, term.Attribute)

ActiveColors return the attrubutes for the controls when it is active: text and background colors

func (*BaseControl) AddChild

func (c *BaseControl) AddChild(control Control)

func (*BaseControl) Align

func (c *BaseControl) Align() Align

func (*BaseControl) BackColor

func (c *BaseControl) BackColor() term.Attribute

func (*BaseControl) ChildExists

func (c *BaseControl) ChildExists(control Control) bool

func (*BaseControl) Children

func (c *BaseControl) Children() []Control

func (*BaseControl) ChildrenScale

func (c *BaseControl) ChildrenScale() int

func (*BaseControl) Constraints

func (c *BaseControl) Constraints() (minw int, minh int)

func (*BaseControl) Draw

func (c *BaseControl) Draw()

func (*BaseControl) DrawChildren

func (c *BaseControl) DrawChildren()

func (*BaseControl) Enabled

func (c *BaseControl) Enabled() bool

func (*BaseControl) Gaps

func (c *BaseControl) Gaps() (dx int, dy int)

func (*BaseControl) HitTest

func (c *BaseControl) HitTest(x, y int) HitResult

func (*BaseControl) MinimalSize

func (c *BaseControl) MinimalSize() (w int, h int)

func (*BaseControl) Modal

func (c *BaseControl) Modal() bool

func (*BaseControl) Pack

func (c *BaseControl) Pack() PackType

func (*BaseControl) Paddings

func (c *BaseControl) Paddings() (px int, py int)

func (*BaseControl) Parent

func (c *BaseControl) Parent() Control

func (*BaseControl) PlaceChildren

func (c *BaseControl) PlaceChildren()

func (*BaseControl) Pos

func (c *BaseControl) Pos() (x int, y int)

func (*BaseControl) ProcessEvent

func (c *BaseControl) ProcessEvent(ev Event) bool

func (*BaseControl) ResizeChildren

func (c *BaseControl) ResizeChildren()

func (*BaseControl) Scale

func (c *BaseControl) Scale() int

func (*BaseControl) SetActive

func (c *BaseControl) SetActive(active bool)

func (*BaseControl) SetActiveBackColor

func (c *BaseControl) SetActiveBackColor(clr term.Attribute)

SetActiveBackColor changes background color of the active control

func (*BaseControl) SetActiveTextColor

func (c *BaseControl) SetActiveTextColor(clr term.Attribute)

SetActiveTextColor changes text color of the active control

func (*BaseControl) SetAlign

func (c *BaseControl) SetAlign(align Align)

func (*BaseControl) SetBackColor

func (c *BaseControl) SetBackColor(clr term.Attribute)

func (*BaseControl) SetConstraints

func (c *BaseControl) SetConstraints(minw, minh int)

func (*BaseControl) SetEnabled

func (c *BaseControl) SetEnabled(enabled bool)

func (*BaseControl) SetGaps

func (c *BaseControl) SetGaps(dx, dy int)

func (*BaseControl) SetModal

func (c *BaseControl) SetModal(modal bool)

func (*BaseControl) SetPack

func (c *BaseControl) SetPack(pack PackType)

func (*BaseControl) SetPaddings

func (c *BaseControl) SetPaddings(px, py int)

func (*BaseControl) SetParent

func (c *BaseControl) SetParent(parent Control)

func (*BaseControl) SetPos

func (c *BaseControl) SetPos(x, y int)

func (*BaseControl) SetScale

func (c *BaseControl) SetScale(scale int)

func (*BaseControl) SetSize

func (c *BaseControl) SetSize(width, height int)

func (*BaseControl) SetTabStop

func (c *BaseControl) SetTabStop(tabstop bool)

func (*BaseControl) SetTextColor

func (c *BaseControl) SetTextColor(clr term.Attribute)

func (*BaseControl) SetTitle

func (c *BaseControl) SetTitle(title string)

func (*BaseControl) Size

func (c *BaseControl) Size() (widht int, height int)

func (*BaseControl) TabStop

func (c *BaseControl) TabStop() bool

func (*BaseControl) TextColor

func (c *BaseControl) TextColor() term.Attribute

func (*BaseControl) Title

func (c *BaseControl) Title() string

type BorderStyle

type BorderStyle int

BorderStyle is a kind of frame: none, single, and double

const (
	BorderNone BorderStyle = iota
	BorderThin
	BorderThick
)

BorderStyle constants

type Button

type Button struct {
	BaseControl
	// contains filtered or unexported fields
}

Button is a simpe push button control. Every time a user clicks a Button, it emits OnClick event. Event has only one valid field Sender. Button can be clicked with mouse or using space on keyboard while the Button is active.

func CreateButton

func CreateButton(parent Control, width, height int, title string, scale int) *Button

NewButton creates a new Button. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width and heigth - are minimal size of the control. title - button title. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*Button) Draw

func (b *Button) Draw()

Repaint draws the control on its View surface

func (*Button) OnClick

func (b *Button) OnClick(fn func(Event))

OnClick sets the callback that is called when one clicks button with mouse or pressing space on keyboard while the button is active

func (*Button) ProcessEvent

func (b *Button) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent

type Canvas

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

Canvas is a 'graphical' engine to draw primitives.

type CheckBox

type CheckBox struct {
	BaseControl
	// contains filtered or unexported fields
}

CheckBox control. It can be two-state one(on and off) - it is default mode - or three-state. State values are 0=off, 1=on, 2=third state

func CreateCheckBox

func CreateCheckBox(parent Control, width int, title string, scale int) *CheckBox

CreateCheckBox creates a new CheckBox control. parent - is container that keeps the control. The same View can be a view and a parent at the same time. width - is minimal width of the control. title - button title. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size. CheckBox state can be changed using mouse or pressing space on keyboard while the control is active

func (*CheckBox) Allow3State

func (c *CheckBox) Allow3State() bool

Allow3State returns true if ComboBox uses 3 states

func (*CheckBox) Draw

func (c *CheckBox) Draw()

Repaint draws the control on its View surface

func (*CheckBox) OnChange

func (c *CheckBox) OnChange(fn func(int))

OnChange sets the callback that is called whenever the state of the CheckBox is changed. Argument of callback is the current CheckBox state: 0 - off, 1 - on, 2 - third state

func (*CheckBox) ProcessEvent

func (c *CheckBox) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control

processes an event it should return true. If the method returns false it means
that the control do not want or cannot process the event and the caller sends
the event to the control parent

func (*CheckBox) SetAllow3State

func (c *CheckBox) SetAllow3State(enable bool)

SetAllow3State sets if ComboBox should use 3 states. If the current state is unknown and one disables Allow3State option then the current value resets to off

func (*CheckBox) SetSize

func (c *CheckBox) SetSize(width, height int)

SetSize changes control size. Constant DoNotChange can be used as placeholder to indicate that the control attrubute should be unchanged. Method does nothing if new size is less than minimal size CheckBox height cannot be changed - it equals 1 always

func (*CheckBox) SetState

func (c *CheckBox) SetState(val int)

SetState changes the current state of CheckBox Value must be 0 or 1 if Allow3State is off, and 0, 1, or 2 if Allow3State is on

func (*CheckBox) State

func (c *CheckBox) State() int

State returns current state of CheckBox

type ColorParser

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

ColorParser is a string parser to process a text with color tags inside the string

func NewColorParser

func NewColorParser(str string, defText, defBack term.Attribute) *ColorParser

NewColorParser creates a new string parser. str is a string to parse. defText is a default text color. defBack is a default background color. Default colors are applied in case of reset color tag

func (*ColorParser) NextElement

func (p *ColorParser) NextElement() TextElement

NextElement parses and returns the next string element

type Column

type Column struct {
	Title     string
	Width     int
	Alignment Align
	Fg, Bg    term.Attribute
	Sort      SortOrder
}

Column is a information about a table column. When one sets a column list, it the fields Title and Width should be set. All other fields can be undefined.

type ColumnDrawInfo

type ColumnDrawInfo struct {
	// row number
	Row int
	// column number
	Col int
	// width of the cell
	Width int
	// cell displayed text
	Text string
	// text alignment
	Alignment Align
	// is the row that contains the cell selected(active)
	RowSelected bool
	// is the column that contains the cell selected(active)
	CellSelected bool
	// current text color
	Fg term.Attribute
	// current background color
	Bg term.Attribute
}

ColumnDrawInfo is a structure used in OnDrawCell event. A callback should assign Text field otherwise the cell will be empty. In addition to it, the callback can change Bg, Fg, and Alignment to display customizes info. All other non-mentioned fields are for a user convinience and used to describe the cell more detailed, changing that fields affects nothing

type Composer

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

Composer is a service object that manages Views and console, processes events, and provides service methods. One application must have only one object of this type

func (*Composer) DestroyWindow

func (c *Composer) DestroyWindow(view Control)

DestroyWindow removes the Window from the list of managed Windows

type ConfirmationDialog

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

ConfirmationDialog is a simple dialog to get a user choice or confirmation. The dialog can contain upto three button with custom titles. There are a few predefined button sets: see Buttons* constants. The dialog is modal, so a user cannot interact other Views until the user closes the dialog

func CreateConfirmationDialog

func CreateConfirmationDialog(title, question string, buttons []string, defaultButton int) *ConfirmationDialog

NewConfirmationDialog creates new confirmation dialog. c is a composer that manages the dialog title is a dialog title question is a text inside dialog for user to explain what happens buttons is a titles for button inside dialog. If the list is empty,

the dialog will have only one button 'OK'. If the list has more
than 3 button then only first three items will be used in the dialog

defaultButton is the number of button that is active right after

dialog is created. If the number is greater than the number of
buttons, no button is active

func (*ConfirmationDialog) OnClose

func (d *ConfirmationDialog) OnClose(fn func())

OnClose sets the callback that is called when the dialog is closed

func (*ConfirmationDialog) Result

func (d *ConfirmationDialog) Result() int

Result returns what button closed the dialog. See DialogButton constants. It can equal DialogAlive that means that the dialog is still visible and a user still does not click any button

type Control

type Control interface {
	// Title returns the current title or text of the control
	Title() string
	// SetTitle changes control text or title
	SetTitle(title string)
	// Size returns current control width and height
	Size() (widht int, height int)
	// SetSize changes control size. Constant KeepValue can be
	// used as placeholder to indicate that the control attrubute
	// should be unchanged.
	SetSize(width, height int)
	// Pos returns the current absolute control position: X and Y.
	Pos() (x int, y int)
	// SetPos changes contols position. Manual call of the method does not
	// make sense for any control except for Window because control positions
	// inside of container always recalculated after its parent resizes
	SetPos(x, y int)
	// Constraints return minimal control widht and height
	Constraints() (minw int, minh int)
	SetConstraints(minw, minh int)
	// Active returns if a control is active. Only active controls can
	// process keyboard events. Parent looks for active controls to
	// make sure that there is only one active control at a time
	Active() bool
	// SetActive activates and deactivates control
	SetActive(active bool)
	// TabStop returns if a control can be selected by traversing
	// controls using TAB key
	TabStop() bool
	SetTabStop(tabstop bool)
	// Enable return if a control can process keyboard and mouse events
	Enabled() bool
	SetEnabled(enabled bool)
	// Parent return control's container or nil if there is no parent container
	// that is true for Windows
	Parent() Control
	// The function should not be called manually. It is for internal use by
	// library
	SetParent(parent Control)
	// Modal returns if a control is always on top and does not allow to
	// change the current control. Used only by Windows, for other kind of
	// controls it does nothing
	Modal() bool
	SetModal(modal bool)
	// Paddings returns a number of spaces used to auto-arrange children inside
	// a container: indent from left and right sides, indent from top and bottom
	// sides.
	Paddings() (px int, py int)
	// SetPaddings changes indents for the container. Use KeepValue as a placeholder
	// if you do not want to touch a parameter
	SetPaddings(px, py int)
	// Gaps returns number of spaces inserted between child controls. dx is used
	// by horizontally-packed parents and dy by vertically-packed ones
	Gaps() (dx int, dy int)
	SetGaps(dx, dy int)
	// Pack returns direction in which a container packs
	// its children: horizontal or vertical
	Pack() PackType
	// SetPack changes the direction of children packing
	SetPack(pack PackType)
	// Scale return scale coefficient that is used to calculate
	// new control size after its parent resizes.
	// Fixed means the controls never changes its size.
	// Any positive value is a real coefficient of scaling.
	// How the scaling works: after resizing, parent control
	// calculates the difference between minimal and current sizes,
	// then divides the difference between controls that has
	// positive scale depending on a scale value. The more scale,
	// the larger control after resizing. Example: if you have
	// two controls with scales 1 and 2, then after every resizing
	// the latter controls expands by 100% more than the first one.
	Scale() int
	// SetScale sets a scale coefficient for the control.
	// See Scale method for details
	SetScale(scale int)
	// Align returns alignment of title in control
	Align() Align
	SetAlign(align Align)

	TextColor() term.Attribute
	// SetTextColor changes text color of the control.
	// Use ColorDefault to apply theme default color for the control
	SetTextColor(clr term.Attribute)
	BackColor() term.Attribute
	// SetBackColor changes background color of the control.
	// Use ColorDefault to apply theme default color for the control
	SetBackColor(clr term.Attribute)
	// ActiveColors return the attrubutes for the controls when it
	// is active: text and background colors.
	// Use ColorDefault to apply theme default color for the control
	ActiveColors() (term.Attribute, term.Attribute)
	// SetActiveBackColor changes background color of the active control.
	// Use ColorDefault to apply theme default color for the control
	SetActiveBackColor(term.Attribute)
	// SetActiveTextColor changes text color of the active control.
	// Use ColorDefault to apply theme default color for the control
	SetActiveTextColor(term.Attribute)

	// AddChild adds a new child to a container
	// The method should not be called manually. It is automatically called
	// if parent is not nil in Create* function
	AddChild(control Control)
	// Children returns the copy of the list of container child controls
	Children() []Control
	// ChildExists returns true if a control has argument as one of its
	// children or child of one of the children
	ChildExists(control Control) bool
	// MinimalSize returns the minimal size required by a control to show
	// it and all its children.
	MinimalSize() (w int, h int)
	// ChildrenScale returns the sum of all scales of all control decendants
	ChildrenScale() int
	// ResizeChildren recalculates new size of all control's children. Calling
	// the function manually is useless because the library calls this method
	// after any size change automatically(including call after adding a new
	// child)
	ResizeChildren()
	// PlaceChildren arranges all children inside a control. Useful to be called
	// after ResizeChildren, but manual call of the method is mostly useless.
	// The function is used by the library internally
	PlaceChildren()

	// Draw repaints the control on its parent surface
	Draw()
	// DrawChildren repaints all control children.
	// Method is added to avoid writing repetetive code for any parent control.
	// Just call the method at the end of your Draw method and all children
	// repaints automatically
	DrawChildren()

	// HitTest returns the area that corresponds to the clicked
	// position X, Y (absolute position in console window): title,
	// internal view area, title button, border or outside the control
	HitTest(x, y int) HitResult
	// ProcessEvent processes all events come from the control parent. If a control
	// processes an event it should return true. If the method returns false it means
	// that the control do not want or cannot process the event and the caller sends
	// the event to the control parent
	ProcessEvent(ev Event) bool
}

Control is an interface that every visible control should implement

func ActiveControl

func ActiveControl(parent Control) Control

ActiveControl returns the active child of the parent or nil if no child is active

func ChildAt

func ChildAt(parent Control, x, y int) Control

ChildAt returns the children of parent control that is at absolute coordinates x, y. Returns nil if x, y are outside parent control and returns parent if no child is at x, y

func FindChild

func FindChild(parent, control Control) Control

FindChild returns control if it is a child of the parent and nil otherwise

func FindFirstControl

func FindFirstControl(parent Control, fn func(Control) bool) Control

FindFirstControl returns the first child for that fn returns true. The function is used to find active or tab-stop control

func FindLastControl

func FindLastControl(parent Control, fn func(Control) bool) Control

FindLastControl returns the first child for that fn returns true. The function is used by TAB processing method if a user goes backwards with TAB key - not supported now

func NextControl

func NextControl(parent Control, curr Control, next bool) Control

NextControl returns the next or previous child (depends on next parameter) that has tab-stop feature on. Used by library when processing TAB key

type Direction

type Direction int

Direction indicates the direction in which a control must draw its content. At that moment it can be applied to Label (text output direction and to ProgressBar (direction of bar filling)

type DragType

type DragType int

Predefined types

const (
	DragNone DragType = iota
	DragMove
	DragResizeLeft
	DragResizeRight
	DragResizeBottom
	DragResizeBottomLeft
	DragResizeBottomRight
	DragResizeTopLeft
	DragResizeTopRight
)

type EditField

type EditField struct {
	BaseControl
	// contains filtered or unexported fields
}

EditField is a single-line text edit contol. Edit field consumes some keyboard events when it is active: all printable charaters; Delete, BackSpace, Home, End, left and right arrows; Ctrl+R to clear EditField. Edit text can be limited. By default a user can enter text of any length. Use SetMaxWidth to limit the maximum text length. If the text is longer than maximun then the text is automatically truncated. EditField calls onChage in case of its text is changed. Event field Msg contains the new text

func CreateEditField

func CreateEditField(parent Control, width int, text string, scale int) *EditField

NewEditField creates a new EditField control view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width - is minimal width of the control. text - text to edit. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the

control should keep its original size.

func (*EditField) Clear

func (e *EditField) Clear()

Clear empties the EditField and emits OnChange event

func (*EditField) Draw

func (e *EditField) Draw()

Repaint draws the control on its View surface

func (*EditField) MaxWidth

func (e *EditField) MaxWidth() int

MaxWidth returns the current maximum text length. Zero means no limit

func (*EditField) OnChange

func (e *EditField) OnChange(fn func(Event))

OnChange sets the callback that is called when EditField content is changed

func (*EditField) OnKeyPress

func (e *EditField) OnKeyPress(fn func(term.Key) bool)

OnKeyPress sets the callback that is called when a user presses a Key while the controls is active. If a handler processes the key it should return true. If handler returns false it means that the default handler will process the key

func (*EditField) PasswordMode

func (e *EditField) PasswordMode() bool

PasswordMode returns whether password mode is enabled for the control

func (*EditField) ProcessEvent

func (e *EditField) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent

func (*EditField) SetMaxWidth

func (e *EditField) SetMaxWidth(w int)

SetMaxWidth sets the maximum lenght of the EditField text. If the current text is longer it is truncated

func (*EditField) SetPasswordMode

func (e *EditField) SetPasswordMode(pass bool)

SetPasswordMode changes the way an EditField displays it content. If PasswordMode is false then the EditField works as regular text entry control. If PasswordMode is true then the EditField shows its content hidden with star characters ('*' by default)

func (*EditField) SetSize

func (e *EditField) SetSize(width, height int)

SetSize changes control size. Constant DoNotChange can be used as placeholder to indicate that the control attrubute should be unchanged. Method does nothing if new size is less than minimal size EditField height cannot be changed - it equals 1 always

func (*EditField) SetTitle

func (e *EditField) SetTitle(title string)

SetTitle changes the EditField content and emits OnChage eventif the new value does not equal to old one

type Event

type Event struct {
	// Event type - the first events are mapped to termbox Event and then a few
	// own events added to the end
	Type EventType
	// Mod - is a key modifier. Only Alt modifier is supported
	Mod term.Modifier
	// Msg is a text part of the event. Used by few events: e.g, ListBox click
	// sends a value of clicked item
	Msg string
	// X and Y are multi-purpose fields: mouse coordinated for click event,
	// X is used to indicate on/off for events like Activate
	// Y is used for vertical-based events like ListBox item selection - id of the item
	X, Y int
	// Err is error got from termbox library
	Err error
	// Key is a pressed key
	Key term.Key
	// Ch is a printable representation of pressed key combinaton
	Ch rune
	// For resize event - new terminal size
	Width  int
	Height int
}

Event is structure used by Views and controls to communicate with Composer and vice versa

type EventType

type EventType int

EventType is a type of event fired by an object

type Frame

type Frame struct {
	BaseControl
	// contains filtered or unexported fields
}

Frame is a decorative control and container - frame with optional title. All area inside a frame is transparent. Frame can be used as spacer element - set border to BorderNone and use that control in any place where a spacer is required

func CreateFrame

func CreateFrame(parent Control, width, height int, bs BorderStyle, scale int) *Frame

NewFrame creates a new frame. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width and heigth - are minimal size of the control. bs - type of border: no border, single or double. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*Frame) Draw

func (f *Frame) Draw()

Repaint draws the control on its View surface

type HitResult

type HitResult int

HitResult is a type of a view area that is under mouse cursor. Used in mouse click events

const (
	HitOutside HitResult = iota
	HitInside
	HitBorder
	HitTop
	HitBottom
	HitRight
	HitLeft
	HitTopLeft
	HitTopRight
	HitBottomRight
	HitBottomLeft
	HitButtonClose
	HitButtonBottom
	HitButtonMaximize
)

HitResult constants

type Label

type Label struct {
	BaseControl
	// contains filtered or unexported fields
}

Label is a decorative control that can display text in horizontal or vertical direction. Other available text features are alignment and multi-line ability. Text can be single- or multi-colored with tags inside the text. Multi-colored strings have limited support of alignment feature: if text is longer than Label width the text is always left aligned

func CreateLabel

func CreateLabel(parent Control, w, h int, title string, scale int) *Label

NewLabel creates a new label. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. w and h - are minimal size of the control. title - is Label title. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*Label) Direction

func (l *Label) Direction() Direction

Direction returns direction of text output: vertical or horizontal

func (*Label) Draw

func (l *Label) Draw()

func (*Label) Multiline

func (l *Label) Multiline() bool

Multiline returns if text is displayed on several lines if the label title is longer than label width or title contains line breaks

func (*Label) SetDirection

func (l *Label) SetDirection(dir Direction)

SetDirection sets the text output direction

func (*Label) SetMultiline

func (l *Label) SetMultiline(multi bool)

SetMultiline sets if the label should output text as one line or automatically display it in several lines

type ListBox

type ListBox struct {
	BaseControl
	// contains filtered or unexported fields
}

ListBox is control to display a list of items and allow to user to select any of them. Content is scrollable with arrow keys or by clicking up and bottom buttons on the scroll(now content is scrollable with mouse dragging only on Windows).

ListBox calls onSelectItem item function after a user changes currently selected item with mouse or using keyboard (extra case: the event is emitted when a user presses Enter - the case is used in ComboBox to select an item from drop down list). Event structure has 2 fields filled: Y - selected item number in list(-1 if nothing is selected), Msg - text of the selected item.

func CreateListBox

func CreateListBox(parent Control, width, height int, scale int) *ListBox

NewListBox creates a new frame. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width and heigth - are minimal size of the control. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*ListBox) AddItem

func (l *ListBox) AddItem(item string) bool

AddItem adds a new item to item list. Returns true if the operation is successful

func (*ListBox) Clear

func (l *ListBox) Clear()

Clear deletes all ListBox items

func (*ListBox) Draw

func (l *ListBox) Draw()

Repaint draws the control on its View surface

func (*ListBox) EnsureVisible

func (l *ListBox) EnsureVisible()

EnsureVisible makes the currently selected item visible and scrolls the item list if it is required

func (*ListBox) FindItem

func (l *ListBox) FindItem(text string, caseSensitive bool) int

FindItem looks for an item in list which text equals to text, by default the search is casesensitive. Returns item number in item list or -1 if nothing is found.

func (*ListBox) ItemCount

func (l *ListBox) ItemCount() int

ItemCount returns the number of items in the ListBox

func (*ListBox) OnKeyPress

func (l *ListBox) OnKeyPress(fn func(term.Key) bool)

OnKeyPress sets the callback that is called when a user presses a Key while the controls is active. If a handler processes the key it should return true. If handler returns false it means that the default handler will process the key

func (*ListBox) OnSelectItem

func (l *ListBox) OnSelectItem(fn func(Event))

OnSelectItem sets a callback that is called every time the selected item is changed

func (*ListBox) ProcessEvent

func (l *ListBox) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent

func (*ListBox) RemoveItem

func (l *ListBox) RemoveItem(id int) bool

RemoveItem deletes an item which number is id in item list Returns true if item is deleted

func (*ListBox) SelectItem

func (l *ListBox) SelectItem(id int) bool

SelectItem slects item which number in the list equals id. If the item exists the ListBox scrolls the list to make the item visible. Returns true if the item is selected successfully

func (*ListBox) SelectedItem

func (l *ListBox) SelectedItem() int

SelectedItem returns currently selected item id

func (*ListBox) SelectedItemText

func (l *ListBox) SelectedItemText() string

SelectedItemText returns text of currently selected item or empty sting if nothing is selected or ListBox is empty.

type PackType

type PackType int

PackType sets how to pack controls inside its parent. Can be Vertical or Horizontal

type ProgressBar

type ProgressBar struct {
	BaseControl
	// contains filtered or unexported fields
}

ProgressBar control visualizes the progression of extended operation.

The control has two sets of colors(almost all other controls have only one set: foreground and background colors): for filled part and for empty one. By default colors are the same.

func CreateProgressBar

func CreateProgressBar(parent Control, width, height int, scale int) *ProgressBar

NewProgressBar creates a new ProgressBar. parent - is container that keeps the control. width and heigth - are minimal size of the control. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*ProgressBar) Draw

func (b *ProgressBar) Draw()

Repaint draws the control on its View surface. Horizontal ProgressBar supports custom title over the bar. One can set title using method SetTitle. There are a few predefined variables that can be used inside title to show value or total progress. Variable must be enclosed with double curly brackets. Available variables: percent - the current percentage rounded to closest integer value - raw ProgressBar value min - lower ProgressBar limit max - upper ProgressBar limit Examples:

pb.SetTitle("{{value}} of {{max}}")
pb.SetTitle("{{percent}}%")

func (*ProgressBar) Limits

func (b *ProgressBar) Limits() (int, int)

Limits returns current minimal and maximal values of ProgressBar

func (*ProgressBar) SecondaryColors

func (b *ProgressBar) SecondaryColors() (term.Attribute, term.Attribute)

SecondaryColors returns text and background colors for empty part of the ProgressBar

func (*ProgressBar) SetLimits

func (b *ProgressBar) SetLimits(min, max int)

SetLimits set new ProgressBar limits. The current value is adjusted if it exceeds new limits

func (*ProgressBar) SetSecondaryColors

func (b *ProgressBar) SetSecondaryColors(fg, bg term.Attribute)

SetSecondaryColors sets new text and background colors for empty part of the ProgressBar

func (*ProgressBar) SetTitleColor

func (b *ProgressBar) SetTitleColor(clr term.Attribute)

SetTitleColor sets text color of ProgressBar's title

func (*ProgressBar) SetValue

func (b *ProgressBar) SetValue(pos int)

SetValue sets new progress value. If value exceeds ProgressBar limits then the limit value is used

func (*ProgressBar) Step

func (b *ProgressBar) Step() int

Step increases ProgressBar value by 1 if the value is less than ProgressBar high limit

func (*ProgressBar) TitleColor

func (b *ProgressBar) TitleColor() term.Attribute

TitleColor returns text color of ProgressBar's title. Title background color always equals background color of the part of the ProgressBar on which it is displayed. In other words, background color of title is transparent

func (*ProgressBar) Value

func (b *ProgressBar) Value() int

Value returns the current ProgressBar value

type Radio

type Radio struct {
	BaseControl
	// contains filtered or unexported fields
}

Radio button control. Unite a few radios in one radio group to make a user select one of available choices.

func CreateRadio

func CreateRadio(parent Control, width int, title string, scale int) *Radio

NewRadio creates a new radio button. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width - is minimal width of the control. title - radio title. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*Radio) Draw

func (c *Radio) Draw()

Repaint draws the control on its View surface

func (*Radio) ProcessEvent

func (c *Radio) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent. The control processes only space button and mouse clicks to make control selected. Deselecting control is not possible: one has to click another radio of the radio group to deselect this button

func (*Radio) Selected

func (c *Radio) Selected() bool

Selected returns if the radio is selected

func (*Radio) SetGroup

func (c *Radio) SetGroup(group *RadioGroup)

SetGroup sets the radio group to which the radio belongs

func (*Radio) SetSelected

func (c *Radio) SetSelected(val bool)

SetSelected makes the button selected. One should not use the method directly, it is for RadioGroup control

type RadioGroup

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

RadioGroup is non-interactive invisible object. It manages set of Radio buttons: at a time no more than one radio button from a group can be selected

func CreateRadioGroup

func CreateRadioGroup() *RadioGroup

NewRadioGroup creates a new RadioGroup

func (*RadioGroup) AddItem

func (c *RadioGroup) AddItem(r *Radio)

AddItem add a new radio button to group

func (*RadioGroup) SelectItem

func (c *RadioGroup) SelectItem(r *Radio) bool

SelectItem makes the radio selected. The function returns false if it failed to find the radio in the radio group

func (*RadioGroup) Selected

func (c *RadioGroup) Selected() int

Selected returns the number of currently selected radio button inside the group or -1 if no button is selected

func (*RadioGroup) SetSelected

func (c *RadioGroup) SetSelected(id int) bool

SetSelected selects the radio by its number. The function returns false if the number is invalid for the radio group

type SelectDialog

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

SelectDialog allows to user to select an item from the list. Items can be displayed in ListBox or in RadioGroup. The dialog is modal, so a user cannot interact other Views until the user closes the dialog

func CreateSelectDialog

func CreateSelectDialog(title string, items []string, selectedItem int, typ SelectDialogType) *SelectDialog

NewSelectDialog creates new dialog to select an item from list. c is a composer that manages the dialog title is a dialog title items is a list of items to select from selectedItem is the index of the item that is selected after

the dialog is created

typ is a selection type: ListBox or RadioGroup Returns nil in case of creation process fails, e.g, if item list is empty

func (*SelectDialog) OnClose

func (d *SelectDialog) OnClose(fn func())

OnClose sets the callback that is called when the dialog is closed

func (*SelectDialog) Result

func (d *SelectDialog) Result() int

Result returns what button closed the dialog. See DialogButton constants. It can equal DialogAlive that means that the dialog is still visible and a user still does not click any button

func (*SelectDialog) Value

func (d *SelectDialog) Value() int

Value returns the number of the selected item or -1 if nothing is selected or the dialog is cancelled

type SelectDialogType

type SelectDialogType uint

SelectDialogType sets the way of choosing an item from a list for SelectionDialog control: a list-based selections, or radio group one

const (
	// SelectDialogList - all items are displayed in a ListBox
	SelectDialogList SelectDialogType = iota
	// SelectDialogList - all items are displayed in a RadioGroup
	SelectDialogRadio
)

SelectDialogType constants

type SortOrder

type SortOrder int

SortOrder is a way of sorting rows in TableView

const (
	// Do not sort
	SortNone SortOrder = iota
	// Sort ascending
	SortAsc
	// Sort descending
	SortDesc
)

SortOrder constants

type SparkChart

type SparkChart struct {
	BaseControl
	// contains filtered or unexported fields
}

SparkChart is a chart that represents a live data that is continuously added to the chart. Or it can be static element that displays predefined set of data - in this case it looks like BarChart. At a moment SparkChart keeps only th enumber of last data that is enough to fill the control area. So, if you enlarge the control, it will show partially filled area until it gets new data. SparkChart displays vertical axis with values on the chart left if ValueWidth greater than 0, horizontal axis with bar titles. Maximum peaks(maximum of the the data that control keeps) can be hilited with different color. By default the data is autoscaled to make the highest bar fit the full height of the control. But it maybe useful to disable autoscale and set the Top value to have more handy diagram. E.g, for CPU load in % you can set AutoScale to false and Top value to 100. Note: negative and zero values are displayed as empty bar

func CreateSparkChart

func CreateSparkChart(parent Control, w, h int, scale int) *SparkChart

NewSparkChart creates a new spark chart. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. w and h - are minimal size of the control. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*SparkChart) AddData

func (b *SparkChart) AddData(val float64)

AddData appends a new bar to a chart

func (*SparkChart) AutoScale

func (b *SparkChart) AutoScale() bool

AutoScale returns whether spark chart scales automatically depending on displayed data or it scales using Top value

func (*SparkChart) ClearData

func (b *SparkChart) ClearData()

ClearData removes all bar from chart

func (*SparkChart) Draw

func (b *SparkChart) Draw()

Repaint draws the control on its View surface

func (*SparkChart) HilitePeaks

func (b *SparkChart) HilitePeaks() bool

HilitePeaks returns whether chart draws maximum peaks with different color

func (*SparkChart) SetAutoScale

func (b *SparkChart) SetAutoScale(auto bool)

SetAutoScale changes the way of scaling the data flow

func (*SparkChart) SetData

func (b *SparkChart) SetData(data []float64)

SetData assign a new bar list to a chart

func (*SparkChart) SetHilitePeaks

func (b *SparkChart) SetHilitePeaks(hilite bool)

SetHilitePeaks enables or disables hiliting maximum values with different colors

func (*SparkChart) SetTop

func (b *SparkChart) SetTop(top float64)

SetTop sets the theoretical highest value of data flow to scale the chart

func (*SparkChart) SetValueWidth

func (b *SparkChart) SetValueWidth(width int)

SetValueWidth changes width of the value panel on the left

func (*SparkChart) Top

func (b *SparkChart) Top() float64

Top returns the value of the top of a chart. The value is used only if autosize is off to scale all the data

func (*SparkChart) ValueWidth

func (b *SparkChart) ValueWidth() int

ValueWidth returns the width of the area at the left of chart used to draw values. Set it to 0 to turn off the value panel

type TableAction

type TableAction int

TableAction is a type of user-generated event for TableView

const (
	// A user pressed F2 or Enter key in TableView
	TableActionEdit TableAction = iota
	// A user pressed Insert key in TableView
	TableActionNew
	// A user pressed Delete key in TableView
	TableActionDelete
	// A user clicked on a column header in TableView
	TableActionSort
)

TableAction constants

type TableEvent

type TableEvent struct {
	// requested action: Add, Edit, Delete, Sort data
	Action TableAction
	// Currently selected column
	Col int
	// Currently selected row (it is not used for TableActionSort)
	Row int
	// Sort order (it is used only in TableActionSort event)
	Sort SortOrder
}

TableEvent is structure to describe the common action that a TableView ask for while a user is interacting with the table

type TableView

type TableView struct {
	BaseControl
	// contains filtered or unexported fields
}

TableView is control to display a list of items in a table(grid). Content is scrollable with arrow keys and mouse. TableView always works in virtual mode - it does not keep table data and always asks for the cell value using callback OnDrawCell.

Predefined hotkeys:

Arrows - move cursor
Home, End - move cursor to first and last column, respectively
Alt+Home, Alt+End - move cursor to first and last row, respectively
PgDn, PgUp - move cursor to a screen down and up
Enter, F2 - emits event TableActionEdit
Insert - emits event TableActionNew
Delete - emits event TableActionDelete
F4 - Change sort mode

Events:

OnDrawCell - called every time the table is going to draw a cell.
      The argument is ColumnDrawInfo prefilled with the current
      cell attributes. Callback should fill at least the field
      Title. Filling Bg, Fg, and Alignment are optional. Changing
      other fields in callback does not make any difference - they
      are only for caller convenience
OnAction - called when a user pressed some hotkey(please, see
      above) or clicks any column header(in this case, the control
      sends TableActionSort event and fills column number and
      sorting type - no sort, ascending, descending)
OnKeyPress - called every time a user presses a key. Callback should
      return true if TableView must skip internal key processing.
      E.g, a user can disable emitting TableActionDelete event by
      adding callback OnKeyPress and retun true in case of Delete
      key is pressed
OnSelectCell - called in case of the currently selected row or
      column is changed

func CreateTableView

func CreateTableView(parent Control, width, height int, scale int) *TableView

NewTableView creates a new frame. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width and heigth - are minimal size of the control. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*TableView) Columns

func (l *TableView) Columns() []Column

Columns returns the current list of table columns

func (*TableView) Draw

func (l *TableView) Draw()

Repaint draws the control on its View surface

func (*TableView) EnsureColVisible

func (l *TableView) EnsureColVisible()

EnsureColVisible scrolls the table horizontally to make the curently selected column fully visible

func (*TableView) EnsureRowVisible

func (l *TableView) EnsureRowVisible()

EnsureRowVisible scrolls the table vertically to make the curently selected row visible

func (*TableView) FullRowSelect

func (l *TableView) FullRowSelect() bool

FullRowSelect returns if TableView hilites the selected cell only or the whole row that contains the selected cell. By default the colors for selected row and cell are different

func (*TableView) OnAction

func (l *TableView) OnAction(fn func(TableEvent))

OnAction is called when the table wants a user application to do some job like add, delete, edit or sort data

func (*TableView) OnDrawCell

func (l *TableView) OnDrawCell(fn func(*ColumnDrawInfo))

OnDrawCell is called every time the table is going to display a cell

func (*TableView) OnKeyPress

func (l *TableView) OnKeyPress(fn func(term.Key) bool)

OnKeyPress sets the callback that is called when a user presses a Key while the controls is active. If a handler processes the key it should return true. If handler returns false it means that the default handler has to process the key

func (*TableView) OnSelectCell

func (l *TableView) OnSelectCell(fn func(int, int))

OnSelectCell sets a callback that is called every time the selected cell is changed

func (*TableView) ProcessEvent

func (l *TableView) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent

func (*TableView) RowCount

func (l *TableView) RowCount() int

RowCount returns current row count

func (*TableView) SelectedCol

func (l *TableView) SelectedCol() int

SelectedCol returns currently selected column number or -1 if no column is selected

func (*TableView) SelectedRow

func (l *TableView) SelectedRow() int

SelectedRow returns currently selected row number or -1 if no row is selected

func (*TableView) SetColumnInfo

func (l *TableView) SetColumnInfo(id int, col Column)

SetColumnInfo replaces the existing column info

func (*TableView) SetColumns

func (l *TableView) SetColumns(cols []Column)

SetColumns replaces existing table column list with a new one. Be sure that every item has correct Title and Width, all other column properties may be undefined

func (*TableView) SetFullRowSelect

func (l *TableView) SetFullRowSelect(fullRow bool)

SetFullRowSelect enables or disables hiliting of the full row that contains the selected cell

func (*TableView) SetRowCount

func (l *TableView) SetRowCount(count int)

SetRowCount sets the new row count

func (*TableView) SetSelectedCol

func (l *TableView) SetSelectedCol(col int)

SetSelectedCol changes the currently selected column. If column is greater than number of columns the last column is selected. Set row to -1 to turn off selection. The table scrolls automatically to display the column

func (*TableView) SetSelectedRow

func (l *TableView) SetSelectedRow(row int)

SetSelectedRow changes the currently selected row. If row is greater than number of row the last row is selected. Set row to -1 to turn off selection. The table scrolls automatically to display the column

func (*TableView) SetShowLines

func (l *TableView) SetShowLines(show bool)

SetShowLines disables and enables displaying vertical lines inside TableView

func (*TableView) SetShowRowNumber

func (l *TableView) SetShowRowNumber(show bool)

SetShowRowNumber turns on and off the first fixed column of the table that displays the row number

func (*TableView) ShowLines

func (l *TableView) ShowLines() bool

ShowLines returns true if table displays vertical lines to separate columns

func (*TableView) ShowRowNumber

func (l *TableView) ShowRowNumber() bool

ShowRowNumber returns true if the table shows the row number as the first table column. This virtual column is always fixed and a user cannot change displayed text

type TextElement

type TextElement struct {
	// Type is an element type
	Type TextElementType
	// Ch is a parsed rune, it is filled only if Type is ElemPrintable
	Ch rune
	// Fg is a text color for the rune
	Fg term.Attribute
	// Bg is a background color for the rune
	Bg term.Attribute
}

TextElement is currently parsed text element

type TextElementType

type TextElementType int

TextElementType type of the parsed element of the string

type TextReader

type TextReader struct {
	BaseControl
	// contains filtered or unexported fields
}

func CreateTextReader

func CreateTextReader(parent Control, width, height int, scale int) *TextReader

func (*TextReader) Draw

func (l *TextReader) Draw()

Repaint draws the control on its View surface

func (*TextReader) LineCount

func (l *TextReader) LineCount() int

func (*TextReader) OnDrawLine

func (l *TextReader) OnDrawLine(fn func(int) string)

OnDrawLine is called every time the reader is going to display a line the argument of the function is the line number to display

func (*TextReader) OnPositionChanged

func (l *TextReader) OnPositionChanged(fn func(int, int))

OnPositionChanged is called every time the reader changes the top line or the total number of lines is changed Callback gets two numbers: the current top line, and the total number of lines. Top line number starts from 0.

func (*TextReader) ProcessEvent

func (l *TextReader) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent

func (*TextReader) SetLineCount

func (l *TextReader) SetLineCount(lineNo int)

func (*TextReader) SetTopLine

func (l *TextReader) SetTopLine(top int)

func (*TextReader) TopLine

func (l *TextReader) TopLine() int

type TextView

type TextView struct {
	BaseControl
	// contains filtered or unexported fields
}

TextView is control to display a read-only text. Text can be loaded from a file or set manually. A portions of text can be added on the fly and if the autoscroll is enabled the control scroll down to the end - it may be useful to create a log viewer. Content is scrollable with arrow keys or by clicking buttons on the scrolls(a control can have upto 2 scrollbars: vertical and horizontal. The latter one is available only if WordWrap mode is off).

func CreateTextView

func CreateTextView(parent Control, width, height int, scale int) *TextView

NewTextView creates a new frame. view - is a View that manages the control parent - is container that keeps the control. The same View can be a view and a parent at the same time. width and heigth - are minimal size of the control. scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the control should keep its original size.

func (*TextView) AddText

func (l *TextView) AddText(text []string)

AddText appends a text to the end of the control content. View position may be changed automatically depending on value of AutoScroll

func (*TextView) AutoScroll

func (l *TextView) AutoScroll() bool

AutoScroll returns if autoscroll mode is enabled. If the autoscroll mode is enabled then the content always scrolled to the end after adding a text

func (*TextView) Draw

func (l *TextView) Draw()

Repaint draws the control on its View surface

func (*TextView) ItemCount

func (l *TextView) ItemCount() int

ItemCount returns the number of items in the TextView

func (*TextView) LoadFile

func (l *TextView) LoadFile(filename string) bool

LoadFile loads a text from file and replace the control text with the file one. Function returns false if loading text from file fails

func (*TextView) MaxItems

func (l *TextView) MaxItems() int

MaxItems returns the maximum number of items that the TextView can keep. 0 means unlimited. It makes a TextView work like a FIFO queue: the oldest(the first) items are deleted if one adds an item to a full TextView

func (*TextView) ProcessEvent

func (l *TextView) ProcessEvent(event Event) bool

ProcessEvent processes all events come from the control parent. If a control processes an event it should return true. If the method returns false it means that the control do not want or cannot process the event and the caller sends the event to the control parent

func (*TextView) SetAutoScroll

func (l *TextView) SetAutoScroll(auto bool)

SetAutoScroll enables and disables autoscroll mode

func (*TextView) SetMaxItems

func (l *TextView) SetMaxItems(max int)

SetMaxItems sets the maximum items that TextView keeps

func (*TextView) SetText

func (l *TextView) SetText(text []string)

SetText replaces existing content of the control

func (*TextView) SetWordWrap

func (l *TextView) SetWordWrap(wrap bool)

SetWordWrap enables or disables wordwrap mode

func (*TextView) WordWrap

func (l *TextView) WordWrap() bool

WordWrap returns if the wordwrap is enabled. If the wordwrap mode is enabled the control hides horizontal scrollbar and draws long lines on a few control lines. There is no visual indication if the line is new of it is the portion of the previous line yet

type ThemeDesc

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

ThemeDesc is a detailed information about theme: title, author, version number

func ThemeInfo

func ThemeInfo(name string) ThemeDesc

ThemeInfo returns detailed info about theme

type ThemeManager

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

ThemeManager support for controls. The current implementation is limited but later the manager will be able to load a requested theme on demand and use deep inheritance. Theme 'default' exists always - it is predefinded and always complete. User-defined themes may omit any theme section, all omitted items are loaded from parent theme. The only required property that a user- defined theme must have is a theme name.

Theme file is a simple text file that has similar to INI file format:

  1. Every line started with '#' or '/' is a comment line.
  2. Invalid lines - lines that do not contain symbol '=' - are skipped.
  3. Valid lines are splitted in two parts: key - the text before the first '=' in the line value - the text after the first '=' in the line (so, values can include '=') key and value are trimmed - spaces are removed from both ends. If line starts and ends with quote or double quote symbol then these symbols are removed, too. It is done to be able to start or finish the object with a space rune
  4. There is no mandatory keys - all of them are optional
  5. Avaiable system keys that used to describe the theme: 'title' - the theme title 'author' - theme author 'version' - theme version 'parent' - name of the parent theme. If it is not set then the 'default' is used as a parent
  6. Non-system keys are divided into two groups: Colors and Objects Colors are the keys that end with 'Back' or 'Text' - background and text color, respectively. If theme manager cannot value to color it uses black color. See Color*Back * Color*Text constants, just drop 'Color' at the beginning of key name. Rules of converting text to color:
  7. If the value does not end neither with 'Back' nor with 'Text' it is considered as raw attribute value(e.g, 'green bold')
  8. If the value ends with 'Back' or 'Text' it means that one of earlier defined attribute must be used. If the current scheme does not have that attribute defined (e.g, it is defined later in file) then parent theme attribute with the same name is used. One can force using parent theme colors - just add prefix 'parent.' to color name. This may be useful if one wants some parent colors reversed. Example: ViewBack=ViewText ViewText=ViewBack this makes both colors the same because ViewBack is defined before ViewText. Only ViewBack value is loaded from parent theme. Better way is: Viewback=parent.ViewText ViewText=parent.ViewBack Converting text to real color fails and retuns black color if a) the string does not look like real color(e.g, typo as in 'grean bold'), b) parent theme has not loaded yet, c) parent theme does not have the color with the same name Other keys are considered as objects - see Obj* constants, just drop 'Obj' at the beginning of the key name One is not limited with only predefined color and object names. The theme can inroduce its own objects, e.g. to provide a runes or colors for new control that is not in standard library

To see the real world example of full featured theme, please see

included theme 'turbovision'

type ViewButton

type ViewButton int

ViewButton is a set of buttons displayed in a view title

type Window

type Window struct {
	BaseControl
	// contains filtered or unexported fields
}

Window is an implemetation of View managed by Composer.

func AddWindow

func AddWindow(posX, posY, width, height int, title string) *Window

AddWindow constucts a new Window, adds it to the composer automatically, and makes it active posX and posY are top left coordinates of the Window width and height are Window size title is a Window title

func CreateWindow

func CreateWindow(x, y, w, h int, title string) *Window

func (*Window) Draw

func (wnd *Window) Draw()

func (*Window) HitTest

func (c *Window) HitTest(x, y int) HitResult

func (*Window) Maximized

func (w *Window) Maximized() bool

Maximized returns if the view is in full screen mode

func (*Window) OnClose

func (w *Window) OnClose(fn func(Event) bool)

func (*Window) OnKeyDown

func (w *Window) OnKeyDown(fn func(Event) bool)

func (*Window) ProcessEvent

func (c *Window) ProcessEvent(ev Event) bool

func (*Window) SetMaximized

func (w *Window) SetMaximized(maximize bool)

SetMaximized opens the view to full screen or restores its previous size

func (*Window) SetVisible

func (w *Window) SetVisible(visible bool)

SetVisible allows to temporarily remove the window from screen and show it later without reconstruction

func (*Window) Visible

func (w *Window) Visible() bool

Visible returns if the window must be drawn on the screen

Directories

Path Synopsis
maindemo
Demo includes: - How to intialize and run the application - How to stop the application - How to use Control's events (Button ones) - How to change theme on the fly - How to use dialogs - How to make composer refresh the screen - How to intercept Enter key(term.KeyCtrlM) in EditField(ListBox is the same)
Demo includes: - How to intialize and run the application - How to stop the application - How to use Control's events (Button ones) - How to change theme on the fly - How to use dialogs - How to make composer refresh the screen - How to intercept Enter key(term.KeyCtrlM) in EditField(ListBox is the same)

Jump to

Keyboard shortcuts

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