]> git.0d.be Git - barnard.git/blob - uiterm/textbox.go
uiterm: make View interface methods private
[barnard.git] / uiterm / textbox.go
1 package uiterm
2
3 import (
4         "strings"
5         "unicode/utf8"
6
7         "github.com/nsf/termbox-go"
8 )
9
10 type InputFunc func(ui *Ui, textbox *Textbox, text string)
11
12 type Textbox struct {
13         Text string
14         Fg   Attribute
15         Bg   Attribute
16
17         Input InputFunc
18
19         active         bool
20         x0, y0, x1, y1 int
21 }
22
23 func (t *Textbox) setBounds(ui *Ui, x0, y0, x1, y1 int) {
24         t.x0 = x0
25         t.y0 = y0
26         t.x1 = x1
27         t.y1 = y1
28 }
29
30 func (t *Textbox) setActive(ui *Ui, active bool) {
31         t.active = active
32 }
33
34 func (t *Textbox) draw(ui *Ui) {
35         var setCursor = false
36         reader := strings.NewReader(t.Text)
37         for y := t.y0; y < t.y1; y++ {
38                 for x := t.x0; x < t.x1; x++ {
39                         var chr rune
40                         if ch, _, err := reader.ReadRune(); err != nil {
41                                 if t.active && !setCursor {
42                                         termbox.SetCursor(x, y)
43                                         setCursor = true
44                                 }
45                                 chr = ' '
46                         } else {
47                                 chr = ch
48                         }
49                         termbox.SetCell(x, y, chr, termbox.Attribute(t.Fg), termbox.Attribute(t.Bg))
50                 }
51         }
52 }
53
54 func (t *Textbox) keyEvent(ui *Ui, mod Modifier, key Key) {
55         redraw := false
56         switch key {
57         case KeyCtrlC:
58                 t.Text = ""
59                 redraw = true
60         case KeyEnter:
61                 if t.Input != nil {
62                         t.Input(ui, t, t.Text)
63                 }
64                 t.Text = ""
65                 redraw = true
66         case KeySpace:
67                 t.Text = t.Text + " "
68                 redraw = true
69         case KeyBackspace:
70         case KeyBackspace2:
71                 if len(t.Text) > 0 {
72                         if r, size := utf8.DecodeLastRuneInString(t.Text); r != utf8.RuneError {
73                                 t.Text = t.Text[:len(t.Text)-size]
74                                 redraw = true
75                         }
76                 }
77         }
78         if redraw {
79                 t.draw(ui)
80                 termbox.Flush()
81         }
82 }
83
84 func (t *Textbox) characterEvent(ui *Ui, chr rune) {
85         t.Text = t.Text + string(chr)
86         t.draw(ui)
87         termbox.Flush()
88 }