1 #define _POSIX_C_SOURCE 200809L
2 #include <stdbool.h>
3 #include <string.h>
4 #include <strings.h>
5 #include "log.h"
6 #include "sway/commands.h"
7 #include "sway/config.h"
8 #include "sway/input/input-manager.h"
9 
parse_coords(const char * str,double * x,double * y,bool * mm)10 static bool parse_coords(const char *str, double *x, double *y, bool *mm) {
11 	*mm = false;
12 
13 	char *end;
14 	*x = strtod(str, &end);
15 	if (end[0] != 'x') {
16 		return false;
17 	}
18 	++end;
19 
20 	*y = strtod(end, &end);
21 	if (end[0] == 'm') {
22 		// Expect mm
23 		if (end[1] != 'm') {
24 			return false;
25 		}
26 		*mm = true;
27 		end = &end[2];
28 	}
29 	if (end[0] != '\0') {
30 		return false;
31 	}
32 
33 	return true;
34 }
35 
input_cmd_map_from_region(int argc,char ** argv)36 struct cmd_results *input_cmd_map_from_region(int argc, char **argv) {
37 	struct cmd_results *error = NULL;
38 	if ((error = checkarg(argc, "map_from_region", EXPECTED_EQUAL_TO, 2))) {
39 		return error;
40 	}
41 	struct input_config *ic = config->handler_context.input_config;
42 	if (!ic) {
43 		return cmd_results_new(CMD_FAILURE, "No input device defined");
44 	}
45 
46 	ic->mapped_from_region =
47 		calloc(1, sizeof(struct input_config_mapped_from_region));
48 
49 	bool mm1, mm2;
50 	if (!parse_coords(argv[0], &ic->mapped_from_region->x1,
51 			&ic->mapped_from_region->y1, &mm1)) {
52 		free(ic->mapped_from_region);
53 		ic->mapped_from_region = NULL;
54 		return cmd_results_new(CMD_FAILURE, "Invalid top-left coordinates");
55 	}
56 	if (!parse_coords(argv[1], &ic->mapped_from_region->x2,
57 			&ic->mapped_from_region->y2, &mm2)) {
58 		free(ic->mapped_from_region);
59 		ic->mapped_from_region = NULL;
60 		return cmd_results_new(CMD_FAILURE, "Invalid bottom-right coordinates");
61 	}
62 	if (ic->mapped_from_region->x1 > ic->mapped_from_region->x2 ||
63 			ic->mapped_from_region->y1 > ic->mapped_from_region->y2) {
64 		free(ic->mapped_from_region);
65 		ic->mapped_from_region = NULL;
66 		return cmd_results_new(CMD_FAILURE, "Invalid rectangle");
67 	}
68 	if (mm1 != mm2) {
69 		free(ic->mapped_from_region);
70 		ic->mapped_from_region = NULL;
71 		return cmd_results_new(CMD_FAILURE,
72 			"Both coordinates must be in the same unit");
73 	}
74 	ic->mapped_from_region->mm = mm1;
75 
76 	return cmd_results_new(CMD_SUCCESS, NULL);
77 }
78