From 2bcb0af2e217f986b59b01fe0b255b619a546fc4 Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Mon, 4 Dec 2023 08:50:27 -0800 Subject: [PATCH] feat: add set-window-title command (#611) Set the terminal window title using termenv. Fixes: https://github.com/charmbracelet/bubbletea/issues/610 --- commands.go | 17 +++++++++++++++ examples/set-window-title/main.go | 35 +++++++++++++++++++++++++++++++ screen.go | 5 +++++ tea.go | 3 +++ tutorials/basics/main.go | 2 +- 5 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 examples/set-window-title/main.go diff --git a/commands.go b/commands.go index 3a0520d..7b139b8 100644 --- a/commands.go +++ b/commands.go @@ -170,3 +170,20 @@ func Sequentially(cmds ...Cmd) Cmd { return nil } } + +// setWindowTitleMsg is an internal message used to set the window title. +type setWindowTitleMsg string + +// SetWindowTitle produces a command that sets the terminal title. +// +// For example: +// +// func (m model) Init() Cmd { +// // Set title. +// return tea.SetWindowTitle("My App") +// } +func SetWindowTitle(title string) Cmd { + return func() Msg { + return setWindowTitleMsg(title) + } +} diff --git a/examples/set-window-title/main.go b/examples/set-window-title/main.go new file mode 100644 index 0000000..2e14609 --- /dev/null +++ b/examples/set-window-title/main.go @@ -0,0 +1,35 @@ +package main + +// A simple example illustrating how to set a window title. + +import ( + "fmt" + "os" + + tea "github.com/charmbracelet/bubbletea" +) + +type model struct{} + +func (m model) Init() tea.Cmd { + return tea.SetWindowTitle("Bubble Tea Example") +} + +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg.(type) { + case tea.KeyMsg: + return m, tea.Quit + } + return m, nil +} + +func (m model) View() string { + return "\nPress any key to quit." +} + +func main() { + if _, err := tea.NewProgram(model{}).Run(); err != nil { + fmt.Println("Uh oh:", err) + os.Exit(1) + } +} diff --git a/screen.go b/screen.go index 899db3d..d064222 100644 --- a/screen.go +++ b/screen.go @@ -167,3 +167,8 @@ func (p *Program) EnableMouseAllMotion() { func (p *Program) DisableMouseAllMotion() { p.renderer.disableMouseAllMotion() } + +// SetWindowTitle sets the terminal window title. +func (p *Program) SetWindowTitle(title string) { + p.output.SetWindowTitle(title) +} diff --git a/tea.go b/tea.go index 74e83e3..ddd1144 100644 --- a/tea.go +++ b/tea.go @@ -388,6 +388,9 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) { p.Send(msg) } }() + + case setWindowTitleMsg: + p.SetWindowTitle(string(msg)) } // Process internal messages for the renderer. diff --git a/tutorials/basics/main.go b/tutorials/basics/main.go index 4970290..71cef0a 100644 --- a/tutorials/basics/main.go +++ b/tutorials/basics/main.go @@ -25,7 +25,7 @@ func initialModel() model { } func (m model) Init() tea.Cmd { - return nil + return tea.SetWindowTitle("Grocery List") } func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {