aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/gizak/termui/widget.go
blob: 80276bf1f1816a19d8807b3fbe4517241773af2d (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.

package termui

import (
    "fmt"
    "sync"
)

// event mixins
type WgtMgr map[string]WgtInfo

type WgtInfo struct {
    Handlers map[string]func(Event)
    WgtRef   Widget
    Id       string
}

type Widget interface {
    Id() string
}

func NewWgtInfo(wgt Widget) WgtInfo {
    return WgtInfo{
        Handlers: make(map[string]func(Event)),
        WgtRef:   wgt,
        Id:       wgt.Id(),
    }
}

func NewWgtMgr() WgtMgr {
    wm := WgtMgr(make(map[string]WgtInfo))
    return wm

}

func (wm WgtMgr) AddWgt(wgt Widget) {
    wm[wgt.Id()] = NewWgtInfo(wgt)
}

func (wm WgtMgr) RmWgt(wgt Widget) {
    wm.RmWgtById(wgt.Id())
}

func (wm WgtMgr) RmWgtById(id string) {
    delete(wm, id)
}

func (wm WgtMgr) AddWgtHandler(id, path string, h func(Event)) {
    if w, ok := wm[id]; ok {
        w.Handlers[path] = h
    }
}

func (wm WgtMgr) RmWgtHandler(id, path string) {
    if w, ok := wm[id]; ok {
        delete(w.Handlers, path)
    }
}

var counter struct {
    sync.RWMutex
    count int
}

func GenId() string {
    counter.Lock()
    defer counter.Unlock()

    counter.count += 1
    return fmt.Sprintf("%d", counter.count)
}

func (wm WgtMgr) WgtHandlersHook() func(Event) {
    return func(e Event) {
        for _, v := range wm {
            if k := findMatch(v.Handlers, e.Path); k != "" {
                v.Handlers[k](e)
            }
        }
    }
}

var DefaultWgtMgr WgtMgr

func (b *Block) Handle(path string, handler func(Event)) {
    if _, ok := DefaultWgtMgr[b.Id()]; !ok {
        DefaultWgtMgr.AddWgt(b)
    }

    DefaultWgtMgr.AddWgtHandler(b.Id(), path, handler)
}