This repository has been archived by the owner on Apr 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
typing.go
322 lines (255 loc) · 5.68 KB
/
typing.go
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package typing
import (
"html"
"sort"
"time"
"github.com/diamondburned/arikawa/discord"
"github.com/diamondburned/arikawa/gateway"
"github.com/diamondburned/arikawa/state"
"github.com/diamondburned/gtkcord3/gtkcord/components/animations"
"github.com/diamondburned/gtkcord3/gtkcord/gtkutils"
"github.com/diamondburned/gtkcord3/gtkcord/semaphore"
"github.com/diamondburned/gtkcord3/internal/humanize"
"github.com/diamondburned/gtkcord3/internal/log"
"github.com/gotk3/gotk3/gtk"
"github.com/gotk3/gotk3/pango"
"github.com/sasha-s/go-deadlock"
)
const TypingTimeout = 8 * time.Second
var typingHandler chan *State
func initHandler() {
if typingHandler == nil {
typingHandler = make(chan *State, 1)
go handler()
}
}
func handler() {
var tOld *State
var tick = time.NewTimer(TypingTimeout)
for {
// First, catch a TypingState
// for tOld == nil {
// tOld = <-typingHandler
// // stop until we get something
// }
// Block until a tick or a typing state
select {
case <-tick.C:
case t := <-typingHandler:
// Drain the ticker if it's not drained:
if !tick.Stop() {
<-tick.C
}
if t != nil {
// Reset the timer to the shortest tick:
if T := t.Shortest(); !T.IsZero() {
tick.Reset(time.Now().Sub(T))
}
}
// Then set the new tOld.
tOld = t
}
// if tOld is nil, skip this turn and let the above for loop do its
// work.
if tOld == nil {
continue
}
// Render the typing state:
tOld.render()
// If there's nothing left to update, mark it.
if tOld.Empty() {
tOld = nil
}
}
}
type State struct {
*gtk.Box
Label *gtk.Label
mu deadlock.Mutex
Users []typingUser
// updated by Render() only
users []string
state *state.State
lastTyped time.Time
}
type typingUser struct {
ID discord.Snowflake
Name string
Time time.Time
}
func NewState(s *state.State) *State {
initHandler()
t := &State{
state: s,
}
// the breathing 3 dot thing
breathing, _ := animations.NewBreathing()
t.Label, _ = gtk.LabelNew("")
t.Label.SetMarginStart(4)
t.Label.SetSingleLineMode(true)
t.Label.SetEllipsize(pango.ELLIPSIZE_END)
t.Box, _ = gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 0)
t.Box.SetHAlign(gtk.ALIGN_START)
t.Box.SetVAlign(gtk.ALIGN_END)
t.Box.SetHExpand(true)
t.Box.Add(breathing)
t.Box.Add(t.Label)
t.Box.SetOpacity(0)
gtkutils.Margin2(t.Box, 0, 10)
return t
}
// Type is async. Kind of.
func (t *State) Type(chID discord.Snowflake) {
now := time.Now()
// if we sent a typing request the past $TypingTimeout:
if now.Add(-TypingTimeout).Before(t.lastTyped) {
return
}
t.lastTyped = now
go func() {
if err := t.state.Typing(chID); err != nil {
log.Errorln("Failed to send typing to ch", chID, ":", err)
}
}()
}
func (t *State) Empty() bool {
t.mu.Lock()
defer t.mu.Unlock()
return len(t.Users) == 0
}
func (t *State) Reset() {
t.mu.Lock()
defer t.mu.Unlock()
t.lastTyped = time.Time{} // zero out
t.Users = t.Users[:0]
semaphore.IdleMust(func() {
t.Label.SetText("")
t.Box.SetOpacity(0)
})
}
func (t *State) Stop() {
t.Reset()
}
func (t *State) render() {
t.mu.Lock()
t.cleanUp()
var text = ""
switch len(t.Users) {
case 0:
// empty text
case 1, 2, 3:
// clear user string
t.users = t.users[:0]
// join
for i := range t.Users {
t.users = append(t.users, t.Users[i].Name)
}
text = humanize.Strings(t.users)
if len(t.Users) == 1 {
text += " is typing..."
} else {
text += " are typing..."
}
default:
text = "Several people are typing..."
}
t.mu.Unlock()
log.Println("Rendered", text)
semaphore.IdleMust(func() {
t.Label.SetMarkup(text)
// Show or hide the breathing animation as well:
if text == "" {
t.Box.SetOpacity(0)
} else {
t.Box.SetOpacity(1)
}
})
}
func (t *State) Update() {
select {
case typingHandler <- t:
default:
log.Println("Not updating typing indicator.")
}
}
func (t *State) Shortest() time.Time {
t.mu.Lock()
defer t.mu.Unlock()
if len(t.Users) == 0 {
return time.Time{}
}
t.sort()
return t.Users[0].Time.Add(-1)
}
func (t *State) cleanUp() {
// now - timeout
now := time.Now().Add(-TypingTimeout)
for i := 0; i < len(t.Users); i++ {
if t.Users[i].Time.Before(now) {
t.Users = append(t.Users[:i], t.Users[i+1:]...)
}
}
}
func (t *State) sort() {
sort.Slice(t.Users, func(i, j int) bool {
// earliest first:
return t.Users[i].Time.Before(t.Users[j].Time)
})
}
func (t *State) Add(typing *gateway.TypingStartEvent) {
if typing.UserID == t.state.Ready.User.ID {
return
}
defer t.Update()
t.mu.Lock()
defer t.mu.Unlock()
// Check duplicates:
for _, u := range t.Users {
if u.ID == typing.UserID {
u.Time = typing.Timestamp.Time()
t.sort()
return
}
}
// Temporarily unlock the mutex:
t.mu.Unlock()
var user = typingUser{
ID: typing.UserID,
Name: "",
Time: typing.Timestamp.Time(),
}
// Attempt 1: if the event gives us the Member struct:
if typing.Member != nil {
user.Name = typing.Member.User.Username
if typing.Member.Nick != "" {
user.Name = typing.Member.Nick
}
}
// Attempt 2: if the event has a GuildID
if user.Name == "" && typing.GuildID.Valid() {
n, err := t.state.MemberDisplayName(typing.GuildID, typing.UserID)
if err == nil {
user.Name = n
}
}
// Attempt 3: just use the ID
if user.Name == "" {
user.Name = typing.UserID.String()
}
// Escape and format the name:
user.Name = `<span weight="bold">` + html.EscapeString(user.Name) + `</span>`
// Lock back the mutex:
t.mu.Lock()
t.Users = append(t.Users, user)
}
func (t *State) Remove(id discord.Snowflake) {
defer t.Update()
t.mu.Lock()
defer t.mu.Unlock()
for i := range t.Users {
if t.Users[i].ID == id {
t.Users = append(t.Users[:i], t.Users[i+1:]...)
return
}
}
}