error_popup.go

 1package termui
 2
 3import (
 4	"fmt"
 5	"github.com/jroimartin/gocui"
 6	"strings"
 7)
 8
 9const errorPopupView = "errorPopupView"
10
11type errorPopup struct {
12	err string
13}
14
15func newErrorPopup() *errorPopup {
16	return &errorPopup{
17		err: "",
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.err == "" {
34		return nil
35	}
36
37	maxX, maxY := g.Size()
38
39	width := minInt(30, maxX)
40	wrapped, nblines := word_wrap(ep.err, 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
53		fmt.Fprintf(v, wrapped)
54	}
55
56	if _, err := g.SetCurrentView(errorPopupView); err != nil {
57		return err
58	}
59
60	return nil
61}
62
63func (ep *errorPopup) close(g *gocui.Gui, v *gocui.View) error {
64	ep.err = ""
65	return g.DeleteView(errorPopupView)
66}
67
68func (ep *errorPopup) isActive() bool {
69	return ep.err != ""
70}
71
72func word_wrap(text string, lineWidth int) (string, int) {
73	words := strings.Fields(strings.TrimSpace(text))
74	if len(words) == 0 {
75		return text, 1
76	}
77	lines := 1
78	wrapped := words[0]
79	spaceLeft := lineWidth - len(wrapped)
80	for _, word := range words[1:] {
81		if len(word)+1 > spaceLeft {
82			wrapped += "\n" + word
83			spaceLeft = lineWidth - len(word)
84			lines++
85		} else {
86			wrapped += " " + word
87			spaceLeft -= 1 + len(word)
88		}
89	}
90
91	return wrapped, lines
92}