-
Notifications
You must be signed in to change notification settings - Fork 11
/
i3bar.go
374 lines (312 loc) · 7.57 KB
/
i3bar.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package goi3bar
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"regexp"
"time"
"github.com/denbeigh2000/goi3bar/util"
)
const (
intro = `{ "version": 1, "click_events": true }`
formatString = "%a %d-%b-%y %I:%M:%S"
)
// These colors are the default colors used for alert state if none are given.
const (
DefaultColorGeneral = "#FFFFFF"
DefaultColorOK = "#00FF00"
DefaultColorWarn = "#FFA500"
DefaultColorCrit = "#FF0000"
)
var ColorRegexp = regexp.MustCompile("#[0-9A-Fa-f]{6}")
// These are colors that should be used through the program.
// They will respect custom configuration given by the user in their
// JSON config.
var DefaultColors = Colors{
General: DefaultColorGeneral,
OK: DefaultColorOK,
Warn: DefaultColorWarn,
Crit: DefaultColorCrit,
}
type InvalidColorErr string
func (i InvalidColorErr) Error() string {
return fmt.Sprintf("Invalid color %v, must be of the form #09abCF", string(i))
}
func ParseColor(c string) (string, error) {
if c == "" {
return DefaultColors.General, nil
}
if err := IsColorValid(c); err != nil {
return "", err
}
return c, nil
}
func IsColorValid(c string) (err error) {
if !ColorRegexp.MatchString(c) {
err = InvalidColorErr(c)
}
return
}
type registerer interface {
Register(key string, p Producer)
}
// Output represends a single item on the i3bar.
type Output struct {
Align string `json:"align,omitempty"`
Color string `json:"color,omitempty"`
FullText string `json:"full_text"`
Instance string `json:"instance,omitempty"`
MinWidth string `json:"min_width,omitempty"`
Name string `json:"name,omitempty"`
ShortText string `json:"short_text,omitempty"`
Separator bool `json:"separator"`
Urgent bool `json:"urgent"`
}
type ClickEvent struct {
Name string `json:"name"`
Instance string `json:"instance"`
Button int `json:"button"`
XCoord int `json:"x"`
YCoord int `json:"y"`
}
type Colors struct {
General string `json:"color_general"`
OK string `json:"color_ok"`
Warn string `json:"color_warn"`
Crit string `json:"color_crit"`
}
func (c *Colors) Update(other Colors) error {
if other.General != "" {
if !ColorRegexp.MatchString(other.General) {
return InvalidColorErr(other.General)
}
c.General = other.General
}
if other.OK != "" {
if !ColorRegexp.MatchString(other.OK) {
return InvalidColorErr(other.OK)
}
c.OK = other.OK
}
if other.Warn != "" {
if !ColorRegexp.MatchString(other.Warn) {
return InvalidColorErr(other.Warn)
}
c.Warn = other.Warn
}
if other.Crit != "" {
if !ColorRegexp.MatchString(other.Crit) {
return InvalidColorErr(other.Crit)
}
c.Crit = other.Crit
}
return nil
}
// output is a helper function that sends the initial data to i3bar, and then
// listens to the incoming channel, encodes the data to JSON and writes it to
// stdout
func output(ch <-chan []Output) {
fmt.Fprintf(os.Stdout, "%v\n", intro)
fmt.Fprintf(os.Stdout, "[\n")
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
for o := range ch {
_, err := buf.Write([]byte("["))
if err != nil {
panic(err)
}
isFirst := true
for _, item := range o {
if !isFirst {
_, err := buf.Write([]byte(","))
if err != nil {
panic(err)
}
} else {
isFirst = false
}
err := enc.Encode(item)
if err != nil {
panic(err)
}
}
_, err = buf.Write([]byte("],\n"))
if err != nil {
panic(err)
}
io.Copy(os.Stdout, &buf)
}
}
// Update is a packet, received from a Producer, that updates the current
// Outputs matching the given Key. The Key should correspond to a registered
// Producer.
type Update struct {
Key string
Out []Output
}
// I3bar is the data structure that represents a single i3bar.
type I3bar struct {
producers map[string]Producer
values map[string][]Output
order []string
interval time.Duration
in chan Update
json chan []Output
clicks chan ClickEvent
kill chan struct{}
}
// NewI3bar returns a new *I3bar. The update duration determines how often data
// will be sent to i3bar through stdout
func NewI3bar(update time.Duration) *I3bar {
return &I3bar{
producers: make(map[string]Producer),
order: make([]string, 0),
interval: update,
in: make(chan Update),
json: make(chan []Output),
kill: make(chan struct{}),
clicks: make(chan ClickEvent),
values: make(map[string][]Output),
}
}
// Start starts the i3bar (and all registered Producers)
func (i *I3bar) Start(clicks io.Reader) {
var o <-chan []Output
for k, p := range i.producers {
o = p.Produce(i.kill)
go func(key string, out <-chan []Output) {
for x := range out {
go func() {
// Ensure that all click events are routed back to the original producer
for _, block := range x {
block.Name = key
}
i.in <- Update{
Key: key,
Out: x,
}
}()
}
}(k, o)
}
clickEvents := generateClicks(clicks)
go func() {
defer close(i.clicks)
for e := range clickEvents {
i.clicks <- e
}
}()
go i.loop()
}
// Kill kills the i3bar (and all resgistered Producers)
func (i I3bar) Kill() {
close(i.kill)
close(i.in)
}
// Register registers a new Producer with the I3bar. The I3bar expects incoming
// Update packets to be associated with a key registered with this function
func (i *I3bar) Register(key string, p Producer) {
_, ok := i.producers[key]
if ok {
panic(fmt.Sprintf("Producer %v exists", key))
}
i.producers[key] = p
i.values[key] = nil
i.order = append(i.order, key)
}
// Order determines the order in which items appear on the i3bar. The given
// slice must have each registered key appearing in it exactly once.
func (i *I3bar) Order(keys []string) error {
if len(keys) != len(i.producers) {
return fmt.Errorf("Number of keys must equal number of items, expected %v got %v",
len(i.producers), len(keys))
}
for _, k := range keys {
if _, ok := i.producers[k]; !ok {
return fmt.Errorf("Producer not present: %v", k)
}
}
i.order = keys
return nil
}
func generateClicks(clicks io.Reader) <-chan ClickEvent {
out := make(chan ClickEvent)
clickDecoder := json.NewDecoder(clicks)
go func() {
defer close(out)
// Read opening bracket
_, err := clickDecoder.Token()
if err != nil {
panic(err)
}
event := ClickEvent{}
for clickDecoder.More() {
fmt.Fprintf(os.Stdin, ",")
err := clickDecoder.Decode(&event)
if err != nil {
// Can't decode the click event, probably bad input
continue
}
out <- event
}
_, err = clickDecoder.Token()
switch err {
case nil, io.EOF:
default:
// TODO: Handle with more grace
panic(err)
}
}()
return out
}
// collect is a helper function which retrieves the current Outputs from the
// i3bar.
func (i *I3bar) collect() []Output {
var items []Output
for _, k := range i.order {
v, ok := i.values[k]
if !ok {
panic(fmt.Sprintf("Missing key %v", k))
}
for _, out := range v {
items = append(items, out)
}
}
return items
}
func (i *I3bar) loop() {
defer close(i.json)
t := util.NewTicker(i.interval, true)
defer t.Kill()
go output(i.json)
for {
select {
case update := <-i.in:
i.values[update.Key] = update.Out
case event := <-i.clicks:
producer, ok := i.producers[event.Name]
if !ok {
// Somebody didn't register with the right name, oh well
continue
}
clicker, ok := producer.(Clicker)
if !ok {
// Producer doesn't support clicking, oh well
continue
}
go clicker.Click(event)
case <-t.C:
items := i.collect()
select {
case <-i.kill:
return
case i.json <- items:
continue
}
case <-i.kill:
return
}
}
}