1 #define _POSIX_C_SOURCE 200809L
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <strings.h>
6 #include <getopt.h>
7 #include <stdint.h>
8 #include <sys/un.h>
9 #include <sys/socket.h>
10 #include <sys/time.h>
11 #include <ctype.h>
12 #include <unistd.h>
13 #include <json.h>
14 #include "stringop.h"
15 #include "ipc-client.h"
16 #include "log.h"
17 
sway_terminate(int exit_code)18 void sway_terminate(int exit_code) {
19 	exit(exit_code);
20 }
21 
success_object(json_object * result)22 static bool success_object(json_object *result) {
23 	json_object *success;
24 
25 	if (!json_object_object_get_ex(result, "success", &success)) {
26 		return true;
27 	}
28 
29 	return json_object_get_boolean(success);
30 }
31 
32 // Iterate results array and return false if any of them failed
success(json_object * r,bool fallback)33 static bool success(json_object *r, bool fallback) {
34 	if (!json_object_is_type(r, json_type_array)) {
35 		if (json_object_is_type(r, json_type_object)) {
36 			return success_object(r);
37 		}
38 		return fallback;
39 	}
40 
41 	size_t results_len = json_object_array_length(r);
42 	if (!results_len) {
43 		return fallback;
44 	}
45 
46 	for (size_t i = 0; i < results_len; ++i) {
47 		json_object *result = json_object_array_get_idx(r, i);
48 
49 		if (!success_object(result)) {
50 			return false;
51 		}
52 	}
53 
54 	return true;
55 }
56 
pretty_print_cmd(json_object * r)57 static void pretty_print_cmd(json_object *r) {
58 	if (!success_object(r)) {
59 		json_object *error;
60 		if (!json_object_object_get_ex(r, "error", &error)) {
61 			printf("An unknkown error occurred");
62 		} else {
63 			printf("Error: %s\n", json_object_get_string(error));
64 		}
65 	}
66 }
67 
pretty_print_workspace(json_object * w)68 static void pretty_print_workspace(json_object *w) {
69 	json_object *name, *rect, *visible, *output, *urgent, *layout,
70 				*representation, *focused;
71 	json_object_object_get_ex(w, "name", &name);
72 	json_object_object_get_ex(w, "rect", &rect);
73 	json_object_object_get_ex(w, "visible", &visible);
74 	json_object_object_get_ex(w, "output", &output);
75 	json_object_object_get_ex(w, "urgent", &urgent);
76 	json_object_object_get_ex(w, "layout", &layout);
77 	json_object_object_get_ex(w, "representation", &representation);
78 	json_object_object_get_ex(w, "focused", &focused);
79 	printf(
80 		"Workspace %s%s%s%s\n"
81 		"  Output: %s\n"
82 		"  Layout: %s\n"
83 		"  Representation: %s\n\n",
84 		json_object_get_string(name),
85 		json_object_get_boolean(focused) ? " (focused)" : "",
86 		!json_object_get_boolean(visible) ? " (off-screen)" : "",
87 		json_object_get_boolean(urgent) ? " (urgent)" : "",
88 		json_object_get_string(output),
89 		json_object_get_string(layout),
90 		json_object_get_string(representation)
91 	);
92 }
93 
pretty_type_name(const char * name)94 static const char *pretty_type_name(const char *name) {
95 	// TODO these constants probably belong in the common lib
96 	struct {
97 		const char *a;
98 		const char *b;
99 	} type_names[] = {
100 		{ "keyboard", "Keyboard" },
101 		{ "pointer", "Mouse" },
102 		{ "touchpad", "Touchpad" },
103 		{ "tablet_pad", "Tablet pad" },
104 		{ "tablet_tool", "Tablet tool" },
105 		{ "touch", "Touch" },
106 		{ "switch", "Switch" },
107 	};
108 
109 	for (size_t i = 0; i < sizeof(type_names) / sizeof(type_names[0]); ++i) {
110 		if (strcmp(type_names[i].a, name) == 0) {
111 			return type_names[i].b;
112 		}
113 	}
114 
115 	return name;
116 }
117 
pretty_print_input(json_object * i)118 static void pretty_print_input(json_object *i) {
119 	json_object *id, *name, *type, *product, *vendor, *kbdlayout, *libinput;
120 	json_object_object_get_ex(i, "identifier", &id);
121 	json_object_object_get_ex(i, "name", &name);
122 	json_object_object_get_ex(i, "type", &type);
123 	json_object_object_get_ex(i, "product", &product);
124 	json_object_object_get_ex(i, "vendor", &vendor);
125 
126 	const char *fmt =
127 		"Input device: %s\n"
128 		"  Type: %s\n"
129 		"  Identifier: %s\n"
130 		"  Product ID: %d\n"
131 		"  Vendor ID: %d\n";
132 
133 
134 	printf(fmt, json_object_get_string(name),
135 		pretty_type_name(json_object_get_string(type)),
136 		json_object_get_string(id),
137 		json_object_get_int(product),
138 		json_object_get_int(vendor));
139 
140 	if (json_object_object_get_ex(i, "xkb_active_layout_name", &kbdlayout)) {
141 		const char *layout = json_object_get_string(kbdlayout);
142 		printf("  Active Keyboard Layout: %s\n", layout ? layout : "(unnamed)");
143 	}
144 
145 	if (json_object_object_get_ex(i, "libinput", &libinput)) {
146 		json_object *events;
147 		if (json_object_object_get_ex(libinput, "send_events", &events)) {
148 			printf("  Libinput Send Events: %s\n",
149 					json_object_get_string(events));
150 		}
151 	}
152 
153 	printf("\n");
154 }
155 
pretty_print_seat(json_object * i)156 static void pretty_print_seat(json_object *i) {
157 	json_object *name, *capabilities, *devices;
158 	json_object_object_get_ex(i, "name", &name);
159 	json_object_object_get_ex(i, "capabilities", &capabilities);
160 	json_object_object_get_ex(i, "devices", &devices);
161 
162 	const char *fmt =
163 		"Seat: %s\n"
164 		"  Capabilities: %d\n";
165 
166 	printf(fmt, json_object_get_string(name),
167 		json_object_get_int(capabilities));
168 
169 	size_t devices_len = json_object_array_length(devices);
170 	if (devices_len > 0) {
171 		printf("  Devices:\n");
172 		for (size_t i = 0; i < devices_len; ++i) {
173 			json_object *device = json_object_array_get_idx(devices, i);
174 
175 			json_object *device_name;
176 			json_object_object_get_ex(device, "name", &device_name);
177 
178 			printf("    %s\n", json_object_get_string(device_name));
179 		}
180 	}
181 
182 	printf("\n");
183 }
184 
pretty_print_output(json_object * o)185 static void pretty_print_output(json_object *o) {
186 	json_object *name, *rect, *focused, *active, *ws, *current_mode;
187 	json_object_object_get_ex(o, "name", &name);
188 	json_object_object_get_ex(o, "rect", &rect);
189 	json_object_object_get_ex(o, "focused", &focused);
190 	json_object_object_get_ex(o, "active", &active);
191 	json_object_object_get_ex(o, "current_workspace", &ws);
192 	json_object *make, *model, *serial, *scale, *scale_filter, *subpixel,
193 		*transform, *max_render_time, *adaptive_sync_status;
194 	json_object_object_get_ex(o, "make", &make);
195 	json_object_object_get_ex(o, "model", &model);
196 	json_object_object_get_ex(o, "serial", &serial);
197 	json_object_object_get_ex(o, "scale", &scale);
198 	json_object_object_get_ex(o, "scale_filter", &scale_filter);
199 	json_object_object_get_ex(o, "subpixel_hinting", &subpixel);
200 	json_object_object_get_ex(o, "transform", &transform);
201 	json_object_object_get_ex(o, "max_render_time", &max_render_time);
202 	json_object_object_get_ex(o, "adaptive_sync_status", &adaptive_sync_status);
203 	json_object *x, *y;
204 	json_object_object_get_ex(rect, "x", &x);
205 	json_object_object_get_ex(rect, "y", &y);
206 	json_object *modes;
207 	json_object_object_get_ex(o, "modes", &modes);
208 	json_object *width, *height, *refresh;
209 	json_object_object_get_ex(o, "current_mode", &current_mode);
210 	json_object_object_get_ex(current_mode, "width", &width);
211 	json_object_object_get_ex(current_mode, "height", &height);
212 	json_object_object_get_ex(current_mode, "refresh", &refresh);
213 
214 	if (json_object_get_boolean(active)) {
215 		printf(
216 			"Output %s '%s %s %s'%s\n"
217 			"  Current mode: %dx%d @ %f Hz\n"
218 			"  Position: %d,%d\n"
219 			"  Scale factor: %f\n"
220 			"  Scale filter: %s\n"
221 			"  Subpixel hinting: %s\n"
222 			"  Transform: %s\n"
223 			"  Workspace: %s\n",
224 			json_object_get_string(name),
225 			json_object_get_string(make),
226 			json_object_get_string(model),
227 			json_object_get_string(serial),
228 			json_object_get_boolean(focused) ? " (focused)" : "",
229 			json_object_get_int(width),
230 			json_object_get_int(height),
231 			(float)json_object_get_int(refresh) / 1000,
232 			json_object_get_int(x), json_object_get_int(y),
233 			json_object_get_double(scale),
234 			json_object_get_string(scale_filter),
235 			json_object_get_string(subpixel),
236 			json_object_get_string(transform),
237 			json_object_get_string(ws)
238 		);
239 
240 		int max_render_time_int = json_object_get_int(max_render_time);
241 		printf("  Max render time: ");
242 		printf(max_render_time_int == 0 ? "off\n" : "%d ms\n", max_render_time_int);
243 
244 		printf("  Adaptive sync: %s\n",
245 			json_object_get_string(adaptive_sync_status));
246 	} else {
247 		printf(
248 			"Output %s '%s %s %s' (inactive)\n",
249 			json_object_get_string(name),
250 			json_object_get_string(make),
251 			json_object_get_string(model),
252 			json_object_get_string(serial)
253 		);
254 	}
255 
256 	size_t modes_len = json_object_is_type(modes, json_type_array)
257 		? json_object_array_length(modes) : 0;
258 	if (modes_len > 0) {
259 		printf("  Available modes:\n");
260 		for (size_t i = 0; i < modes_len; ++i) {
261 			json_object *mode = json_object_array_get_idx(modes, i);
262 
263 			json_object *mode_width, *mode_height, *mode_refresh;
264 			json_object_object_get_ex(mode, "width", &mode_width);
265 			json_object_object_get_ex(mode, "height", &mode_height);
266 			json_object_object_get_ex(mode, "refresh", &mode_refresh);
267 
268 			printf("    %dx%d @ %f Hz\n", json_object_get_int(mode_width),
269 				json_object_get_int(mode_height),
270 				(float)json_object_get_int(mode_refresh) / 1000);
271 		}
272 	}
273 
274 	printf("\n");
275 }
276 
pretty_print_version(json_object * v)277 static void pretty_print_version(json_object *v) {
278 	json_object *ver;
279 	json_object_object_get_ex(v, "human_readable", &ver);
280 	printf("sway version %s\n", json_object_get_string(ver));
281 }
282 
pretty_print_config(json_object * c)283 static void pretty_print_config(json_object *c) {
284 	json_object *config;
285 	json_object_object_get_ex(c, "config", &config);
286 	printf("%s\n", json_object_get_string(config));
287 }
288 
pretty_print(int type,json_object * resp)289 static void pretty_print(int type, json_object *resp) {
290 	if (type != IPC_COMMAND && type != IPC_GET_WORKSPACES &&
291 			type != IPC_GET_INPUTS && type != IPC_GET_OUTPUTS &&
292 			type != IPC_GET_VERSION && type != IPC_GET_SEATS &&
293 			type != IPC_GET_CONFIG && type != IPC_SEND_TICK) {
294 		printf("%s\n", json_object_to_json_string_ext(resp,
295 			JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED));
296 		return;
297 	}
298 
299 	if (type == IPC_SEND_TICK) {
300 		return;
301 	}
302 
303 	if (type == IPC_GET_VERSION) {
304 		pretty_print_version(resp);
305 		return;
306 	}
307 
308 	if (type == IPC_GET_CONFIG) {
309 		pretty_print_config(resp);
310 		return;
311 	}
312 
313 	json_object *obj;
314 	size_t len = json_object_array_length(resp);
315 	for (size_t i = 0; i < len; ++i) {
316 		obj = json_object_array_get_idx(resp, i);
317 		switch (type) {
318 		case IPC_COMMAND:
319 			pretty_print_cmd(obj);
320 			break;
321 		case IPC_GET_WORKSPACES:
322 			pretty_print_workspace(obj);
323 			break;
324 		case IPC_GET_INPUTS:
325 			pretty_print_input(obj);
326 			break;
327 		case IPC_GET_OUTPUTS:
328 			pretty_print_output(obj);
329 			break;
330 		case IPC_GET_SEATS:
331 			pretty_print_seat(obj);
332 			break;
333 		}
334 	}
335 }
336 
main(int argc,char ** argv)337 int main(int argc, char **argv) {
338 	static bool quiet = false;
339 	static bool raw = false;
340 	static bool monitor = false;
341 	char *socket_path = NULL;
342 	char *cmdtype = NULL;
343 
344 	sway_log_init(SWAY_INFO, NULL);
345 
346 	static struct option long_options[] = {
347 		{"help", no_argument, NULL, 'h'},
348 		{"monitor", no_argument, NULL, 'm'},
349 		{"pretty", no_argument, NULL, 'p'},
350 		{"quiet", no_argument, NULL, 'q'},
351 		{"raw", no_argument, NULL, 'r'},
352 		{"socket", required_argument, NULL, 's'},
353 		{"type", required_argument, NULL, 't'},
354 		{"version", no_argument, NULL, 'v'},
355 		{0, 0, 0, 0}
356 	};
357 
358 	const char *usage =
359 		"Usage: swaymsg [options] [message]\n"
360 		"\n"
361 		"  -h, --help             Show help message and quit.\n"
362 		"  -m, --monitor          Monitor until killed (-t SUBSCRIBE only)\n"
363 		"  -p, --pretty           Use pretty output even when not using a tty\n"
364 		"  -q, --quiet            Be quiet.\n"
365 		"  -r, --raw              Use raw output even if using a tty\n"
366 		"  -s, --socket <socket>  Use the specified socket.\n"
367 		"  -t, --type <type>      Specify the message type.\n"
368 		"  -v, --version          Show the version number and quit.\n";
369 
370 	raw = !isatty(STDOUT_FILENO);
371 
372 	int c;
373 	while (1) {
374 		int option_index = 0;
375 		c = getopt_long(argc, argv, "hmpqrs:t:v", long_options, &option_index);
376 		if (c == -1) {
377 			break;
378 		}
379 		switch (c) {
380 		case 'm': // Monitor
381 			monitor = true;
382 			break;
383 		case 'p': // Pretty
384 			raw = false;
385 			break;
386 		case 'q': // Quiet
387 			quiet = true;
388 			break;
389 		case 'r': // Raw
390 			raw = true;
391 			break;
392 		case 's': // Socket
393 			socket_path = strdup(optarg);
394 			break;
395 		case 't': // Type
396 			cmdtype = strdup(optarg);
397 			break;
398 		case 'v':
399 			fprintf(stdout, "swaymsg version " SWAY_VERSION "\n");
400 			exit(EXIT_SUCCESS);
401 			break;
402 		default:
403 			fprintf(stderr, "%s", usage);
404 			exit(EXIT_FAILURE);
405 		}
406 	}
407 
408 	if (!cmdtype) {
409 		cmdtype = strdup("command");
410 	}
411 	if (!socket_path) {
412 		socket_path = get_socketpath();
413 		if (!socket_path) {
414 			if (quiet) {
415 				exit(EXIT_FAILURE);
416 			}
417 			sway_abort("Unable to retrieve socket path");
418 		}
419 	}
420 
421 	uint32_t type = IPC_COMMAND;
422 
423 	if (strcasecmp(cmdtype, "command") == 0) {
424 		type = IPC_COMMAND;
425 	} else if (strcasecmp(cmdtype, "get_workspaces") == 0) {
426 		type = IPC_GET_WORKSPACES;
427 	} else if (strcasecmp(cmdtype, "get_seats") == 0) {
428 		type = IPC_GET_SEATS;
429 	} else if (strcasecmp(cmdtype, "get_inputs") == 0) {
430 		type = IPC_GET_INPUTS;
431 	} else if (strcasecmp(cmdtype, "get_outputs") == 0) {
432 		type = IPC_GET_OUTPUTS;
433 	} else if (strcasecmp(cmdtype, "get_tree") == 0) {
434 		type = IPC_GET_TREE;
435 	} else if (strcasecmp(cmdtype, "get_marks") == 0) {
436 		type = IPC_GET_MARKS;
437 	} else if (strcasecmp(cmdtype, "get_bar_config") == 0) {
438 		type = IPC_GET_BAR_CONFIG;
439 	} else if (strcasecmp(cmdtype, "get_version") == 0) {
440 		type = IPC_GET_VERSION;
441 	} else if (strcasecmp(cmdtype, "get_binding_modes") == 0) {
442 		type = IPC_GET_BINDING_MODES;
443 	} else if (strcasecmp(cmdtype, "get_binding_state") == 0) {
444 		type = IPC_GET_BINDING_STATE;
445 	} else if (strcasecmp(cmdtype, "get_config") == 0) {
446 		type = IPC_GET_CONFIG;
447 	} else if (strcasecmp(cmdtype, "send_tick") == 0) {
448 		type = IPC_SEND_TICK;
449 	} else if (strcasecmp(cmdtype, "subscribe") == 0) {
450 		type = IPC_SUBSCRIBE;
451 	} else {
452 		if (quiet) {
453 			exit(EXIT_FAILURE);
454 		}
455 		sway_abort("Unknown message type %s", cmdtype);
456 	}
457 
458 	free(cmdtype);
459 
460 	if (monitor && type != IPC_SUBSCRIBE) {
461 		if (!quiet) {
462 			sway_log(SWAY_ERROR, "Monitor can only be used with -t SUBSCRIBE");
463 		}
464 		free(socket_path);
465 		return 1;
466 	}
467 
468 	char *command = NULL;
469 	if (optind < argc) {
470 		command = join_args(argv + optind, argc - optind);
471 	} else {
472 		command = strdup("");
473 	}
474 
475 	int ret = 0;
476 	int socketfd = ipc_open_socket(socket_path);
477 	struct timeval timeout = {.tv_sec = 3, .tv_usec = 0};
478 	ipc_set_recv_timeout(socketfd, timeout);
479 	uint32_t len = strlen(command);
480 	char *resp = ipc_single_command(socketfd, type, command, &len);
481 
482 	// pretty print the json
483 	json_object *obj = json_tokener_parse(resp);
484 	if (obj == NULL) {
485 		if (!quiet) {
486 			fprintf(stderr, "ERROR: Could not parse json response from ipc. "
487 					"This is a bug in sway.");
488 			printf("%s\n", resp);
489 		}
490 		ret = 1;
491 	} else {
492 		if (!success(obj, true)) {
493 			ret = 2;
494 		}
495 		if (!quiet && (type != IPC_SUBSCRIBE  || ret != 0)) {
496 			if (raw) {
497 				printf("%s\n", json_object_to_json_string_ext(obj,
498 					JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED));
499 			} else {
500 				pretty_print(type, obj);
501 			}
502 		}
503 		json_object_put(obj);
504 	}
505 	free(command);
506 	free(resp);
507 
508 	if (type == IPC_SUBSCRIBE && ret == 0) {
509 		// Remove the timeout for subscribed events
510 		timeout.tv_sec = 0;
511 		timeout.tv_usec = 0;
512 		ipc_set_recv_timeout(socketfd, timeout);
513 
514 		do {
515 			struct ipc_response *reply = ipc_recv_response(socketfd);
516 			if (!reply) {
517 				break;
518 			}
519 
520 			json_object *obj = json_tokener_parse(reply->payload);
521 			if (obj == NULL) {
522 				if (!quiet) {
523 					fprintf(stderr, "ERROR: Could not parse json response from"
524 							" ipc. This is a bug in sway.");
525 					ret = 1;
526 				}
527 				break;
528 			} else if (quiet) {
529 				json_object_put(obj);
530 			} else {
531 				if (raw) {
532 					printf("%s\n", json_object_to_json_string(obj));
533 				} else {
534 					printf("%s\n", json_object_to_json_string_ext(obj,
535 						JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED));
536 				}
537 				fflush(stdout);
538 				json_object_put(obj);
539 			}
540 
541 			free_ipc_response(reply);
542 		} while (monitor);
543 	}
544 
545 	close(socketfd);
546 	free(socket_path);
547 	return ret;
548 }
549