ditty/gui_key.go

101 lines
2.4 KiB
Go

package main
import (
"fmt"
"strings"
"github.com/gdamore/tcell"
"gitlab.com/tslocum/cbind"
)
const (
actionSelect = "select"
actionPause = "pause"
actionRefresh = "refresh"
actionBrowseParent = "browse-parent"
actionVolumeMute = "volume-mute"
actionVolumeDown = "volume-down"
actionVolumeUp = "volume-up"
actionPreviousItem = "previous-item"
actionNextItem = "next-item"
actionPreviousPage = "previous-page"
actionNextPage = "next-page"
actionPreviousTrack = "previous-track"
actionNextTrack = "next-track"
actionExit = "exit"
)
var actionHandlers = map[string]func(){
actionSelect: listSelect,
actionPause: pause,
actionRefresh: listRefresh,
actionBrowseParent: browseParent,
actionVolumeMute: toggleMute,
actionVolumeDown: decreaseVolume,
actionVolumeUp: increaseVolume,
actionPreviousItem: listPrevious,
actionNextItem: listNext,
actionPreviousPage: listPreviousPage,
actionNextPage: listNextPage,
actionPreviousTrack: skipPrevious,
actionNextTrack: skipNext,
actionExit: exit,
}
var inputConfig = cbind.NewConfiguration()
func wrapEventHandler(f func()) func(_ *tcell.EventKey) *tcell.EventKey {
return func(_ *tcell.EventKey) *tcell.EventKey {
f()
return nil
}
}
func setKeyBinds() error {
if len(config.Input) == 0 {
setDefaultKeyBinds()
}
for a, keys := range config.Input {
a = strings.ToLower(a)
handler := actionHandlers[a]
if handler == nil {
return fmt.Errorf("failed to set keybind for %s: unknown action", a)
}
for _, k := range keys {
mod, key, ch, err := cbind.Decode(k)
if err != nil {
return fmt.Errorf("failed to set keybind %s for %s: %s", k, a, err)
}
if key == tcell.KeyRune {
inputConfig.SetRune(mod, ch, wrapEventHandler(handler))
} else {
inputConfig.SetKey(mod, key, wrapEventHandler(handler))
}
}
}
return nil
}
func setDefaultKeyBinds() {
config.Input = map[string][]string{
actionSelect: {"Enter"},
actionPause: {"Space"},
actionRefresh: {"r"},
actionBrowseParent: {"Backspace"},
actionVolumeMute: {"m"},
actionVolumeDown: {"-"},
actionVolumeUp: {"+"},
actionPreviousItem: {"Up", "k"},
actionNextItem: {"Down", "j"},
actionPreviousPage: {"PageUp"},
actionNextPage: {"PageDown"},
actionPreviousTrack: {"p"},
actionNextTrack: {"n"},
actionExit: {"Escape"},
}
}