69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package ui
|
|
|
|
import (
|
|
"os"
|
|
"reflect"
|
|
"sync"
|
|
|
|
tea "github.com/charmbracelet/bubbletea"
|
|
|
|
"ghosttyconf/internal/keybind"
|
|
)
|
|
|
|
// rawSequence extracts the bytes of an escape sequence Bubble Tea did not
|
|
// recognize. Bubble Tea v1 reports those as an unexported []byte message
|
|
// type, which is where kitty keyboard protocol key events end up.
|
|
func rawSequence(msg tea.Msg) ([]byte, bool) {
|
|
if msg == nil {
|
|
return nil, false
|
|
}
|
|
t := reflect.TypeOf(msg)
|
|
if t.Kind() != reflect.Slice || t.Elem().Kind() != reflect.Uint8 ||
|
|
t.PkgPath() != "github.com/charmbracelet/bubbletea" {
|
|
return nil, false
|
|
}
|
|
return reflect.ValueOf(msg).Bytes(), true
|
|
}
|
|
|
|
var (
|
|
kittyMu sync.Mutex
|
|
kittyActive bool
|
|
)
|
|
|
|
func writeTerminal(s string) {
|
|
_, _ = os.Stdout.WriteString(s)
|
|
}
|
|
|
|
// enableKeyCapture switches the terminal to the kitty keyboard protocol so
|
|
// that every key (including cmd/super combinations) can be recorded.
|
|
func enableKeyCapture() tea.Cmd {
|
|
return func() tea.Msg {
|
|
kittyMu.Lock()
|
|
defer kittyMu.Unlock()
|
|
if !kittyActive {
|
|
writeTerminal(keybind.PushKitty + keybind.QueryKitty)
|
|
kittyActive = true
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// disableKeyCapture restores the previous keyboard mode.
|
|
func disableKeyCapture() tea.Cmd {
|
|
return func() tea.Msg {
|
|
RestoreTerminal()
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// RestoreTerminal undoes enableKeyCapture. It is safe to call at any time
|
|
// and is called on exit in case the program stops while recording.
|
|
func RestoreTerminal() {
|
|
kittyMu.Lock()
|
|
defer kittyMu.Unlock()
|
|
if kittyActive {
|
|
writeTerminal(keybind.PopKitty)
|
|
kittyActive = false
|
|
}
|
|
}
|