-
Notifications
You must be signed in to change notification settings - Fork 16
/
subscribe.go
386 lines (346 loc) · 10.2 KB
/
subscribe.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
375
376
377
378
379
380
381
382
383
384
385
386
package i3
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net"
"time"
)
// Event is an event received from i3.
//
// Type-assert or type-switch on Event to obtain a more specific type.
type Event interface{}
// WorkspaceEvent contains details about various workspace-related changes.
//
// See https://i3wm.org/docs/ipc.html#_workspace_event for more details.
type WorkspaceEvent struct {
Change string `json:"change"`
Current Node `json:"current"`
Old Node `json:"old"`
}
// OutputEvent contains details about various output-related changes.
//
// See https://i3wm.org/docs/ipc.html#_output_event for more details.
type OutputEvent struct {
Change string `json:"change"`
}
// ModeEvent contains details about various mode-related changes.
//
// See https://i3wm.org/docs/ipc.html#_mode_event for more details.
type ModeEvent struct {
Change string `json:"change"`
PangoMarkup bool `json:"pango_markup"`
}
// WindowEvent contains details about various window-related changes.
//
// See https://i3wm.org/docs/ipc.html#_window_event for more details.
type WindowEvent struct {
Change string `json:"change"`
Container Node `json:"container"`
}
// BarconfigUpdateEvent contains details about various bar config-related changes.
//
// See https://i3wm.org/docs/ipc.html#_barconfig_update_event for more details.
type BarconfigUpdateEvent BarConfig
// BindingEvent contains details about various binding-related changes.
//
// See https://i3wm.org/docs/ipc.html#_binding_event for more details.
type BindingEvent struct {
Change string `json:"change"`
Binding struct {
Command string `json:"command"`
EventStateMask []string `json:"event_state_mask"`
InputCode int64 `json:"input_code"`
Symbol string `json:"symbol"`
InputType string `json:"input_type"`
} `json:"binding"`
}
// ShutdownEvent contains the reason for which the IPC connection is about to be
// shut down.
//
// See https://i3wm.org/docs/ipc.html#_shutdown_event for more details.
type ShutdownEvent struct {
Change string `json:"change"`
}
// TickEvent contains the payload of the last tick command.
//
// See https://i3wm.org/docs/ipc.html#_tick_event for more details.
type TickEvent struct {
First bool `json:"first"`
Payload string `json:"payload"`
}
type eventReplyType int
const (
eventReplyTypeWorkspace eventReplyType = iota
eventReplyTypeOutput
eventReplyTypeMode
eventReplyTypeWindow
eventReplyTypeBarconfigUpdate
eventReplyTypeBinding
eventReplyTypeShutdown
eventReplyTypeTick
)
const (
eventFlagMask = uint32(0x80000000)
eventTypeMask = ^eventFlagMask
)
// EventReceiver is not safe for concurrent use.
type EventReceiver struct {
types []EventType // for re-subscribing on io.EOF
sock *socket
conn net.Conn
ev Event
err error
reconnect bool
closed bool
}
// Event returns the most recent event received from i3 by a call to Next.
func (r *EventReceiver) Event() Event {
return r.ev
}
func (r *EventReceiver) subscribe() error {
var err error
if r.conn != nil {
r.conn.Close()
}
if wasRestart {
r.reconnect = false
}
r.sock, r.conn, err = getIPCSocket(r.reconnect)
r.reconnect = true
if err != nil {
return err
}
payload, err := json.Marshal(r.types)
if err != nil {
return err
}
b, err := r.sock.roundTrip(messageTypeSubscribe, payload)
if err != nil {
return err
}
var reply struct {
Success bool `json:"success"`
}
if err := json.Unmarshal(b.Payload, &reply); err != nil {
return err
}
if !reply.Success {
return fmt.Errorf("could not subscribe, check the i3 log")
}
r.err = nil
return nil
}
func (r *EventReceiver) next() (Event, error) {
reply, err := r.sock.recvMsg()
if err != nil {
return nil, err
}
if (uint32(reply.Type) & eventFlagMask) == 0 {
return nil, fmt.Errorf("unexpectedly did not receive an event")
}
t := uint32(reply.Type) & eventTypeMask
switch eventReplyType(t) {
case eventReplyTypeWorkspace:
var e WorkspaceEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeOutput:
var e OutputEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeMode:
var e ModeEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeWindow:
var e WindowEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeBarconfigUpdate:
var e BarconfigUpdateEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeBinding:
var e BindingEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeShutdown:
var e ShutdownEvent
return &e, json.Unmarshal(reply.Payload, &e)
case eventReplyTypeTick:
var e TickEvent
return &e, json.Unmarshal(reply.Payload, &e)
}
return nil, fmt.Errorf("BUG: event reply type %d not implemented yet", t)
}
// Next advances the EventReceiver to the next event, which will then be
// available through the Event method. It returns false when reaching an
// error. After Next returns false, the Close method will return the first
// error.
//
// Until you call Close, you must call Next in a loop for every EventReceiver
// (usually in a separate goroutine), otherwise i3 will deadlock as soon as the
// UNIX socket buffer is full of unprocessed events.
func (r *EventReceiver) Next() bool {
Outer:
for r.err == nil {
r.ev, r.err = r.next()
if r.err == nil {
return true // happy path
}
if r.closed {
return false
}
// reconnect
start := time.Now()
for time.Since(start) < reconnectTimeout && (r.sock == nil || i3Running()) {
if err := r.subscribe(); err == nil {
continue Outer
} else {
r.err = err
}
// Reconnect within [10, 20) ms to prevent CPU-starving i3.
time.Sleep(time.Duration(10+rand.Int63n(10)) * time.Millisecond)
}
}
return r.err == nil
}
// Close closes the connection to i3. If you don’t ever call Close, you must
// consume events via Next to prevent i3 from deadlocking.
func (r *EventReceiver) Close() error {
r.closed = true
if r.conn != nil {
if r.err == nil {
r.err = r.conn.Close()
} else {
// Retain the original error.
r.conn.Close()
}
r.conn = nil
r.sock = nil
}
return r.err
}
// EventType indicates the specific kind of event to subscribe to.
type EventType string
// i3 currently implements the following event types:
const (
WorkspaceEventType EventType = "workspace" // since 4.0
OutputEventType EventType = "output" // since 4.0
ModeEventType EventType = "mode" // since 4.4
WindowEventType EventType = "window" // since 4.5
BarconfigUpdateEventType EventType = "barconfig_update" // since 4.6
BindingEventType EventType = "binding" // since 4.9
ShutdownEventType EventType = "shutdown" // since 4.14
TickEventType EventType = "tick" // since 4.15
)
type majorMinor struct {
major int64
minor int64
}
var eventAtLeast = map[EventType]majorMinor{
WorkspaceEventType: {4, 0},
OutputEventType: {4, 0},
ModeEventType: {4, 4},
WindowEventType: {4, 5},
BarconfigUpdateEventType: {4, 6},
BindingEventType: {4, 9},
ShutdownEventType: {4, 14},
TickEventType: {4, 15},
}
// Subscribe returns an EventReceiver for receiving events of the specified
// types from i3.
//
// Unless the ordering of events matters to your use-case, you are encouraged to
// call Subscribe once per event type, so that you can use type assertions
// instead of type switches.
//
// Subscribe is supported in i3 ≥ v4.0 (2011-07-31).
func Subscribe(eventTypes ...EventType) *EventReceiver {
// Error out early in case any requested event type is not yet supported by
// the running i3 version.
for _, t := range eventTypes {
if err := AtLeast(eventAtLeast[t].major, eventAtLeast[t].minor); err != nil {
return &EventReceiver{err: err}
}
}
return &EventReceiver{types: eventTypes}
}
// restart runs the restart i3 command without entering an infinite loop: as
// RUN_COMMAND with payload "restart" does not result in a reply, we subscribe
// to the shutdown event beforehand (on a dedicated connection), which we can
// receive instead of a reply.
func restart(firstAttempt bool) error {
sock, conn, err := getIPCSocket(!firstAttempt)
if err != nil {
return err
}
defer conn.Close()
payload, err := json.Marshal([]EventType{ShutdownEventType})
if err != nil {
return err
}
b, err := sock.roundTrip(messageTypeSubscribe, payload)
if err != nil {
return err
}
var sreply struct {
Success bool `json:"success"`
}
if err := json.Unmarshal(b.Payload, &sreply); err != nil {
return err
}
if !sreply.Success {
return fmt.Errorf("could not subscribe, check the i3 log")
}
rreply, err := sock.roundTrip(messageTypeRunCommand, []byte("restart"))
if err != nil {
return err
}
if (uint32(rreply.Type) & eventFlagMask) == 0 {
var crs []CommandResult
err = json.Unmarshal(rreply.Payload, &crs)
if err == nil {
for _, cr := range crs {
if !cr.Success {
return &CommandUnsuccessfulError{
command: "restart",
cr: cr,
}
}
}
}
return nil // restart command successful
}
t := uint32(rreply.Type) & eventTypeMask
if got, want := eventReplyType(t), eventReplyTypeShutdown; got != want {
return fmt.Errorf("unexpected reply type: got %d, want %d", got, want)
}
return nil // shutdown event received
}
var wasRestart = false
// Restart sends the restart command to i3. Sending restart via RunCommand will
// result in a deadlock: since i3 restarts before it sends the reply to the
// restart command, RunCommand will retry the command indefinitely.
//
// Restart is supported in i3 ≥ v4.14 (2017-09-04).
func Restart() error {
if err := AtLeast(eventAtLeast[ShutdownEventType].major, eventAtLeast[ShutdownEventType].minor); err != nil {
return err
}
if AtLeast(4, 17) == nil {
_, err := roundTrip(messageTypeRunCommand, []byte("restart"))
return err
}
log.Println("preventing any further X11 connections to work around issue #3")
wasRestart = true
var (
firstAttempt = true
start = time.Now()
lastErr error
)
for time.Since(start) < reconnectTimeout && (firstAttempt || i3Running()) {
lastErr = restart(firstAttempt)
if lastErr == nil {
return nil // success
}
firstAttempt = false
}
return lastErr
}