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
- Variables
- func ActivateControl(parent, control Control) bool
- func AlignColorizedText(str string, width int, align Align) (int, string)
- func AlignText(str string, width int, align Align) (shift int, out string)
- func BackColor() term.Attribute
- func CalcClipper(c Control) (int, int, int, int)
- func ClipRect() (x int, y int, w int, h int)
- func ColorToString(attr term.Attribute) string
- func ControlInRect(c Control, x int, y int, w int, h int) bool
- func CurrentTheme() string
- func CutText(str string, maxWidth int) string
- func DeactivateControls(parent Control)
- func DeinitLibrary()
- func DrawFrame(x, y, w, h int, border BorderStyle)
- func DrawHorizontalLine(x, y, w int, r rune)
- func DrawRawText(x, y int, text string)
- func DrawRawTextVertical(x, y int, text string)
- func DrawScrollBar(x, y, w, h, pos int)
- func DrawText(x, y int, text string)
- func DrawTextVertical(x, y int, text string)
- func DrawVerticalLine(x, y, h int, r rune)
- func Ellipsize(str string, maxWidth int) string
- func FillRect(x, y, w, h int, r rune)
- func Flush()
- func GetColorMap() map[string]term.Attribute
- func GrabEvents(c Control)
- func InClipRect(x, y int) bool
- func InitLibrary() bool
- func InitLogger()
- func IsDeadKey(key term.Key) bool
- func IsMouseClickEvent(ev Event) bool
- func ItemByThumbPosition(position, itemCount, length int) int
- func Logger() *log.Logger
- func MainLoop()
- func PopAttributes()
- func PopClip()
- func ProcessEvent(ev Event)
- func PushAttributes()
- func PushClip()
- func PutChar(x, y int, r rune) bool
- func PutEvent(ev Event)
- func RealColor(clr term.Attribute, style string, id string) term.Attribute
- func RefreshScreen()
- func ReleaseEvents()
- func ReloadTheme(name string)
- func Reset()
- func ScreenSize() (width int, height int)
- func SendEventToChild(parent Control, ev Event) bool
- func SetBackColor(clr term.Attribute)
- func SetClipRect(x, y, w, h int)
- func SetColorMap(cmap map[string]term.Attribute)
- func SetCurrentTheme(name string) bool
- func SetCursorPos(x int, y int)
- func SetScreenSize(width int, height int)
- func SetTextColor(clr term.Attribute)
- func SetThemePath(path string)
- func SliceColorized(str string, start, end int) string
- func Stop()
- func StringToColor(str string) term.Attribute
- func Symbol(x, y int) (term.Cell, bool)
- func SysColor(color string) term.Attribute
- func SysObject(object string) string
- func TextColor() term.Attribute
- func TextExtent(text string) (int, int)
- func ThemeNames() []string
- func ThemePath() string
- func ThemeReset()
- func ThumbPosition(itemNo, itemCount, length int) int
- func UnColorizeText(str string) string
- type Align
- type BarChart
- func (b *BarChart) AddData(val BarData)
- func (b *BarChart) AutoSize() bool
- func (b *BarChart) BarGap() int32
- func (b *BarChart) ClearData()
- func (b *BarChart) Draw()
- func (b *BarChart) LegendWidth() int32
- func (b *BarChart) MinBarWidth() int32
- func (b *BarChart) OnDrawCell(fn func(*BarDataCell))
- func (b *BarChart) SetAutoSize(auto bool)
- func (b *BarChart) SetBarGap(gap int32)
- func (b *BarChart) SetData(data []BarData)
- func (b *BarChart) SetLegendWidth(width int32)
- func (b *BarChart) SetMinBarWidth(size int32)
- func (b *BarChart) SetShowMarks(show bool)
- func (b *BarChart) SetShowTitles(show bool)
- func (b *BarChart) SetValueWidth(width int32)
- func (b *BarChart) ShowMarks() bool
- func (b *BarChart) ShowTitles() bool
- func (b *BarChart) ValueWidth() int32
- type BarData
- type BarDataCell
- type BaseControl
- func (c *BaseControl) Active() bool
- func (c *BaseControl) ActiveColors() (term.Attribute, term.Attribute)
- func (c *BaseControl) AddChild(control Control)
- func (c *BaseControl) Align() Align
- func (c *BaseControl) BackColor() term.Attribute
- func (c *BaseControl) ChildExists(control Control) bool
- func (c *BaseControl) Children() []Control
- func (c *BaseControl) ChildrenScale() int
- func (c *BaseControl) Clipped() bool
- func (c *BaseControl) Clipper() (int, int, int, int)
- func (c *BaseControl) Constraints() (minw int, minh int)
- func (c *BaseControl) Destroy()
- func (c *BaseControl) Draw()
- func (c *BaseControl) DrawChildren()
- func (c *BaseControl) Enabled() bool
- func (c *BaseControl) Gaps() (dx int, dy int)
- func (c *BaseControl) HitTest(x, y int) HitResult
- func (c *BaseControl) MinimalSize() (w int, h int)
- func (c *BaseControl) Modal() bool
- func (c *BaseControl) OnActive(fn func(active bool))
- func (c *BaseControl) Pack() PackType
- func (c *BaseControl) Paddings() (px int, py int)
- func (c *BaseControl) Parent() Control
- func (c *BaseControl) PlaceChildren()
- func (c *BaseControl) Pos() (x int, y int)
- func (c *BaseControl) ProcessEvent(ev Event) bool
- func (c *BaseControl) RefID() int64
- func (c *BaseControl) ResizeChildren()
- func (c *BaseControl) Scale() int
- func (c *BaseControl) SetActive(active bool)
- func (c *BaseControl) SetActiveBackColor(clr term.Attribute)
- func (c *BaseControl) SetActiveTextColor(clr term.Attribute)
- func (c *BaseControl) SetAlign(align Align)
- func (c *BaseControl) SetBackColor(clr term.Attribute)
- func (c *BaseControl) SetClipped(clipped bool)
- func (c *BaseControl) SetConstraints(minw, minh int)
- func (c *BaseControl) SetEnabled(enabled bool)
- func (c *BaseControl) SetGaps(dx, dy int)
- func (c *BaseControl) SetModal(modal bool)
- func (c *BaseControl) SetPack(pack PackType)
- func (c *BaseControl) SetPaddings(px, py int)
- func (c *BaseControl) SetParent(parent Control)
- func (c *BaseControl) SetPos(x, y int)
- func (c *BaseControl) SetScale(scale int)
- func (c *BaseControl) SetSize(width, height int)
- func (c *BaseControl) SetStyle(style string)
- func (c *BaseControl) SetTabStop(tabstop bool)
- func (c *BaseControl) SetTextColor(clr term.Attribute)
- func (c *BaseControl) SetTitle(title string)
- func (c *BaseControl) SetVisible(visible bool)
- func (c *BaseControl) Size() (widht int, height int)
- func (c *BaseControl) Style() string
- func (c *BaseControl) TabStop() bool
- func (c *BaseControl) TextColor() term.Attribute
- func (c *BaseControl) Title() string
- func (c *BaseControl) Visible() bool
- type BorderStyle
- type Button
- type ButtonShadow
- type Canvas
- type CheckBox
- func (c *CheckBox) Allow3State() bool
- func (c *CheckBox) Draw()
- func (c *CheckBox) OnChange(fn func(int))
- func (c *CheckBox) ProcessEvent(event Event) bool
- func (c *CheckBox) SetAllow3State(enable bool)
- func (c *CheckBox) SetSize(width, height int)
- func (c *CheckBox) SetState(val int)
- func (c *CheckBox) State() int
- type ColorParser
- type Column
- type ColumnDrawInfo
- type Composer
- type ConfirmationDialog
- type Control
- func ActiveControl(parent Control) Control
- func ChildAt(parent Control, x, y int) Control
- func ClippedParent(c Control) Control
- func FindChild(parent, control Control) Control
- func FindFirstActiveControl(parent Control) Control
- func FindFirstControl(parent Control, fn func(Control) bool) Control
- func FindLastControl(parent Control, fn func(Control) bool) Control
- func NextControl(parent Control, curr Control, next bool) Control
- type Direction
- type DragType
- type EditField
- func (e *EditField) Clear()
- func (e *EditField) Draw()
- func (e *EditField) MaxWidth() int
- func (e *EditField) OnChange(fn func(Event))
- func (e *EditField) OnKeyPress(fn func(term.Key, rune) bool)
- func (e *EditField) PasswordMode() bool
- func (e *EditField) ProcessEvent(event Event) bool
- func (e *EditField) SetMaxWidth(w int)
- func (e *EditField) SetPasswordMode(pass bool)
- func (e *EditField) SetSize(width, height int)
- func (e *EditField) SetTitle(title string)
- type Event
- type EventType
- type FileSelectDialog
- type Frame
- type HitResult
- type Label
- type ListBox
- func (l *ListBox) AddItem(item string) bool
- func (l *ListBox) Clear()
- func (l *ListBox) Draw()
- func (l *ListBox) EnsureVisible()
- func (l *ListBox) FindItem(text string, caseSensitive bool) int
- func (l *ListBox) Item(id int) (string, bool)
- func (l *ListBox) ItemCount() int
- func (l *ListBox) OnKeyPress(fn func(term.Key) bool)
- func (l *ListBox) OnSelectItem(fn func(Event))
- func (l *ListBox) PartialFindItem(text string, caseSensitive bool) int
- func (l *ListBox) ProcessEvent(event Event) bool
- func (l *ListBox) RemoveItem(id int) bool
- func (l *ListBox) SelectItem(id int) bool
- func (l *ListBox) SelectedItem() int
- func (l *ListBox) SelectedItemText() string
- type LoginDialog
- type PackType
- type ProgressBar
- func (b *ProgressBar) Draw()
- func (b *ProgressBar) Limits() (int, int)
- func (b *ProgressBar) SecondaryColors() (term.Attribute, term.Attribute)
- func (b *ProgressBar) SetLimits(min, max int)
- func (b *ProgressBar) SetSecondaryColors(fg, bg term.Attribute)
- func (b *ProgressBar) SetTitleColor(clr term.Attribute)
- func (b *ProgressBar) SetValue(pos int)
- func (b *ProgressBar) Step() int
- func (b *ProgressBar) TitleColor() term.Attribute
- func (b *ProgressBar) Value() int
- type Radio
- type RadioGroup
- type SelectDialog
- type SelectDialogType
- type SortOrder
- type SparkChart
- func (b *SparkChart) AddData(val float64)
- func (b *SparkChart) AutoScale() bool
- func (b *SparkChart) ClearData()
- func (b *SparkChart) Draw()
- func (b *SparkChart) HilitePeaks() bool
- func (b *SparkChart) SetAutoScale(auto bool)
- func (b *SparkChart) SetData(data []float64)
- func (b *SparkChart) SetHilitePeaks(hilite bool)
- func (b *SparkChart) SetTop(top float64)
- func (b *SparkChart) SetValueWidth(width int)
- func (b *SparkChart) Top() float64
- func (b *SparkChart) ValueWidth() int
- type TableAction
- type TableEvent
- type TableView
- func (l *TableView) Columns() []Column
- func (l *TableView) Draw()
- func (l *TableView) EnsureColVisible()
- func (l *TableView) EnsureRowVisible()
- func (l *TableView) FullRowSelect() bool
- func (l *TableView) OnAction(fn func(TableEvent))
- func (l *TableView) OnBeforeDraw(fn func(int, int, int, int))
- func (l *TableView) OnDrawCell(fn func(*ColumnDrawInfo))
- func (l *TableView) OnKeyPress(fn func(term.Key) bool)
- func (l *TableView) OnSelectCell(fn func(int, int))
- func (l *TableView) ProcessEvent(event Event) bool
- func (l *TableView) RowCount() int
- func (l *TableView) SelectedCol() int
- func (l *TableView) SelectedRow() int
- func (l *TableView) SetColumnInfo(id int, col Column)
- func (l *TableView) SetColumns(cols []Column)
- func (l *TableView) SetFullRowSelect(fullRow bool)
- func (l *TableView) SetRowCount(count int)
- func (l *TableView) SetSelectedCol(col int)
- func (l *TableView) SetSelectedRow(row int)
- func (l *TableView) SetShowLines(show bool)
- func (l *TableView) SetShowRowNumber(show bool)
- func (l *TableView) ShowLines() bool
- func (l *TableView) ShowRowNumber() bool
- func (l *TableView) VisibleArea() (firstCol, firstRow, colCount, rowCount int)
- type TextDisplay
- func (l *TextDisplay) Draw()
- func (l *TextDisplay) LineCount() int
- func (l *TextDisplay) OnDrawLine(fn func(int) string)
- func (l *TextDisplay) OnPositionChanged(fn func(int, int))
- func (l *TextDisplay) ProcessEvent(event Event) bool
- func (l *TextDisplay) SetLineCount(lineNo int)
- func (l *TextDisplay) SetTopLine(top int)
- func (l *TextDisplay) TopLine() int
- type TextElement
- type TextElementType
- type TextReader
- type TextView
- func (l *TextView) AddText(text []string)
- func (l *TextView) AutoScroll() bool
- func (l *TextView) Draw()
- func (l *TextView) ItemCount() int
- func (l *TextView) LoadFile(filename string) bool
- func (l *TextView) MaxItems() int
- func (l *TextView) ProcessEvent(event Event) bool
- func (l *TextView) SetAutoScroll(auto bool)
- func (l *TextView) SetMaxItems(max int)
- func (l *TextView) SetText(text []string)
- func (l *TextView) SetWordWrap(wrap bool)
- func (l *TextView) WordWrap() bool
- type ThemeDesc
- type ThemeManager
- type ViewButton
- type Window
- func (w *Window) Border() BorderStyle
- func (wnd *Window) Draw()
- func (c *Window) HitTest(x, y int) HitResult
- func (w *Window) Maximized() bool
- func (w *Window) Movable() bool
- func (w *Window) OnClose(fn func(Event) bool)
- func (w *Window) OnKeyDown(fn func(Event, interface{}) bool, data interface{})
- func (w *Window) OnScreenResize(fn func(Event))
- func (c *Window) ProcessEvent(ev Event) bool
- func (w *Window) SetBorder(border BorderStyle)
- func (w *Window) SetMaximized(maximize bool)
- func (w *Window) SetMovable(movable bool)
- func (w *Window) SetSizable(sizable bool)
- func (w *Window) SetTitleButtons(buttons ViewButton)
- func (w *Window) SetVisible(visible bool)
- func (w *Window) Sizable() bool
- func (w *Window) TitleButtons() ViewButton
- func (w *Window) Visible() bool
Constants ¶
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
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 )
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
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
const ( Horizontal = iota Vertical )
Output direction Used for Label text output direction and for Radio items distribution, and for container controls
const ( ObjSingleBorder = "SingleBorder" ObjDoubleBorder = "DoubleBorder" ObjEdit = "Edit" ObjScrollBar = "ScrollBar" ObjViewButtons = "ViewButtons" ObjCheckBox = "CheckBox" ObjRadio = "Radio" ObjProgressBar = "ProgressBar" ObjBarChart = "BarChart" ObjSparkChart = "SparkChart" ObjTableView = "TableView" ObjButton = "Button" )
Available object identifiers that can be used in themes
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
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 // Make a control (Target field of Event structure) to recalculate and reposition all its children EventLayout // A scroll-able control's child has been activated, then notify its parent to handle // the scrolling EventActivateChild )
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
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
const ( LoginOk = iota LoginCanceled LoginInvalid )
Variables ¶
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 ¶
ActivateControl makes control active and disables all other children of the parent. Returns true if control was found and activated
func AlignColorizedText ¶
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 ¶
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 CalcClipper ¶ added in v1.1.0
CalcClipper calculates the clipper size based on the control's size, position and paddings
func ColorToString ¶
ColorToString returns string representation of the attribute
func ControlInRect ¶ added in v1.1.0
ControlInRect returns true if c is within a given rect
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 ¶
DrawHorizontalLine draws the part of the horizontal line that is inside current clipping rectangle
func DrawRawText ¶
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 ¶
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 ¶
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 ¶
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 ¶
DrawVerticalLine draws the part of the vertical line that is inside current clipping rectangle
func Ellipsize ¶
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 GetColorMap ¶ added in v1.1.0
GetColorMap returns the color map (id is the color name, value its code)
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 ¶
InClipRect returns true if x and y position is inside current clipping rectangle
func InitLibrary ¶
func InitLibrary() bool
func InitLogger ¶
func InitLogger()
func IsDeadKey ¶
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 ¶
IsMouseClickEvent returns if a user action can be treated as mouse click.
func ItemByThumbPosition ¶
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 PopAttributes ¶
func PopAttributes()
PopAttributes restores saved with PushAttributes colors. Function does nothing if there is no saved colors
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 PutChar ¶
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 ¶
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.
With the style argument themes may be grouped by control, i.e an application may have multiple list controls where they all share the same theme attributes however the same application may have one specific list control with some different theme attributes, in that case the user may call control.SetStyle("custom") and define a set of custom.* attributes, i.e:
custom.EditBox = white custom.EditText = black bold ...
clr - current object color style - the theme prefix style set id - color ID in theme
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 SendEventToChild ¶
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 ¶
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 SetColorMap ¶ added in v1.1.0
SetColorMap sets a custom color map (id is the color name, value its code)
func SetCurrentTheme ¶
SetCurrentTheme changes the current theme. Returns false if changing failed - e.g, theme does not exist
func SetCursorPos ¶
SetCursorPos sets text caret position. Used by controls like EditField
func SetScreenSize ¶
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 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 ¶
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 ¶
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 SysColor ¶
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 ¶
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 TextExtent ¶
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()
ThemeReset removes all loaded themes from cache and reinitialize the default theme
func ThumbPosition ¶
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 ¶
UnColorizeText removes all color-related tags from the string. Tags to remove: <(f|t|b|c):.*>
Types ¶
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 ¶
CreateBarChart 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) AutoSize ¶
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) LegendWidth ¶
LegendWidth returns width of chart legend displayed at the right side of the chart. Set it to 0 to disable legend
func (*BarChart) MinBarWidth ¶
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 ¶
SetAutoSize enables or disables automatic bar width calculation
func (*BarChart) SetLegendWidth ¶
SetLegendWidth sets new legend panel width
func (*BarChart) SetMinBarWidth ¶
SetMinBarWidth changes the minimal bar width
func (*BarChart) SetShowMarks ¶
SetShowMarks turns on and off marks under horizontal axis
func (*BarChart) SetShowTitles ¶
SetShowTitles turns on and off horizontal axis and bar titles
func (*BarChart) SetValueWidth ¶
SetValueWidth changes width of the value panel on the left
func (*BarChart) ShowMarks ¶
ShowMarks returns if horizontal axis has mark under each bar. To show marks, ShowTitles must be enabled.
func (*BarChart) ShowTitles ¶
ShowTitles returns if chart displays horizontal axis and bar titles under it
func (*BarChart) ValueWidth ¶
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 ¶
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 NewBaseControl ¶ added in v0.8.0
func NewBaseControl() BaseControl
func (*BaseControl) Active ¶
func (c *BaseControl) Active() bool
func (*BaseControl) ActiveColors ¶
func (c *BaseControl) ActiveColors() (term.Attribute, term.Attribute)
ActiveColors return the attributes 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) Clipped ¶ added in v1.1.0
func (c *BaseControl) Clipped() bool
func (*BaseControl) Constraints ¶
func (c *BaseControl) Constraints() (minw int, minh int)
func (*BaseControl) Destroy ¶ added in v0.8.0
func (c *BaseControl) Destroy()
Destroy removes an object from its parental chain
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) OnActive ¶ added in v1.1.0
func (c *BaseControl) OnActive(fn func(active 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) RefID ¶ added in v0.8.0
func (c *BaseControl) RefID() int64
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) SetClipped ¶ added in v1.1.0
func (c *BaseControl) SetClipped(clipped bool)
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) SetStyle ¶ added in v1.1.0
func (c *BaseControl) SetStyle(style string)
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) SetVisible ¶ added in v0.8.0
func (c *BaseControl) SetVisible(visible bool)
func (*BaseControl) Size ¶
func (c *BaseControl) Size() (widht int, height int)
func (*BaseControl) Style ¶ added in v1.1.0
func (c *BaseControl) Style() string
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
func (*BaseControl) Visible ¶ added in v0.8.0
func (c *BaseControl) Visible() bool
type BorderStyle ¶
type BorderStyle int
BorderStyle is a kind of frame: auto, none, thin, and thick
const ( BorderAuto BorderStyle = iota - 1 BorderNone 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 ¶
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) OnClick ¶
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 ¶
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 (*Button) SetShadowType ¶ added in v1.2.1
func (b *Button) SetShadowType(sh ButtonShadow)
SetShadowType changes the shadow the button drops
func (*Button) ShadowType ¶ added in v1.2.1
func (b *Button) ShadowType() ButtonShadow
ShadowType returns type of a show the button drops
type ButtonShadow ¶ added in v1.2.1
type ButtonShadow int
ButtonShadow is a type of shadow that a Button drops
const ( // Basic button shadow ShadowFull ButtonShadow = iota // Half-symbols are used to draw a shadow that makes it slimmer ShadowHalf // No shadow and button turns a flat one ShadowNone )
ButtonShadow constants
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 ¶
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 ¶
Allow3State returns true if ComboBox uses 3 states
func (*CheckBox) OnChange ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 convenience 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 WindowManager ¶ added in v0.8.0
func WindowManager() *Composer
WindowManager returns main Window manager (that is Composer). Use it at your own risk because it provides an access to some low level Window manipulations. Note: Now it is not thread safe to call Composer methods from a few threads.
func (*Composer) BeginUpdate ¶ added in v0.8.0
func (c *Composer) BeginUpdate()
BeginUpdate locks any screen update until EndUpdate is called. Useful only in multithreading application if you create a new Window in some thread that is not main one (e.g, create new Window inside OnSelectItem handler of ListBox) Note: Do not lock for a long time because while the lock is on the screen is not updated
func (*Composer) BorderStyle ¶ added in v1.1.0
func (c *Composer) BorderStyle() BorderStyle
Border returns the default window border
func (*Composer) DestroyWindow ¶
DestroyWindow removes the Window from the list of managed Windows
func (*Composer) EndUpdate ¶ added in v0.8.0
func (c *Composer) EndUpdate()
EndUpdate unlocks the screen for any manipulations. Useful only in multithreading application if you create a new Window in some thread that is not main one (e.g, create new Window inside OnSelectItem handler of ListBox)
func (*Composer) SetBorder ¶ added in v1.1.0
func (c *Composer) SetBorder(border BorderStyle)
SetBorder changes the default window border
type ConfirmationDialog ¶
type ConfirmationDialog struct { View *Window // 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 CreateAlertDialog ¶ added in v0.8.0
func CreateAlertDialog(title, message string, button string) *ConfirmationDialog
CreateAlertDialog creates a new alert dialog. title is a dialog title message is a text inside dialog for user to be notified of a fact button is a title for button inside dialog.
func CreateConfirmationDialog ¶
func CreateConfirmationDialog(title, question string, buttons []string, defaultButton int) *ConfirmationDialog
CreateConfirmationDialog 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) // Visible return if a control is visible Visible() bool SetVisible(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 // RefID returns the controls internal reference id RefID() int64 // Destroy is the public interface to remove an object from its parental chain // it implies this control will stop receiving events and will not be drawn nor // will impact on other objects position and size calculation Destroy() // SetStyle sets a control's custom style grouper/modifier, with a style set // the control will prefix the control theme with style, i.e if a button is modified // and set style to "MyCustom" then the theme will engine will first attempt to apply // MyCustomButtonBack and MyCustomButtonText if not present then apply the default // and standard ButtonBack and ButtonText SetStyle(style string) // Style returns the custom style grouper/modifier Style() string // SetClipped marks a control as clip-able, meaning the children components will not // affect the control's size - i.e will not make it expand SetClipped(clipped bool) // Clipped returns the current control's clipped flag Clipped() bool // Clipper if the component is clipped then return the clipper geometry, however // the size and pos is returned Clipper() (int, int, int, int) // contains filtered or unexported methods }
Control is an interface that every visible control should implement
func ActiveControl ¶
ActiveControl returns the active child of the parent or nil if no child is active
func ChildAt ¶
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 ClippedParent ¶ added in v1.1.0
ClippedParent finds the first c parent with clipped flag
func FindFirstActiveControl ¶ added in v1.1.0
FindFirstActiveControl returns the first active control of a parent
func FindFirstControl ¶
FindFirstControl returns the first child for that fn returns true. The function is used to find active or tab-stop control
func FindLastControl ¶
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
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 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 ¶
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) OnChange ¶
OnChange sets the callback that is called when EditField content is changed
func (*EditField) OnKeyPress ¶
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 ¶
PasswordMode returns whether password mode is enabled for the control
func (*EditField) ProcessEvent ¶
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 ¶
SetMaxWidth sets the maximum lenght of the EditField text. If the current text is longer it is truncated
func (*EditField) SetPasswordMode ¶
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)
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 Target Control }
Event is structure used by Views and controls to communicate with Composer and vice versa
type FileSelectDialog ¶ added in v1.1.0
type FileSelectDialog struct { View *Window FilePath string Exists bool Selected bool // contains filtered or unexported fields }
FileSelectDialog is a dialog to select a file or directory. Public properties:
- Selected - whether a user has selected an object, or the user canceled or closed the dialog. In latter case all other properties are not used and contain default values
- FilePath - full path to the selected file or directory
- Exists - if the selected object exists or a user entered manually a name of the object
func CreateFileSelectDialog ¶ added in v1.1.0
func CreateFileSelectDialog(title, fileMasks, initPath string, selectDir, mustExist bool) *FileSelectDialog
CreateFileSelectDialog creates a new file select dialog. It is useful if the application needs a way to select a file or directory for reading and writing data.
- title - custom dialog title (the final dialog title includes this one and the file mask
- fileMasks - a list of file masks separated with comma or path separator. If selectDir is true this option is not used. Setting fileMasks to '*', '*.*', or empty string means all files
- selectDir - what kind of object to select: file (false) or directory (true). If selectDir is true then the dialog does not show files
- mustExists - if it is true then the dialog allows a user to select only existing object ('open file' case). If it is false then the dialog makes possible to enter a name manually and click 'Select' (useful for file 'file save' case)
func (*FileSelectDialog) OnClose ¶ added in v1.1.0
func (d *FileSelectDialog) OnClose(fn func())
OnClose sets the callback that is called when the dialog is closed
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) ProcessEvent ¶ added in v1.1.0
func (*Frame) ScrollTo ¶ added in v1.1.0
ScrollTo in case of a scrollable frame this api will scroll the content without adjusting the clipper
func (*Frame) Scrollable ¶ added in v1.1.0
func (*Frame) SetScrollable ¶ added in v1.1.0
type HitResult ¶
type HitResult int
HitResult is a type of a view area that is under mouse cursor. Used in mouse click events
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 ¶
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) Multiline ¶
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 ¶
SetDirection sets the text output direction
func (*Label) SetMultiline ¶
SetMultiline sets if the label should output text as one line or automatically display it in several lines
func (*Label) SetTextDisplay ¶ added in v1.1.0
SetTextDisplay sets which part of the title is displayed in case of the title is longer than the lable. Only AlignLeft and AlignRigth are valid values for the property. Any other value does is skipped and does not affect displaying the title
func (*Label) TextDisplay ¶ added in v1.1.0
TextDisplay returns which part of the lable title is displayed in case of title is longer than the label: - AlignLeft - the head of the title is shown - AlignRight - the tail of the title is shown The property is used only by single line Label
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. 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 ¶
CreateListBox 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 height - 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 ¶
AddItem adds a new item to item list. Returns true if the operation is successful
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 ¶
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) Item ¶ added in v1.1.0
Item returns item text by its index. If index is out of range an empty string and false are returned
func (*ListBox) OnKeyPress ¶
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 ¶
OnSelectItem sets a callback that is called every time the selected item is changed
func (*ListBox) PartialFindItem ¶ added in v1.1.0
PartialFindItem looks for an item in list which text starts from the given substring, by default the search is casesensitive. Returns item number in item list or -1 if nothing is found.
func (*ListBox) ProcessEvent ¶
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 ¶
RemoveItem deletes an item which number is id in item list Returns true if item is deleted
func (*ListBox) SelectItem ¶
SelectItem selects 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 ¶
SelectedItem returns currently selected item id
func (*ListBox) SelectedItemText ¶
SelectedItemText returns text of currently selected item or empty sting if nothing is selected or ListBox is empty.
type LoginDialog ¶ added in v1.1.0
type LoginDialog struct { View *Window Username string Password string Action int // contains filtered or unexported fields }
LoginDialog is a login dialog with fields to enter user name and password Public properties:
- Username - login entered by a user
- Password - password entered by a user
- Action - how the dialog was closed:
- LoginOk - button "OK" was clicked
- LoginCanceled - button "Cancel" was clicked or dialog was dismissed
- LoginInvalid - invalid credentials were entered. This value appears only in case of callback is used and button "OK" is clicked while entered username or password is incorrect
func CreateLoginDialog ¶ added in v1.1.0
func CreateLoginDialog(title, userName string) *LoginDialog
LoginDialog creates a new login dialog
- title - custom dialog title
- userName - initial username. Maybe useful if you want to implement a feature "remember me"
The active control depends on userName: if it is empty then the cursor is
in Username field, and in Password field otherwise.
By default the dialog is closed when button "OK" is clicked. But if you set
OnCheck callback the dialog closes only if callback returns true or button "Cancel" is clicked. This is helpful if you do not want to recreate the dialog after every incorrect credentials. So, you define a callback that checks whether pair of Usename and Password is correct and then the button "OK" closed the dialog only if the callback returns true. If the credentials are not valid, then the dialog shows a warning. The warning automatically disappears when a user starts typing in Password or Username field.
func (*LoginDialog) OnCheck ¶ added in v1.1.0
func (d *LoginDialog) OnCheck(fn func(string, string) bool)
OnCheck sets the callback that is called when the button "OK" is clicked. The dialog sends to the callback two arguments: username and password. The callback validates the arguments and if the credentials are valid it returns true. That means the dialog can be closed. If the callback returns false then the dialog remains on the screen.
func (*LoginDialog) OnClose ¶ added in v1.1.0
func (d *LoginDialog) OnClose(fn func())
OnClose sets the callback that is called when the dialog is closed
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
CreateProgressBar 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()
Draw repaints 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 ¶
CreateRadio 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) OnChange ¶ added in v1.1.0
OnChange sets the callback that is called whenever the state of the Radio is changed. Argument of callback is the current
func (*Radio) ProcessEvent ¶
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) SetGroup ¶
func (c *Radio) SetGroup(group *RadioGroup)
SetGroup sets the radio group to which the radio belongs
func (*Radio) SetSelected ¶
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
CreateRadioGroup creates a new RadioGroup
func (*RadioGroup) AddItem ¶
func (c *RadioGroup) AddItem(r *Radio)
AddItem adds 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 { View *Window // 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 CreateEditDialog ¶ added in v0.8.0
func CreateEditDialog(title, message, initialText string) *SelectDialog
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) EditResult ¶ added in v0.8.0
func (d *SelectDialog) EditResult() string
EditResult returns the text from editfield
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 // SelectDialogRadio - all items are displayed in a RadioGroup SelectDialogRadio // SelectDialogEdit - Creates an editbox for user input SelectDialogEdit )
SelectDialogType 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 the number 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 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
CreateSparkChart 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) 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 assigns 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 return true in case of Delete key is pressed OnSelectCell - called in case of the currently selected row or column is changed OnBeforeDraw - called right before the TableView is going to repaint itself. It can be used to prepare all the data beforehand and then quickly use cached data inside OnDrawCell. Callback receives 4 arguments: first visible column, first visible row, number of visible columns, number of visible rows.
func CreateTableView ¶
CreateTableView 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 height - 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) EnsureColVisible ¶
func (l *TableView) EnsureColVisible()
EnsureColVisible scrolls the table horizontally to make the currently selected column fully visible
func (*TableView) EnsureRowVisible ¶
func (l *TableView) EnsureRowVisible()
EnsureRowVisible scrolls the table vertically to make the currently selected row visible
func (*TableView) FullRowSelect ¶
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) OnBeforeDraw ¶ added in v1.1.0
OnBeforeDraw is called when TableView is going to draw its cells. Can be used to precache the data, and make OnDrawCell faster. Callback receives 4 arguments: first visible column, first visible row, the number of visible columns, the number of visible rows
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 ¶
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 ¶
OnSelectCell sets a callback that is called every time the selected cell is changed
func (*TableView) ProcessEvent ¶
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) SelectedCol ¶
SelectedCol returns currently selected column number or -1 if no column is selected
func (*TableView) SelectedRow ¶
SelectedRow returns currently selected row number or -1 if no row is selected
func (*TableView) SetColumnInfo ¶
SetColumnInfo replaces the existing column info
func (*TableView) SetColumns ¶
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 ¶
SetFullRowSelect enables or disables hiliting of the full row that contains the selected cell
func (*TableView) SetRowCount ¶
SetRowCount sets the new row count
func (*TableView) SetSelectedCol ¶
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 ¶
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 ¶
SetShowLines disables and enables displaying vertical lines inside TableView
func (*TableView) SetShowRowNumber ¶
SetShowRowNumber turns on and off the first fixed column of the table that displays the row number
func (*TableView) ShowLines ¶
ShowLines returns true if table displays vertical lines to separate columns
func (*TableView) ShowRowNumber ¶
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
func (*TableView) VisibleArea ¶ added in v1.1.0
VisibleArea returns which rows and columns are currently visible. It can be used instead of OnBeforeDraw event to prepare the data for drawing without waiting until TableView starts drawing itself. It can be useful in case of you update your database, so at the same moment you can request the visible area and update database cache - it can improve performance. Returns: * firstCol - first visible column * firstRow - first visible row * colCount - the number of visible columns * rowCount - the number of visible rows
type TextDisplay ¶ added in v1.1.0
type TextDisplay struct { BaseControl // contains filtered or unexported fields }
func CreateTextDisplay ¶ added in v1.1.0
func CreateTextDisplay(parent Control, width, height int, scale int) *TextDisplay
func CreateTextReader ¶
func CreateTextReader(parent Control, width, height int, scale int) *TextDisplay
func (*TextDisplay) Draw ¶ added in v1.1.0
func (l *TextDisplay) Draw()
Draw repaints the control on its View surface
func (*TextDisplay) LineCount ¶ added in v1.1.0
func (l *TextDisplay) LineCount() int
func (*TextDisplay) OnDrawLine ¶ added in v1.1.0
func (l *TextDisplay) 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 (*TextDisplay) OnPositionChanged ¶ added in v1.1.0
func (l *TextDisplay) 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 (*TextDisplay) ProcessEvent ¶ added in v1.1.0
func (l *TextDisplay) 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 (*TextDisplay) SetLineCount ¶ added in v1.1.0
func (l *TextDisplay) SetLineCount(lineNo int)
func (*TextDisplay) SetTopLine ¶ added in v1.1.0
func (l *TextDisplay) SetTopLine(top int)
func (*TextDisplay) TopLine ¶ added in v1.1.0
func (l *TextDisplay) TopLine() int
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 = TextDisplay
TextReader is deprecated due to its confusing name. Use TextDisplay instead. In next major library version TextReader will be removed
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 up to 2 scrollbars: vertical and horizontal. The latter one is available only if WordWrap mode is off).
func CreateTextView ¶
CreateTextView 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 height - 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 ¶
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 ¶
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) LoadFile ¶
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 ¶
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 ¶
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 ¶
SetAutoScroll enables and disables autoscroll mode
func (*TextView) SetMaxItems ¶
SetMaxItems sets the maximum items that TextView keeps
func (*TextView) SetWordWrap ¶
SetWordWrap enables or disables wordwrap mode
type ThemeDesc ¶
type ThemeDesc struct {
// contains filtered or unexported fields
}
ThemeDesc is a detailed information about theme: title, author, version number
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:
- Every line started with '#' or '/' is a comment line.
- Invalid lines - lines that do not contain symbol '=' - are skipped.
- Valid lines are split 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
- There is no mandatory keys - all of them are optional
- Available 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
- 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:
- If the value does not end neither with 'Back' nor with 'Text' it is considered as raw attribute value(e.g, 'green bold')
- 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 returns 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 introduce 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 Window ¶
type Window struct { BaseControl // contains filtered or unexported fields }
Window is an implementation of View managed by Composer.
func AddWindow ¶
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 (*Window) Border ¶ added in v1.1.0
func (w *Window) Border() BorderStyle
Border returns the default window border
func (*Window) HitTest ¶
HitTest returns type of a Window region at a given screen coordinates. The method is used to detect if a mouse cursor on a window border or outside, which window icon is under cursor etc
func (*Window) Movable ¶ added in v0.8.0
Movable returns if the Window can be moved with mouse or keyboard
func (*Window) OnClose ¶
OnClose sets the callback that is called when the Window is about to destroy
func (*Window) OnKeyDown ¶
OnKeyDown sets the callback that is called when a user presses a key while the Window is active
func (*Window) OnScreenResize ¶ added in v0.8.0
OnScreenResize sets the callback that is called when size of terminal changes
func (*Window) ProcessEvent ¶
func (*Window) SetBorder ¶ added in v1.1.0
func (w *Window) SetBorder(border BorderStyle)
SetBorder changes the default window border
func (*Window) SetMaximized ¶
SetMaximized opens the view to full screen or restores its previous size
func (*Window) SetMovable ¶ added in v0.8.0
SetMovable turns on and off ability to change Window position with mouse or keyboard
func (*Window) SetSizable ¶ added in v0.8.0
SetSizable turns on and off ability to change Window size with mouse or keyboard
func (*Window) SetTitleButtons ¶ added in v0.8.0
func (w *Window) SetTitleButtons(buttons ViewButton)
SetTitleButtons sets the title bar buttons available for a user
func (*Window) SetVisible ¶
SetVisible allows to temporarily remove the window from screen and show it later without reconstruction
func (*Window) Sizable ¶ added in v0.8.0
Sizable returns if size of the Window can be changed with mouse or keyboard
func (*Window) TitleButtons ¶ added in v0.8.0
func (w *Window) TitleButtons() ViewButton
TitleButtons returns a set of buttons shown in the Window title bar
Source Files ¶
- barchart.go
- base_control.go
- button.go
- canvas.go
- checkbox.go
- clui2_api.go
- colorparse.go
- composer.go
- consts.go
- control_intf.go
- ctrlutil.go
- dialog.go
- edit.go
- edit_other.go
- fileselectdlg.go
- frame.go
- intro.go
- label.go
- listbox.go
- logger.go
- logindlg.go
- mainloop.go
- progressbar.go
- radio.go
- radiogroup.go
- sparkchart.go
- tableview.go
- textdisplay.go
- textutil.go
- textview.go
- theme.go
- window.go
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) |
tableview-preload
* Demo includes: * - How to use OnBeforeDraw event * - a simple example of "DBCache" for faster drawing
|
* Demo includes: * - How to use OnBeforeDraw event * - a simple example of "DBCache" for faster drawing |