]> git.sur5r.net Git - i3/i3/blob - i3bar/src/ipc.c
Make i3bar get its config from i3 via IPC
[i3/i3] / i3bar / src / ipc.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3bar - an xcb-based status- and ws-bar for i3
5  *
6  * © 2010-2011 Axel Wagner and contributors
7  *
8  * See file LICNSE for license information
9  *
10  * src/ipc.c: Communicating with i3
11  *
12  */
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <stdint.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 #include <i3/ipc.h>
22 #include <ev.h>
23
24 #include "common.h"
25
26 ev_io      *i3_connection;
27 ev_timer   *reconn = NULL;
28
29 const char *sock_path;
30
31 typedef void(*handler_t)(char*);
32
33 /*
34  * Retry to connect.
35  *
36  */
37 void retry_connection(struct ev_loop *loop, ev_timer *w, int events) {
38     static int retries = 8;
39     if (init_connection(sock_path) == 0) {
40         if (retries == 0) {
41             ELOG("Retried 8 times - connection failed!\n");
42             exit(EXIT_FAILURE);
43         }
44         retries--;
45         return;
46     }
47     retries = 8;
48     ev_timer_stop(loop, w);
49     subscribe_events();
50
51     /* We get the current outputs and workspaces, to
52      * reconfigure all bars with the current configuration */
53     i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_OUTPUTS, NULL);
54     if (!config.disable_ws) {
55         i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_WORKSPACES, NULL);
56     }
57 }
58
59 /*
60  * Schedule a reconnect
61  *
62  */
63 void reconnect() {
64     if (reconn == NULL) {
65         if ((reconn = malloc(sizeof(ev_timer))) == NULL) {
66             ELOG("malloc() failed: %s\n", strerror(errno));
67             exit(EXIT_FAILURE);
68         }
69     } else {
70         ev_timer_stop(main_loop, reconn);
71     }
72     ev_timer_init(reconn, retry_connection, 0.25, 0.25);
73     ev_timer_start(main_loop, reconn);
74 }
75
76 /*
77  * Called, when we get a reply to a command from i3.
78  * Since i3 does not give us much feedback on commands, we do not much
79  *
80  */
81 void got_command_reply(char *reply) {
82     /* TODO: Error handling for command-replies */
83 }
84
85 /*
86  * Called, when we get a reply with workspaces-data
87  *
88  */
89 void got_workspace_reply(char *reply) {
90     DLOG("Got Workspace-Data!\n");
91     parse_workspaces_json(reply);
92     draw_bars();
93 }
94
95 /*
96  * Called, when we get a reply for a subscription.
97  * Since i3 does not give us much feedback on commands, we do not much
98  *
99  */
100 void got_subscribe_reply(char *reply) {
101     DLOG("Got Subscribe Reply: %s\n", reply);
102     /* TODO: Error handling for subscribe-commands */
103 }
104
105 /*
106  * Called, when we get a reply with outputs-data
107  *
108  */
109 void got_output_reply(char *reply) {
110     DLOG("Parsing Outputs-JSON...\n");
111     parse_outputs_json(reply);
112     DLOG("Reconfiguring Windows...\n");
113     realloc_sl_buffer();
114     reconfig_windows();
115 }
116
117 /*
118  * Called when we get the configuration for our bar instance
119  *
120  */
121 void got_bar_config(char *reply) {
122     DLOG("Received bar config \"%s\"\n", reply);
123     /* We initiate the main-function by requesting infos about the outputs and
124      * workspaces. Everything else (creating the bars, showing the right workspace-
125      * buttons and more) is taken care of by the event-drivenness of the code */
126     i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_OUTPUTS, NULL);
127     parse_config_json(reply);
128
129     /* Now we can actually use 'config', so let's subscribe to the appropriate
130      * events and request the workspaces if necessary. */
131     subscribe_events();
132     if (!config.disable_ws)
133         i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_WORKSPACES, NULL);
134
135     /* Initialize the rest of XCB */
136     init_xcb_late(config.fontname);
137
138     /* Resolve color strings to colorpixels and save them, then free the strings. */
139     init_colors(&(config.colors));
140     free_colors(&(config.colors));
141
142     /* The name of this function is actually misleading. Even if no command is
143      * specified, this function initiates the watchers to listen on stdin and
144      * react accordingly */
145     start_child(config.command);
146     FREE(config.command);
147 }
148
149 /* Data-structure to easily call the reply-handlers later */
150 handler_t reply_handlers[] = {
151     &got_command_reply,
152     &got_workspace_reply,
153     &got_subscribe_reply,
154     &got_output_reply,
155     NULL,
156     NULL,
157     &got_bar_config,
158 };
159
160 /*
161  * Called, when a workspace-event arrives (i.e. the user changed the workspace)
162  *
163  */
164 void got_workspace_event(char *event) {
165     DLOG("Got Workspace Event!\n");
166     i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_WORKSPACES, NULL);
167 }
168
169 /*
170  * Called, when an output-event arrives (i.e. the screen-configuration changed)
171  *
172  */
173 void got_output_event(char *event) {
174     DLOG("Got Output Event!\n");
175     i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_OUTPUTS, NULL);
176     if (!config.disable_ws) {
177         i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_WORKSPACES, NULL);
178     }
179 }
180
181 /* Data-structure to easily call the reply-handlers later */
182 handler_t event_handlers[] = {
183     &got_workspace_event,
184     &got_output_event
185 };
186
187 /*
188  * Called, when we get a message from i3
189  *
190  */
191 void got_data(struct ev_loop *loop, ev_io *watcher, int events) {
192     DLOG("Got data!\n");
193     int fd = watcher->fd;
194
195     /* First we only read the header, because we know its length */
196     uint32_t header_len = strlen(I3_IPC_MAGIC) + sizeof(uint32_t)*2;
197     char *header = malloc(header_len);
198     if (header == NULL) {
199         ELOG("Could not allocate memory: %s\n", strerror(errno));
200         exit(EXIT_FAILURE);
201     }
202
203     /* We first parse the fixed-length IPC-header, to know, how much data
204      * we have to expect */
205     uint32_t rec = 0;
206     while (rec < header_len) {
207         int n = read(fd, header + rec, header_len - rec);
208         if (n == -1) {
209             ELOG("read() failed: %s\n", strerror(errno));
210             exit(EXIT_FAILURE);
211         }
212         if (n == 0) {
213             /* EOF received. We try to recover a few times, because most likely
214              * i3 just restarted */
215             ELOG("EOF received, try to recover...\n");
216             destroy_connection();
217             reconnect();
218             return;
219         }
220         rec += n;
221     }
222
223     if (strncmp(header, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC))) {
224         ELOG("Wrong magic code: %.*s\n Expected: %s\n",
225              (int) strlen(I3_IPC_MAGIC),
226              header,
227              I3_IPC_MAGIC);
228         exit(EXIT_FAILURE);
229     }
230
231     char *walk = header + strlen(I3_IPC_MAGIC);
232     uint32_t size;
233     memcpy(&size, (uint32_t*)walk, sizeof(uint32_t));
234     walk += sizeof(uint32_t);
235     uint32_t type;
236     memcpy(&type, (uint32_t*)walk, sizeof(uint32_t));
237
238     /* Now that we know, what to expect, we can start read()ing the rest
239      * of the message */
240     char *buffer = malloc(size + 1);
241     if (buffer == NULL) {
242         /* EOF received. We try to recover a few times, because most likely
243          * i3 just restarted */
244         ELOG("EOF received, try to recover...\n");
245         destroy_connection();
246         reconnect();
247         return;
248     }
249     rec = 0;
250
251     while (rec < size) {
252         int n = read(fd, buffer + rec, size - rec);
253         if (n == -1) {
254             ELOG("read() failed: %s\n", strerror(errno));
255             exit(EXIT_FAILURE);
256         }
257         if (n == 0) {
258             ELOG("Nothing to read!\n");
259             exit(EXIT_FAILURE);
260         }
261         rec += n;
262     }
263     buffer[size] = '\0';
264
265     /* And call the callback (indexed by the type) */
266     if (type & (1 << 31)) {
267         type ^= 1 << 31;
268         event_handlers[type](buffer);
269     } else {
270         if (reply_handlers[type])
271             reply_handlers[type](buffer);
272     }
273
274     FREE(header);
275     FREE(buffer);
276 }
277
278 /*
279  * Sends a Message to i3.
280  * type must be a valid I3_IPC_MESSAGE_TYPE (see i3/ipc.h for further information)
281  *
282  */
283 int i3_send_msg(uint32_t type, const char *payload) {
284     uint32_t len = 0;
285     if (payload != NULL) {
286         len = strlen(payload);
287     }
288
289     /* We are a wellbehaved client and send a proper header first */
290     uint32_t to_write = strlen (I3_IPC_MAGIC) + sizeof(uint32_t)*2 + len;
291     /* TODO: I'm not entirely sure if this buffer really has to contain more
292      * than the pure header (why not just write() the payload from *payload?),
293      * but we leave it for now */
294     char *buffer = malloc(to_write);
295     if (buffer == NULL) {
296         ELOG("Could not allocate memory: %s\n", strerror(errno));
297         exit(EXIT_FAILURE);
298     }
299
300     char *walk = buffer;
301
302     strncpy(buffer, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC));
303     walk += strlen(I3_IPC_MAGIC);
304     memcpy(walk, &len, sizeof(uint32_t));
305     walk += sizeof(uint32_t);
306     memcpy(walk, &type, sizeof(uint32_t));
307     walk += sizeof(uint32_t);
308
309     if (payload != NULL)
310         strncpy(walk, payload, len);
311
312     uint32_t written = 0;
313
314     while (to_write > 0) {
315         int n = write(i3_connection->fd, buffer + written, to_write);
316         if (n == -1) {
317             ELOG("write() failed: %s\n", strerror(errno));
318             exit(EXIT_FAILURE);
319         }
320
321         to_write -= n;
322         written += n;
323     }
324
325     FREE(buffer);
326
327     return 1;
328 }
329
330 /*
331  * Initiate a connection to i3.
332  * socket-path must be a valid path to the ipc_socket of i3
333  *
334  */
335 int init_connection(const char *socket_path) {
336     sock_path = socket_path;
337     int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
338     if (sockfd == -1) {
339         ELOG("Could not create Socket: %s\n", strerror(errno));
340         exit(EXIT_FAILURE);
341     }
342
343     struct sockaddr_un addr;
344     memset(&addr, 0, sizeof(struct sockaddr_un));
345     addr.sun_family = AF_LOCAL;
346     strcpy(addr.sun_path, sock_path);
347     if (connect(sockfd, (const struct sockaddr*) &addr, sizeof(struct sockaddr_un)) < 0) {
348         ELOG("Could not connect to i3! %s: %s\n", sock_path, strerror(errno));
349         reconnect();
350         return 0;
351     }
352
353     i3_connection = malloc(sizeof(ev_io));
354     if (i3_connection == NULL) {
355         ELOG("malloc() failed: %s\n", strerror(errno));
356         exit(EXIT_FAILURE);
357     }
358     ev_io_init(i3_connection, &got_data, sockfd, EV_READ);
359     ev_io_start(main_loop, i3_connection);
360     return 1;
361 }
362
363 /*
364  * Destroy the connection to i3.
365  */
366 void destroy_connection() {
367     close(i3_connection->fd);
368     ev_io_stop(main_loop, i3_connection);
369 }
370
371 /*
372  * Subscribe to all the i3-events, we need
373  *
374  */
375 void subscribe_events() {
376     if (config.disable_ws) {
377         i3_send_msg(I3_IPC_MESSAGE_TYPE_SUBSCRIBE, "[ \"output\" ]");
378     } else {
379         i3_send_msg(I3_IPC_MESSAGE_TYPE_SUBSCRIBE, "[ \"workspace\", \"output\" ]");
380     }
381 }