package ui import ( "strings" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "ghosttyconf/internal/ghostty" "ghosttyconf/internal/keybind" "ghosttyconf/internal/schema" ) const triggerPlaceholder = "e.g. super+shift+t, ctrl+a>n, global:ctrl+backquote" // keybindEditor edits a single "trigger=action" binding with a separate // field for each half, key recording for the trigger and completion for // action names. type keybindEditor struct { trigger textinput.Model action textinput.Model focus int // 0 = trigger, 1 = action actions []ghostty.Action matches []ghostty.Action cursor int top int err string // conflict describes an existing binding of a trigger ("" if none). conflict func(trigger string) string recording bool recorded []string beforeRecord string kittyReply bool // the terminal confirmed the kitty keyboard protocol } func newKeybindEditor(value string, actions []ghostty.Action) *keybindEditor { t, a := schema.SplitKeybind(schema.Unquote(value)) e := &keybindEditor{ trigger: newInput(t, triggerPlaceholder), action: newInput(a, "e.g. new_tab, goto_split:right, text:\\x15"), actions: actions, } e.trigger.Prompt = "Trigger › " e.action.Prompt = "Action › " if t != "" { e.focus = 1 e.trigger.Blur() } else { e.action.Blur() } e.refilter() return e } // capturing reports whether all keys must go to this editor (recording). func (e *keybindEditor) capturing() bool { return e.recording } func (e *keybindEditor) refilter() { name := strings.ToLower(keybind.ActionName(e.action.Value())) var prefix, rest []ghostty.Action for _, a := range e.actions { switch { case strings.HasPrefix(a.Name, name): prefix = append(prefix, a) case strings.Contains(a.Name, name) || (name != "" && strings.Contains(strings.ToLower(a.Summary), name)): rest = append(rest, a) } } e.matches = append(prefix, rest...) e.cursor, e.top = 0, 0 for i, a := range e.matches { if a.Name == name { e.cursor = i break } } } func (e *keybindEditor) setFocus(f int) { e.focus = f if f == 0 { e.trigger.Focus() e.action.Blur() } else { e.action.Focus() e.trigger.Blur() } } func (e *keybindEditor) startRecording() tea.Cmd { e.setFocus(0) e.recording = true e.recorded = nil e.beforeRecord = e.trigger.Value() e.trigger.SetValue("") e.trigger.Placeholder = "waiting for keys…" e.err = "" return enableKeyCapture() } func (e *keybindEditor) stopRecording(keep bool) tea.Cmd { e.recording = false e.trigger.Placeholder = triggerPlaceholder if !keep || len(e.recorded) == 0 { e.trigger.SetValue(e.beforeRecord) } else { e.trigger.SetValue(strings.Join(e.recorded, ">")) e.setFocus(1) } e.trigger.CursorEnd() return disableKeyCapture() } // updateRecording handles input while recording: every key combination is // appended to the trigger; plain Enter finishes, plain Esc cancels and plain // Backspace removes the last combination. func (e *keybindEditor) updateRecording(msg tea.Msg) tea.Cmd { var combo keybind.Combo var ok bool if raw, isRaw := rawSequence(msg); isRaw { if keybind.IsKittyReply(raw) { e.kittyReply = true return nil } combo, ok = keybind.DecodeCSI(raw) } else if km, isKey := msg.(tea.KeyMsg); isKey { combo, ok = keybind.DecodeKeyName(km.String()) } else { return nil } if !ok || combo.Modifier { return nil } if combo.Plain() { switch combo.Key { case "enter": return e.stopRecording(true) case "escape": return e.stopRecording(false) case "backspace": if len(e.recorded) > 0 { e.recorded = e.recorded[:len(e.recorded)-1] } e.trigger.SetValue(strings.Join(e.recorded, ">")) return nil } } e.recorded = append(e.recorded, combo.String()) e.trigger.SetValue(strings.Join(e.recorded, ">")) return nil } func (e *keybindEditor) Update(msg tea.Msg) (tea.Cmd, *result) { if e.recording { return e.updateRecording(msg), nil } if km, ok := msg.(tea.KeyMsg); ok { key := km.String() switch key { case "esc": return nil, cancelled() case "ctrl+r": return e.startRecording(), nil case "enter": t := strings.TrimSpace(e.trigger.Value()) a := strings.TrimSpace(e.action.Value()) if t == "" && a == "" { return nil, &result{} } if t == "clear" && a == "" { return nil, valuesResult("clear") } if t == "" { e.err = "the trigger is empty" e.setFocus(0) return nil, nil } if a == "" { e.err = "the action is empty" e.setFocus(1) return nil, nil } return nil, valuesResult(t + "=" + a) case "shift+tab": e.setFocus(0) return nil, nil case "tab": if e.focus == 0 { e.setFocus(1) return nil, nil } if len(e.matches) > 0 { name := e.matches[e.cursor].Name _, param, hasParam := strings.Cut(e.action.Value(), ":") v := name if hasParam { v += ":" + param } e.action.SetValue(v) e.action.CursorEnd() e.refilter() } return nil, nil case "up", "down", "pgup", "pgdown": if e.focus == 1 { if key == "up" && e.cursor == 0 { e.setFocus(0) return nil, nil } e.cursor, _ = moveCursor(key, e.cursor, len(e.matches), 5) return nil, nil } if key == "down" { e.setFocus(1) } return nil, nil } } var cmd tea.Cmd if e.focus == 0 { e.trigger, cmd = e.trigger.Update(msg) } else { before := e.action.Value() e.action, cmd = e.action.Update(msg) if e.action.Value() != before { e.refilter() } } e.err = "" return cmd, nil } // triggerStatus validates the trigger and reports conflicts. func (e *keybindEditor) triggerStatus() []string { t := strings.TrimSpace(e.trigger.Value()) if t == "" || t == "clear" { return nil } if _, err := keybind.Normalize(t); err != nil { return []string{stError.Render("✗ " + err.Error())} } if e.conflict != nil { if c := e.conflict(t); c != "" { return []string{stChanged.Render("⚠ " + c)} } } return []string{stOK.Render("✓ trigger is free")} } func (e *keybindEditor) actionStatus() []string { name := keybind.ActionName(e.action.Value()) if name == "" || len(e.actions) == 0 { return nil } for _, a := range e.actions { if a.Name == name { return nil } } return []string{stChanged.Render("⚠ unknown action " + name)} } func (e *keybindEditor) View(width, height int) string { e.trigger.Width = max(10, width-14) e.action.Width = max(10, width-14) var lines []string if e.recording { lines = append(lines, stRecording.Render(" ● REC ")+" "+stBold.Render("Press the key combination now."), "", e.trigger.View(), "", stDim.Render("enter finish · esc cancel · backspace remove last key"), stDim.Render("Press several combinations in a row to record a sequence (ctrl+a>n)."), "", stDim.Render("Keys that Ghostty or macOS already use (e.g. a current Ghostty"), stDim.Render("shortcut) never reach this program: type those instead."), ) if !e.kittyReply { lines = append(lines, "", stChanged.Render("The terminal did not confirm the kitty keyboard protocol;"), stChanged.Render("super/cmd combinations may not be recorded.")) } return strings.Join(lines, "\n") } lines = append(lines, e.trigger.View()) lines = append(lines, e.triggerStatus()...) lines = append(lines, e.action.View()) lines = append(lines, e.actionStatus()...) lines = append(lines, "") if e.err != "" { lines = append(lines, stError.Render("✗ "+e.err), "") } if e.focus == 0 { lines = append(lines, stKey.Render("ctrl+r")+" record the keys instead of typing them", "", stDim.Render("Modifiers: ")+"super (cmd), ctrl, alt (opt), shift", stDim.Render("Keys: ")+"a, 1, ,, arrow_up, page_down, enter, f1, backquote, …", stDim.Render("Sequences: ")+"ctrl+a>n (press ctrl+a, then n)", stDim.Render("Prefixes: ")+"global:, all:, unconsumed:, performable:", ) return strings.Join(lines, "\n") } if len(e.actions) == 0 { lines = append(lines, stDim.Render("Action list unavailable (ghostty binary not found).")) return strings.Join(lines, "\n") } lines = append(lines, stDim.Render("Actions (tab to complete, add :param where needed):")) listH := min(8, max(3, height-len(lines)-6)) e.top = scrollWindow(e.cursor, e.top, listH, len(e.matches)) for i := e.top; i < len(e.matches) && i < e.top+listH; i++ { a := e.matches[i] segs := []seg{cursorSeg(i == e.cursor), plain(fit(a.Name, 30) + " "), styled(a.Summary, stDim)} lines = append(lines, renderRow(segs, width, i == e.cursor)) } if len(e.matches) == 0 { lines = append(lines, stDim.Render(" no matching action")) } if len(e.matches) > 0 { doc := e.matches[e.cursor].Doc if rest := height - len(lines) - 1; rest > 2 { lines = append(lines, "") docLines := strings.Split(renderDoc(doc, width), "\n") if len(docLines) > rest { docLines = docLines[:rest] } lines = append(lines, docLines...) } } return strings.Join(lines, "\n") } func (e *keybindEditor) Help() string { if e.recording { return "recording: press keys · enter finish · esc cancel" } return "ctrl+r record keys · tab next field / complete · ↑↓ choose action · enter save · esc cancel" }