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