initial commit [141.14.140.180,mike]

This commit is contained in:
mike committed 2026-10-22 13:21:28 +02:00
commit 156bb18c91
50 files changed
+13466

No files matched your search

+966
View File
@@ -0,0 +1,966 @@
// Package ui implements the terminal user interface.
package ui
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"ghosttyconf/internal/config"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
const (
catSet = "Set in Config"
catAll = "All Options"
)
type pane int
const (
paneCats pane = iota
paneOpts
)
// Messages delivering data loaded in the background.
type itemsMsg struct {
source string // "themes" or "fonts"
items []string
err error
}
type actionsMsg struct {
items []ghostty.Action
err error
}
// reloadMsg reports the result of asking Ghostty to reload its config.
type reloadMsg struct {
saved string // status text describing the save
err error
}
type undoEntry struct {
file *config.File
key string
}
type rect struct{ x, y, w, h int }
func (r rect) contains(x, y int) bool {
return x >= r.x && x < r.x+r.w && y >= r.y && y < r.y+r.h
}
// App is the Bubble Tea model of the editor.
type App struct {
sch *schema.Schema
gh *ghostty.Ghostty
file *config.File
saved *config.File
undo []undoEntry
rev int // incremented on every change to file
backup bool // a .bak copy was written this session
unknown map[string]*schema.Option
osName string
width, height int
focus pane
cats []string
catIdx int
catTop int
opts []*schema.Option
optIdx int
optTop int
search textinput.Model
searching bool
query string
hideForeign bool
doc viewport.Model
docFor string
editor editor
editOpt *schema.Option
dlg *dialog
status string
statusStyle lipgloss.Style
quitAfterSave bool
autoReload bool
// Screen regions from the last render, for mouse handling.
catRect, optRect, docRect rect
optListY int
themes []string
themesErr error
themesLoaded bool
fonts []string
fontsErr error
fontsLoaded bool
actions []ghostty.Action
actionsLoaded bool
themeCache map[string]*ghostty.Theme
}
// New creates the editor for file. gh may be nil when Ghostty is not
// installed; validation, themes, fonts and actions are then unavailable.
func New(sch *schema.Schema, gh *ghostty.Ghostty, file *config.File) *App {
a := &App{
sch: sch,
gh: gh,
file: file,
saved: file.Clone(),
unknown: map[string]*schema.Option{},
themeCache: map[string]*ghostty.Theme{},
doc: viewport.New(0, 0),
focus: paneOpts,
autoReload: true,
}
switch runtime.GOOS {
case "darwin":
a.osName = "macOS"
case "linux", "freebsd":
a.osName = "Linux"
}
a.search = textinput.New()
a.search.Prompt = "/ "
a.search.PromptStyle = stAccent
a.search.Placeholder = "search options and documentation"
a.search.PlaceholderStyle = stDim
a.cats = append([]string{catSet, catAll}, sch.Categories()...)
if len(file.Keys()) == 0 {
a.catIdx = 2 // nothing set yet: start with the first real category
}
a.rebuild()
if gh == nil {
a.setStatus("Running without the ghostty binary: built-in docs only; validation, themes, fonts and actions are unavailable.", stChanged)
}
return a
}
// SetAutoReload controls whether Ghostty is asked to reload its config
// after every save (on by default).
func (a *App) SetAutoReload(on bool) { a.autoReload = on }
func (a *App) Init() tea.Cmd {
if a.gh == nil {
return nil
}
gh := a.gh
return tea.Batch(
func() tea.Msg { t, err := gh.Themes(); return itemsMsg{"themes", t, err} },
func() tea.Msg { f, err := gh.Fonts(); return itemsMsg{"fonts", f, err} },
func() tea.Msg { ac, err := gh.Actions(); return actionsMsg{ac, err} },
)
}
func (a *App) setStatus(s string, st lipgloss.Style) {
a.status, a.statusStyle = s, st
}
func (a *App) dirty() bool { return !a.file.Equal(a.saved) }
// option returns the schema entry for key, synthesizing one for keys in the
// config file that Ghostty does not know.
func (a *App) option(key string) *schema.Option {
if o := a.sch.Lookup(key); o != nil {
return o
}
if o := a.unknown[key]; o != nil {
return o
}
o := &schema.Option{
Key: key,
Kind: schema.KindText,
Repeatable: len(a.file.GetAll(key)) > 1,
Category: catSet,
Doc: "This key is not a known Ghostty " + a.sch.GhosttyVersion + " option. " +
"It may be misspelled or belong to a different Ghostty version. " +
"Ghostty will report it as an error; press r to remove it.",
}
a.unknown[key] = o
return o
}
func (a *App) selected() *schema.Option {
if a.optIdx >= 0 && a.optIdx < len(a.opts) {
return a.opts[a.optIdx]
}
return nil
}
func (a *App) visible(o *schema.Option) bool {
return !a.hideForeign || o.Platform == "" || a.osName == "" || o.Platform == a.osName
}
// categoryOptions returns the options listed under a category.
func (a *App) categoryOptions(cat string) []*schema.Option {
var list []*schema.Option
switch cat {
case catSet:
for _, k := range a.file.Keys() {
list = append(list, a.option(k))
}
return list // always show everything that is set
case catAll:
list = append(list, a.sch.Options...)
sort.Slice(list, func(i, j int) bool { return list[i].Key < list[j].Key })
default:
list = a.sch.InCategory(cat)
}
var out []*schema.Option
for _, o := range list {
if a.visible(o) {
out = append(out, o)
}
}
return out
}
// searchOptions ranks options by how well they match the query: key
// matches first, then documentation matches.
func (a *App) searchOptions(q string) []*schema.Option {
terms := strings.Fields(strings.ToLower(q))
var byKey, byDoc []*schema.Option
for _, o := range a.sch.Options {
if !a.visible(o) {
continue
}
key, doc := o.Key, strings.ToLower(o.Doc)
inKey, inAny := true, true
for _, t := range terms {
if !strings.Contains(key, t) {
inKey = false
if !strings.Contains(doc, t) {
inAny = false
}
}
}
switch {
case inKey:
byKey = append(byKey, o)
case inAny:
byDoc = append(byDoc, o)
}
}
return append(byKey, byDoc...)
}
// rebuild recomputes the visible option list, keeping the selection.
func (a *App) rebuild() {
var keep string
if o := a.selected(); o != nil {
keep = o.Key
}
if a.query != "" {
a.opts = a.searchOptions(a.query)
} else {
a.opts = a.categoryOptions(a.cats[a.catIdx])
}
a.optIdx = min(a.optIdx, max(0, len(a.opts)-1))
for i, o := range a.opts {
if o.Key == keep {
a.optIdx = i
break
}
}
}
func (a *App) selectCategory(i int) {
if i == a.catIdx && a.query == "" {
return
}
a.catIdx = i
a.clearSearch()
a.optIdx, a.optTop = 0, 0
a.opts = nil
a.rebuild()
}
func (a *App) clearSearch() {
a.query = ""
a.searching = false
a.search.SetValue("")
a.search.Blur()
}
// ---------------------------------------------------------------------------
// Update
func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
a.width, a.height = msg.Width, msg.Height
return a, nil
case itemsMsg:
switch msg.source {
case "themes":
a.themes, a.themesErr, a.themesLoaded = msg.items, msg.err, true
case "fonts":
a.fonts, a.fontsErr, a.fontsLoaded = msg.items, msg.err, true
}
case actionsMsg:
a.actions, a.actionsLoaded = msg.items, true
case reloadMsg:
switch {
case msg.err == nil:
a.setStatus(msg.saved+" Ghostty reloaded the configuration.", stOK)
case errors.Is(msg.err, ghostty.ErrNotRunning):
a.setStatus(msg.saved+" Ghostty is not running; it will use the new config on its next start.", stOK)
default:
a.setStatus(msg.saved+" Automatic reload failed: "+msg.err.Error()+". Reload with "+reloadShortcut()+".", stChanged)
}
return a, nil
case tea.MouseMsg:
return a, a.handleMouse(msg)
case tea.KeyMsg:
if msg.String() == "ctrl+c" && !a.capturing() {
if a.dlg != nil && a.dlg.quit {
return a, tea.Quit
}
return a, a.quit()
}
if a.dlg != nil {
return a, a.dlg.update(a, msg)
}
if a.editor != nil {
return a, a.updateEditor(msg)
}
return a, a.updateBrowse(msg)
}
if a.editor != nil {
return a, a.updateEditor(msg)
}
return a, nil
}
// capturing reports whether the editor records raw key presses, in which
// case no key may be interpreted by the application.
func (a *App) capturing() bool {
c, ok := a.editor.(interface{ capturing() bool })
return ok && c.capturing()
}
func (a *App) updateEditor(msg tea.Msg) tea.Cmd {
if km, ok := msg.(tea.KeyMsg); ok && !a.capturing() {
switch km.String() {
case "shift+down":
a.doc.ScrollDown(3)
return nil
case "shift+up":
a.doc.ScrollUp(3)
return nil
}
}
cmd, res := a.editor.Update(msg)
if res != nil {
o := a.editOpt
a.editor, a.editOpt = nil, nil
a.apply(o, res)
}
return cmd
}
func (a *App) updateBrowse(km tea.KeyMsg) tea.Cmd {
key := km.String()
if a.searching {
switch key {
case "esc":
a.clearSearch()
a.rebuild()
case "enter", "down", "tab":
a.searching = false
a.search.Blur()
a.focus = paneOpts
default:
var cmd tea.Cmd
a.search, cmd = a.search.Update(km)
if v := a.search.Value(); v != a.query {
a.query = v
a.optIdx, a.optTop = 0, 0
a.rebuild()
}
return cmd
}
return nil
}
a.status = ""
switch key {
case "q":
return a.quit()
case "?", "f1":
a.dlg = helpDialog()
return nil
case "/", "ctrl+f":
// Every search starts fresh, like "/" in less or vim.
a.search.SetValue("")
if a.query != "" {
a.query = ""
a.rebuild()
}
a.searching = true
a.focus = paneOpts
return a.search.Focus()
case "ctrl+s":
return a.save(false, false)
case "u", "ctrl+z":
a.undoLast()
return nil
case "c":
a.dlg = a.changesDialog()
return nil
case "b":
if o := a.sch.Lookup("keybind"); o != nil {
return a.edit(o)
}
return nil
case "p":
a.hideForeign = !a.hideForeign
if a.hideForeign {
a.setStatus("Hiding options that do not apply to "+a.osName+".", stDim)
} else {
a.setStatus("Showing options for all platforms.", stDim)
}
a.rebuild()
return nil
case "tab":
if a.focus == paneCats {
a.focus = paneOpts
} else {
a.focus = paneCats
}
return nil
case "esc":
if a.query != "" {
a.clearSearch()
a.rebuild()
}
return nil
case "ctrl+d", "shift+down":
a.doc.ScrollDown(max(3, a.doc.Height/2))
return nil
case "ctrl+u", "shift+up":
a.doc.ScrollUp(max(3, a.doc.Height/2))
return nil
}
if a.focus == paneCats {
if c, moved := moveCursor(key, a.catIdx, len(a.cats), 5); moved {
a.selectCategory(c)
return nil
}
switch key {
case "right", "l", "enter":
a.focus = paneOpts
}
return nil
}
if c, moved := moveCursor(key, a.optIdx, len(a.opts), max(1, a.optRect.h-3)); moved {
a.optIdx = c
return nil
}
o := a.selected()
switch key {
case "left", "h":
a.focus = paneCats
case "enter", "e", "right", "l":
if o != nil {
if key == "right" || key == "l" {
// Only open editors that are not instant toggles.
if o.Kind == schema.KindBool && !o.Repeatable {
return nil
}
}
return a.edit(o)
}
case " ":
if o != nil {
a.quickToggle(o)
}
case "+", "=", "-", "_":
if o != nil && !o.Repeatable {
delta := 1
if key == "-" || key == "_" {
delta = -1
}
a.step(o, delta)
}
case "r", "delete", "backspace", "d":
if o != nil {
a.apply(o, &result{})
}
}
return nil
}
// edit opens the editor for o. Booleans are toggled directly.
func (a *App) edit(o *schema.Option) tea.Cmd {
if o.Kind == schema.KindBool && !o.Repeatable {
a.quickToggle(o)
return nil
}
values := a.file.GetAll(o.Key)
current, _ := a.file.Get(o.Key)
switch {
case o.Kind == schema.KindKeybind:
a.editor = newKeybindManager(o, values, a.actions, func(v string) editor {
return a.valueEditor(o, v)
})
case o.Kind == schema.KindPalette:
pe := newPaletteEditor(o, values)
if th := a.currentTheme(); th != nil {
pe.useTheme(th)
}
a.editor = pe
case o.Repeatable:
a.editor = newListEditor(o, values, func(v string) editor {
e := a.valueEditor(o, v)
if t, ok := e.(*textEditor); ok {
t.item = true
}
return e
})
default:
a.editor = a.valueEditor(o, current)
}
a.editOpt = o
a.docFor = "" // force docs to re-render for the editor layout
return nil
}
func (a *App) valueEditor(o *schema.Option, current string) editor {
switch o.Kind {
case schema.KindBool, schema.KindEnum, schema.KindChoice:
return newChoiceEditor(o, current)
case schema.KindFlags:
return newFlagsEditor(o, current)
case schema.KindTheme:
p := newPickerEditor(o, "themes", current)
p.preview = a.loadTheme
var overrides []string
for _, k := range []string{"background", "foreground", "cursor-color", "cursor-text", "selection-background", "selection-foreground", "palette"} {
if a.file.Has(k) {
overrides = append(overrides, k)
}
}
if len(overrides) > 0 {
p.note = "Your config also sets " + strings.Join(overrides, ", ") + ", which take precedence over the theme."
}
if a.themesLoaded {
p.setItems(a.themes, a.themesErr)
} else if a.gh == nil {
p.setItems(nil, fmt.Errorf("ghostty not found"))
}
return p
case schema.KindFont:
p := newPickerEditor(o, "fonts", current)
if a.fontsLoaded {
p.setItems(a.fonts, a.fontsErr)
} else if a.gh == nil {
p.setItems(nil, fmt.Errorf("ghostty not found"))
}
return p
case schema.KindKeybind:
return newKeybindEditor(current, a.actions)
default:
return newTextEditor(o, current)
}
}
func (a *App) loadTheme(name string) *ghostty.Theme {
if a.gh == nil {
return nil
}
if t, ok := a.themeCache[name]; ok {
return t
}
t, err := a.gh.LoadTheme(name)
if err != nil {
t = nil
}
a.themeCache[name] = t
return t
}
// currentTheme loads the theme set in the config (the dark variant for
// "light:A,dark:B"), or nil.
func (a *App) currentTheme() *ghostty.Theme {
v, ok := a.file.Get("theme")
if !ok {
return nil
}
v = schema.Unquote(v)
name := v
if strings.Contains(v, ":") && !strings.HasPrefix(v, "/") {
for _, part := range strings.Split(v, ",") {
mode, n, found := strings.Cut(strings.TrimSpace(part), ":")
if found && (mode == "dark" || name == v) {
name = strings.TrimSpace(n)
}
}
}
return a.loadTheme(name)
}
// quickToggle flips booleans and cycles through enum values in place.
func (a *App) quickToggle(o *schema.Option) {
if o.Repeatable {
return
}
cur, ok := a.file.Get(o.Key)
if !ok {
cur = o.Default()
}
cur = schema.Unquote(cur)
var values []string
switch o.Kind {
case schema.KindBool:
values = []string{"false", "true"}
if cur == "" {
cur = "false"
}
case schema.KindEnum:
values = o.Values
default:
a.setStatus("Space toggles booleans and cycles choices; press enter to edit "+o.Key+".", stDim)
return
}
next := values[0]
for i, v := range values {
if v == cur {
next = values[(i+1)%len(values)]
break
}
}
a.apply(o, valuesResult(next))
}
func (a *App) step(o *schema.Option, delta int) {
switch o.Kind {
case schema.KindInt, schema.KindFloat, schema.KindMetric:
default:
return
}
cur, _ := a.file.Get(o.Key)
v, ok := stepValue(o, cur, delta)
if !ok {
return
}
if err := o.Validate(v); err != nil {
a.setStatus(err.Error(), stError)
return
}
a.apply(o, valuesResult(v))
}
// apply writes an editor result into the in-memory config.
func (a *App) apply(o *schema.Option, res *result) {
if res == nil || res.cancel {
return
}
before := a.file.Clone()
switch {
case res.values == nil:
a.file.Unset(o.Key)
case o.Repeatable:
a.file.SetAll(o.Key, res.values)
default:
a.file.Set(o.Key, res.values[0])
}
if a.file.Equal(before) {
return
}
a.rev++
a.undo = append(a.undo, undoEntry{file: before, key: o.Key})
if len(a.undo) > 500 {
a.undo = a.undo[1:]
}
switch {
case res.values == nil:
a.setStatus("Reset "+o.Key+" to its default.", stChanged)
case o.Repeatable:
a.setStatus(fmt.Sprintf("Updated %s (%d entr%s).", o.Key, len(res.values), plural(len(res.values), "y", "ies")), stChanged)
default:
a.setStatus("Set "+o.Key+" = "+res.values[0], stChanged)
}
a.rebuild()
}
func (a *App) undoLast() {
if len(a.undo) == 0 {
a.setStatus("Nothing to undo.", stDim)
return
}
last := a.undo[len(a.undo)-1]
a.undo = a.undo[:len(a.undo)-1]
a.file = last.file
a.rev++
a.setStatus("Undid change to "+last.key+".", stChanged)
a.rebuild()
}
// ---------------------------------------------------------------------------
// Saving and quitting
func (a *App) save(skipDiskCheck, skipValidation bool) tea.Cmd {
if !a.dirty() {
a.setStatus("No changes to save.", stDim)
if a.quitAfterSave {
return tea.Quit
}
return nil
}
if !skipDiskCheck && a.file.ChangedOnDisk() {
a.dlg = &dialog{
title: "File changed on disk",
lines: []string{
"The config file was modified outside the editor since it was loaded:",
"",
a.file.Path,
"",
"Saving will overwrite those changes.",
},
keys: []dialogKey{{"o", "Overwrite"}, {"esc", "Cancel"}},
onKey: func(k string) tea.Cmd {
if k == "o" {
return a.save(true, skipValidation)
}
a.quitAfterSave = false
return nil
},
warn: true,
}
return nil
}
if !skipValidation && a.gh != nil {
if errs := a.validate(); len(errs) > 0 {
lines := []string{"Ghostty reported problems with the new configuration:", ""}
for _, e := range errs {
lines = append(lines, stError.Render("• ")+e)
}
lines = append(lines, "", "Ghostty ignores invalid lines and uses defaults instead.")
a.dlg = &dialog{
title: "Validation failed",
lines: lines,
keys: []dialogKey{{"s", "Save anyway"}, {"esc", "Back to editing"}},
onKey: func(k string) tea.Cmd {
if k == "s" {
return a.save(true, true)
}
a.quitAfterSave = false
return nil
},
warn: true,
}
return nil
}
}
makeBackup := !a.backup && a.file.Exists
if err := a.file.Save(makeBackup); err != nil {
a.setStatus("Save failed: "+err.Error(), stError)
a.quitAfterSave = false
return nil
}
a.backup = a.backup || makeBackup
a.saved = a.file.Clone()
msg := "Saved."
if makeBackup {
msg += " Backup: " + filepath.Base(a.file.Path) + ".bak."
}
if a.autoReload {
a.setStatus(msg+" Reloading Ghostty…", stOK)
reload := func() tea.Msg { return reloadMsg{saved: msg, err: ghostty.Reload()} }
if a.quitAfterSave {
return tea.Sequence(reload, tea.Quit)
}
return reload
}
a.setStatus(msg+" Reload Ghostty's config with "+reloadShortcut()+" to apply.", stOK)
if a.quitAfterSave {
return tea.Quit
}
return nil
}
// validate checks the pending config with `ghostty +validate-config`.
func (a *App) validate() []string {
tmp, err := a.file.WriteTemp()
if err != nil {
return []string{"could not write temporary file: " + err.Error()}
}
defer os.Remove(tmp)
errs, err := a.gh.Validate(tmp)
if err != nil {
return nil // validation unavailable; do not block saving
}
var out []string
for _, e := range errs {
out = append(out, e.String())
}
return out
}
func (a *App) quit() tea.Cmd {
if !a.dirty() {
return tea.Quit
}
n := len(a.changedKeys())
a.dlg = &dialog{
title: "Unsaved changes",
lines: []string{fmt.Sprintf("You have unsaved changes to %d option(s).", n)},
keys: []dialogKey{{"s", "Save and quit"}, {"d", "Discard and quit"}, {"esc", "Cancel"}},
onKey: func(k string) tea.Cmd {
switch k {
case "s":
a.quitAfterSave = true
return a.save(false, false)
case "d":
return tea.Quit
}
return nil
},
quit: true,
}
return nil
}
// changedKeys lists keys whose values differ from the saved file.
func (a *App) changedKeys() []string {
seen := map[string]bool{}
var keys []string
for _, k := range append(a.saved.Keys(), a.file.Keys()...) {
if seen[k] {
continue
}
seen[k] = true
if !equalStrings(a.saved.GetAll(k), a.file.GetAll(k)) {
keys = append(keys, k)
}
}
return keys
}
func (a *App) changesDialog() *dialog {
keys := a.changedKeys()
var lines []string
if len(keys) == 0 {
lines = append(lines, "No unsaved changes.")
}
for _, k := range keys {
lines = append(lines, stBold.Render(k))
for _, c := range config.Diff(a.saved.GetAll(k), a.file.GetAll(k)) {
if c.Removed {
lines = append(lines, stError.Render(" - "+config.FormatLine(k, c.Value)))
} else {
lines = append(lines, stOK.Render(" + "+config.FormatLine(k, c.Value)))
}
}
}
return &dialog{
title: fmt.Sprintf("Unsaved changes (%d)", len(keys)),
lines: lines,
keys: []dialogKey{{"esc", "Close"}},
}
}
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func reloadShortcut() string {
if runtime.GOOS == "darwin" {
return "⌘⇧,"
}
return "ctrl+shift+,"
}
func shortPath(p string) string {
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home+string(os.PathSeparator)) {
return "~" + p[len(home):]
}
return p
}
// ---------------------------------------------------------------------------
// Mouse
func (a *App) handleMouse(m tea.MouseMsg) tea.Cmd {
if a.dlg != nil || a.capturing() {
return nil
}
wheel := 0
switch m.Button {
case tea.MouseButtonWheelUp:
wheel = -1
case tea.MouseButtonWheelDown:
wheel = 1
}
if wheel != 0 {
switch {
case a.docRect.contains(m.X, m.Y):
if wheel > 0 {
a.doc.ScrollDown(3)
} else {
a.doc.ScrollUp(3)
}
case a.editor != nil:
if _, isText := a.editor.(*textEditor); isText {
return nil // up/down would change numeric values
}
key := tea.KeyMsg{Type: tea.KeyDown}
if wheel < 0 {
key = tea.KeyMsg{Type: tea.KeyUp}
}
return a.updateEditor(key)
case a.optRect.contains(m.X, m.Y):
a.optIdx = min(max(0, a.optIdx+wheel), max(0, len(a.opts)-1))
case a.catRect.contains(m.X, m.Y):
a.selectCategory(min(max(0, a.catIdx+wheel), len(a.cats)-1))
}
return nil
}
if a.editor != nil || m.Action != tea.MouseActionPress || m.Button != tea.MouseButtonLeft {
return nil
}
switch {
case a.catRect.contains(m.X, m.Y):
a.focus = paneCats
row := m.Y - a.catRect.y - 1 + a.catTop
if i := a.catRowIndex(row); i >= 0 {
a.selectCategory(i)
}
case a.optRect.contains(m.X, m.Y):
a.focus = paneOpts
i := m.Y - a.optListY + a.optTop
if m.Y >= a.optListY && i >= 0 && i < len(a.opts) {
if i == a.optIdx {
return a.edit(a.opts[i])
}
a.optIdx = i
}
}
return nil
}
+220
View File
@@ -0,0 +1,220 @@
package ui
import (
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/config"
"ghosttyconf/internal/schema"
)
func newTestApp(t *testing.T, content string) *App {
t.Helper()
sch, err := schema.Embedded()
if err != nil {
t.Fatal(err)
}
f := &config.File{Path: "/tmp/ghosttyconf-test/config.ghostty", Lines: config.Parse([]byte(content))}
a := New(sch, nil, f)
a.Update(tea.WindowSizeMsg{Width: 160, Height: 45})
return a
}
func press(a *App, keys ...string) {
for _, k := range keys {
var msg tea.KeyMsg
switch k {
case "enter":
msg = tea.KeyMsg{Type: tea.KeyEnter}
case "esc":
msg = tea.KeyMsg{Type: tea.KeyEsc}
case "down":
msg = tea.KeyMsg{Type: tea.KeyDown}
case "up":
msg = tea.KeyMsg{Type: tea.KeyUp}
case "tab":
msg = tea.KeyMsg{Type: tea.KeyTab}
case "shift+tab":
msg = tea.KeyMsg{Type: tea.KeyShiftTab}
case "space":
msg = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}}
default:
msg = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)}
}
a.Update(msg)
}
}
// TestEveryEditorRenders opens the editor of every option at several
// terminal sizes to catch panics and layout bugs.
func TestEveryEditorRenders(t *testing.T) {
a := newTestApp(t, "font-family = Hack\nkeybind = ctrl+a=new_tab\npalette = 1=#ff0000\n")
sizes := [][2]int{{160, 45}, {100, 30}, {60, 16}, {40, 12}}
for _, o := range a.sch.Options {
for _, sz := range sizes {
a.Update(tea.WindowSizeMsg{Width: sz[0], Height: sz[1]})
a.edit(o)
if a.editor == nil && o.Kind != schema.KindBool {
t.Fatalf("%s: no editor opened", o.Key)
}
_ = a.View()
press(a, "down", "down")
_ = a.View()
for i := 0; i < 3 && a.editor != nil; i++ {
press(a, "esc")
}
if a.editor != nil {
t.Fatalf("%s: editor did not close on esc", o.Key)
}
_ = a.View()
}
}
}
func TestEditEnumAndUndo(t *testing.T) {
a := newTestApp(t, "# keep me\ncursor-style = block\n")
press(a, "/")
for _, r := range "cursor-style" {
press(a, string(r))
}
press(a, "enter")
if o := a.selected(); o == nil || o.Key != "cursor-style" {
t.Fatalf("selected = %v", o)
}
press(a, "enter", "down", "enter") // block -> bar
if v, _ := a.file.Get("cursor-style"); v != "bar" {
t.Fatalf("cursor-style = %q", v)
}
if !a.dirty() {
t.Fatal("expected unsaved changes")
}
press(a, "u")
if v, _ := a.file.Get("cursor-style"); v != "block" {
t.Fatalf("after undo cursor-style = %q", v)
}
if a.dirty() {
t.Fatal("undo should restore the saved state")
}
if !strings.HasPrefix(string(a.file.Bytes()), "# keep me\n") {
t.Fatal("comment lost")
}
}
func TestToggleStepAndReset(t *testing.T) {
a := newTestApp(t, "font-size = 13\n")
a.selectCategory(0) // Set in Config
press(a, "+", "+")
if v, _ := a.file.Get("font-size"); v != "14" {
t.Fatalf("font-size = %q", v)
}
press(a, "r")
if a.file.Has("font-size") {
t.Fatal("font-size should have been removed")
}
}
func TestKeybindListAdd(t *testing.T) {
a := newTestApp(t, "")
a.edit(a.sch.Lookup("keybind"))
press(a, "a")
for _, r := range "ctrl+shift+t" {
press(a, string(r))
}
press(a, "tab")
for _, r := range "new_tab" {
press(a, string(r))
}
press(a, "enter", "esc")
if got := a.file.GetAll("keybind"); len(got) != 1 || got[0] != "ctrl+shift+t=new_tab" {
t.Fatalf("keybind = %v", got)
}
}
func TestKeybindManagerChangeDefault(t *testing.T) {
a := newTestApp(t, "")
o := a.sch.Lookup("keybind")
a.edit(o)
m, ok := a.editor.(*keybindManager)
if !ok {
t.Fatalf("editor is %T", a.editor)
}
// Find the built-in super+d binding and move it to super+shift+d.
press(a, "/")
for _, r := range "super+d" {
press(a, string(r))
}
press(a, "enter")
b := m.selected()
if b == nil || b.Trigger != "super+d" {
t.Fatalf("selected = %+v", b)
}
press(a, "enter") // change
press(a, "shift+tab") // trigger field
a.Update(tea.KeyMsg{Type: tea.KeyCtrlU}) // clear it
for _, r := range "super+shift+d" {
press(a, string(r))
}
press(a, "enter", "esc")
got := strings.Join(a.file.GetAll("keybind"), " | ")
if got != "super+d=unbind | super+shift+d="+b.Action {
t.Fatalf("keybind = %s", got)
}
}
func TestKeybindManagerUnbindRestore(t *testing.T) {
a := newTestApp(t, "")
a.edit(a.sch.Lookup("keybind"))
m := a.editor.(*keybindManager)
b := *m.selected()
press(a, "d")
if v := m.set.Values(); len(v) != 1 || !strings.HasSuffix(v[0], "=unbind") {
t.Fatalf("after unbind: %v", v)
}
press(a, "r")
if v := m.set.Values(); len(v) != 0 {
t.Fatalf("after restore: %v", v)
}
press(a, "esc")
if a.file.Has("keybind") {
t.Fatalf("no change expected, got %v (binding %s)", a.file.GetAll("keybind"), b.Trigger)
}
}
func TestKeybindRecording(t *testing.T) {
a := newTestApp(t, "")
a.edit(a.sch.Lookup("keybind"))
press(a, "a")
a.Update(tea.KeyMsg{Type: tea.KeyCtrlR})
if !a.capturing() {
t.Fatal("not recording")
}
// ctrl+c must be recorded, not quit the program.
_, cmd := a.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
if a.dlg != nil || cmd != nil && a.capturing() == false {
t.Fatal("ctrl+c was not captured")
}
press(a, "enter")
if a.capturing() {
t.Fatal("still recording")
}
for _, r := range "copy_to_clipboard" {
press(a, string(r))
}
press(a, "enter", "esc")
if got := a.file.GetAll("keybind"); len(got) != 1 || got[0] != "ctrl+c=copy_to_clipboard" {
t.Fatalf("keybind = %v", got)
}
}
func TestUnknownKeyIsListed(t *testing.T) {
a := newTestApp(t, "bogus-key = 1\n")
a.selectCategory(0)
if len(a.opts) != 1 || a.opts[0].Key != "bogus-key" {
t.Fatalf("opts = %v", a.opts)
}
if !strings.Contains(a.View(), "bogus-key") {
t.Fatal("unknown key not rendered")
}
}
+154
View File
@@ -0,0 +1,154 @@
package ui
import (
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
type dialogKey struct{ key, label string }
// dialog is a modal box drawn over the main view.
type dialog struct {
title string
lines []string
keys []dialogKey
onKey func(key string) tea.Cmd
scroll int
warn bool
quit bool // the unsaved-changes prompt: a second ctrl+c quits
height int // visible body lines in the last render
}
func (d *dialog) update(a *App, km tea.KeyMsg) tea.Cmd {
key := km.String()
switch key {
case "up", "k":
d.scroll = max(0, d.scroll-1)
return nil
case "down", "j":
d.scroll = min(d.scroll+1, max(0, len(d.lines)-d.height))
return nil
case "pgup":
d.scroll = max(0, d.scroll-d.height)
return nil
case "pgdown", " ":
d.scroll = min(d.scroll+d.height, max(0, len(d.lines)-d.height))
return nil
}
for _, k := range d.keys {
if k.key == key {
a.dlg = nil
if d.onKey != nil {
return d.onKey(key)
}
return nil
}
}
if key == "esc" || key == "q" || key == "enter" {
a.dlg = nil
if d.onKey != nil {
return d.onKey("esc")
}
}
return nil
}
func (d *dialog) view(width, height int) string {
var keys []string
for _, k := range d.keys {
keys = append(keys, stKey.Render(k.key)+" "+k.label)
}
hint := strings.Join(keys, " ")
// Size the box to its content, within the screen.
want := max(40, ansi.StringWidth(hint)+18, ansi.StringWidth(d.title)+8)
for _, l := range d.lines {
want = max(want, ansi.StringWidth(l)+4)
}
w := min(width-4, 84, want)
inner := w - 4
var body []string
for _, l := range d.lines {
if l == "" {
body = append(body, "")
continue
}
body = append(body, strings.Split(ansi.Wrap(l, inner, ""), "\n")...)
}
maxBody := max(3, height-8)
d.height = min(len(body), maxBody)
d.scroll = min(d.scroll, max(0, len(body)-d.height))
visible := body[d.scroll : d.scroll+d.height]
if len(body) > d.height {
hint += stDim.Render(" ↑↓ scroll")
}
lines := []string{""}
for _, l := range visible {
lines = append(lines, " "+l)
}
lines = append(lines, "", " "+hint)
content := strings.Join(lines, "\n")
color := colAccent
if d.warn {
color = colChanged
}
return framed(d.title, content, w, len(lines)+2, color)
}
func helpDialog() *dialog {
k := func(key, desc string) string { return stKey.Render(fit(key, 16)) + desc }
return &dialog{
title: "Help",
lines: []string{
stBold.Render("Browsing"),
k("↑↓ / j k", "move"),
k("← → / tab", "switch between categories and options"),
k("enter", "edit the selected option (booleans toggle)"),
k("space", "toggle a boolean / cycle through choices"),
k("+ / -", "increase / decrease numbers"),
k("r / del", "reset to the default (removes the line from the file)"),
k("/", "search option names and documentation"),
k("b", "open the key binding editor"),
k("shift+↑↓", "scroll the documentation (also ctrl+u / ctrl+d)"),
k("p", "hide options for other platforms"),
k("u / ctrl+z", "undo the last change"),
k("c", "show unsaved changes"),
k("ctrl+s", "validate with Ghostty, save and reload Ghostty's config"),
k("q / ctrl+c", "quit"),
"",
stBold.Render("Editors"),
k("enter", "apply the value"),
k("esc", "cancel (in list editors: done)"),
k("↑↓", "choose; in number fields: increase / decrease"),
k("tab", "complete the highlighted theme, font or action"),
"",
stBold.Render("Key bindings") + stDim.Render(" (b, or enter on keybind)"),
k("enter", "change the selected binding (also built-in ones)"),
k("a", "add a binding"),
k("d", "unbind: the key no longer does anything in Ghostty"),
k("r", "restore Ghostty's default for this key"),
k("ctrl+r", "in the binding form: record the key combination"),
k("/ c s", "filter · show changes only · sort by action or key"),
k("R", "edit the raw keybind entries"),
"",
stBold.Render("List editors") + stDim.Render(" (font-family, env, config-file, …)"),
k("a", "add an entry"),
k("enter / e", "edit the entry; on a built-in default: copy it"),
k("r", "edit the entry as raw text"),
k("d", "delete the entry"),
k("J / K", "move the entry down / up"),
k("v", "show or hide Ghostty's built-in defaults"),
"",
stBold.Render("Markers"),
stSet.Render("●") + " set in your config " + stChanged.Render("●") + " changed, not saved " + stChanged.Render("○") + " removed, not saved",
"",
"Comments, blank lines and the order of untouched lines in your config file are kept. " +
"Before the first save a backup is written to <config>.bak.",
},
keys: []dialogKey{{"esc", "Close"}},
}
}
+117
View File
@@ -0,0 +1,117 @@
package ui
import (
"strings"
"github.com/charmbracelet/x/ansi"
)
// renderDoc reflows Ghostty's option documentation (lightly formatted
// Markdown) to width: paragraphs are re-wrapped, list items get a hanging
// indent, indented code examples are kept verbatim and `code` spans are
// highlighted.
func renderDoc(doc string, width int) string {
if width < 10 {
width = 10
}
var out []string
var para []string
prefix, hang := "", ""
flush := func() {
if len(para) == 0 {
return
}
text := strings.Join(para, " ")
wrapped := strings.Split(ansi.Wrap(text, width-ansi.StringWidth(prefix), ""), "\n")
inCode := false
for i, l := range wrapped {
p := hang
if i == 0 {
p = prefix
}
var styled string
styled, inCode = styleInline(l, inCode)
out = append(out, p+styled)
}
para, prefix, hang = nil, "", ""
}
inBullet := false
bulletIndent := 0
for _, line := range strings.Split(doc, "\n") {
trimmed := strings.TrimSpace(line)
indent := len(line) - len(strings.TrimLeft(line, " "))
switch {
case trimmed == "":
flush()
inBullet = false
out = append(out, "")
case isBullet(trimmed):
flush()
inBullet = true
bulletIndent = indent + 2
lead := strings.Repeat(" ", min(indent, 4))
prefix = lead + "• "
hang = lead + " "
para = append(para, strings.TrimSpace(trimmed[2:]))
case inBullet && indent >= bulletIndent:
para = append(para, trimmed)
case indent >= 4 || strings.HasPrefix(line, "\t"):
flush()
inBullet = false
out = append(out, stCode.Render(ansi.Truncate(" "+trimmed, width, "…")))
default:
if inBullet {
flush()
inBullet = false
}
para = append(para, trimmed)
}
}
flush()
// Collapse repeated blank lines.
var res []string
for i, l := range out {
if l == "" && (i == 0 || out[i-1] == "") {
continue
}
res = append(res, l)
}
return strings.TrimRight(strings.Join(res, "\n"), "\n")
}
func isBullet(s string) bool {
return strings.HasPrefix(s, "* ") || strings.HasPrefix(s, "- ")
}
// styleInline highlights `code` spans. inCode carries an open span across
// wrapped lines.
func styleInline(line string, inCode bool) (string, bool) {
if !strings.Contains(line, "`") && !inCode {
return line, false
}
var b, seg strings.Builder
emit := func() {
if seg.Len() == 0 {
return
}
if inCode {
b.WriteString(stCode.Render(seg.String()))
} else {
b.WriteString(seg.String())
}
seg.Reset()
}
for _, r := range line {
if r == '`' {
emit()
inCode = !inCode
continue
}
seg.WriteRune(r)
}
emit()
return b.String(), inCode
}
+435
View File
@@ -0,0 +1,435 @@
package ui
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/cursor"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"ghosttyconf/internal/schema"
)
// result is what an editor produces when it closes.
type result struct {
cancel bool
// values are the new raw values. nil (without cancel) removes the
// option from the config file, restoring the default.
values []string
}
func cancelled() *result { return &result{cancel: true} }
func valuesResult(v ...string) *result { return &result{values: v} }
// editor edits the value of one option (or one entry of a list option).
type editor interface {
Update(msg tea.Msg) (tea.Cmd, *result)
View(width, height int) string
Help() string
}
func newInput(value, placeholder string) textinput.Model {
ti := textinput.New()
ti.Prompt = "› "
ti.PromptStyle = stAccent
ti.Placeholder = placeholder
ti.PlaceholderStyle = stDim
ti.Cursor.SetMode(cursor.CursorStatic)
ti.SetValue(value)
ti.CursorEnd()
ti.Focus()
return ti
}
// scrollWindow returns the first visible row so that cursor stays visible.
func scrollWindow(cursor, top, height, n int) int {
if height <= 0 {
return 0
}
if cursor < top {
top = cursor
}
if cursor >= top+height {
top = cursor - height + 1
}
if top > n-height {
top = max(0, n-height)
}
return max(0, top)
}
// moveCursor applies common list navigation keys.
func moveCursor(key string, cursor, n, page int) (int, bool) {
if n == 0 {
return 0, false
}
switch key {
case "up", "k", "ctrl+p":
cursor--
case "down", "j", "ctrl+n":
cursor++
case "pgup":
cursor -= page
case "pgdown":
cursor += page
case "home", "g":
cursor = 0
case "end", "G":
cursor = n - 1
default:
return cursor, false
}
return min(max(cursor, 0), n-1), true
}
// ---------------------------------------------------------------------------
// Choice editor: booleans, enums and enums with a custom value.
type choiceItem struct {
value string
label string
custom bool
}
type choiceEditor struct {
opt *schema.Option
items []choiceItem
cursor int
top int
height int
current string
text *textEditor // active while typing a custom value
}
func newChoiceEditor(o *schema.Option, current string) *choiceEditor {
e := &choiceEditor{opt: o, current: schema.Unquote(current)}
values := o.Values
if o.Kind == schema.KindBool {
values = []string{"true", "false"}
}
for _, v := range values {
e.items = append(e.items, choiceItem{value: v, label: v})
}
if o.Kind == schema.KindChoice {
label := "Custom value…"
if e.current != "" && !contains(values, e.current) {
label = "Custom value: " + e.current
}
e.items = append(e.items, choiceItem{label: label, custom: true})
}
e.cursor = 0
effective := e.current
if effective == "" {
effective = o.Default()
}
for i, it := range e.items {
if it.value == effective || (it.custom && effective != "" && !contains(values, effective)) {
e.cursor = i
break
}
}
return e
}
func (e *choiceEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.text != nil {
cmd, res := e.text.Update(msg)
if res != nil {
e.text = nil
if res.cancel {
return nil, nil
}
return nil, res
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, len(e.items), max(1, e.height-1)); moved {
e.cursor = c
return nil, nil
}
switch key {
case "esc", "q":
return nil, cancelled()
case "enter", " ":
it := e.items[e.cursor]
if it.custom {
v := ""
if !contains(e.opt.Values, e.current) {
v = e.current
}
e.text = newTextEditor(e.opt, v)
return nil, nil
}
return nil, valuesResult(it.value)
}
return nil, nil
}
func (e *choiceEditor) View(width, height int) string {
if e.text != nil {
return e.text.View(width, height)
}
e.height = height
e.top = scrollWindow(e.cursor, e.top, height, len(e.items))
var lines []string
def := e.opt.Default()
for i := e.top; i < len(e.items) && len(lines) < height; i++ {
it := e.items[i]
sel := i == e.cursor
labelSt := lipgloss.NewStyle()
if sel {
labelSt = stBold
}
segs := []seg{cursorSeg(sel), styled(fit(it.label, 28), labelSt), plain(" ")}
if !it.custom && it.value == e.current {
segs = append(segs, styled("● current ", stSet))
}
if !it.custom && it.value == def {
segs = append(segs, styled("default", stDim))
}
lines = append(lines, renderRow(segs, width, sel))
}
return strings.Join(lines, "\n")
}
func (e *choiceEditor) Help() string {
if e.text != nil {
return e.text.Help()
}
return "↑↓ choose · enter select · esc cancel"
}
// ---------------------------------------------------------------------------
// Flags editor: packed structs such as shell-integration-features.
type flagsEditor struct {
opt *schema.Option
state map[string]bool
def map[string]bool
cursor int
}
func newFlagsEditor(o *schema.Option, current string) *flagsEditor {
return &flagsEditor{opt: o, state: o.ParseFlags(current), def: o.ParseFlags("")}
}
func (e *flagsEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, len(e.opt.Flags), 5); moved {
e.cursor = c
return nil, nil
}
switch key {
case "esc", "q":
return nil, cancelled()
case " ", "x":
f := e.opt.Flags[e.cursor]
e.state[f] = !e.state[f]
case "a":
for _, f := range e.opt.Flags {
e.state[f] = true
}
case "n":
for _, f := range e.opt.Flags {
e.state[f] = false
}
case "d":
for _, f := range e.opt.Flags {
e.state[f] = e.def[f]
}
case "enter":
return nil, valuesResult(e.opt.FormatFlags(e.state))
}
return nil, nil
}
func (e *flagsEditor) View(width, height int) string {
var lines []string
for i, f := range e.opt.Flags {
box := styled("[ ]", stDim)
if e.state[f] {
box = styled("[✓]", stSet)
}
segs := []seg{cursorSeg(i == e.cursor), box, plain(" " + fit(f, 22) + " ")}
if e.state[f] != e.def[f] {
segs = append(segs, styled("changed from default", stChanged))
}
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
lines = append(lines, "", stDim.Render("Result: ")+stCode.Render(e.opt.FormatFlags(e.state)))
return strings.Join(lines, "\n")
}
func (e *flagsEditor) Help() string {
return "↑↓ move · space toggle · a all · n none · d defaults · enter apply · esc cancel"
}
// ---------------------------------------------------------------------------
// Text editor with validation, used for numbers, colors, durations, paths
// and free text.
type textEditor struct {
opt *schema.Option
input textinput.Model
err string
// item is set when editing one entry of a list option: an empty value
// then means "remove this entry" rather than "reset to default".
item bool
}
func newTextEditor(o *schema.Option, value string) *textEditor {
placeholder := o.Default()
if placeholder == "" {
placeholder = o.Hint
}
return &textEditor{opt: o, input: newInput(value, placeholder)}
}
func (e *textEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if km, ok := msg.(tea.KeyMsg); ok {
switch km.String() {
case "esc":
return nil, cancelled()
case "enter":
v := strings.TrimSpace(e.input.Value())
if v == "" {
return nil, &result{}
}
if err := e.opt.Validate(v); err != nil {
e.err = err.Error()
return nil, nil
}
return nil, valuesResult(v)
case "up", "down":
if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric {
delta := 1
if km.String() == "down" {
delta = -1
}
if v, ok := stepValue(e.opt, e.input.Value(), delta); ok {
e.input.SetValue(v)
e.input.CursorEnd()
}
return nil, nil
}
}
}
var cmd tea.Cmd
e.input, cmd = e.input.Update(msg)
e.err = ""
return cmd, nil
}
func (e *textEditor) View(width, height int) string {
e.input.Width = max(10, width-4)
var lines []string
lines = append(lines, e.input.View(), "")
v := strings.TrimSpace(e.input.Value())
switch {
case e.err != "":
lines = append(lines, stError.Render("✗ "+e.err))
case v == "" && e.item:
lines = append(lines, stDim.Render("Empty: the entry will be removed."))
case v == "":
lines = append(lines, stDim.Render("Empty: the option will be reset to its default."))
default:
if err := e.opt.Validate(v); err != nil {
lines = append(lines, stError.Render("✗ "+err.Error()))
} else {
lines = append(lines, stOK.Render("✓ valid"))
}
}
if e.opt.Kind == schema.KindColor || e.opt.Kind == schema.KindPalette || e.opt.Kind == schema.KindColorList {
var sw []string
for _, part := range strings.Split(v, ",") {
if s := swatch(part); s != "" {
sw = append(sw, s+s+s)
}
}
if len(sw) > 0 {
lines = append(lines, "", strings.Join(sw, " ")+" "+stDim.Render("preview"))
}
}
if e.opt.Hint != "" {
lines = append(lines, "", stDim.Render("Format: ")+e.opt.Hint)
}
if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric {
lines = append(lines, "", stDim.Render("Use ↑/↓ to increase or decrease the value."))
}
return strings.Join(lines, "\n")
}
func (e *textEditor) Help() string {
return "type to edit · enter apply · esc cancel"
}
// stepValue increments or decrements numeric values, keeping a percentage
// suffix for metric modifiers.
func stepValue(o *schema.Option, value string, delta int) (string, bool) {
v := strings.TrimSpace(schema.Unquote(value))
if v == "" {
v = o.Default()
}
pct := strings.HasSuffix(v, "%")
v = strings.TrimSuffix(v, "%")
if v == "" {
v = "0"
}
var f float64
if _, err := fmt.Sscanf(v, "%g", &f); err != nil {
return "", false
}
step := 1.0
if o.Kind == schema.KindFloat {
switch {
case o.Max != nil && *o.Max <= 1:
step = 0.05
case f < 1 && f > -1 && o.Key != "font-size":
step = 0.1
case o.Key == "font-size":
step = 0.5
}
}
f += float64(delta) * step
if o.Min != nil && f < *o.Min {
f = *o.Min
}
if o.Max != nil && f > *o.Max {
f = *o.Max
}
var s string
if o.Kind == schema.KindFloat {
s = strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), ".")
if s == "" || s == "-" {
s = "0"
}
} else {
s = fmt.Sprintf("%d", int64(f))
}
if pct {
s += "%"
}
return s, true
}
func contains(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}
+342
View File
@@ -0,0 +1,342 @@
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"
}
+472
View File
@@ -0,0 +1,472 @@
package ui
import (
"fmt"
"sort"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/keybind"
"ghosttyconf/internal/schema"
)
// keybindManager shows the effective key bindings — Ghostty's defaults
// merged with the user's keybind entries — and lets the user change,
// unbind, restore and add bindings. Edits are translated into the minimal
// set of keybind entries.
type keybindManager struct {
opt *schema.Option
set *keybind.Set
original []string
defaults []string
actions []ghostty.Action
summaries map[string]string
rows []keybind.Binding
cursor int
top int
height int
filter textinput.Model
filtering bool
changesOnly bool
byTrigger bool
msg string
msgStyle lipgloss.Style
child editor
childFor *keybind.Binding // binding being edited; nil when adding
childRaw bool // child is the raw entry list
newItem func(string) editor
}
func newKeybindManager(o *schema.Option, values []string, actions []ghostty.Action, newItem func(string) editor) *keybindManager {
m := &keybindManager{
opt: o,
original: append([]string(nil), values...),
defaults: o.DefaultList(),
actions: actions,
summaries: map[string]string{},
newItem: newItem,
filter: newInput("", "filter by key, action or description"),
}
m.filter.Prompt = "/ "
m.filter.Blur()
for _, a := range actions {
m.summaries[a.Name] = a.Summary
}
m.set = keybind.NewSet(m.defaults, values)
m.refresh("")
return m
}
func (m *keybindManager) capturing() bool {
c, ok := m.child.(interface{ capturing() bool })
return ok && c.capturing()
}
// refresh recomputes the visible rows and keeps the cursor on norm (or on
// the current row when norm is empty).
func (m *keybindManager) refresh(norm string) {
if norm == "" && m.cursor < len(m.rows) {
norm = m.rows[m.cursor].Norm
}
query := strings.TrimSpace(m.filter.Value())
terms := strings.Fields(strings.ToLower(query))
// A query that is a valid trigger ("cmd+d") also finds that exact
// binding, whatever spelling it uses.
exact, err := keybind.Normalize(query)
if err != nil || query == "" {
exact = ""
}
var rows []keybind.Binding
for _, b := range m.set.Bindings() {
if m.changesOnly && b.Source == keybind.Default && !b.InConfig {
continue
}
if exact != "" && b.Norm == exact {
rows = append(rows, b)
continue
}
hay := strings.ToLower(b.Trigger + " " + b.Action + " " + b.Source.String() + " " + m.summaries[keybind.ActionName(b.Action)])
ok := true
for _, t := range terms {
if !strings.Contains(hay, t) {
ok = false
break
}
}
if ok {
rows = append(rows, b)
}
}
sort.SliceStable(rows, func(i, j int) bool {
a, b := rows[i], rows[j]
if (a.Norm == exact) != (b.Norm == exact) {
return a.Norm == exact
}
if m.byTrigger {
return a.Norm < b.Norm
}
if a.Action != b.Action {
return a.Action < b.Action
}
return a.Norm < b.Norm
})
m.rows = rows
m.cursor = min(m.cursor, max(0, len(rows)-1))
for i, b := range rows {
if b.Norm == norm {
m.cursor = i
break
}
}
}
func (m *keybindManager) selected() *keybind.Binding {
if m.cursor < len(m.rows) {
b := m.rows[m.cursor]
return &b
}
return nil
}
func (m *keybindManager) changed() bool {
return !equalStrings(m.set.Values(), m.original)
}
func (m *keybindManager) setMsg(s string, st lipgloss.Style) { m.msg, m.msgStyle = s, st }
func (m *keybindManager) openEditor(b *keybind.Binding) {
value := ""
if b != nil {
value = b.Trigger + "=" + b.Action
}
e := newKeybindEditor(value, m.actions)
if b == nil {
e.setFocus(0)
}
e.conflict = func(trigger string) string {
n, err := keybind.Normalize(trigger)
if err != nil || (b != nil && n == b.Norm) {
return ""
}
if cur, ok := m.set.Lookup(n); ok {
return fmt.Sprintf("already bound to %s (%s); saving replaces that binding", cur.Action, cur.Source)
}
return ""
}
m.child, m.childFor, m.childRaw = e, b, false
}
func (m *keybindManager) Update(msg tea.Msg) (tea.Cmd, *result) {
if m.child != nil {
cmd, res := m.child.Update(msg)
if res != nil {
m.finishChild(res)
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if m.filtering {
switch key {
case "esc":
m.filter.SetValue("")
m.filtering = false
m.filter.Blur()
m.refresh("")
case "enter", "down", "tab":
m.filtering = false
m.filter.Blur()
default:
var cmd tea.Cmd
before := m.filter.Value()
m.filter, cmd = m.filter.Update(km)
if m.filter.Value() != before {
m.cursor, m.top = 0, 0
m.refresh("")
}
return cmd, nil
}
return nil, nil
}
if c, moved := moveCursor(key, m.cursor, len(m.rows), max(1, m.height-1)); moved {
m.cursor = c
return nil, nil
}
m.msg = ""
b := m.selected()
switch key {
case "esc", "q":
if m.filter.Value() != "" && key == "esc" {
m.filter.SetValue("")
m.refresh("")
return nil, nil
}
if !m.changed() {
return nil, cancelled()
}
v := m.set.Values()
if len(v) == 0 {
return nil, &result{}
}
return nil, valuesResult(v...)
case "/":
m.filtering = true
return m.filter.Focus(), nil
case "enter", "e":
if b != nil {
m.openEditor(b)
}
case "a", "n", "+", "insert":
m.openEditor(nil)
case "d", "x", "delete", "backspace":
if b == nil {
break
}
if b.Source == keybind.Unbound {
m.setMsg(b.Trigger+" is already unbound. Press r to restore it.", stDim)
break
}
m.set.Unbind(*b)
m.setMsg("Unbound "+b.Trigger+".", stChanged)
m.refresh(b.Norm)
case "r":
if b == nil {
break
}
m.set.Restore(*b)
if b.Default != "" {
m.setMsg("Restored "+b.Trigger+" → "+b.Default+".", stChanged)
} else {
m.setMsg("Removed "+b.Trigger+" (it has no default binding).", stChanged)
}
m.refresh(b.Norm)
case "c":
m.changesOnly = !m.changesOnly
m.refresh("")
case "s":
m.byTrigger = !m.byTrigger
m.refresh("")
case "R":
le := newListEditor(m.opt, m.set.Values(), m.newItem)
m.child, m.childFor, m.childRaw = le, nil, true
}
return nil, nil
}
func (m *keybindManager) finishChild(res *result) {
defer func() { m.child, m.childFor, m.childRaw = nil, nil, false }()
if res.cancel {
return
}
if m.childRaw {
m.set = keybind.NewSet(m.defaults, res.values)
m.refresh("")
m.setMsg("Updated the raw keybind entries.", stChanged)
return
}
if len(res.values) == 0 {
return
}
v := res.values[0]
if v == "clear" {
m.set = keybind.NewSet(m.defaults, append(m.set.Values(), "clear"))
m.refresh("")
m.setMsg("Added keybind = clear: all built-in bindings are removed.", stChanged)
return
}
if err := m.set.Change(m.childFor, v); err != nil {
m.setMsg("Not changed: "+err.Error(), stError)
return
}
trigger, action := keybind.Split(v)
norm := keybind.NormalizeLoose(trigger)
if m.changesOnly || m.filter.Value() != "" {
// Make sure the edited binding stays visible.
m.changesOnly = false
m.filter.SetValue("")
}
m.refresh(norm)
m.setMsg("Bound "+trigger+" → "+action+".", stChanged)
}
func (m *keybindManager) View(width, height int) string {
if m.child != nil {
title := "New binding"
switch {
case m.childRaw:
title = "Raw keybind entries"
case m.childFor != nil:
title = "Change " + m.childFor.Trigger
if m.childFor.Source == keybind.Default {
title += stDim.Render(" (built-in binding)")
}
}
return stBold.Render(title) + "\n\n" + m.child.View(width, height-2)
}
var lines []string
counts := map[keybind.Source]int{}
for _, b := range m.set.Bindings() {
counts[b.Source]++
}
summary := fmt.Sprintf("%d active · %s · %s · %s",
counts[keybind.Default]+counts[keybind.Changed]+counts[keybind.Custom],
stChanged.Render(fmt.Sprintf("%d changed", counts[keybind.Changed])),
stSet.Render(fmt.Sprintf("%d custom", counts[keybind.Custom])),
stError.Render(fmt.Sprintf("%d unbound", counts[keybind.Unbound])))
view := "all"
if m.changesOnly {
view = "changes only"
}
sortBy := "action"
if m.byTrigger {
sortBy = "key"
}
lines = append(lines, summary+stDim.Render(fmt.Sprintf(" showing %s, sorted by %s", view, sortBy)))
if m.set.HasClear() {
lines = append(lines, stChanged.Render("Your config contains keybind = clear: built-in bindings before it are removed."))
}
if m.filtering || m.filter.Value() != "" {
m.filter.Width = max(10, width-4)
lines = append(lines, m.filter.View())
}
lines = append(lines, "")
trigW := 12
for _, b := range m.rows {
trigW = max(trigW, ansi.StringWidth(b.Trigger))
}
trigW = min(trigW+2, width*40/100)
srcW := 9
actW := max(10, width-trigW-srcW-3)
lines = append(lines, stDim.Render(" "+fit("Key", trigW)+fit("Action", actW)+" Source"))
detailH := 3
listH := max(3, height-len(lines)-detailH-1)
m.height = listH
m.top = scrollWindow(m.cursor, m.top, listH, len(m.rows))
if len(m.rows) == 0 {
lines = append(lines, stDim.Render(" No bindings match."))
}
for i := m.top; i < len(m.rows) && i < m.top+listH; i++ {
lines = append(lines, renderRow(m.rowSegs(m.rows[i], i == m.cursor, trigW, actW), width, i == m.cursor))
}
for len(lines) < height-detailH {
lines = append(lines, "")
}
lines = append(lines, m.detail(width)...)
return strings.Join(lines, "\n")
}
func (m *keybindManager) rowSegs(b keybind.Binding, selected bool, trigW, actW int) []seg {
action := b.Action
if len(b.Chain) > 0 {
action += " + " + strings.Join(b.Chain, " + ")
}
actSt := lipgloss.NewStyle()
var src seg
switch b.Source {
case keybind.Default:
src = styled("default", stDim)
actSt = stDim
if b.InConfig {
actSt = lipgloss.NewStyle()
}
case keybind.Changed:
src = styled("changed", stChanged)
case keybind.Custom:
src = styled("custom", stSet)
case keybind.Unbound:
src = styled("unbound", stError)
actSt = stDim.Strikethrough(true)
}
return []seg{
cursorSeg(selected),
styled(fit(b.Trigger, trigW), stKey),
styled(fit(action, actW), actSt),
plain(" "),
src,
}
}
func (m *keybindManager) detail(width int) []string {
b := m.selected()
var lines []string
if m.msg != "" {
lines = append(lines, m.msgStyle.Render(ansi.Truncate(m.msg, width, "…")))
} else {
lines = append(lines, "")
}
if b == nil {
return append(lines, "", "")
}
var info string
switch b.Source {
case keybind.Default:
info = "Ghostty's built-in binding."
case keybind.Changed:
info = "Changed in your config. Ghostty's default: " + b.Default + " (press r to restore)."
case keybind.Custom:
info = "Added in your config."
case keybind.Unbound:
info = "Removed in your config. Press r to restore " + b.Default + "."
}
sum := m.summaries[keybind.ActionName(b.Action)]
lines = append(lines,
stDim.Render(ansi.Truncate(info, width, "…")),
ansi.Truncate(stKey.Render(keybind.ActionName(b.Action))+" "+sum, width, "…"))
return lines
}
// docFor shows the documentation of the selected binding's action and all
// keys bound to it.
func (m *keybindManager) docFor() (id, title, body string, ok bool) {
b := m.selected()
if m.child != nil || b == nil {
return "", "", "", false
}
name := keybind.ActionName(b.Action)
var doc string
for _, a := range m.actions {
if a.Name == name {
doc = a.Doc
break
}
}
if doc == "" {
doc = "No documentation available for this action."
}
var keys []string
for _, other := range m.set.Bindings() {
if keybind.ActionName(other.Action) == name && other.Source != keybind.Unbound {
keys = append(keys, "* `"+other.Trigger+"` → `"+other.Action+"` ("+other.Source.String()+")")
}
}
body = doc
if len(keys) > 0 {
body += "\n\nKeys bound to " + name + ":\n\n" + strings.Join(keys, "\n")
}
return fmt.Sprintf("action:%s#%d", name, len(m.set.Values())) + strings.Join(m.set.Values(), "\x00"), name, body, true
}
func (m *keybindManager) Help() string {
if m.child != nil {
return m.child.Help()
}
if m.filtering {
return "type to filter · enter/↓ results · esc clear"
}
return "enter change · a add · d unbind · r restore · / filter · c changes only · s sort · R raw · esc done"
}
+243
View File
@@ -0,0 +1,243 @@
package ui
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/schema"
)
// listEditor edits repeatable options (font-family, keybind, env, …). The
// entries from the config file can be added, edited, removed and
// reordered; Ghostty's built-in default entries are shown read-only and can
// be copied as a starting point.
type listEditor struct {
opt *schema.Option
items []string
defaults []string
showDefaults bool
cursor int
top int
height int
changed bool
child editor
childIndex int // index being edited, or -1 for a new entry
childTitle string
newItem func(value string) editor
}
func newListEditor(o *schema.Option, items []string, newItem func(string) editor) *listEditor {
return &listEditor{
opt: o,
items: append([]string(nil), items...),
defaults: o.DefaultList(),
newItem: newItem,
}
}
func (e *listEditor) capturing() bool {
c, ok := e.child.(interface{ capturing() bool })
return ok && c.capturing()
}
func (e *listEditor) rows() int {
n := len(e.items)
if e.showDefaults {
n += len(e.defaults)
}
return n
}
func (e *listEditor) onDefault() (string, bool) {
if e.cursor >= len(e.items) {
return e.defaults[e.cursor-len(e.items)], true
}
return "", false
}
func (e *listEditor) startChild(index int, value, title string, raw bool) {
e.childIndex = index
e.childTitle = title
if raw {
t := newTextEditor(e.opt, value)
t.item = true
e.child = t
} else {
e.child = e.newItem(value)
}
}
func (e *listEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.child != nil {
cmd, res := e.child.Update(msg)
if res != nil {
e.finishChild(res)
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, e.rows(), max(1, e.height-1)); moved {
e.cursor = c
return nil, nil
}
def, isDefault := "", false
if e.rows() > 0 {
def, isDefault = e.onDefault()
}
switch key {
case "esc", "q":
if !e.changed {
return nil, cancelled()
}
if len(e.items) == 0 {
return nil, &result{}
}
return nil, valuesResult(e.items...)
case "a", "n", "insert", "+":
e.startChild(-1, "", "New entry", false)
case "enter", "e":
switch {
case e.rows() == 0:
e.startChild(-1, "", "New entry", false)
case isDefault:
e.startChild(-1, def, "New entry (copied from default)", false)
default:
e.startChild(e.cursor, e.items[e.cursor], "Edit entry", false)
}
case "r":
if e.rows() > 0 && !isDefault {
e.startChild(e.cursor, e.items[e.cursor], "Edit entry (raw text)", true)
}
case "d", "x", "delete", "backspace":
if e.rows() == 0 {
break
}
if isDefault {
if e.opt.Kind == schema.KindKeybind {
trigger, _ := schema.SplitKeybind(def)
e.items = append(e.items, trigger+"=unbind")
e.changed = true
e.cursor = len(e.items) - 1
}
break
}
e.items = append(e.items[:e.cursor], e.items[e.cursor+1:]...)
e.changed = true
e.cursor = min(e.cursor, max(0, e.rows()-1))
case "K", "shift+up":
if !isDefault && e.cursor > 0 && e.cursor < len(e.items) {
e.items[e.cursor-1], e.items[e.cursor] = e.items[e.cursor], e.items[e.cursor-1]
e.cursor--
e.changed = true
}
case "J", "shift+down":
if !isDefault && e.cursor < len(e.items)-1 {
e.items[e.cursor+1], e.items[e.cursor] = e.items[e.cursor], e.items[e.cursor+1]
e.cursor++
e.changed = true
}
case "v":
if len(e.defaults) > 0 {
e.showDefaults = !e.showDefaults
e.cursor = min(e.cursor, max(0, e.rows()-1))
}
}
return nil, nil
}
func (e *listEditor) finishChild(res *result) {
defer func() { e.child = nil }()
if res.cancel {
return
}
value := ""
if len(res.values) > 0 {
value = res.values[0]
}
switch {
case e.childIndex < 0 && value == "":
return
case e.childIndex < 0:
e.items = append(e.items, value)
e.cursor = len(e.items) - 1
case value == "":
e.items = append(e.items[:e.childIndex], e.items[e.childIndex+1:]...)
e.cursor = min(e.childIndex, max(0, e.rows()-1))
default:
e.items[e.childIndex] = value
}
e.changed = true
}
func (e *listEditor) View(width, height int) string {
if e.child != nil {
title := stBold.Render(e.childTitle)
return title + "\n\n" + e.child.View(width, height-2)
}
var lines []string
if len(e.items) == 0 {
lines = append(lines, stDim.Render("No entries in your config. Press a to add one."))
}
e.height = height - 2
listH := e.height
e.top = scrollWindow(e.cursor, e.top, listH, e.rows())
for i := e.top; i < e.rows() && len(lines) < listH; i++ {
isDefault := i >= len(e.items)
var v string
if isDefault {
if i == len(e.items) {
if len(lines) > 0 {
lines = append(lines, "")
}
lines = append(lines, stDim.Render(fmt.Sprintf("Built-in defaults (%d, read-only):", len(e.defaults))))
}
v = e.defaults[i-len(e.items)]
} else {
v = e.items[i]
}
segs := append([]seg{cursorSeg(i == e.cursor)}, e.itemSegs(v, isDefault)...)
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
if len(e.defaults) > 0 && !e.showDefaults {
lines = append(lines, "", stDim.Render(fmt.Sprintf("Ghostty has %d built-in default entries. Press v to show them.", len(e.defaults))))
}
if e.changed {
lines = append(lines, "", stChanged.Render("Modified. Press esc to keep the changes."))
}
return strings.Join(lines, "\n")
}
func (e *listEditor) itemSegs(v string, isDefault bool) []seg {
if isDefault {
return []seg{styled(v, stDim)}
}
switch e.opt.Kind {
case schema.KindKeybind:
trigger, action := schema.SplitKeybind(v)
if action == "" {
return []seg{plain(v)}
}
return []seg{styled(trigger, stKey), styled(" → ", stDim), plain(action)}
case schema.KindColor:
return []seg{rawSeg(swatch(v)), plain(" " + v)}
}
return []seg{plain(v)}
}
func (e *listEditor) Help() string {
if e.child != nil {
return e.child.Help()
}
h := "a add · enter edit · r raw · d delete · J/K move · esc done"
if len(e.defaults) > 0 {
h += " · v defaults"
}
return h
}
+161
View File
@@ -0,0 +1,161 @@
package ui
import (
"fmt"
"sort"
"strings"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
// paletteEditor shows all 256 palette colors and edits individual
// overrides (written as "palette = N=COLOR").
type paletteEditor struct {
opt *schema.Option
defaults [256]string
overrides map[int]string
extra []string // entries that could not be parsed; kept as is
cursor int
top int
height int
changed bool
child *textEditor
colorOpt *schema.Option
theme string // theme providing the defaults of colors 0-15
}
// useTheme takes the base colors from the configured theme, since those
// are what an override replaces.
func (e *paletteEditor) useTheme(t *ghostty.Theme) {
for i, c := range t.Palette {
if c != "" {
e.defaults[i] = c
e.theme = t.Name
}
}
}
func newPaletteEditor(o *schema.Option, entries []string) *paletteEditor {
e := &paletteEditor{
opt: o,
overrides: map[int]string{},
colorOpt: &schema.Option{Key: "palette", Kind: schema.KindColor},
}
for _, d := range o.DefaultList() {
if i, c, ok := schema.SplitPalette(d); ok {
e.defaults[i] = c
}
}
for _, v := range entries {
if i, c, ok := schema.SplitPalette(v); ok {
e.overrides[i] = c
} else {
e.extra = append(e.extra, v)
}
}
return e
}
func (e *paletteEditor) values() []string {
idx := make([]int, 0, len(e.overrides))
for i := range e.overrides {
idx = append(idx, i)
}
sort.Ints(idx)
var out []string
for _, i := range idx {
out = append(out, fmt.Sprintf("%d=%s", i, e.overrides[i]))
}
return append(out, e.extra...)
}
func (e *paletteEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.child != nil {
cmd, res := e.child.Update(msg)
if res != nil {
if !res.cancel {
if len(res.values) == 0 {
delete(e.overrides, e.cursor)
} else {
e.overrides[e.cursor] = res.values[0]
}
e.changed = true
}
e.child = nil
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, 256, max(1, e.height-1)); moved {
e.cursor = c
return nil, nil
}
switch key {
case "esc", "q":
if !e.changed {
return nil, cancelled()
}
v := e.values()
if len(v) == 0 {
return nil, &result{}
}
return nil, valuesResult(v...)
case "enter", "e":
cur := e.overrides[e.cursor]
e.child = newTextEditor(e.colorOpt, cur)
e.child.item = true
e.child.input.Placeholder = e.defaults[e.cursor]
case "d", "x", "delete", "backspace":
if _, ok := e.overrides[e.cursor]; ok {
delete(e.overrides, e.cursor)
e.changed = true
}
}
return nil, nil
}
func (e *paletteEditor) View(width, height int) string {
if e.child != nil {
head := stBold.Render(fmt.Sprintf("Palette color %d", e.cursor))
if d := e.defaults[e.cursor]; d != "" {
head += stDim.Render(" default ") + swatch(d) + " " + d
}
return head + "\n\n" + e.child.View(width, height-2)
}
var lines []string
lines = append(lines, stDim.Render(fmt.Sprintf("%d of 256 colors overridden. 0–7 normal, 8–15 bright, 16–255 extended.", len(e.overrides))))
if e.theme != "" {
lines = append(lines, stDim.Render("Colors 0–15 default to the theme "+e.theme+"."))
}
lines = append(lines, "")
e.height = height - len(lines)
e.top = scrollWindow(e.cursor, e.top, e.height, 256)
for i := e.top; i < 256 && i < e.top+e.height; i++ {
value, set := e.overrides[i]
if !set {
value = e.defaults[i]
}
segs := []seg{cursorSeg(i == e.cursor), plain(fmt.Sprintf("%3d ", i)), rawSeg(swatch(value)), plain(" ")}
if set {
segs = append(segs, styled("● "+value, stSet), styled(" (default "+e.defaults[i]+")", stDim))
} else {
segs = append(segs, styled(" "+value, stDim))
}
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
return strings.Join(lines, "\n")
}
func (e *paletteEditor) Help() string {
if e.child != nil {
return e.child.Help()
}
return "↑↓ move · enter edit · d reset color · esc done"
}
+222
View File
@@ -0,0 +1,222 @@
package ui
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/colors"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
// pickerEditor selects a value from a long, filterable list (themes, font
// families). Any typed value can be used as well.
type pickerEditor struct {
opt *schema.Option
source string // "themes" or "fonts"
all []string
loading bool
loadErr error
filter textinput.Model
matches []string
cursor int
top int
height int
current string
preview func(name string) *ghostty.Theme
note string
}
func newPickerEditor(o *schema.Option, source, current string) *pickerEditor {
p := &pickerEditor{
opt: o,
source: source,
current: schema.Unquote(current),
loading: true,
filter: newInput("", "type to filter, or enter any value"),
}
p.filter.Prompt = "Search: "
return p
}
// setItems delivers the asynchronously loaded list.
func (p *pickerEditor) setItems(items []string, err error) {
p.all, p.loadErr, p.loading = items, err, false
p.refilter()
for i, m := range p.matches {
if m == p.current {
p.cursor = i
break
}
}
}
func (p *pickerEditor) refilter() {
q := strings.ToLower(strings.TrimSpace(p.filter.Value()))
terms := strings.Fields(q)
var prefix, rest []string
for _, it := range p.all {
l := strings.ToLower(it)
ok := true
for _, t := range terms {
if !strings.Contains(l, t) {
ok = false
break
}
}
if !ok {
continue
}
if q != "" && strings.HasPrefix(l, q) {
prefix = append(prefix, it)
} else {
rest = append(rest, it)
}
}
p.matches = append(prefix, rest...)
p.cursor = 0
p.top = 0
}
func (p *pickerEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if km, ok := msg.(tea.KeyMsg); ok {
key := km.String()
switch key {
case "esc":
return nil, cancelled()
case "enter":
if len(p.matches) > 0 {
return nil, valuesResult(p.matches[p.cursor])
}
v := strings.TrimSpace(p.filter.Value())
if v == "" {
return nil, &result{}
}
return nil, valuesResult(v)
case "tab":
if len(p.matches) > 0 {
p.filter.SetValue(p.matches[p.cursor])
p.filter.CursorEnd()
p.refilter()
}
return nil, nil
case "up", "down", "pgup", "pgdown", "ctrl+p", "ctrl+n":
p.cursor, _ = moveCursor(key, p.cursor, len(p.matches), max(1, p.height-1))
return nil, nil
}
}
before := p.filter.Value()
var cmd tea.Cmd
p.filter, cmd = p.filter.Update(msg)
if p.filter.Value() != before {
p.refilter()
}
return cmd, nil
}
func (p *pickerEditor) View(width, height int) string {
p.filter.Width = max(10, width-12)
var lines []string
count := ""
if !p.loading {
count = stDim.Render(fmt.Sprintf("%d of %d", len(p.matches), len(p.all)))
}
lines = append(lines, p.filter.View(), count)
if p.note != "" {
var note []string
for _, l := range strings.Split(ansi.Wrap(p.note, width, ""), "\n") {
note = append(note, stChanged.Render(l))
}
lines = append(lines[:1], append(note, lines[1:]...)...)
}
var previewLines []string
if p.preview != nil && len(p.matches) > 0 && height >= 16 {
if t := p.preview(p.matches[p.cursor]); t != nil {
previewLines = strings.Split(renderThemePreview(t, width), "\n")
}
}
listH := height - len(lines) - len(previewLines)
if len(previewLines) > 0 {
listH--
}
p.height = listH
switch {
case p.loading:
lines = append(lines, stDim.Render("Loading "+p.source+"…"))
case p.loadErr != nil:
lines = append(lines, stError.Render("Could not load "+p.source+": "+p.loadErr.Error()),
stDim.Render("Type a value and press enter."))
case len(p.matches) == 0:
lines = append(lines, stDim.Render("No matches. Press enter to use the typed value."))
default:
p.top = scrollWindow(p.cursor, p.top, listH, len(p.matches))
for i := p.top; i < len(p.matches) && i < p.top+listH; i++ {
m := p.matches[i]
segs := []seg{cursorSeg(i == p.cursor), plain(m)}
if m == p.current {
segs = append(segs, styled(" ● current", stSet))
}
lines = append(lines, renderRow(segs, width, i == p.cursor))
}
}
if len(previewLines) > 0 {
for len(lines) < height-len(previewLines) {
lines = append(lines, "")
}
lines = append(lines, previewLines...)
}
return strings.Join(lines, "\n")
}
func (p *pickerEditor) Help() string {
return "type to filter · ↑↓ choose · tab complete · enter select · esc cancel"
}
// renderThemePreview draws a small terminal mock-up using a theme's colors.
func renderThemePreview(t *ghostty.Theme, width int) string {
bg, fg := t.Background, t.Foreground
if !colors.Valid(bg) {
bg = "#000000"
}
if !colors.Valid(fg) {
fg = "#ffffff"
}
hexOf := func(v, fallback string) lipgloss.Color {
if h, ok := colors.Hex(v); ok {
return lipgloss.Color(h)
}
return lipgloss.Color(fallback)
}
base := lipgloss.NewStyle().Background(hexOf(bg, "#000000")).Foreground(hexOf(fg, "#ffffff"))
col := func(i int) lipgloss.Style { return base.Foreground(hexOf(t.Palette[i], fg)) }
w := min(width, 48)
row := func(parts ...string) string {
s := strings.Join(parts, "")
return s + base.Render(strings.Repeat(" ", max(0, w-lipglossWidth(s))))
}
var lines []string
lines = append(lines,
row(base.Render(" ")),
row(base.Render(" "), col(2).Bold(true).Render("user@host"), base.Render(" "), col(4).Render("~/src"), base.Render(" $ "), base.Render("ls --color")),
row(base.Render(" "), col(4).Bold(true).Render("docs"), base.Render(" "), col(2).Render("build.sh"), base.Render(" "), col(1).Render("error.log"), base.Render(" "), col(3).Render("notes.md")),
row(base.Render(" "), col(5).Render("import"), base.Render(" os "), col(6).Render("# comment"), base.Render(" "), col(8).Render("dimmed")),
)
var normal, bright strings.Builder
normal.WriteString(base.Render(" "))
bright.WriteString(base.Render(" "))
for i := 0; i < 8; i++ {
normal.WriteString(lipgloss.NewStyle().Background(hexOf(t.Palette[i], bg)).Render(" ") + base.Render(" "))
bright.WriteString(lipgloss.NewStyle().Background(hexOf(t.Palette[i+8], bg)).Render(" ") + base.Render(" "))
}
lines = append(lines, row(base.Render(" ")), row(normal.String()), row(bright.String()), row(base.Render(" ")))
return strings.Join(lines, "\n")
}
func lipglossWidth(s string) int { return lipgloss.Width(s) }
+184
View File
@@ -0,0 +1,184 @@
package ui
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/colors"
)
// The UI uses the 16 ANSI colors so it follows the user's terminal theme.
var (
colAccent = lipgloss.Color("12")
colBorder = lipgloss.Color("8")
colDim = lipgloss.Color("8")
colSet = lipgloss.Color("2")
colChanged = lipgloss.Color("3")
colError = lipgloss.Color("1")
colCode = lipgloss.Color("6")
colSelected = lipgloss.AdaptiveColor{Light: "254", Dark: "237"}
stTitle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("0")).Background(colAccent).Padding(0, 1)
stHeader = lipgloss.NewStyle().Foreground(colDim)
stDim = lipgloss.NewStyle().Foreground(colDim)
stBold = lipgloss.NewStyle().Bold(true)
stAccent = lipgloss.NewStyle().Foreground(colAccent)
stSet = lipgloss.NewStyle().Foreground(colSet)
stChanged = lipgloss.NewStyle().Foreground(colChanged)
stError = lipgloss.NewStyle().Foreground(colError)
stOK = lipgloss.NewStyle().Foreground(colSet)
stCode = lipgloss.NewStyle().Foreground(colCode)
stSelected = lipgloss.NewStyle().Background(colSelected)
stKey = lipgloss.NewStyle().Foreground(colAccent).Bold(true)
stLabel = lipgloss.NewStyle().Foreground(colDim).Width(9)
stRecording = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("0")).Background(colError)
)
// swatch renders a small color sample, or "" if value is not a color.
func swatch(value string) string {
h, ok := colors.Hex(value)
if !ok {
return ""
}
return lipgloss.NewStyle().Background(lipgloss.Color(h)).Render(" ")
}
// fit truncates or pads s to exactly width cells.
func fit(s string, width int) string {
if width <= 0 {
return ""
}
if w := ansi.StringWidth(s); w > width {
return ansi.Truncate(s, width, "…")
} else if w < width {
return s + strings.Repeat(" ", width-w)
}
return s
}
// panel draws a rounded box with a title in the top border. The content is
// clipped to the inner area.
func panel(title, content string, width, height int, focused bool) string {
if focused {
return framed(title, content, width, height, colAccent)
}
return framed(title, content, width, height, colBorder)
}
// framed is panel with an explicit border color.
func framed(title, content string, width, height int, color lipgloss.TerminalColor) string {
if width < 4 || height < 2 {
return ""
}
border := lipgloss.NewStyle().Foreground(color)
titleSt := stDim
if color != colBorder {
titleSt = lipgloss.NewStyle().Foreground(color).Bold(true)
}
inner := width - 2
var b strings.Builder
t := ""
if title != "" {
t = ansi.Truncate(" "+title+" ", inner-2, "… ")
}
dashes := max(0, inner-1-ansi.StringWidth(t))
b.WriteString(border.Render("╭─") + titleSt.Render(t) + border.Render(strings.Repeat("─", dashes)+"╮") + "\n")
lines := strings.Split(content, "\n")
for i := 0; i < height-2; i++ {
line := ""
if i < len(lines) {
line = lines[i]
}
b.WriteString(border.Render("│") + fit(line, inner) + "\x1b[0m" + border.Render("│") + "\n")
}
b.WriteString(border.Render("╰" + strings.Repeat("─", inner) + "╯"))
return b.String()
}
// overlay draws box centered on top of base.
func overlay(base, box string, width, height int) string {
baseLines := strings.Split(base, "\n")
for len(baseLines) < height {
baseLines = append(baseLines, "")
}
boxLines := strings.Split(box, "\n")
bw := 0
for _, l := range boxLines {
if w := ansi.StringWidth(l); w > bw {
bw = w
}
}
x := max(0, (width-bw)/2)
y := max(0, (height-len(boxLines))/2)
for i, l := range boxLines {
row := y + i
if row >= len(baseLines) {
break
}
bl := baseLines[row]
left := fit(ansi.Truncate(bl, x, ""), x)
right := ansi.TruncateLeft(bl, x+bw, "")
baseLines[row] = left + "\x1b[0m" + fit(l, bw) + "\x1b[0m" + right
}
return strings.Join(baseLines, "\n")
}
// seg is a styled piece of a list row.
type seg struct {
text string
st lipgloss.Style
raw bool // pre-rendered (e.g. a swatch); keeps its own background
}
func plain(s string) seg { return seg{text: s, st: lipgloss.NewStyle()} }
func styled(s string, st lipgloss.Style) seg { return seg{text: s, st: st} }
func rawSeg(s string) seg { return seg{text: s, raw: true} }
// renderRow joins segments into a row of exactly width cells. Selected rows
// get a background on every segment, so nested styles do not interrupt the
// highlight.
func renderRow(segs []seg, width int, selected bool) string {
var b strings.Builder
used := 0
for _, s := range segs {
if used >= width {
break
}
w := ansi.StringWidth(s.text)
text := s.text
if used+w > width {
text = ansi.Truncate(text, width-used, "…")
w = ansi.StringWidth(text)
}
switch {
case s.raw:
b.WriteString(text)
case selected:
b.WriteString(s.st.Background(colSelected).Render(text))
default:
b.WriteString(s.st.Render(text))
}
used += w
}
if used < width {
pad := strings.Repeat(" ", width-used)
if selected {
pad = stSelected.Render(pad)
}
b.WriteString(pad)
}
return b.String()
}
// cursorSeg is the "▸ " marker in front of the selected row.
func cursorSeg(selected bool) seg {
if selected {
return styled("▸ ", stAccent)
}
return plain(" ")
}
+68
View File
@@ -0,0 +1,68 @@
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
}
}
+51
View File
@@ -0,0 +1,51 @@
package ui
import (
"io"
"strings"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
)
// rawProbe stops at the first message rawSequence accepts.
type rawProbe struct{ got []byte }
func (p *rawProbe) Init() tea.Cmd { return nil }
func (p *rawProbe) View() string { return "" }
func (p *rawProbe) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if b, ok := rawSequence(msg); ok {
p.got = b
return p, tea.Quit
}
return p, nil
}
// TestRawSequenceFromBubbleTea feeds a kitty keyboard protocol key event
// through Bubble Tea's input parser. It breaks if a Bubble Tea upgrade
// changes how unknown escape sequences are delivered.
func TestRawSequenceFromBubbleTea(t *testing.T) {
const seq = "\x1b[92;9u" // super+\
p := &rawProbe{}
prog := tea.NewProgram(p, tea.WithInput(strings.NewReader(seq)), tea.WithOutput(io.Discard),
tea.WithoutRenderer(), tea.WithoutSignals())
done := make(chan error, 1)
go func() {
_, err := prog.Run()
done <- err
}()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(3 * time.Second):
prog.Kill()
t.Fatal("Bubble Tea did not deliver the sequence")
}
if string(p.got) != seq {
t.Fatalf("rawSequence = %q, want %q", p.got, seq)
}
}
+488
View File
@@ -0,0 +1,488 @@
package ui
import (
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/keybind"
"ghosttyconf/internal/schema"
)
func (a *App) View() string {
if a.width < 40 || a.height < 12 {
return "Terminal too small for the Ghostty config editor (min. 40×12)."
}
bodyH := a.height - 3
var body string
if a.editor != nil {
body = a.viewEditor(a.width, bodyH)
} else {
body = a.viewBrowse(a.width, bodyH)
}
out := a.viewHeader() + "\n" + body + "\n" + a.viewFooter()
if a.dlg != nil {
out = overlay(out, a.dlg.view(a.width, a.height), a.width, a.height)
}
return out
}
func (a *App) viewHeader() string {
title := stTitle.Render("Ghostty Config Editor") + " "
right := stHeader.Render(fmt.Sprintf(" %s · %d options ", a.sch.Source, len(a.sch.Options)))
if lipgloss.Width(title)+lipgloss.Width(right)+20 > a.width {
right = ""
}
path := shortPath(a.file.Path)
if !a.file.Exists {
path += " (new file)"
}
pathW := a.width - lipgloss.Width(title) - lipgloss.Width(right)
if ansi.StringWidth(path) > pathW {
// Keep the end of the path, which is the informative part.
path = "…" + ansi.TruncateLeft(path, ansi.StringWidth(path)-pathW+1, "")
}
return title + fit(stHeader.Render(path), pathW) + right
}
func (a *App) viewFooter() string {
right := ""
if n := len(a.changedKeys()); n > 0 {
right = stChanged.Render(fmt.Sprintf("● %d unsaved ", n))
}
status := a.statusStyle.Render(a.status)
statusW := a.width - lipgloss.Width(right) - 1
line1 := " " + fit(status, statusW) + right
var help string
switch {
case a.editor != nil:
help = a.editor.Help() + " · shift+↑↓ scroll docs"
case a.searching:
help = "type to search keys and docs · enter/↓ go to results · esc clear"
case a.focus == paneCats:
help = "↑↓ category · → options · / search · b keybindings · c changes · ctrl+s save · ? help · q quit"
default:
help = "↑↓ move · enter edit · space toggle · +/- adjust · r reset · u undo · / search · ctrl+s save · ? help · q quit"
}
return line1 + "\n" + stDim.Render(fit(" "+help, a.width))
}
// ---------------------------------------------------------------------------
// Browse screen
func (a *App) viewBrowse(w, h int) string {
catW := 26
if w < 90 {
catW = 20
}
rightW := w - catW
a.catRect = rect{0, 1, catW, h}
cats := panel("Categories", a.renderCats(catW-2, h-2), catW, h, a.focus == paneCats && !a.searching)
optTitle := a.cats[a.catIdx]
if a.query != "" || a.searching {
optTitle = fmt.Sprintf("Search (%d)", len(a.opts))
} else {
optTitle = fmt.Sprintf("%s (%d)", optTitle, len(a.opts))
}
if rightW >= 120 {
optW := rightW * 52 / 100
docW := rightW - optW
a.optRect = rect{catW, 1, optW, h}
a.docRect = rect{catW + optW, 1, docW, h}
opts := panel(optTitle, a.renderOpts(optW-2, h-2), optW, h, a.focus == paneOpts)
content := a.renderDocs(a.selected(), docW-4, h-2)
docs := panel(a.docTitle(), content, docW, h, false)
return lipgloss.JoinHorizontal(lipgloss.Top, cats, opts, docs)
}
optH := max(7, h*55/100)
docH := h - optH
a.optRect = rect{catW, 1, rightW, optH}
a.docRect = rect{catW, 1 + optH, rightW, docH}
opts := panel(optTitle, a.renderOpts(rightW-2, optH-2), rightW, optH, a.focus == paneOpts)
content := a.renderDocs(a.selected(), rightW-4, docH-2)
docs := panel(a.docTitle(), content, rightW, docH, false)
return lipgloss.JoinHorizontal(lipgloss.Top, cats, lipgloss.JoinVertical(lipgloss.Left, opts, docs))
}
// catRows returns the rendered category rows; -1 marks the separator.
func (a *App) catRows() []int {
rows := []int{0, 1, -1}
for i := 2; i < len(a.cats); i++ {
rows = append(rows, i)
}
return rows
}
func (a *App) catRowIndex(row int) int {
rows := a.catRows()
if row < 0 || row >= len(rows) {
return -1
}
return rows[row]
}
func (a *App) renderCats(w, h int) string {
rows := a.catRows()
sel := 0
for i, r := range rows {
if r == a.catIdx {
sel = i
}
}
a.catTop = scrollWindow(sel, a.catTop, h, len(rows))
var lines []string
for i := a.catTop; i < len(rows) && len(lines) < h; i++ {
ci := rows[i]
if ci < 0 {
lines = append(lines, stDim.Render(strings.Repeat("─", w)))
continue
}
name := a.cats[ci]
n := len(a.categoryOptions(name))
count := fmt.Sprintf("%d", n)
selected := ci == a.catIdx && a.query == ""
nameSt := lipgloss.NewStyle()
if ci == 0 && n > 0 {
nameSt = stSet
}
if selected && a.focus == paneCats {
nameSt = nameSt.Bold(true)
}
nameW := w - 2 - len(count) - 1
segs := []seg{cursorSeg(selected), styled(fit(name, nameW), nameSt), plain(" "), styled(count, stDim)}
lines = append(lines, renderRow(segs, w, selected && a.focus == paneCats))
}
return strings.Join(lines, "\n")
}
func (a *App) renderOpts(w, h int) string {
var lines []string
listY := a.optRect.y + 1
if a.searching || a.query != "" {
a.search.Width = max(10, w-4)
lines = append(lines, a.search.View(), "")
h -= 2
listY += 2
}
a.optListY = listY
if len(a.opts) == 0 {
msg := "No options."
switch {
case a.query != "":
msg = "No options match your search."
case a.cats[a.catIdx] == catSet:
msg = "Your config file does not set any options yet."
}
lines = append(lines, stDim.Render(" "+msg))
return strings.Join(lines, "\n")
}
keyW := 0
for _, o := range a.opts {
keyW = max(keyW, len(o.Key))
}
keyW = min(keyW+1, w*55/100)
valW := w - keyW - 4
a.optTop = scrollWindow(a.optIdx, a.optTop, h, len(a.opts))
for i := a.optTop; i < len(a.opts) && i < a.optTop+h; i++ {
o := a.opts[i]
selected := i == a.optIdx
keySt := lipgloss.NewStyle()
switch {
case a.unknown[o.Key] == o:
keySt = stError
case o.Platform != "" && a.osName != "" && o.Platform != a.osName:
keySt = stDim
}
if selected && a.focus == paneOpts {
keySt = keySt.Bold(true)
}
segs := []seg{cursorSeg(selected), a.marker(o), styled(fit(o.Key, keyW), keySt), plain(" ")}
segs = append(segs, a.valueSegs(o, valW)...)
lines = append(lines, renderRow(segs, w, selected && a.focus == paneOpts))
}
return strings.Join(lines, "\n")
}
// marker shows whether an option is set in the file and whether it has
// unsaved changes.
func (a *App) marker(o *schema.Option) seg {
now := a.file.GetAll(o.Key)
changed := !equalStrings(now, a.saved.GetAll(o.Key))
switch {
case changed && len(now) == 0:
return styled("○ ", stChanged)
case changed:
return styled("● ", stChanged)
case len(now) > 0:
return styled("● ", stSet)
}
return plain(" ")
}
// valueSegs summarizes the current value for the option list.
func (a *App) valueSegs(o *schema.Option, w int) []seg {
vals := a.file.GetAll(o.Key)
set := len(vals) > 0
switch {
case o.Kind == schema.KindKeybind:
counts := map[keybind.Source]int{}
for _, b := range keybind.NewSet(o.DefaultList(), vals).Bindings() {
counts[b.Source]++
}
var parts []seg
add := func(n int, label string, st lipgloss.Style) {
if n == 0 {
return
}
if len(parts) > 0 {
parts = append(parts, styled(" · ", stDim))
}
parts = append(parts, styled(fmt.Sprintf("%d %s", n, label), st))
}
add(counts[keybind.Changed], "changed", stChanged)
add(counts[keybind.Custom], "custom", stSet)
add(counts[keybind.Unbound], "unbound", stError)
if len(parts) == 0 {
return []seg{styled(fmt.Sprintf("%d built-in bindings", counts[keybind.Default]), stDim)}
}
return parts
case o.Kind == schema.KindPalette:
if set {
return []seg{plain(fmt.Sprintf("%d color(s) overridden", len(vals)))}
}
return []seg{styled("default palette", stDim)}
case o.Repeatable:
if set {
s := vals[0]
if o.Kind == schema.KindKeybind {
s = keybindSummary(vals[0])
}
if len(vals) > 1 {
return []seg{plain(ansi.Truncate(s, max(5, w-10), "…")), styled(fmt.Sprintf(" +%d more", len(vals)-1), stDim)}
}
return []seg{plain(s)}
}
defs := o.DefaultList()
switch len(defs) {
case 0:
return []seg{styled("—", stDim)}
case 1:
return []seg{styled(defs[0], stDim)}
}
return []seg{styled(fmt.Sprintf("%d built-in entries", len(defs)), stDim)}
}
v := o.Default()
st := stDim
if set {
v, st = vals[len(vals)-1], lipgloss.NewStyle()
if o.Validate(v) != nil {
st = stError
}
}
if v == "" {
return []seg{styled("—", stDim)}
}
v = strings.ReplaceAll(v, "\t", "\\t")
if o.Kind == schema.KindColor || o.Kind == schema.KindColorList {
if sw := swatch(strings.Split(v, ",")[0]); sw != "" {
return []seg{rawSeg(sw), plain(" "), styled(v, st)}
}
}
return []seg{styled(v, st)}
}
func keybindSummary(v string) string {
t, act := schema.SplitKeybind(v)
if act == "" {
return v
}
return t + " → " + act
}
// renderDocs renders the documentation panel content for o into a.doc and
// returns the visible part.
func (a *App) renderDocs(o *schema.Option, w, h int) string {
if o == nil {
return ""
}
a.doc.Width, a.doc.Height = w, h
id := o.Key
var content func() string
// Editors can show documentation of their own (e.g. of the selected
// keybind action) instead of the option's.
if dp, ok := a.editor.(interface {
docFor() (id, title, body string, ok bool)
}); ok {
if did, title, body, ok := dp.docFor(); ok {
id = did
content = func() string { return stAccent.Bold(true).Render(title) + "\n\n" + renderDoc(body, w) }
}
}
if content == nil {
content = func() string { return a.docContent(o, w) }
}
key := fmt.Sprintf("%s|%d|%d", id, w, a.rev)
if a.editor != nil {
key += "|edit"
}
if key != a.docFor {
if !strings.HasPrefix(a.docFor, id+"|") {
a.doc.GotoTop()
}
a.docFor = key
a.doc.SetContent(content())
}
lines := strings.Split(a.doc.View(), "\n")
for i := range lines {
lines[i] = " " + lines[i]
}
return strings.Join(lines, "\n")
}
// docTitle is the documentation panel title, with a scroll position when
// the text does not fit. Call it after renderDocs.
func (a *App) docTitle() string {
if a.doc.TotalLineCount() <= a.doc.Height {
return "Documentation"
}
return fmt.Sprintf("Documentation · %d%% · shift+↑↓ scroll", int(a.doc.ScrollPercent()*100))
}
func (a *App) docContent(o *schema.Option, w int) string {
var b strings.Builder
b.WriteString(stAccent.Bold(true).Render(o.Key) + "\n\n")
row := func(label, value string) {
b.WriteString(stLabel.Render(label) + " " + ansi.Wrap(value, max(10, w-10), "") + "\n")
}
if a.editor == nil {
row("Type", o.TypeLabel())
vals := a.file.GetAll(o.Key)
switch {
case o.Repeatable:
defs := o.DefaultList()
if len(defs) > 0 {
row("Default", fmt.Sprintf("%d built-in entries", len(defs)))
} else {
row("Default", "none")
}
if len(vals) == 0 {
row("Value", stDim.Render("not set"))
} else {
row("Value", fmt.Sprintf("%d entr%s in your config", len(vals), plural(len(vals), "y", "ies")))
for i, v := range vals {
if i == 8 {
b.WriteString(stDim.Render(fmt.Sprintf(" … and %d more", len(vals)-8)) + "\n")
break
}
b.WriteString(" " + ansi.Truncate(v, max(10, w-10), "…") + "\n")
}
}
default:
def := o.Default()
if def == "" {
def = stDim.Render("(unset)")
} else if sw := swatch(def); sw != "" && o.Kind == schema.KindColor {
def = sw + " " + def
}
row("Default", strings.ReplaceAll(def, "\t", "\\t"))
if len(vals) == 0 {
row("Value", stDim.Render("not set (uses default)"))
} else {
v := vals[len(vals)-1]
if sw := swatch(v); sw != "" && o.Kind == schema.KindColor {
v = sw + " " + v
}
row("Value", v+" "+stSet.Render("● set in config"))
if err := o.Validate(vals[len(vals)-1]); err != nil {
b.WriteString(stError.Render(" ✗ invalid: "+err.Error()) + "\n")
}
if len(vals) > 1 {
b.WriteString(stChanged.Render(fmt.Sprintf(" set %d times; the last one wins", len(vals))) + "\n")
}
}
}
if o.Platform != "" {
row("Platform", o.Platform+" only")
}
row("Category", o.Category)
b.WriteString("\n")
}
if o.Doc == "" {
b.WriteString(stDim.Render("No documentation available."))
} else {
b.WriteString(renderDoc(o.Doc, w))
}
return b.String()
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// ---------------------------------------------------------------------------
// Editor screen
func (a *App) viewEditor(w, h int) string {
o := a.editOpt
title := "Edit " + o.Key
if w >= 110 {
edW := w * 55 / 100
docW := w - edW
a.optRect = rect{0, 1, edW, h}
a.docRect = rect{edW, 1, docW, h}
left := panel(title, a.renderEditor(edW-4, h-2), edW, h, true)
content := a.renderDocs(o, docW-4, h-2)
right := panel(a.docTitle(), content, docW, h, false)
return lipgloss.JoinHorizontal(lipgloss.Top, left, right)
}
edH := max(10, h*62/100)
switch a.editor.(type) {
case *keybindManager, *listEditor, *paletteEditor:
edH = max(10, h*75/100) // long lists need the room
}
docH := h - edH
a.optRect = rect{0, 1, w, edH}
a.docRect = rect{0, 1 + edH, w, docH}
top := panel(title, a.renderEditor(w-4, edH-2), w, edH, true)
if docH < 3 {
return top
}
content := a.renderDocs(o, w-4, docH-2)
bottom := panel(a.docTitle(), content, w, docH, false)
return lipgloss.JoinVertical(lipgloss.Left, top, bottom)
}
func (a *App) renderEditor(w, h int) string {
o := a.editOpt
var head []string
head = append(head, stLabel.Render("Type")+" "+ansi.Truncate(o.TypeLabel(), max(10, w-10), "…"))
if !o.Repeatable {
def := o.Default()
if def == "" {
def = stDim.Render("(unset)")
}
cur, ok := a.file.Get(o.Key)
if !ok {
cur = stDim.Render("not set")
}
head = append(head,
stLabel.Render("Default")+" "+ansi.Truncate(strings.ReplaceAll(def, "\t", "\\t"), max(10, w-10), "…"),
stLabel.Render("Current")+" "+ansi.Truncate(cur, max(10, w-10), "…"))
}
head = append(head, "")
body := a.editor.View(w, h-len(head))
lines := append(head, strings.Split(body, "\n")...)
for i := range lines {
lines[i] = " " + lines[i]
}
return strings.Join(lines, "\n")
}