Debian Codegraph @

lib/ui/textinput.go

raw
1 package ui
2
3 import (
4 "context"
5 "math"
6 "strings"
7 "sync"
8 "time"
9
10 "github.com/mattn/go-runewidth"
11
12 "git.sr.ht/~rjarry/aerc/config"
13 "git.sr.ht/~rjarry/aerc/lib/log"
14 "git.sr.ht/~rjarry/go-opt/v2"
15 "go.rockorager.dev/vaxis"
16 )
17
18 // TODO: Attach history providers
19
20 type TextInput struct {
21 sync.Mutex
22 cells int
23 ctx *Context
24 focus bool
25 index int
26 password bool
27 prompt string
28 scroll int
29 text []vaxis.Character
30 change []func(ti *TextInput)
31 focusLost []func(ti *TextInput)
32 tabcomplete func(ctx context.Context, s string) ([]opt.Completion, string)
33 tabcompleteCancel context.CancelFunc
34 completions []opt.Completion
35 prefix string
36 completeIndex int
37 completeDelay time.Duration
38 completeDebouncer *time.Timer
39 completeMinChars int
40 completeKey *config.KeyStroke
41 uiConfig *config.UIConfig
42 }
43
44 // Creates a new TextInput. TextInputs will render a "textbox" in the entire
45 // context they're given, and process keypresses to build a string from user
46 // input.
47 func NewTextInput(text string, ui *config.UIConfig) *TextInput {
48 chars := vaxis.Characters(text)
49 return &TextInput{
50 cells: -1,
51 text: chars,
52 index: len(chars),
53 uiConfig: ui,
54 tabcompleteCancel: func() {},
55 }
56 }
57
58 func (ti *TextInput) Password(password bool) *TextInput {
59 ti.password = password
60 return ti
61 }
62
63 func (ti *TextInput) Prompt(prompt string) *TextInput {
64 ti.prompt = prompt
65 return ti
66 }
67
68 func (ti *TextInput) TabComplete(
69 tabcomplete func(ctx context.Context, s string) ([]opt.Completion, string),
70 d time.Duration, minChars int, key *config.KeyStroke,
71 ) *TextInput {
72 ti.tabcomplete = tabcomplete
73 ti.completeDelay = d
74 ti.completeMinChars = minChars
75 ti.completeKey = key
76 return ti
77 }
78
79 func (ti *TextInput) String() string {
80 return charactersToString(ti.text)
81 }
82
83 func (ti *TextInput) StringLeft() string {
84 if ti.index > len(ti.text) {
85 ti.index = len(ti.text)
86 }
87 left := ti.text[:ti.index]
88 return charactersToString(left)
89 }
90
91 func (ti *TextInput) StringRight() string {
92 if ti.index >= len(ti.text) {
93 return ""
94 }
95 right := ti.text[ti.index:]
96 return charactersToString(right)
97 }
98
99 func charactersToString(chars []vaxis.Character) string {
100 buf := strings.Builder{}
101 for _, ch := range chars {
102 buf.WriteString(ch.Grapheme)
103 }
104 return buf.String()
105 }
106
107 func (ti *TextInput) Set(value string) *TextInput {
108 ti.text = vaxis.Characters(value)
109 ti.index = len(ti.text)
110 ti.scroll = 0
111 return ti
112 }
113
114 func (ti *TextInput) Invalidate() {
115 Invalidate()
116 }
117
118 func (ti *TextInput) Draw(ctx *Context) {
119 scroll := 0
120 if ti.focus {
121 ti.ensureScroll()
122 scroll = ti.scroll
123 }
124 ti.ctx = ctx // gross
125
126 defaultStyle := ti.uiConfig.GetStyle(config.STYLE_DEFAULT)
127 ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', defaultStyle)
128
129 text := ti.text[scroll:]
130 sindex := ti.index - scroll
131 if ti.password {
132 x := ctx.Printf(0, 0, defaultStyle, "%s", ti.prompt)
133 cells := len(ti.text)
134 ctx.Fill(x, 0, cells, 1, '*', defaultStyle)
135 } else {
136 ctx.Printf(0, 0, defaultStyle, "%s%s", ti.prompt, charactersToString(text))
137 }
138 cells := runewidth.StringWidth(charactersToString(text[:sindex]) + ti.prompt)
139 if ti.focus {
140 ctx.SetCursor(cells, 0, vaxis.CursorDefault)
141 ti.drawPopover(ctx)
142 }
143 }
144
145 func (ti *TextInput) drawPopover(ctx *Context) {
146 if len(ti.completions) == 0 {
147 return
148 }
149
150 valWidth := 0
151 descWidth := 0
152 for _, c := range ti.completions {
153 valWidth = max(valWidth, runewidth.StringWidth(unquote(c.Value)))
154 descWidth = max(descWidth, runewidth.StringWidth(c.Description))
155 }
156 descWidth = min(descWidth, 80)
157 // one space padding
158 width := 1 + valWidth
159 if descWidth != 0 {
160 // two spaces padding + parentheses
161 width += 2 + descWidth + 2
162 }
163 // one space padding + gutter
164 width += 2
165
166 cmp := &completions{ti: ti, valWidth: valWidth, descWidth: descWidth}
167 height := len(ti.completions)
168
169 pos := len(ti.prefix) - ti.scroll
170 if pos+width > ctx.Width() {
171 pos = ctx.Width() - width
172 }
173 if pos < 0 {
174 pos = 0
175 }
176
177 ctx.Popover(pos, 0, width, height, cmp)
178 }
179
180 func (ti *TextInput) MouseEvent(localX int, localY int, event vaxis.Event) {
181 if event, ok := event.(vaxis.Mouse); ok {
182 if event.Button == vaxis.MouseLeftButton {
183 if localX >= len(ti.prompt)+1 && localX <= len(ti.text[ti.scroll:])+len(ti.prompt)+1 {
184 ti.index = localX - len(ti.prompt) - 1
185 ti.ensureScroll()
186 ti.Invalidate()
187 }
188 }
189 }
190 }
191
192 func (ti *TextInput) Focus(focus bool) {
193 if ti.focus && !focus {
194 ti.onFocusLost()
195 }
196 ti.focus = focus
197 if focus && ti.ctx != nil {
198 cells := runewidth.StringWidth(charactersToString(ti.text[:ti.index]))
199 ti.ctx.SetCursor(cells+1, 0, vaxis.CursorDefault)
200 } else if !focus && ti.ctx != nil {
201 ti.ctx.HideCursor()
202 }
203 }
204
205 func (ti *TextInput) ensureScroll() {
206 if ti.ctx == nil {
207 return
208 }
209 w := ti.ctx.Width() - len(ti.prompt)
210 if ti.index >= ti.scroll+w {
211 ti.scroll = ti.index - w + 1
212 }
213 if ti.index < ti.scroll {
214 ti.scroll = ti.index
215 }
216 }
217
218 func (ti *TextInput) insert(ch vaxis.Character) {
219 left := ti.text[:ti.index]
220 right := ti.text[ti.index:]
221 ti.text = append(left, append([]vaxis.Character{ch}, right...)...) //nolint:gocritic // intentional append to different slice
222 ti.index++
223 ti.ensureScroll()
224 ti.Invalidate()
225 ti.onChange()
226 }
227
228 func (ti *TextInput) wordStart() int {
229 if len(ti.text) == 0 || ti.index <= 0 {
230 return ti.index
231 }
232 separators := "/'\""
233 i := ti.index - 1
234 for i >= 0 && ti.text[i].Grapheme == " " {
235 i--
236 }
237 if i >= 0 && strings.Contains(separators, ti.text[i].Grapheme) {
238 for i >= 0 && strings.Contains(separators, ti.text[i].Grapheme) {
239 i--
240 }
241 } else {
242 separators += " "
243 for i >= 0 && !strings.Contains(separators, ti.text[i].Grapheme) {
244 i--
245 }
246 }
247 return i + 1
248 }
249
250 func (ti *TextInput) nextWordStart() int {
251 if len(ti.text) == 0 || ti.index >= len(ti.text) {
252 return ti.index
253 }
254 separators := "/'\""
255 i := ti.index
256 if i < len(ti.text) && strings.Contains(separators, ti.text[i].Grapheme) {
257 for i < len(ti.text) && strings.Contains(separators, ti.text[i].Grapheme) {
258 i++
259 }
260 } else {
261 separators += " "
262 for i < len(ti.text) && !strings.Contains(separators, ti.text[i].Grapheme) {
263 i++
264 }
265 }
266 for i < len(ti.text) && ti.text[i].Grapheme == " " {
267 i++
268 }
269
270 // Trailing spaces in the string - first seek to the end of the last
271 // word, only then seek to the end of the string
272 if i == len(ti.text) && ti.text[ti.index].Grapheme != " " {
273 for i > 0 && ti.text[i-1].Grapheme == " " {
274 i--
275 }
276 }
277
278 return i
279 }
280
281 func (ti *TextInput) deleteWord() {
282 if len(ti.text) == 0 || ti.index <= 0 {
283 return
284 }
285 i := ti.wordStart()
286 ti.text = append(ti.text[:i], ti.text[ti.index:]...)
287 ti.index = i
288 ti.ensureScroll()
289 ti.Invalidate()
290 ti.onChange()
291 }
292
293 func (ti *TextInput) deleteLineForward() {
294 if len(ti.text) == 0 || len(ti.text) == ti.index {
295 return
296 }
297
298 ti.text = ti.text[:ti.index]
299 ti.ensureScroll()
300 ti.Invalidate()
301 ti.onChange()
302 }
303
304 func (ti *TextInput) deleteLineBackward() {
305 if len(ti.text) == 0 || ti.index == 0 {
306 return
307 }
308
309 ti.text = ti.text[ti.index:]
310 ti.index = 0
311 ti.ensureScroll()
312 ti.Invalidate()
313 ti.onChange()
314 }
315
316 func (ti *TextInput) deleteChar() {
317 if len(ti.text) > 0 && ti.index != len(ti.text) {
318 ti.text = append(ti.text[:ti.index], ti.text[ti.index+1:]...)
319 ti.ensureScroll()
320 ti.Invalidate()
321 ti.onChange()
322 }
323 }
324
325 func (ti *TextInput) backspace() {
326 if len(ti.text) > 0 && ti.index != 0 {
327 ti.text = append(ti.text[:ti.index-1], ti.text[ti.index:]...)
328 ti.index--
329 ti.ensureScroll()
330 ti.Invalidate()
331 ti.onChange()
332 }
333 }
334
335 func (ti *TextInput) executeCompletion() {
336 if len(ti.completions) > 0 {
337 ti.Set(ti.prefix + ti.completions[ti.completeIndex].Value + ti.StringRight())
338 }
339 }
340
341 func (ti *TextInput) invalidateCompletions() {
342 ti.completions = nil
343 }
344
345 func (ti *TextInput) onChange() {
346 ti.updateCompletions()
347 for _, change := range ti.change {
348 change(ti)
349 }
350 }
351
352 func (ti *TextInput) onFocusLost() {
353 for _, focusLost := range ti.focusLost {
354 focusLost(ti)
355 }
356 }
357
358 func (ti *TextInput) updateCompletions() {
359 if ti.tabcomplete == nil {
360 // no completer
361 return
362 }
363 if ti.completeMinChars == config.MANUAL_COMPLETE {
364 // only manually triggered completion
365 return
366 }
367 if ti.completeDebouncer == nil {
368 ti.completeDebouncer = time.AfterFunc(ti.completeDelay, func() {
369 defer log.PanicHandler()
370 ti.Lock()
371 if len(ti.StringLeft()) >= ti.completeMinChars {
372 ti.showCompletions(false)
373 }
374 ti.Unlock()
375 })
376 } else {
377 ti.completeDebouncer.Stop()
378 ti.completeDebouncer.Reset(ti.completeDelay)
379 }
380 }
381
382 func (ti *TextInput) showCompletions(explicit bool) {
383 if ti.tabcomplete == nil {
384 // no completer
385 return
386 }
387 if ti.tabcompleteCancel != nil {
388 // Cancel any inflight completions we currently have
389 ti.tabcompleteCancel()
390 }
391 ctx, cancel := context.WithCancel(context.Background())
392 ti.tabcompleteCancel = cancel
393 go func() {
394 defer log.PanicHandler()
395 matches, prefix := ti.tabcomplete(ctx, ti.StringLeft())
396 select {
397 case <-ctx.Done():
398 return
399 default:
400 ti.Lock()
401 defer ti.Unlock()
402 ti.completions = matches
403 ti.prefix = prefix
404 if explicit && len(ti.completions) == 1 {
405 // automatically accept if there is only one choice
406 ti.completeIndex = 0
407 ti.executeCompletion()
408 ti.invalidateCompletions()
409 } else {
410 ti.completeIndex = -1
411 }
412 Invalidate()
413 }
414 }()
415 }
416
417 func (ti *TextInput) OnChange(onChange func(ti *TextInput)) {
418 ti.change = append(ti.change, onChange)
419 }
420
421 func (ti *TextInput) OnFocusLost(onFocusLost func(ti *TextInput)) {
422 ti.focusLost = append(ti.focusLost, onFocusLost)
423 }
424
425 func (ti *TextInput) Event(event vaxis.Event) bool {
426 ti.Lock()
427 defer ti.Unlock()
428 if key, ok := event.(vaxis.Key); ok {
429 c := ti.completeKey
430 if c != nil && key.Matches(c.Key, c.Modifiers) {
431 ti.showCompletions(true)
432 return true
433 }
434
435 ti.invalidateCompletions()
436
437 switch {
438 case key.Matches(vaxis.KeyBackspace):
439 ti.backspace()
440 case key.Matches('d', vaxis.ModCtrl), key.Matches(vaxis.KeyDelete):
441 ti.deleteChar()
442 case key.Matches('b', vaxis.ModCtrl), key.Matches(vaxis.KeyLeft):
443 if ti.index > 0 {
444 ti.index--
445 ti.ensureScroll()
446 ti.Invalidate()
447 }
448 case key.Matches('f', vaxis.ModCtrl), key.Matches(vaxis.KeyRight):
449 if ti.index < len(ti.text) {
450 ti.index++
451 ti.ensureScroll()
452 ti.Invalidate()
453 }
454 case key.Matches(vaxis.KeyLeft, vaxis.ModCtrl):
455 ti.index = ti.wordStart()
456 ti.ensureScroll()
457 ti.Invalidate()
458 case key.Matches(vaxis.KeyRight, vaxis.ModCtrl):
459 ti.index = ti.nextWordStart()
460 ti.ensureScroll()
461 ti.Invalidate()
462 case key.Matches('a', vaxis.ModCtrl), key.Matches(vaxis.KeyHome):
463 ti.index = 0
464 ti.ensureScroll()
465 ti.Invalidate()
466 case key.Matches('e', vaxis.ModCtrl), key.Matches(vaxis.KeyEnd):
467 ti.index = len(ti.text)
468 ti.ensureScroll()
469 ti.Invalidate()
470 case key.Matches('k', vaxis.ModCtrl):
471 ti.deleteLineForward()
472 case key.Matches('w', vaxis.ModCtrl):
473 ti.deleteWord()
474 case key.Matches('u', vaxis.ModCtrl):
475 ti.deleteLineBackward()
476 case key.Matches(vaxis.KeyEsc):
477 ti.Invalidate()
478 case key.Text != "":
479 chars := vaxis.Characters(key.Text)
480 for _, ch := range chars {
481 ti.insert(ch)
482 }
483 }
484 }
485 return true
486 }
487
488 type completions struct {
489 ti *TextInput
490 valWidth int
491 descWidth int
492 }
493
494 func unquote(s string) string {
495 if strings.HasPrefix(s, "'") && strings.HasSuffix(s, "'") {
496 s = strings.ReplaceAll(s[1:len(s)-1], `'"'"'`, "'")
497 }
498 return s
499 }
500
501 func (c *completions) Draw(ctx *Context) {
502 bg := c.ti.uiConfig.GetStyle(config.STYLE_COMPLETION_DEFAULT)
503 bgDesc := c.ti.uiConfig.GetStyle(config.STYLE_COMPLETION_DESCRIPTION)
504 gutter := c.ti.uiConfig.GetStyle(config.STYLE_COMPLETION_GUTTER)
505 pill := c.ti.uiConfig.GetStyle(config.STYLE_COMPLETION_PILL)
506 sel := c.ti.uiConfig.GetStyleSelected(config.STYLE_COMPLETION_DEFAULT)
507 selDesc := c.ti.uiConfig.GetStyleSelected(config.STYLE_COMPLETION_DESCRIPTION)
508
509 ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', bg)
510
511 numVisible := ctx.Height()
512 startIdx := 0
513 if len(c.ti.completions) > numVisible && c.index()+1 > numVisible {
514 startIdx = c.index() - (numVisible - 1)
515 }
516 endIdx := startIdx + numVisible - 1
517
518 for idx, opt := range c.ti.completions {
519 if idx < startIdx {
520 continue
521 }
522 if idx > endIdx {
523 continue
524 }
525 val := runewidth.FillRight(unquote(opt.Value), c.valWidth)
526 desc := opt.Description
527 if desc != "" {
528 if runewidth.StringWidth(desc) > c.descWidth {
529 desc = runewidth.Truncate(desc, c.descWidth, "…")
530 }
531 desc = " " + runewidth.FillRight("("+desc+")", c.descWidth+2)
532 }
533 if c.index() == idx {
534 n := ctx.Printf(0, idx-startIdx, sel, " %s", val)
535 ctx.Printf(n, idx-startIdx, selDesc, "%s ", desc)
536 } else {
537 n := ctx.Printf(0, idx-startIdx, bg, " %s", val)
538 ctx.Printf(n, idx-startIdx, bgDesc, "%s ", desc)
539 }
540 }
541
542 percentVisible := float64(numVisible) / float64(len(c.ti.completions))
543 if percentVisible >= 1.0 {
544 return
545 }
546
547 // gutter
548 ctx.Fill(ctx.Width()-1, 0, 1, ctx.Height(), ' ', gutter)
549
550 pillSize := int(math.Ceil(float64(ctx.Height()) * percentVisible))
551 percentScrolled := float64(startIdx) / float64(len(c.ti.completions))
552 pillOffset := int(math.Floor(float64(ctx.Height()) * percentScrolled))
553 ctx.Fill(ctx.Width()-1, pillOffset, 1, pillSize, ' ', pill)
554 }
555
556 func (c *completions) index() int {
557 return c.ti.completeIndex
558 }
559
560 func (c *completions) next() {
561 index := c.index()
562 index++
563 if index >= len(c.ti.completions) {
564 index = -1
565 }
566 c.ti.completeIndex = index
567 Invalidate()
568 }
569
570 func (c *completions) prev() {
571 index := c.index()
572 index--
573 if index < -1 {
574 index = len(c.ti.completions) - 1
575 }
576 c.ti.completeIndex = index
577 Invalidate()
578 }
579
580 func (c *completions) exec() {
581 c.ti.executeCompletion()
582 c.ti.invalidateCompletions()
583 Invalidate()
584 }
585
586 func (c *completions) Event(e vaxis.Event) bool {
587 if e, ok := e.(vaxis.Key); ok {
588 k := c.ti.completeKey
589 if k != nil && e.Matches(k.Key, k.Modifiers) {
590 if len(c.ti.completions) == 1 {
591 c.ti.completeIndex = 0
592 c.exec()
593 } else {
594 stem := findStem(c.ti.completions)
595 if c.needsStem(stem) {
596 c.stem(stem)
597 }
598 c.next()
599 }
600 return true
601 }
602
603 switch {
604 case e.Matches('n', vaxis.ModCtrl), e.Matches(vaxis.KeyDown):
605 c.next()
606 return true
607 case e.Matches(vaxis.KeyTab, vaxis.ModShift),
608 e.Matches('p', vaxis.ModCtrl),
609 e.Matches(vaxis.KeyUp):
610 c.prev()
611 return true
612 case e.Matches(vaxis.KeyEnter), e.Matches('y', vaxis.ModCtrl):
613 if c.index() >= 0 {
614 c.exec()
615 return true
616 }
617 }
618 }
619 return false
620 }
621
622 func (c *completions) needsStem(stem string) bool {
623 if stem == "" || c.index() >= 0 {
624 return false
625 }
626 if len(stem)+len(c.ti.prefix) > len(c.ti.StringLeft()) {
627 return true
628 }
629 return false
630 }
631
632 func (c *completions) stem(stem string) {
633 c.ti.Set(c.ti.prefix + stem + c.ti.StringRight())
634 c.ti.index = len(vaxis.Characters(c.ti.prefix + stem))
635 }
636
637 func findStem(words []opt.Completion) string {
638 if len(words) == 0 {
639 return ""
640 }
641 if len(words) == 1 {
642 return words[0].Value
643 }
644 var stem string
645 stemLen := 1
646 firstWord := []rune(words[0].Value)
647 for {
648 if len(firstWord) < stemLen {
649 return stem
650 }
651 var r rune = firstWord[stemLen-1]
652 for _, word := range words[1:] {
653 runes := []rune(word.Value)
654 if len(runes) < stemLen {
655 return stem
656 }
657 if runes[stemLen-1] != r {
658 return stem
659 }
660 }
661 stem += string(r)
662 stemLen++
663 }
664 }
665
666 func (c *completions) Focus(_ bool) {}
667
668 func (c *completions) Invalidate() {}