// 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 version string update string // a newer release, if one is known // 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 } // SetVersion sets the program version shown in the help. func (a *App) SetVersion(v string) { a.version = v } // SetUpdate names a newer release, shown in the header and the help. func (a *App) SetUpdate(v string) { a.update = v } 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(a.version, a.update) 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 }