Files
tcell-widgets/wdgt_cli.go
2025-10-09 12:24:00 -05:00

449 lines
10 KiB
Go

/*
Copyright © Brian Buller <brian@bullercodeworks.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package widgets
import (
"fmt"
"strings"
wh "git.bullercodeworks.com/brian/tcell-widgets/helpers"
"github.com/gdamore/tcell"
)
// Cli is a greedy widget and will consume all of the space you give it.
type Cli struct {
id string
style tcell.Style
x, y int
w, h int
active bool
visible bool
focusable bool
minimized bool
title string
rawLog []string
log []string
logPosition int
value string
cursor int
history []string
historyPosition int
commands []*CliCommand
keyMap KeyMap
}
// TODO: Fix Command/SubCommand finding
var _ Widget = (*Cli)(nil)
func NewCli(id string, s tcell.Style) *Cli {
ret := &Cli{}
ret.Init(id, s)
return ret
}
func (w *Cli) Init(id string, s tcell.Style) {
w.id, w.style = id, s
w.visible = true
w.initKeyMap()
w.focusable = true
}
func (w *Cli) Id() string { return w.id }
func (w *Cli) HandleResize(ev *tcell.EventResize) {
w.w, w.h = ev.Size()
if w.minimized {
w.h = 3
}
}
func (w *Cli) SetKeyMap(km KeyMap) { w.keyMap = km }
func (w *Cli) AddToKeyMap(km KeyMap) { w.keyMap.Merge(km) }
func (w *Cli) RemoveFromKeyMap(km KeyMap) {
for k := range km.Keys {
w.keyMap.Remove(k)
}
for r := range km.Runes {
w.keyMap.RemoveRune(r)
}
}
func (w *Cli) HandleKey(ev *tcell.EventKey) bool {
if !w.active {
return false
}
if wh.IsKey(*ev, tcell.KeyEsc) {
w.SetActive(false)
return true
}
if wh.IsBS(*ev) {
if w.cursor > 0 {
w.cursor--
}
if w.cursor < len(w.value) {
w.value = w.value[:w.cursor] + w.value[w.cursor+1:]
}
}
if ok := w.keyMap.Handle(ev); ok {
return true
}
var ch string
if wh.KeyIsDisplayable(*ev) {
ch = string(ev.Rune())
if w.cursor < len(w.value) {
strPt1 := w.value[:w.cursor]
strPt2 := w.value[w.cursor:]
w.value = fmt.Sprintf("%s%s%s", strPt1, ch, strPt2)
} else {
w.value = fmt.Sprintf("%s%s", w.value, ch)
}
w.cursor++
return true
}
return false
}
func (w *Cli) HandleTime(ev *tcell.EventTime) {}
func (w *Cli) Draw(screen tcell.Screen) {
if !w.visible {
return
}
dStyle := w.style
if !w.active {
dStyle = dStyle.Dim(true)
}
if w.title != "" {
wh.TitledBorderFilled(w.x, w.y, w.x+w.w-1, w.y+w.h, w.title, wh.BRD_SIMPLE, dStyle, screen)
} else {
wh.BorderFilled(w.x, w.y, w.x+w.w-1, w.y+w.h, wh.BRD_SIMPLE, dStyle, screen)
}
x, y := w.x+1, w.y+1+w.h-3
if !w.minimized {
for i := 0; i < w.h-2; i++ {
if len(w.log) > (i + w.logPosition) {
idx := len(w.log) - (i + w.logPosition) - 1
if idx < 0 {
y--
wh.DrawText(x, y, wh.PadR("", w.w-2), dStyle, screen)
continue
}
line := w.log[idx]
if len(line) > w.w-2 {
line = line[:w.w-2]
}
wh.DrawText(x, y, wh.PadR(line, w.w-2), dStyle, screen)
y--
}
}
}
y = w.y + w.h - 1
cursor := " "
pre := "> "
var post string
if len(w.value) > 0 {
pre = fmt.Sprintf("%s%s", pre, w.value[:w.cursor])
if w.cursor < len(w.value) {
cursor = string(w.value[w.cursor])
post = w.value[w.cursor+1:]
}
}
wh.DrawText(x, y, pre, dStyle, screen)
x += len(pre)
wh.DrawText(x, y, cursor, dStyle.Reverse(w.active), screen)
x += 1
wh.DrawText(x, y, wh.PadR(post, w.w-x-2), dStyle, screen)
}
func (w *Cli) Active() bool { return w.active }
func (w *Cli) SetActive(a bool) { w.active = a }
func (w *Cli) Visible() bool { return w.visible }
func (w *Cli) SetVisible(a bool) { w.visible = a }
func (w *Cli) Focusable() bool { return true }
func (w *Cli) SetFocusable(b bool) { w.focusable = b }
func (w *Cli) SetX(x int) { w.x = x }
func (w *Cli) SetY(y int) { w.y = y }
func (w *Cli) GetX() int { return w.x }
func (w *Cli) GetY() int { return w.y }
func (w *Cli) GetPos() Coord { return Coord{X: w.x, Y: w.y} }
func (w *Cli) SetPos(c Coord) { w.x, w.y = c.X, c.Y }
func (w *Cli) GetW() int { return w.w }
func (w *Cli) GetH() int { return w.h }
func (w *Cli) SetW(wd int) { w.w = wd }
func (w *Cli) SetH(h int) { w.h = h }
func (w *Cli) SetSize(c Coord) { w.w, w.h = c.X, c.Y }
func (w *Cli) WantW() int { return wh.MaxInt }
func (w *Cli) WantH() int {
if w.minimized {
return 3
} else {
return wh.MaxInt
}
}
func (w *Cli) MinW() int { return 20 }
func (w *Cli) MinH() int { return 6 }
func (w *Cli) initKeyMap() {
w.keyMap = NewKeyMap(map[tcell.Key]func(ev *tcell.EventKey) bool{
tcell.KeyEsc: func(ev *tcell.EventKey) bool {
w.SetActive(false)
return true
},
tcell.KeyUp: func(ev *tcell.EventKey) bool {
if w.historyPosition < len(w.history)-1 {
w.historyPosition++
w.value = w.history[w.historyPosition]
w.cursor = len(w.value)
return true
}
return false
},
tcell.KeyDown: func(ev *tcell.EventKey) bool {
if w.historyPosition > -1 {
w.historyPosition--
if w.historyPosition == -1 {
w.value = ""
} else {
w.value = w.history[w.historyPosition]
}
w.cursor = len(w.value)
return true
}
return false
},
tcell.KeyLeft: func(ev *tcell.EventKey) bool {
if w.cursor > 0 {
w.cursor--
return true
}
return false
},
tcell.KeyRight: func(ev *tcell.EventKey) bool {
if w.cursor < len(w.value) {
w.cursor++
return true
}
return false
},
tcell.KeyCtrlU: func(ev *tcell.EventKey) bool {
w.value = w.value[w.cursor:]
w.cursor = 0
return true
},
tcell.KeyTab: func(ev *tcell.EventKey) bool {
// Auto-complete
guess := w.findBestGuess()
if guess != nil {
wrk := strings.Split(w.value, " ")
wrk = append(wrk[:len(wrk)-1], guess.cmd)
w.value = strings.Join(wrk, " ")
w.cursor = len(w.value)
return true
}
return false
},
tcell.KeyEnter: func(ev *tcell.EventKey) bool {
args := strings.Split(w.value, " ")
w.historyPosition = -1
w.value = ""
w.cursor = 0
v := w.value
if len(args) > 0 {
v = args[0]
}
if wrk := w.GetCommandFor(v); wrk != nil {
w.history = append(w.history, w.value)
return wrk.Run(args...)
}
w.history = append(w.history, fmt.Sprintf("%s: command not found", w.value))
return true
},
tcell.KeyPgUp: func(ev *tcell.EventKey) bool {
if w.historyPosition < len(w.log)-w.h-2 {
w.historyPosition += (w.h - 2)
if w.historyPosition > len(w.log) {
w.historyPosition = len(w.log)
}
return true
}
return false
},
tcell.KeyPgDn: func(ev *tcell.EventKey) bool {
if w.historyPosition > 0 {
w.historyPosition -= (w.h - 2)
if w.historyPosition < 0 {
w.historyPosition = 0
}
return true
}
return false
},
})
}
func (w *Cli) SetTitle(ttl string) { w.title = ttl }
func (w *Cli) Title() string { return w.title }
func (w *Cli) SetValue(val string) {
w.value = val
w.cursor = len(val)
}
func (w *Cli) GetCommandFor(txt string) *CliCommand {
for i := range w.commands {
if w.commands[i].cmd == txt {
return w.commands[i]
}
}
return nil
}
func (w *Cli) HasCommand(cmd *CliCommand) bool {
for i := range w.commands {
if w.commands[i].cmd == cmd.cmd {
return true
}
}
return false
}
func (w *Cli) AddCommand(cmd *CliCommand) {
if !w.HasCommand(cmd) {
w.commands = append(w.commands, cmd)
}
}
func (w *Cli) RemoveCommand(cmd string) {
var idx int
for idx = range w.commands {
if w.commands[idx].cmd == cmd {
break
}
}
w.commands = append(w.commands[:idx], w.commands[idx+1:]...)
}
func (w *Cli) findBestGuess() *CliCommand {
if w.value == "" {
return nil
}
args := strings.Split(w.value, " ")
if len(args) > 1 {
if wrk := w.GetCommandFor(args[0]); wrk != nil {
return wrk.findBestGuess(args[1:]...)
}
}
for _, v := range w.commands {
if strings.HasPrefix(v.cmd, w.value) {
return v
}
}
return nil
}
func (w *Cli) Log(txt string, args ...any) {
val := fmt.Sprintf(txt, args...)
w.rawLog = append(w.rawLog, val)
w.log = append(w.log, wh.WrapStringToSlice(val, w.w-2)...)
}
func (w *Cli) Clear() {
w.rawLog = []string{}
w.log = []string{}
}
func (w *Cli) SetMinimized(m bool) { w.minimized = m }
func (w *Cli) IsMinimized() bool { return w.minimized }
type CliCommand struct {
cmd string
do func(args ...string) bool
subCommands []*CliCommand
}
func NewCliCommand(nm string, do func(args ...string) bool, subs ...*CliCommand) *CliCommand {
c := CliCommand{
cmd: nm,
do: do,
}
for i := range subs {
c.AddCommand(subs[i])
}
return &c
}
func (c *CliCommand) Run(args ...string) bool {
if len(c.subCommands) > 0 {
wrk := c.findBestGuess(args...)
if wrk != nil {
return wrk.Run(args...)
}
}
if c.do != nil {
return c.do(args...)
}
return false
}
func (c *CliCommand) AddCommand(cc *CliCommand) error {
if c.HasCommand(cc.cmd) {
return fmt.Errorf("command already exists: %s", cc.cmd)
}
c.subCommands = append(c.subCommands, cc)
return nil
}
func (c *CliCommand) HasCommand(cmd string) bool {
for i := range c.subCommands {
if c.subCommands[i].cmd == cmd {
return true
}
}
return false
}
func (c *CliCommand) GetCommandFor(cmd string) *CliCommand {
for i := range c.subCommands {
if c.subCommands[i].cmd == cmd {
return c.subCommands[i]
}
}
return nil
}
func (c *CliCommand) findBestGuess(args ...string) *CliCommand {
if len(args) == 0 {
return nil
}
// Find the best guess
for _, v := range c.subCommands {
if strings.HasPrefix(args[0], v.cmd) {
return v
}
}
return nil
}