-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
270 lines (244 loc) · 7.15 KB
/
main.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
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strings"
"syscall"
)
func main() {
var debugFile string
var logFile string
var cmdsFile string
var header Header
stdFlagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
stdFlagSet.StringVar(&debugFile, "debug-file", "", "Outputs JSON to this file as well; for debugging what is sent to i3bar.")
stdFlagSet.StringVar(&logFile, "log-file", "", "Logs i3cat events in this file. Defaults to STDERR")
stdFlagSet.StringVar(&cmdsFile, "cmd-file", "$HOME/.i3/i3cat.conf", "File listing of the commands to run. It will read from STDIN if - is provided")
stdFlagSet.IntVar(&header.Version, "header-version", 1, "The i3bar header version")
stdFlagSet.BoolVar(&header.ClickEvents, "header-clickevents", false, "The i3bar header click_events")
decFlagSet := flag.NewFlagSet("decode", flag.ExitOnError)
var decField string
encFlagSet := flag.NewFlagSet("encode", flag.ExitOnError)
var block Block
var singleBlock bool
encFlagSet.BoolVar(&singleBlock, "single", false, "If true, the block will not be in a JSON array. This allows to combine other blocks before sending to i3bar.")
encFlagSet.StringVar(&block.ShortText, "short-text", "", "the block.short_text field to encode.")
encFlagSet.StringVar(&block.Color, "color", "", "the block.color field to encode.")
encFlagSet.IntVar(&block.MinWidth, "min-width", 0, "the block.min_width field to encode.")
encFlagSet.StringVar(&block.Align, "align", "", "the block.align field to encode.")
encFlagSet.StringVar(&block.Name, "name", "", "the block.name field to encode.")
encFlagSet.StringVar(&block.Instance, "instance", "", "the block.instance field to encode.")
encFlagSet.BoolVar(&block.Urgent, "urgent", false, "the block.urgent field to encode.")
encFlagSet.BoolVar(&block.Separator, "separator", true, "the block.separator field to encode.")
encFlagSet.IntVar(&block.SeparatorBlockWidth, "separator-block-width", 0, "the block.separator_block_width field to encode.")
encFlagSet.StringVar(&block.Background, "background", "", "the block.background field to encode.")
encFlagSet.StringVar(&block.Border, "border", "", "the block.border field to encode.")
encFlagSet.StringVar(&block.Markup, "markup", "", "the block.markup field to encode.")
usage := func() {
fmt.Fprintf(os.Stderr, `Usage: i3cat [COMMAND] [ARGS]
If COMMAND is not specified, i3cat will print i3bar blocks to stdout.
`)
stdFlagSet.PrintDefaults()
fmt.Fprintf(os.Stderr, `
decode: FIELD
Reads STDIN and decodes a JSON payload representing a click event; typically sent by i3bar.
It will print the FIELD from the JSON structure to stdout.
Possible fields are name, instance, button, x, y.
`)
decFlagSet.PrintDefaults()
fmt.Fprintf(os.Stderr, `
encode: [OPTS] [FULL_TEXT...]
Concats FULL_TEXT arguments, separated with spaces, and encodes it as an i3bar block JSON payload.
If FULL_TEXT is -, it will read from STDIN instead.
The other fields of an i3bar block are optional and specified with the following options:
`)
encFlagSet.PrintDefaults()
}
switch {
case len(os.Args) > 1 && os.Args[1] == "decode":
if err := decFlagSet.Parse(os.Args[2:]); err != nil {
log.Print(err)
usage()
os.Exit(2)
}
if decFlagSet.NArg() == 0 {
usage()
os.Exit(2)
}
decField = decFlagSet.Arg(0)
if err := DecodeClickEvent(os.Stdout, os.Stdin, decField); err != nil {
log.Fatal(err)
}
case len(os.Args) > 1 && os.Args[1] == "encode":
if err := encFlagSet.Parse(os.Args[2:]); err != nil {
log.Print(err)
usage()
os.Exit(2)
}
switch {
case encFlagSet.NArg() == 0:
fallthrough
case encFlagSet.NArg() == 1 && encFlagSet.Arg(0) == "-":
fullText, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
block.FullText = string(fullText)
case encFlagSet.NArg() > 0:
block.FullText = strings.Join(encFlagSet.Args(), " ")
}
if err := EncodeBlock(os.Stdout, block, singleBlock); err != nil {
log.Fatal(err)
}
default:
if err := stdFlagSet.Parse(os.Args[1:]); err != nil {
log.Print(err)
usage()
os.Exit(2)
}
if stdFlagSet.NArg() > 0 {
usage()
os.Exit(2)
}
CatBlocksToI3Bar(cmdsFile, header, logFile, debugFile)
}
}
func EncodeBlock(w io.Writer, block Block, single bool) error {
var v interface{}
if single {
v = block
} else {
v = []Block{block}
}
return json.NewEncoder(w).Encode(v)
}
func DecodeClickEvent(w io.Writer, r io.Reader, field string) error {
var ce ClickEvent
if err := json.NewDecoder(r).Decode(&ce); err != nil {
return err
}
var v interface{}
switch field {
case "name":
v = ce.Name
case "instance":
v = ce.Instance
case "button":
v = ce.Button
case "x":
v = ce.X
case "y":
v = ce.Y
default:
return fmt.Errorf("unknown property %s", field)
}
fmt.Fprintln(w, v)
return nil
}
func CatBlocksToI3Bar(cmdsFile string, header Header, logFile string, debugFile string) {
// Read and parse commands to run.
var cmdsReader io.ReadCloser
if cmdsFile == "-" {
cmdsReader = ioutil.NopCloser(os.Stdin)
} else {
f, err := os.Open(os.ExpandEnv(cmdsFile))
if err != nil {
log.Fatal(err)
}
cmdsReader = f
}
var commands []string
scanner := bufio.NewScanner(cmdsReader)
for scanner.Scan() {
cmd := strings.TrimSpace(scanner.Text())
if cmd != "" && !strings.HasPrefix(cmd, "#") {
commands = append(commands, cmd)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
if err := cmdsReader.Close(); err != nil {
log.Fatal(err)
}
// Init log output.
if logFile != "" {
f, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
log.Fatal(err)
}
defer func() {
_ = f.Close()
}()
log.SetOutput(f)
}
// Init where i3cat will print its output.
var out io.Writer
if debugFile != "" {
f, err := os.OpenFile(debugFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
log.Fatal(err)
}
defer func() {
_ = f.Close()
}()
out = io.MultiWriter(os.Stdout, f)
} else {
out = os.Stdout
}
// We print the header of i3bar
hb, err := json.Marshal(header)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(out, "%s\n[\n", hb)
// Listen for click events sent from i3bar
cel := NewClickEventsListener(os.Stdin)
go cel.Listen()
// Create the block aggregator and start the commands
blocksCh := make(chan *BlockAggregate)
var cmdios []*CmdIO
ba := NewBlockAggregator(out)
for _, c := range commands {
cmdio, err := NewCmdIO(c)
if err != nil {
log.Fatal(err)
}
cmdios = append(cmdios, cmdio)
if err := cmdio.Start(blocksCh); err != nil {
log.Fatal(err)
} else {
log.Printf("Starting command: %s", c)
}
}
ba.CmdIOs = cmdios
go ba.Aggregate(blocksCh)
ceCh := cel.Notify()
go ba.ForwardClickEvents(ceCh)
// Listen for worthy signals
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
for {
s := <-c
switch s {
case syscall.SIGTERM:
fallthrough
case os.Interrupt:
// Kill all processes on interrupt
log.Println("SIGINT or SIGTERM received: terminating all processes...")
for _, cmdio := range ba.CmdIOs {
if err := cmdio.Close(); err != nil {
log.Println(err)
}
}
os.Exit(0)
}
}
}