Skip to content
Myr

Add basic mouse support

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent 3a70ecd · Browse files · 4 files+192 added−12 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+192 added−12 removed

  • other:+192 added−12 removed

4 files+192 added−12 removed

added:examples/mouse/main.go+60 added
1package main23import (4 "fmt"5 "log"67 tea "github.com/charmbracelet/bubbletea"8)910func main() {11 p := tea.NewProgram(initialize, update, view)1213 p.EnterAltScreen()14 defer p.ExitAltScreen()15 p.EnableMouseAllMotion()16 defer p.DisableMouseAllMotion()1718 if err := p.Start(); err != nil {19 log.Fatal(err)20 }21}2223type model struct {24 init bool25 mouseEvent tea.MouseEvent26}2728func initialize() (tea.Model, tea.Cmd) {29 return model{}, nil30}3132func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {33 m, _ := mdl.(model)3435 switch msg := msg.(type) {36 case tea.KeyMsg:37 if msg.Type == tea.KeyCtrlC || (msg.Type == tea.KeyRune && msg.Rune == 'q') {38 return m, tea.Quit39 }4041 case tea.MouseMsg:42 m.init = true43 m.mouseEvent = tea.MouseEvent(msg)44 }4546 return m, nil47}4849func view(mdl tea.Model) string {50 m, _ := mdl.(model)5152 s := "Do mouse stuff. When you're done press q to quit.\n\n"5354 if m.init {55 e := m.mouseEvent56 s += fmt.Sprintf("(X: %d, Y: %d) %s", e.X, e.Y, e)57 }5859 return s60}
modified:key.go+17 added-10 removed
225 unmodified lines
226 "1b5b313b3343": {Type: KeyRight, Alt: true},227 "1b5b313b3344": {Type: KeyLeft, Alt: true},228}229230// ReadKey reads keypress input from a TTY and returns a string representation231// of a key.232func ReadKey(r io.Reader) (Key, error) {230// ReadInput reads keypress and mouse input from a TTY and returns a message231// containing information about the key or mouse event accordingly232func ReadInput(r io.Reader) (Msg, error) {233 var buf [256]byte234235 // Read and block236 numBytes, err := r.Read(buf[:])237 if err != nil {238 return Key{}, err238 return nil, err239 }240241 // See if it's a mouse event. For now we're parsing X10-type mouse events242 // only.243 mouseEvent, err := parseX10MouseEvent(buf[:numBytes])244 if err == nil {245 return MouseMsg(mouseEvent), nil246 }247248 hex := fmt.Sprintf("%x", buf[:numBytes])249250 // Some of these need special handling251 if k, ok := hexes[hex]; ok {
2 unmodified lines
254255 // Get unicode value256 char, _ := utf8.DecodeRune(buf[:])257 if char == utf8.RuneError {251 return Key{}, errors.New("could not decode rune")258 return nil, errors.New("could not decode rune")259 }260261 // Is it a control character?262 if numBytes == 1 && char <= keyUS || char == keyDEL {256 return Key{Type: KeyType(char)}, nil263 return KeyMsg(Key{Type: KeyType(char)}), nil264 }265266 // Is it a special sequence, like an arrow key?267 if k, ok := sequences[string(buf[:numBytes])]; ok {261 return Key{Type: k}, nil268 return KeyMsg(Key{Type: k}), nil269 }270271 // Is the alt key pressed? The buffer will be prefixed with an escape272 // sequence if so
1 unmodified line
274 // Now remove the initial escape sequence and re-process to get the275 // character.276 c, _ := utf8.DecodeRune(buf[1:])277 if c == utf8.RuneError {271 return Key{}, errors.New("could not decode rune after removing initial escape")278 return nil, errors.New("could not decode rune after removing initial escape")279 }273 return Key{Alt: true, Type: KeyRune, Rune: c}, nil280 return KeyMsg(Key{Alt: true, Type: KeyRune, Rune: c}), nil281 }282283 // Just a regular, ol' rune277 return Key{Type: KeyRune, Rune: char}, nil284 return KeyMsg(Key{Type: KeyRune, Rune: char}), nil285}
added:mouse.go+89 added
1package tea23import "errors"45type MouseMsg MouseEvent67type MouseEvent struct {8 X int9 Y int10 Button MouseButton11 Alt bool12 Ctrl bool13}1415func (m MouseEvent) String() (s string) {16 if m.Ctrl {17 s += "ctrl+"18 }19 if m.Alt {20 s += "alt+"21 }22 s += mouseButtonNames[m.Button]23 return s24}2526type MouseButton int2728const (29 MouseLeft MouseButton = iota30 MouseRight31 MouseMiddle32 MouseRelease33 MouseWheelUp34 MouseWheelDown35 MouseMotion36)3738var mouseButtonNames = map[MouseButton]string{39 MouseLeft: "left",40 MouseRight: "right",41 MouseMiddle: "middle",42 MouseRelease: "release",43 MouseWheelUp: "wheel up",44 MouseWheelDown: "wheel down",45 MouseMotion: "motion",46}4748// Parse an X10-encoded mouse event. The simplest kind. The last release of49// X10 was December 1986, by the way.50func parseX10MouseEvent(buf []byte) (m MouseEvent, err error) {51 if len(buf) != 6 || string(buf[:3]) != "\x1b[M" {52 return m, errors.New("not an X10 mouse event")53 }5455 e := buf[3] - 325657 switch e {58 case 35:59 m.Button = MouseMotion60 case 64:61 m.Button = MouseWheelUp62 case 65:63 m.Button = MouseWheelDown64 default:65 switch e & 3 {66 case 0:67 m.Button = MouseLeft68 case 1:69 m.Button = MouseMiddle70 case 2:71 m.Button = MouseRight72 case 3:73 m.Button = MouseRelease74 }75 }7677 if e&8 != 0 {78 m.Alt = true79 }80 if e&16 != 0 {81 m.Ctrl = true82 }8384 // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).85 m.X = int(buf[4]) - 32 - 186 m.Y = int(buf[5]) - 32 - 18788 return m, nil89}
modified:tea.go+26 added-2 removed
117 unmodified lines
118119 // Subscribe to user input120 go func() {121 for {122 msg, err := ReadKey(os.Stdin)122 msg, err := ReadInput(os.Stdin)123 if err != nil {124 errs <- err125 }126 msgs <- KeyMsg(msg)126 msgs <- msg127 }128 }()129130 // Get initial terminal size
69 unmodified lines
200 p.mtx.Lock()201 defer p.mtx.Unlock()202 fmt.Fprintf(p.output, te.CSI+te.ExitAltScreenSeq)203}204205func (p *Program) EnableMouseCellMotion() {206 p.mtx.Lock()207 defer p.mtx.Unlock()208 fmt.Fprintf(p.output, te.CSI+"?1002h")209}210211func (p *Program) DisableMouseCellMotion() {212 p.mtx.Lock()213 defer p.mtx.Unlock()214 fmt.Fprintf(p.output, te.CSI+"?1002l")215}216217func (p *Program) EnableMouseAllMotion() {218 p.mtx.Lock()219 defer p.mtx.Unlock()220 fmt.Fprintf(p.output, te.CSI+"?1003h")221}222223func (p *Program) DisableMouseAllMotion() {224 p.mtx.Lock()225 defer p.mtx.Unlock()226 fmt.Fprintf(p.output, te.CSI+"?1003l")227}