]> git.0d.be Git - barnard.git/blob - uiterm/textbox.go
code formatting
[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 Textbox struct {
11         Text   string
12         Fg, Bg Attribute
13
14         Input func(ui *Ui, textbox *Textbox, text string)
15
16         ui             *Ui
17         active         bool
18         x0, y0, x1, y1 int
19 }
20
21 func (t *Textbox) uiInitialize(ui *Ui) {
22         t.ui = ui
23 }
24
25 func (t *Textbox) uiSetActive(active bool) {
26         t.active = active
27         t.uiDraw()
28 }
29
30 func (t *Textbox) uiSetBounds(x0, y0, x1, y1 int) {
31         t.x0 = x0
32         t.y0 = y0
33         t.x1 = x1
34         t.y1 = y1
35         t.uiDraw()
36 }
37
38 func (t *Textbox) uiDraw() {
39         t.ui.beginDraw()
40         defer t.ui.endDraw()
41
42         var setCursor = false
43         reader := strings.NewReader(t.Text)
44         for y := t.y0; y < t.y1; y++ {
45                 for x := t.x0; x < t.x1; x++ {
46                         var chr rune
47                         if ch, _, err := reader.ReadRune(); err != nil {
48                                 if t.active && !setCursor {
49                                         termbox.SetCursor(x, y)
50                                         setCursor = true
51                                 }
52                                 chr = ' '
53                         } else {
54                                 chr = ch
55                         }
56                         termbox.SetCell(x, y, chr, termbox.Attribute(t.Fg), termbox.Attribute(t.Bg))
57                 }
58         }
59 }
60
61 func (t *Textbox) uiKeyEvent(mod Modifier, key Key) {
62         redraw := false
63         switch key {
64         case KeyCtrlC:
65                 t.Text = ""
66                 redraw = true
67         case KeyEnter:
68                 if t.Input != nil {
69                         t.Input(t.ui, t, t.Text)
70                 }
71                 t.Text = ""
72                 redraw = true
73         case KeySpace:
74                 t.Text = t.Text + " "
75                 redraw = true
76         case KeyBackspace:
77         case KeyBackspace2:
78                 if len(t.Text) > 0 {
79                         if r, size := utf8.DecodeLastRuneInString(t.Text); r != utf8.RuneError {
80                                 t.Text = t.Text[:len(t.Text)-size]
81                                 redraw = true
82                         }
83                 }
84         }
85         if redraw {
86                 t.uiDraw()
87         }
88 }
89
90 func (t *Textbox) uiCharacterEvent(chr rune) {
91         t.Text = t.Text + string(chr)
92         t.uiDraw()
93 }