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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
package main
import (
"citrons.xyz/talk/client/client"
"citrons.xyz/talk/client/object"
"citrons.xyz/talk/client/buffer"
"citrons.xyz/talk/proto"
"citrons.xyz/talk/tui"
"zgo.at/termfo/keys"
)
type application struct {
client.Client
reconnecting bool
authenticated bool
uid string
cache object.ObjCache
currentBuffer *buffer.Buffer
cmdBuffer cmdBuffer
}
func newApplication(serverAddress string) *application {
var app application
app.Client = client.New(serverAddress)
app.cache = object.NewCache(&app)
app.cmdBuffer.Buffer = buffer.New("buffer")
app.currentBuffer = &app.cmdBuffer.Buffer
app.cmdBuffer.info("connecting to %s", app.Client.Address)
return &app
}
func (a *application) OnConnect() {
a.reconnecting = false
a.cmdBuffer.info("connected to %s", a.Client.Address)
a.auth("test user")
}
func (a *application) OnDisconnect(err error) {
a.authenticated = false
a.uid = ""
if !a.reconnecting {
a.cmdBuffer.err(
"disconnected from %s: %s\nreconnecting...", a.Client.Address, err,
)
a.reconnecting = true
}
}
func (a *application) OnEvent(cmd proto.Command) {
switch cmd.Kind {
case "update":
if len(cmd.Args) > 0 {
a.cache.Update(cmd.Target, cmd.Args[0])
}
case "delete":
a.cache.Gone(cmd.Target)
}
}
func (a *application) OnResponse(requestId string, cmd proto.Command) {
switch cmd.Kind {
case "you-are":
if len(cmd.Args) > 0 {
a.cmdBuffer.info("your name is: %s", cmd.Args[0].Fields[""])
}
}
}
func (a *application) Sub(id string) {
a.Request(proto.NewCmd("s", id), func(cmd proto.Command) {
if cmd.Kind == "i" && len(cmd.Args) > 0 {
a.cache.Update(id, cmd.Args[0])
}
})
}
func (a *application) Unsub(id string) {
a.Request(proto.NewCmd("u", id), nil)
}
func (a *application) GetInfo(id string, callback func(proto.Command)) {
a.Request(proto.NewCmd("i", id), callback)
}
func (a *application) auth(name string) {
callback := func(response proto.Command) {
switch response.Kind {
case "you-are":
if len(response.Args) == 0 {
break
}
me := response.Args[0]
a.authenticated = true
a.uid = me.Id
a.cache.Watch(a.uid)
case "fail":
// todo
}
}
a.Request(proto.NewCmd("auth", "", proto.Object {
"anonymous", "", map[string]string {"": name},
}), callback)
}
func (a *application) onInput(ev tui.Event) {
a.currentBuffer.Scroll(-ev.Mouse.Scroll * 2)
switch ev.Key {
case keys.Up:
a.currentBuffer.Scroll(1)
case keys.Down:
a.currentBuffer.Scroll(-1)
}
}
func (a *application) show() {
tui.Clear()
s := tui.Size()
tui.Push("", tui.Box {
Width: tui.BoxSize(s.Width), Height: tui.BoxSize(s.Height),
})
a.currentBuffer.Show()
tui.Pop()
tui.DrawLayout()
tui.Present()
}
|