4 "github.com/gdamore/tcell"
7 // Messenger is an object that can send messages to the user and get input from the user (with a prompt)
8 type Messenger struct {
21 // NewMessenger returns a new Messenger struct
22 func NewMessenger(s tcell.Screen) *Messenger {
28 // Message sends a message to the user
29 func (m *Messenger) Message(msg string) {
31 m.style = tcell.StyleDefault
33 if _, ok := colorscheme["message"]; ok {
34 m.style = colorscheme["message"]
39 // Error sends an error message to the user
40 func (m *Messenger) Error(msg string) {
42 m.style = tcell.StyleDefault.
43 Foreground(tcell.ColorBlack).
44 Background(tcell.ColorMaroon)
46 if _, ok := colorscheme["error-message"]; ok {
47 m.style = colorscheme["error-message"]
52 // Prompt sends the user a message and waits for a response to be typed in
53 // This function blocks the main loop while waiting for input
54 func (m *Messenger) Prompt(prompt string) (string, bool) {
58 response, canceled := "", true
64 event := m.s.PollEvent()
66 switch e := event.(type) {
68 if e.Key() == tcell.KeyEscape {
71 } else if e.Key() == tcell.KeyCtrlC {
74 } else if e.Key() == tcell.KeyCtrlQ {
77 } else if e.Key() == tcell.KeyEnter {
78 // User is done entering their response
80 response, canceled = m.response, false
88 return response, canceled
91 // HandleEvent handles an event for the prompter
92 func (m *Messenger) HandleEvent(event tcell.Event) {
93 switch e := event.(type) {
100 case tcell.KeyBackspace2:
102 m.response = string([]rune(m.response)[:Count(m.response)-1])
109 m.response += string(e.Rune())
118 // Reset resets the messenger's cursor, message and response
119 func (m *Messenger) Reset() {
125 // Clear clears the line at the bottom of the editor
126 func (m *Messenger) Clear() {
128 for x := 0; x < w; x++ {
129 m.s.SetContent(x, h-1, ' ', nil, tcell.StyleDefault)
133 // Display displays and messages or prompts
134 func (m *Messenger) Display() {
137 runes := []rune(m.message + m.response)
138 for x := 0; x < len(runes); x++ {
139 m.s.SetContent(x, h-1, runes[x], nil, m.style)
143 m.s.ShowCursor(Count(m.message)+m.cursorx, h-1)