]> git.sur5r.net Git - i3/i3/blob - i3-msg/main.c
i3bar: replace magic numbers with more meaningful constructs
[i3/i3] / i3-msg / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * i3-msg/main.c: Utility which sends messages to a running i3-instance using
8  * IPC via UNIX domain sockets.
9  *
10  * This (in combination with libi3/ipc_send_message.c and
11  * libi3/ipc_recv_message.c) serves as an example for how to send your own
12  * messages to i3.
13  *
14  * Additionally, it’s even useful sometimes :-).
15  *
16  */
17 #include "libi3.h"
18
19 #include <stdio.h>
20 #include <stdbool.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <err.h>
29 #include <stdint.h>
30 #include <getopt.h>
31 #include <limits.h>
32
33 #include <yajl/yajl_parse.h>
34 #include <yajl/yajl_version.h>
35
36 #include <xcb/xcb.h>
37 #include <xcb/xcb_aux.h>
38
39 #include <i3/ipc.h>
40
41 static char *socket_path;
42
43 /*
44  * Having verboselog() and errorlog() is necessary when using libi3.
45  *
46  */
47 void verboselog(char *fmt, ...) {
48     va_list args;
49
50     va_start(args, fmt);
51     vfprintf(stdout, fmt, args);
52     va_end(args);
53 }
54
55 void errorlog(char *fmt, ...) {
56     va_list args;
57
58     va_start(args, fmt);
59     vfprintf(stderr, fmt, args);
60     va_end(args);
61 }
62
63 static char *last_key = NULL;
64
65 typedef struct reply_t {
66     bool success;
67     char *error;
68     char *input;
69     char *errorposition;
70 } reply_t;
71
72 static reply_t last_reply;
73
74 static int reply_boolean_cb(void *params, int val) {
75     if (strcmp(last_key, "success") == 0)
76         last_reply.success = val;
77     return 1;
78 }
79
80 static int reply_string_cb(void *params, const unsigned char *val, size_t len) {
81     char *str = scalloc(len + 1, 1);
82     strncpy(str, (const char *)val, len);
83     if (strcmp(last_key, "error") == 0)
84         last_reply.error = str;
85     else if (strcmp(last_key, "input") == 0)
86         last_reply.input = str;
87     else if (strcmp(last_key, "errorposition") == 0)
88         last_reply.errorposition = str;
89     else
90         free(str);
91     return 1;
92 }
93
94 static int reply_start_map_cb(void *params) {
95     return 1;
96 }
97
98 static int reply_end_map_cb(void *params) {
99     if (!last_reply.success) {
100         fprintf(stderr, "ERROR: Your command: %s\n", last_reply.input);
101         fprintf(stderr, "ERROR:               %s\n", last_reply.errorposition);
102         fprintf(stderr, "ERROR: %s\n", last_reply.error);
103     }
104     return 1;
105 }
106
107 static int reply_map_key_cb(void *params, const unsigned char *keyVal, size_t keyLen) {
108     free(last_key);
109     last_key = scalloc(keyLen + 1, 1);
110     strncpy(last_key, (const char *)keyVal, keyLen);
111     return 1;
112 }
113
114 static yajl_callbacks reply_callbacks = {
115     .yajl_boolean = reply_boolean_cb,
116     .yajl_string = reply_string_cb,
117     .yajl_start_map = reply_start_map_cb,
118     .yajl_map_key = reply_map_key_cb,
119     .yajl_end_map = reply_end_map_cb,
120 };
121
122 /*******************************************************************************
123  * Config reply callbacks
124  *******************************************************************************/
125
126 static char *config_last_key = NULL;
127
128 static int config_string_cb(void *params, const unsigned char *val, size_t len) {
129     char *str = scalloc(len + 1, 1);
130     strncpy(str, (const char *)val, len);
131     if (strcmp(config_last_key, "config") == 0) {
132         fprintf(stdout, "%s", str);
133     }
134     free(str);
135     return 1;
136 }
137
138 static int config_start_map_cb(void *params) {
139     return 1;
140 }
141
142 static int config_end_map_cb(void *params) {
143     return 1;
144 }
145
146 static int config_map_key_cb(void *params, const unsigned char *keyVal, size_t keyLen) {
147     config_last_key = scalloc(keyLen + 1, 1);
148     strncpy(config_last_key, (const char *)keyVal, keyLen);
149     return 1;
150 }
151
152 static yajl_callbacks config_callbacks = {
153     .yajl_string = config_string_cb,
154     .yajl_start_map = config_start_map_cb,
155     .yajl_map_key = config_map_key_cb,
156     .yajl_end_map = config_end_map_cb,
157 };
158
159 int main(int argc, char *argv[]) {
160 #if defined(__OpenBSD__)
161     if (pledge("stdio rpath unix", NULL) == -1)
162         err(EXIT_FAILURE, "pledge");
163 #endif
164     char *env_socket_path = getenv("I3SOCK");
165     if (env_socket_path)
166         socket_path = sstrdup(env_socket_path);
167     else
168         socket_path = NULL;
169     int o, option_index = 0;
170     uint32_t message_type = I3_IPC_MESSAGE_TYPE_RUN_COMMAND;
171     char *payload = NULL;
172     bool quiet = false;
173
174     static struct option long_options[] = {
175         {"socket", required_argument, 0, 's'},
176         {"type", required_argument, 0, 't'},
177         {"version", no_argument, 0, 'v'},
178         {"quiet", no_argument, 0, 'q'},
179         {"help", no_argument, 0, 'h'},
180         {0, 0, 0, 0}};
181
182     char *options_string = "s:t:vhq";
183
184     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
185         if (o == 's') {
186             if (socket_path != NULL)
187                 free(socket_path);
188             socket_path = sstrdup(optarg);
189         } else if (o == 't') {
190             if (strcasecmp(optarg, "command") == 0) {
191                 message_type = I3_IPC_MESSAGE_TYPE_RUN_COMMAND;
192             } else if (strcasecmp(optarg, "run_command") == 0) {
193                 message_type = I3_IPC_MESSAGE_TYPE_RUN_COMMAND;
194             } else if (strcasecmp(optarg, "get_workspaces") == 0) {
195                 message_type = I3_IPC_MESSAGE_TYPE_GET_WORKSPACES;
196             } else if (strcasecmp(optarg, "get_outputs") == 0) {
197                 message_type = I3_IPC_MESSAGE_TYPE_GET_OUTPUTS;
198             } else if (strcasecmp(optarg, "get_tree") == 0) {
199                 message_type = I3_IPC_MESSAGE_TYPE_GET_TREE;
200             } else if (strcasecmp(optarg, "get_marks") == 0) {
201                 message_type = I3_IPC_MESSAGE_TYPE_GET_MARKS;
202             } else if (strcasecmp(optarg, "get_bar_config") == 0) {
203                 message_type = I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG;
204             } else if (strcasecmp(optarg, "get_binding_modes") == 0) {
205                 message_type = I3_IPC_MESSAGE_TYPE_GET_BINDING_MODES;
206             } else if (strcasecmp(optarg, "get_version") == 0) {
207                 message_type = I3_IPC_MESSAGE_TYPE_GET_VERSION;
208             } else if (strcasecmp(optarg, "get_config") == 0) {
209                 message_type = I3_IPC_MESSAGE_TYPE_GET_CONFIG;
210             } else if (strcasecmp(optarg, "send_tick") == 0) {
211                 message_type = I3_IPC_MESSAGE_TYPE_SEND_TICK;
212             } else {
213                 printf("Unknown message type\n");
214                 printf("Known types: run_command, get_workspaces, get_outputs, get_tree, get_marks, get_bar_config, get_binding_modes, get_version, get_config, send_tick\n");
215                 exit(EXIT_FAILURE);
216             }
217         } else if (o == 'q') {
218             quiet = true;
219         } else if (o == 'v') {
220             printf("i3-msg " I3_VERSION "\n");
221             return 0;
222         } else if (o == 'h') {
223             printf("i3-msg " I3_VERSION "\n");
224             printf("i3-msg [-s <socket>] [-t <type>] <message>\n");
225             return 0;
226         } else if (o == '?') {
227             exit(EXIT_FAILURE);
228         }
229     }
230
231     if (socket_path == NULL)
232         socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
233
234     /* Fall back to the default socket path */
235     if (socket_path == NULL)
236         socket_path = sstrdup("/tmp/i3-ipc.sock");
237
238     /* Use all arguments, separated by whitespace, as payload.
239      * This way, you don’t have to do i3-msg 'mark foo', you can use
240      * i3-msg mark foo */
241     while (optind < argc) {
242         if (!payload) {
243             payload = sstrdup(argv[optind]);
244         } else {
245             char *both;
246             sasprintf(&both, "%s %s", payload, argv[optind]);
247             free(payload);
248             payload = both;
249         }
250         optind++;
251     }
252
253     if (!payload)
254         payload = sstrdup("");
255
256     int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
257     if (sockfd == -1)
258         err(EXIT_FAILURE, "Could not create socket");
259
260     struct sockaddr_un addr;
261     memset(&addr, 0, sizeof(struct sockaddr_un));
262     addr.sun_family = AF_LOCAL;
263     strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
264     if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
265         err(EXIT_FAILURE, "Could not connect to i3 on socket \"%s\"", socket_path);
266
267     if (ipc_send_message(sockfd, strlen(payload), message_type, (uint8_t *)payload) == -1)
268         err(EXIT_FAILURE, "IPC: write()");
269     free(payload);
270
271     if (quiet)
272         return 0;
273
274     uint32_t reply_length;
275     uint32_t reply_type;
276     uint8_t *reply;
277     int ret;
278     if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
279         if (ret == -1)
280             err(EXIT_FAILURE, "IPC: read()");
281         exit(1);
282     }
283     if (reply_type != message_type)
284         errx(EXIT_FAILURE, "IPC: Received reply of type %d but expected %d", reply_type, message_type);
285     /* For the reply of commands, have a look if that command was successful.
286      * If not, nicely format the error message. */
287     if (reply_type == I3_IPC_REPLY_TYPE_COMMAND) {
288         yajl_handle handle = yajl_alloc(&reply_callbacks, NULL, NULL);
289         yajl_status state = yajl_parse(handle, (const unsigned char *)reply, reply_length);
290         yajl_free(handle);
291
292         switch (state) {
293             case yajl_status_ok:
294                 break;
295             case yajl_status_client_canceled:
296             case yajl_status_error:
297                 errx(EXIT_FAILURE, "IPC: Could not parse JSON reply.");
298         }
299
300         /* NB: We still fall-through and print the reply, because even if one
301          * command failed, that doesn’t mean that all commands failed. */
302     } else if (reply_type == I3_IPC_REPLY_TYPE_CONFIG) {
303         yajl_handle handle = yajl_alloc(&config_callbacks, NULL, NULL);
304         yajl_status state = yajl_parse(handle, (const unsigned char *)reply, reply_length);
305         yajl_free(handle);
306
307         switch (state) {
308             case yajl_status_ok:
309                 break;
310             case yajl_status_client_canceled:
311             case yajl_status_error:
312                 errx(EXIT_FAILURE, "IPC: Could not parse JSON reply.");
313         }
314
315         goto exit;
316     }
317     printf("%.*s\n", reply_length, reply);
318
319 exit:
320     free(reply);
321
322     close(sockfd);
323
324     return 0;
325 }