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
Provenance
- Commit
d86cb56- Tree
97a0f90- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
3a70ecd
4 files changed+192 added−12 removed
added:examples/mouse/main.go+60 added
1+package main2+3+import (4+ "fmt"5+ "log"6+7+ tea "github.com/charmbracelet/bubbletea"8+)9+10+func main() {11+ p := tea.NewProgram(initialize, update, view)12+13+ p.EnterAltScreen()14+ defer p.ExitAltScreen()15+ p.EnableMouseAllMotion()16+ defer p.DisableMouseAllMotion()17+18+ if err := p.Start(); err != nil {19+ log.Fatal(err)20+ }21+}22+23+type model struct {24+ init bool25+ mouseEvent tea.MouseEvent26+}27+28+func initialize() (tea.Model, tea.Cmd) {29+ return model{}, nil30+}31+32+func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {33+ m, _ := mdl.(model)34+35+ 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+ }40+41+ case tea.MouseMsg:42+ m.init = true43+ m.mouseEvent = tea.MouseEvent(msg)44+ }45+46+ return m, nil47+}48+49+func view(mdl tea.Model) string {50+ m, _ := mdl.(model)51+52+ s := "Do mouse stuff. When you're done press q to quit.\n\n"53+54+ if m.init {55+ e := m.mouseEvent56+ s += fmt.Sprintf("(X: %d, Y: %d) %s", e.X, e.Y, e)57+ }58+59+ return s60+}modified:key.go+17 added-10 removed
225 unmodified lines226 "1b5b313b3343": {Type: KeyRight, Alt: true},227 "1b5b313b3344": {Type: KeyLeft, Alt: true},228 }229 230-// ReadKey reads keypress input from a TTY and returns a string representation231-// of a key.232-func 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 accordingly232+func ReadInput(r io.Reader) (Msg, error) {233 var buf [256]byte234 235 // Read and block236 numBytes, err := r.Read(buf[:])237 if err != nil {238- return Key{}, err238+ return nil, err239 }240 241+ // 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+ }247+248 hex := fmt.Sprintf("%x", buf[:numBytes])249 250 // Some of these need special handling251 if k, ok := hexes[hex]; ok {2 unmodified lines254 255 // 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 }260 261 // 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 }265 266 // 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 }270 271 // Is the alt key pressed? The buffer will be prefixed with an escape272 // sequence if so1 unmodified line274 // 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 }282 283 // 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
1+package tea2+3+import "errors"4+5+type MouseMsg MouseEvent6+7+type MouseEvent struct {8+ X int9+ Y int10+ Button MouseButton11+ Alt bool12+ Ctrl bool13+}14+15+func (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+}25+26+type MouseButton int27+28+const (29+ MouseLeft MouseButton = iota30+ MouseRight31+ MouseMiddle32+ MouseRelease33+ MouseWheelUp34+ MouseWheelDown35+ MouseMotion36+)37+38+var 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+}47+48+// Parse an X10-encoded mouse event. The simplest kind. The last release of49+// X10 was December 1986, by the way.50+func 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+ }54+55+ e := buf[3] - 3256+57+ 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+ }76+77+ if e&8 != 0 {78+ m.Alt = true79+ }80+ if e&16 != 0 {81+ m.Ctrl = true82+ }83+84+ // (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 - 187+88+ return m, nil89+}modified:tea.go+26 added-2 removed
117 unmodified lines118 119 // 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 }()129 130 // Get initial terminal size69 unmodified lines200 p.mtx.Lock()201 defer p.mtx.Unlock()202 fmt.Fprintf(p.output, te.CSI+te.ExitAltScreenSeq)203 }204+205+func (p *Program) EnableMouseCellMotion() {206+ p.mtx.Lock()207+ defer p.mtx.Unlock()208+ fmt.Fprintf(p.output, te.CSI+"?1002h")209+}210+211+func (p *Program) DisableMouseCellMotion() {212+ p.mtx.Lock()213+ defer p.mtx.Unlock()214+ fmt.Fprintf(p.output, te.CSI+"?1002l")215+}216+217+func (p *Program) EnableMouseAllMotion() {218+ p.mtx.Lock()219+ defer p.mtx.Unlock()220+ fmt.Fprintf(p.output, te.CSI+"?1003h")221+}222+223+func (p *Program) DisableMouseAllMotion() {224+ p.mtx.Lock()225+ defer p.mtx.Unlock()226+ fmt.Fprintf(p.output, te.CSI+"?1003l")227+}