1package termui
2
3import (
4 "fmt"
5 "github.com/jroimartin/gocui"
6 "strings"
7)
8
9const errorPopupView = "errorPopupView"
10
11type errorPopup struct {
12 message string
13}
14
15func newErrorPopup() *errorPopup {
16 return &errorPopup{
17 message: "",
18 }
19}
20
21func (ep *errorPopup) keybindings(g *gocui.Gui) error {
22 if err := g.SetKeybinding(errorPopupView, gocui.KeySpace, gocui.ModNone, ep.close); err != nil {
23 return err
24 }
25 if err := g.SetKeybinding(errorPopupView, gocui.KeyEnter, gocui.ModNone, ep.close); err != nil {
26 return err
27 }
28
29 return nil
30}
31
32func (ep *errorPopup) layout(g *gocui.Gui) error {
33 if ep.message == "" {
34 return nil
35 }
36
37 maxX, maxY := g.Size()
38
39 width := minInt(30, maxX)
40 wrapped, nblines := word_wrap(ep.message, width-2)
41 height := minInt(nblines+2, maxY)
42 x0 := (maxX - width) / 2
43 y0 := (maxY - height) / 2
44
45 v, err := g.SetView(errorPopupView, x0, y0, x0+width, y0+height)
46 if err != nil {
47 if err != gocui.ErrUnknownView {
48 return err
49 }
50
51 v.Frame = true
52 v.Title = "Error"
53
54 fmt.Fprintf(v, wrapped)
55 }
56
57 if _, err := g.SetCurrentView(errorPopupView); err != nil {
58 return err
59 }
60
61 return nil
62}
63
64func (ep *errorPopup) close(g *gocui.Gui, v *gocui.View) error {
65 ep.message = ""
66 return g.DeleteView(errorPopupView)
67}
68
69func (ep *errorPopup) activate(message string) {
70 ep.message = message
71}
72
73func word_wrap(text string, lineWidth int) (string, int) {
74 words := strings.Fields(strings.TrimSpace(text))
75 if len(words) == 0 {
76 return text, 1
77 }
78 lines := 1
79 wrapped := words[0]
80 spaceLeft := lineWidth - len(wrapped)
81 for _, word := range words[1:] {
82 if len(word)+1 > spaceLeft {
83 wrapped += "\n" + word
84 spaceLeft = lineWidth - len(word)
85 lines++
86 } else {
87 wrapped += " " + word
88 spaceLeft -= 1 + len(word)
89 }
90 }
91
92 return wrapped, lines
93}