aboutsummaryrefslogtreecommitdiffstats
path: root/termui/error_popup.go
blob: 855bd05d5bbc091e07c3d4c21725892a9b65afa1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package termui

import (
	"fmt"
	"github.com/MichaelMure/git-bug/util"
	"github.com/jroimartin/gocui"
)

const errorPopupView = "errorPopupView"

type errorPopup struct {
	message string
}

func newErrorPopup() *errorPopup {
	return &errorPopup{
		message: "",
	}
}

func (ep *errorPopup) keybindings(g *gocui.Gui) error {
	if err := g.SetKeybinding(errorPopupView, gocui.KeySpace, gocui.ModNone, ep.close); err != nil {
		return err
	}
	if err := g.SetKeybinding(errorPopupView, gocui.KeyEnter, gocui.ModNone, ep.close); err != nil {
		return err
	}

	return nil
}

func (ep *errorPopup) layout(g *gocui.Gui) error {
	if ep.message == "" {
		return nil
	}

	maxX, maxY := g.Size()

	width := minInt(30, maxX)
	wrapped, nblines := util.WordWrap(ep.message, width-2)
	height := minInt(nblines+2, maxY)
	x0 := (maxX - width) / 2
	y0 := (maxY - height) / 2

	v, err := g.SetView(errorPopupView, x0, y0, x0+width, y0+height)
	if err != nil {
		if err != gocui.ErrUnknownView {
			return err
		}

		v.Frame = true
		v.Title = "Error"

		fmt.Fprintf(v, wrapped)
	}

	if _, err := g.SetCurrentView(errorPopupView); err != nil {
		return err
	}

	return nil
}

func (ep *errorPopup) close(g *gocui.Gui, v *gocui.View) error {
	ep.message = ""
	return g.DeleteView(errorPopupView)
}

func (ep *errorPopup) activate(message string) {
	ep.message = message
}