]> git.sur5r.net Git - i3/i3/blob - src/commands.c
move owindow definition into the command parser
[i3/i3] / src / commands.c
1 #undef I3__FILE__
2 #define I3__FILE__ "commands.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * commands.c: all command functions (see commands_parser.c)
10  *
11  */
12 #include <float.h>
13 #include <stdarg.h>
14
15 #include "all.h"
16
17 // Macros to make the YAJL API a bit easier to use.
18 #define y(x, ...) yajl_gen_ ## x (cmd_output->json_gen, ##__VA_ARGS__)
19 #define ystr(str) yajl_gen_string(cmd_output->json_gen, (unsigned char*)str, strlen(str))
20 #define ysuccess(success) do { \
21     y(map_open); \
22     ystr("success"); \
23     y(bool, success); \
24     y(map_close); \
25 } while (0)
26
27 /** When the command did not include match criteria (!), we use the currently
28  * focused container. Do not confuse this case with a command which included
29  * criteria but which did not match any windows. This macro has to be called in
30  * every command.
31  */
32 #define HANDLE_EMPTY_MATCH do { \
33     if (match_is_empty(current_match)) { \
34         owindow *ow = smalloc(sizeof(owindow)); \
35         ow->con = focused; \
36         TAILQ_INIT(&owindows); \
37         TAILQ_INSERT_TAIL(&owindows, ow, owindows); \
38     } \
39 } while (0)
40
41
42 /*
43  * Returns true if a is definitely greater than b (using the given epsilon)
44  *
45  */
46 static bool definitelyGreaterThan(float a, float b, float epsilon) {
47     return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
48 }
49
50 /*
51  * Returns an 'output' corresponding to one of left/right/down/up or a specific
52  * output name.
53  *
54  */
55 static Output *get_output_from_string(Output *current_output, const char *output_str) {
56     Output *output;
57
58     if (strcasecmp(output_str, "left") == 0) {
59         output = get_output_next(D_LEFT, current_output, CLOSEST_OUTPUT);
60         if (!output)
61             output = get_output_most(D_RIGHT, current_output);
62     } else if (strcasecmp(output_str, "right") == 0) {
63         output = get_output_next(D_RIGHT, current_output, CLOSEST_OUTPUT);
64         if (!output)
65             output = get_output_most(D_LEFT, current_output);
66     } else if (strcasecmp(output_str, "up") == 0) {
67         output = get_output_next(D_UP, current_output, CLOSEST_OUTPUT);
68         if (!output)
69             output = get_output_most(D_DOWN, current_output);
70     } else if (strcasecmp(output_str, "down") == 0) {
71         output = get_output_next(D_DOWN, current_output, CLOSEST_OUTPUT);
72         if (!output)
73             output = get_output_most(D_UP, current_output);
74     } else output = get_output_by_name(output_str);
75
76     return output;
77 }
78
79 /*
80  * Checks whether we switched to a new workspace and returns false in that case,
81  * signaling that further workspace switching should be done by the calling function
82  * If not, calls workspace_back_and_forth() if workspace_auto_back_and_forth is set
83  * and return true, signaling that no further workspace switching should occur in the calling function.
84  *
85  */
86 static bool maybe_back_and_forth(struct CommandResult *cmd_output, char *name) {
87     Con *ws = con_get_workspace(focused);
88
89     /* If we switched to a different workspace, do nothing */
90     if (strcmp(ws->name, name) != 0)
91         return false;
92
93     DLOG("This workspace is already focused.\n");
94     if (config.workspace_auto_back_and_forth) {
95         workspace_back_and_forth();
96         cmd_output->needs_tree_render = true;
97     }
98     return true;
99 }
100
101 /*
102  * Return the passed workspace unless it is the current one and auto back and
103  * forth is enabled, in which case the back_and_forth workspace is returned.
104  */
105 static Con *maybe_auto_back_and_forth_workspace(Con *workspace) {
106     Con *current, *baf;
107
108     if (!config.workspace_auto_back_and_forth)
109         return workspace;
110
111     current = con_get_workspace(focused);
112
113     if (current == workspace) {
114         baf = workspace_back_and_forth_get();
115         if (baf != NULL) {
116             DLOG("Substituting workspace with back_and_forth, as it is focused.\n");
117             return baf;
118         }
119     }
120
121     return workspace;
122 }
123
124 // This code is commented out because we might recycle it for popping up error
125 // messages on parser errors.
126 #if 0
127 static pid_t migration_pid = -1;
128
129 /*
130  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
131  * it exited (or could not be started, depending on the exit code).
132  *
133  */
134 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
135     ev_child_stop(EV_A_ watcher);
136     if (!WIFEXITED(watcher->rstatus)) {
137         fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
138         return;
139     }
140
141     int exitcode = WEXITSTATUS(watcher->rstatus);
142     printf("i3-nagbar process exited with status %d\n", exitcode);
143     if (exitcode == 2) {
144         fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
145     }
146
147     migration_pid = -1;
148 }
149
150 /* We need ev >= 4 for the following code. Since it is not *that* important (it
151  * only makes sure that there are no i3-nagbar instances left behind) we still
152  * support old systems with libev 3. */
153 #if EV_VERSION_MAJOR >= 4
154 /*
155  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
156  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
157  *
158  */
159 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
160     if (migration_pid != -1) {
161         LOG("Sending SIGKILL (9) to i3-nagbar with PID %d\n", migration_pid);
162         kill(migration_pid, SIGKILL);
163     }
164 }
165 #endif
166
167 void cmd_MIGRATION_start_nagbar(void) {
168     if (migration_pid != -1) {
169         fprintf(stderr, "i3-nagbar already running.\n");
170         return;
171     }
172     fprintf(stderr, "Starting i3-nagbar, command parsing differs from expected output.\n");
173     ELOG("Please report this on IRC or in the bugtracker. Make sure to include the full debug level logfile:\n");
174     ELOG("i3-dump-log | gzip -9c > /tmp/i3.log.gz\n");
175     ELOG("FYI: Your i3 version is " I3_VERSION "\n");
176     migration_pid = fork();
177     if (migration_pid == -1) {
178         warn("Could not fork()");
179         return;
180     }
181
182     /* child */
183     if (migration_pid == 0) {
184         char *pageraction;
185         sasprintf(&pageraction, "i3-sensible-terminal -e i3-sensible-pager \"%s\"", errorfilename);
186         char *argv[] = {
187             NULL, /* will be replaced by the executable path */
188             "-t",
189             "error",
190             "-m",
191             "You found a parsing error. Please, please, please, report it!",
192             "-b",
193             "show errors",
194             pageraction,
195             NULL
196         };
197         exec_i3_utility("i3-nagbar", argv);
198     }
199
200     /* parent */
201     /* install a child watcher */
202     ev_child *child = smalloc(sizeof(ev_child));
203     ev_child_init(child, &nagbar_exited, migration_pid, 0);
204     ev_child_start(main_loop, child);
205
206 /* We need ev >= 4 for the following code. Since it is not *that* important (it
207  * only makes sure that there are no i3-nagbar instances left behind) we still
208  * support old systems with libev 3. */
209 #if EV_VERSION_MAJOR >= 4
210     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
211      * still running) */
212     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
213     ev_cleanup_init(cleanup, nagbar_cleanup);
214     ev_cleanup_start(main_loop, cleanup);
215 #endif
216 }
217
218 #endif
219
220 /*******************************************************************************
221  * Criteria functions.
222  ******************************************************************************/
223
224 /*
225  * Helper data structure for an operation window (window on which the operation
226  * will be performed). Used to build the TAILQ owindows.
227  *
228  */
229 typedef struct owindow {
230     Con *con;
231     TAILQ_ENTRY(owindow) owindows;
232 } owindow;
233
234 typedef TAILQ_HEAD(owindows_head, owindow) owindows_head;
235
236 static owindows_head owindows;
237
238 /*
239  * Initializes the specified 'Match' data structure and the initial state of
240  * commands.c for matching target windows of a command.
241  *
242  */
243 void cmd_criteria_init(I3_CMD) {
244     Con *con;
245     owindow *ow;
246
247     DLOG("Initializing criteria, current_match = %p\n", current_match);
248     match_init(current_match);
249     while (!TAILQ_EMPTY(&owindows)) {
250         ow = TAILQ_FIRST(&owindows);
251         TAILQ_REMOVE(&owindows, ow, owindows);
252         free(ow);
253     }
254     TAILQ_INIT(&owindows);
255     /* copy all_cons */
256     TAILQ_FOREACH(con, &all_cons, all_cons) {
257         ow = smalloc(sizeof(owindow));
258         ow->con = con;
259         TAILQ_INSERT_TAIL(&owindows, ow, owindows);
260     }
261 }
262
263 /*
264  * A match specification just finished (the closing square bracket was found),
265  * so we filter the list of owindows.
266  *
267  */
268 void cmd_criteria_match_windows(I3_CMD) {
269     owindow *next, *current;
270
271     DLOG("match specification finished, matching...\n");
272     /* copy the old list head to iterate through it and start with a fresh
273      * list which will contain only matching windows */
274     struct owindows_head old = owindows;
275     TAILQ_INIT(&owindows);
276     for (next = TAILQ_FIRST(&old); next != TAILQ_END(&old);) {
277         /* make a copy of the next pointer and advance the pointer to the
278          * next element as we are going to invalidate the element’s
279          * next/prev pointers by calling TAILQ_INSERT_TAIL later */
280         current = next;
281         next = TAILQ_NEXT(next, owindows);
282
283         DLOG("checking if con %p / %s matches\n", current->con, current->con->name);
284         if (current_match->con_id != NULL) {
285             if (current_match->con_id == current->con) {
286                 DLOG("matches container!\n");
287                 TAILQ_INSERT_TAIL(&owindows, current, owindows);
288             }
289         } else if (current_match->mark != NULL && current->con->mark != NULL &&
290                    regex_matches(current_match->mark, current->con->mark)) {
291             DLOG("match by mark\n");
292             TAILQ_INSERT_TAIL(&owindows, current, owindows);
293         } else {
294             if (current->con->window == NULL)
295                 continue;
296             if (match_matches_window(current_match, current->con->window)) {
297                 DLOG("matches window!\n");
298                 TAILQ_INSERT_TAIL(&owindows, current, owindows);
299             } else {
300                 DLOG("doesnt match\n");
301                 free(current);
302             }
303         }
304     }
305
306     TAILQ_FOREACH(current, &owindows, owindows) {
307         DLOG("matching: %p / %s\n", current->con, current->con->name);
308     }
309 }
310
311 /*
312  * Interprets a ctype=cvalue pair and adds it to the current match
313  * specification.
314  *
315  */
316 void cmd_criteria_add(I3_CMD, char *ctype, char *cvalue) {
317     DLOG("ctype=*%s*, cvalue=*%s*\n", ctype, cvalue);
318
319     if (strcmp(ctype, "class") == 0) {
320         current_match->class = regex_new(cvalue);
321         return;
322     }
323
324     if (strcmp(ctype, "instance") == 0) {
325         current_match->instance = regex_new(cvalue);
326         return;
327     }
328
329     if (strcmp(ctype, "window_role") == 0) {
330         current_match->role = regex_new(cvalue);
331         return;
332     }
333
334     if (strcmp(ctype, "con_id") == 0) {
335         char *end;
336         long parsed = strtol(cvalue, &end, 10);
337         if (parsed == LONG_MIN ||
338             parsed == LONG_MAX ||
339             parsed < 0 ||
340             (end && *end != '\0')) {
341             ELOG("Could not parse con id \"%s\"\n", cvalue);
342         } else {
343             current_match->con_id = (Con*)parsed;
344             printf("id as int = %p\n", current_match->con_id);
345         }
346         return;
347     }
348
349     if (strcmp(ctype, "id") == 0) {
350         char *end;
351         long parsed = strtol(cvalue, &end, 10);
352         if (parsed == LONG_MIN ||
353             parsed == LONG_MAX ||
354             parsed < 0 ||
355             (end && *end != '\0')) {
356             ELOG("Could not parse window id \"%s\"\n", cvalue);
357         } else {
358             current_match->id = parsed;
359             printf("window id as int = %d\n", current_match->id);
360         }
361         return;
362     }
363
364     if (strcmp(ctype, "con_mark") == 0) {
365         current_match->mark = regex_new(cvalue);
366         return;
367     }
368
369     if (strcmp(ctype, "title") == 0) {
370         current_match->title = regex_new(cvalue);
371         return;
372     }
373
374     if (strcmp(ctype, "urgent") == 0) {
375         if (strcasecmp(cvalue, "latest") == 0 ||
376             strcasecmp(cvalue, "newest") == 0 ||
377             strcasecmp(cvalue, "recent") == 0 ||
378             strcasecmp(cvalue, "last") == 0) {
379             current_match->urgent = U_LATEST;
380         } else if (strcasecmp(cvalue, "oldest") == 0 ||
381                    strcasecmp(cvalue, "first") == 0) {
382             current_match->urgent = U_OLDEST;
383         }
384         return;
385     }
386
387     ELOG("Unknown criterion: %s\n", ctype);
388 }
389
390 /*
391  * Implementation of 'move [window|container] [to] workspace
392  * next|prev|next_on_output|prev_on_output|current'.
393  *
394  */
395 void cmd_move_con_to_workspace(I3_CMD, char *which) {
396     owindow *current;
397
398     DLOG("which=%s\n", which);
399
400     /* We have nothing to move:
401      *  when criteria was specified but didn't match any window or
402      *  when criteria wasn't specified and we don't have any window focused. */
403     if ((!match_is_empty(current_match) && TAILQ_EMPTY(&owindows)) ||
404         (match_is_empty(current_match) && focused->type == CT_WORKSPACE &&
405         con_is_leaf(focused))) {
406         ysuccess(false);
407         return;
408     }
409
410     HANDLE_EMPTY_MATCH;
411
412     /* get the workspace */
413     Con *ws;
414     if (strcmp(which, "next") == 0)
415         ws = workspace_next();
416     else if (strcmp(which, "prev") == 0)
417         ws = workspace_prev();
418     else if (strcmp(which, "next_on_output") == 0)
419         ws = workspace_next_on_output();
420     else if (strcmp(which, "prev_on_output") == 0)
421         ws = workspace_prev_on_output();
422     else if (strcmp(which, "current") == 0)
423         ws = con_get_workspace(focused);
424     else {
425         ELOG("BUG: called with which=%s\n", which);
426         ysuccess(false);
427         return;
428     }
429
430     TAILQ_FOREACH(current, &owindows, owindows) {
431         DLOG("matching: %p / %s\n", current->con, current->con->name);
432         con_move_to_workspace(current->con, ws, true, false);
433     }
434
435     cmd_output->needs_tree_render = true;
436     // XXX: default reply for now, make this a better reply
437     ysuccess(true);
438 }
439
440 /**
441  * Implementation of 'move [window|container] [to] workspace back_and_forth'.
442  *
443  */
444 void cmd_move_con_to_workspace_back_and_forth(I3_CMD) {
445     owindow *current;
446     Con *ws;
447
448     ws = workspace_back_and_forth_get();
449
450     if (ws == NULL) {
451         y(map_open);
452         ystr("success");
453         y(bool, false);
454         ystr("error");
455         ystr("No workspace was previously active.");
456         y(map_close);
457         return;
458     }
459
460     HANDLE_EMPTY_MATCH;
461
462     TAILQ_FOREACH(current, &owindows, owindows) {
463         DLOG("matching: %p / %s\n", current->con, current->con->name);
464         con_move_to_workspace(current->con, ws, true, false);
465     }
466
467     cmd_output->needs_tree_render = true;
468     // XXX: default reply for now, make this a better reply
469     ysuccess(true);
470 }
471
472 /*
473  * Implementation of 'move [window|container] [to] workspace <name>'.
474  *
475  */
476 void cmd_move_con_to_workspace_name(I3_CMD, char *name) {
477     if (strncasecmp(name, "__i3_", strlen("__i3_")) == 0) {
478         LOG("You cannot switch to the i3 internal workspaces.\n");
479         ysuccess(false);
480         return;
481     }
482
483     owindow *current;
484
485     /* We have nothing to move:
486      *  when criteria was specified but didn't match any window or
487      *  when criteria wasn't specified and we don't have any window focused. */
488     if (!match_is_empty(current_match) && TAILQ_EMPTY(&owindows)) {
489         ELOG("No windows match your criteria, cannot move.\n");
490         ysuccess(false);
491         return;
492     }
493     else if (match_is_empty(current_match) && focused->type == CT_WORKSPACE &&
494         con_is_leaf(focused)) {
495         ysuccess(false);
496         return;
497     }
498
499     LOG("should move window to workspace %s\n", name);
500     /* get the workspace */
501     Con *ws = workspace_get(name, NULL);
502
503     ws = maybe_auto_back_and_forth_workspace(ws);
504
505     HANDLE_EMPTY_MATCH;
506
507     TAILQ_FOREACH(current, &owindows, owindows) {
508         DLOG("matching: %p / %s\n", current->con, current->con->name);
509         con_move_to_workspace(current->con, ws, true, false);
510     }
511
512     cmd_output->needs_tree_render = true;
513     // XXX: default reply for now, make this a better reply
514     ysuccess(true);
515 }
516
517 /*
518  * Implementation of 'move [window|container] [to] workspace number <name>'.
519  *
520  */
521 void cmd_move_con_to_workspace_number(I3_CMD, char *which) {
522     owindow *current;
523
524     /* We have nothing to move:
525      *  when criteria was specified but didn't match any window or
526      *  when criteria wasn't specified and we don't have any window focused. */
527     if ((!match_is_empty(current_match) && TAILQ_EMPTY(&owindows)) ||
528         (match_is_empty(current_match) && focused->type == CT_WORKSPACE &&
529         con_is_leaf(focused))) {
530         ysuccess(false);
531         return;
532     }
533
534     LOG("should move window to workspace %s\n", which);
535     /* get the workspace */
536     Con *output, *workspace = NULL;
537
538     char *endptr = NULL;
539     long parsed_num = strtol(which, &endptr, 10);
540     if (parsed_num == LONG_MIN ||
541         parsed_num == LONG_MAX ||
542         parsed_num < 0 ||
543         endptr == which) {
544         LOG("Could not parse initial part of \"%s\" as a number.\n", which);
545         y(map_open);
546         ystr("success");
547         y(bool, false);
548         ystr("error");
549         // TODO: better error message
550         ystr("Could not parse number");
551         y(map_close);
552         return;
553     }
554
555     TAILQ_FOREACH(output, &(croot->nodes_head), nodes)
556         GREP_FIRST(workspace, output_get_content(output),
557             child->num == parsed_num);
558
559     if (!workspace) {
560         workspace = workspace_get(which, NULL);
561     }
562
563     workspace = maybe_auto_back_and_forth_workspace(workspace);
564
565     HANDLE_EMPTY_MATCH;
566
567     TAILQ_FOREACH(current, &owindows, owindows) {
568         DLOG("matching: %p / %s\n", current->con, current->con->name);
569         con_move_to_workspace(current->con, workspace, true, false);
570     }
571
572     cmd_output->needs_tree_render = true;
573     // XXX: default reply for now, make this a better reply
574     ysuccess(true);
575 }
576
577 static void cmd_resize_floating(I3_CMD, char *way, char *direction, Con *floating_con, int px) {
578     LOG("floating resize\n");
579     if (strcmp(direction, "up") == 0) {
580         floating_con->rect.y -= px;
581         floating_con->rect.height += px;
582     } else if (strcmp(direction, "down") == 0 || strcmp(direction, "height") == 0) {
583         floating_con->rect.height += px;
584     } else if (strcmp(direction, "left") == 0) {
585         floating_con->rect.x -= px;
586         floating_con->rect.width += px;
587     } else {
588         floating_con->rect.width += px;
589     }
590 }
591
592 static bool cmd_resize_tiling_direction(I3_CMD, Con *current, char *way, char *direction, int ppt) {
593     LOG("tiling resize\n");
594     /* get the appropriate current container (skip stacked/tabbed cons) */
595     Con *other = NULL;
596     double percentage = 0;
597     while (current->parent->layout == L_STACKED ||
598            current->parent->layout == L_TABBED)
599         current = current->parent;
600
601     /* Then further go up until we find one with the matching orientation. */
602     orientation_t search_orientation =
603         (strcmp(direction, "left") == 0 || strcmp(direction, "right") == 0 ? HORIZ : VERT);
604
605     do {
606         if (con_orientation(current->parent) != search_orientation) {
607             current = current->parent;
608             continue;
609         }
610
611         /* get the default percentage */
612         int children = con_num_children(current->parent);
613         LOG("ins. %d children\n", children);
614         percentage = 1.0 / children;
615         LOG("default percentage = %f\n", percentage);
616
617         orientation_t orientation = con_orientation(current->parent);
618
619         if ((orientation == HORIZ &&
620              (strcmp(direction, "up") == 0 || strcmp(direction, "down") == 0)) ||
621             (orientation == VERT &&
622              (strcmp(direction, "left") == 0 || strcmp(direction, "right") == 0))) {
623             LOG("You cannot resize in that direction. Your focus is in a %s split container currently.\n",
624                 (orientation == HORIZ ? "horizontal" : "vertical"));
625             ysuccess(false);
626             return false;
627         }
628
629         if (strcmp(direction, "up") == 0 || strcmp(direction, "left") == 0) {
630             other = TAILQ_PREV(current, nodes_head, nodes);
631         } else {
632             other = TAILQ_NEXT(current, nodes);
633         }
634         if (other == TAILQ_END(workspaces)) {
635             LOG("No other container in this direction found, trying to look further up in the tree...\n");
636             current = current->parent;
637             continue;
638         }
639         break;
640     } while (current->type != CT_WORKSPACE &&
641              current->type != CT_FLOATING_CON);
642
643     if (other == NULL) {
644         LOG("No other container in this direction found, trying to look further up in the tree...\n");
645         ysuccess(false);
646         return false;
647     }
648
649     LOG("other->percent = %f\n", other->percent);
650     LOG("current->percent before = %f\n", current->percent);
651     if (current->percent == 0.0)
652         current->percent = percentage;
653     if (other->percent == 0.0)
654         other->percent = percentage;
655     double new_current_percent = current->percent + ((double)ppt / 100.0);
656     double new_other_percent = other->percent - ((double)ppt / 100.0);
657     LOG("new_current_percent = %f\n", new_current_percent);
658     LOG("new_other_percent = %f\n", new_other_percent);
659     /* Ensure that the new percentages are positive and greater than
660      * 0.05 to have a reasonable minimum size. */
661     if (definitelyGreaterThan(new_current_percent, 0.05, DBL_EPSILON) &&
662         definitelyGreaterThan(new_other_percent, 0.05, DBL_EPSILON)) {
663         current->percent += ((double)ppt / 100.0);
664         other->percent -= ((double)ppt / 100.0);
665         LOG("current->percent after = %f\n", current->percent);
666         LOG("other->percent after = %f\n", other->percent);
667     } else {
668         LOG("Not resizing, already at minimum size\n");
669     }
670
671     return true;
672 }
673
674 static bool cmd_resize_tiling_width_height(I3_CMD, Con *current, char *way, char *direction, int ppt) {
675     LOG("width/height resize\n");
676     /* get the appropriate current container (skip stacked/tabbed cons) */
677     while (current->parent->layout == L_STACKED ||
678            current->parent->layout == L_TABBED)
679         current = current->parent;
680
681     /* Then further go up until we find one with the matching orientation. */
682     orientation_t search_orientation =
683         (strcmp(direction, "width") == 0 ? HORIZ : VERT);
684
685     while (current->type != CT_WORKSPACE &&
686            current->type != CT_FLOATING_CON &&
687            con_orientation(current->parent) != search_orientation)
688         current = current->parent;
689
690     /* get the default percentage */
691     int children = con_num_children(current->parent);
692     LOG("ins. %d children\n", children);
693     double percentage = 1.0 / children;
694     LOG("default percentage = %f\n", percentage);
695
696     orientation_t orientation = con_orientation(current->parent);
697
698     if ((orientation == HORIZ &&
699          strcmp(direction, "height") == 0) ||
700         (orientation == VERT &&
701          strcmp(direction, "width") == 0)) {
702         LOG("You cannot resize in that direction. Your focus is in a %s split container currently.\n",
703             (orientation == HORIZ ? "horizontal" : "vertical"));
704         ysuccess(false);
705         return false;
706     }
707
708     if (children == 1) {
709         LOG("This is the only container, cannot resize.\n");
710         ysuccess(false);
711         return false;
712     }
713
714     /* Ensure all the other children have a percentage set. */
715     Con *child;
716     TAILQ_FOREACH(child, &(current->parent->nodes_head), nodes) {
717         LOG("child->percent = %f (child %p)\n", child->percent, child);
718         if (child->percent == 0.0)
719             child->percent = percentage;
720     }
721
722     double new_current_percent = current->percent + ((double)ppt / 100.0);
723     double subtract_percent = ((double)ppt / 100.0) / (children - 1);
724     LOG("new_current_percent = %f\n", new_current_percent);
725     LOG("subtract_percent = %f\n", subtract_percent);
726     /* Ensure that the new percentages are positive and greater than
727      * 0.05 to have a reasonable minimum size. */
728     TAILQ_FOREACH(child, &(current->parent->nodes_head), nodes) {
729         if (child == current)
730             continue;
731         if (!definitelyGreaterThan(child->percent - subtract_percent, 0.05, DBL_EPSILON)) {
732             LOG("Not resizing, already at minimum size (child %p would end up with a size of %.f\n", child, child->percent - subtract_percent);
733             ysuccess(false);
734             return false;
735         }
736     }
737     if (!definitelyGreaterThan(new_current_percent, 0.05, DBL_EPSILON)) {
738         LOG("Not resizing, already at minimum size\n");
739         ysuccess(false);
740         return false;
741     }
742
743     current->percent += ((double)ppt / 100.0);
744     LOG("current->percent after = %f\n", current->percent);
745
746     TAILQ_FOREACH(child, &(current->parent->nodes_head), nodes) {
747         if (child == current)
748             continue;
749         child->percent -= subtract_percent;
750         LOG("child->percent after (%p) = %f\n", child, child->percent);
751     }
752
753     return true;
754 }
755
756 /*
757  * Implementation of 'resize grow|shrink <direction> [<px> px] [or <ppt> ppt]'.
758  *
759  */
760 void cmd_resize(I3_CMD, char *way, char *direction, char *resize_px, char *resize_ppt) {
761     /* resize <grow|shrink> <direction> [<px> px] [or <ppt> ppt] */
762     DLOG("resizing in way %s, direction %s, px %s or ppt %s\n", way, direction, resize_px, resize_ppt);
763     // TODO: We could either handle this in the parser itself as a separate token (and make the stack typed) or we need a better way to convert a string to a number with error checking
764     int px = atoi(resize_px);
765     int ppt = atoi(resize_ppt);
766     if (strcmp(way, "shrink") == 0) {
767         px *= -1;
768         ppt *= -1;
769     }
770
771     HANDLE_EMPTY_MATCH;
772
773     owindow *current;
774     TAILQ_FOREACH(current, &owindows, owindows) {
775         Con *floating_con;
776         if ((floating_con = con_inside_floating(current->con))) {
777             cmd_resize_floating(current_match, cmd_output, way, direction, floating_con, px);
778         } else {
779             if (strcmp(direction, "width") == 0 ||
780                 strcmp(direction, "height") == 0) {
781                 if (!cmd_resize_tiling_width_height(current_match, cmd_output, current->con, way, direction, ppt))
782                     return;
783             } else {
784                 if (!cmd_resize_tiling_direction(current_match, cmd_output, current->con, way, direction, ppt))
785                     return;
786             }
787         }
788     }
789
790     cmd_output->needs_tree_render = true;
791     // XXX: default reply for now, make this a better reply
792     ysuccess(true);
793 }
794
795 /*
796  * Implementation of 'border normal|none|1pixel|toggle|pixel'.
797  *
798  */
799 void cmd_border(I3_CMD, char *border_style_str, char *border_width ) {
800     DLOG("border style should be changed to %s with border width %s\n", border_style_str, border_width);
801     owindow *current;
802
803     HANDLE_EMPTY_MATCH;
804
805     TAILQ_FOREACH(current, &owindows, owindows) {
806         DLOG("matching: %p / %s\n", current->con, current->con->name);
807         int border_style = current->con->border_style;
808         char *end;
809         int tmp_border_width = -1;
810         tmp_border_width = strtol(border_width, &end, 10);
811         if (end == border_width) {
812             /* no valid digits found */
813             tmp_border_width = -1;
814         }
815         if (strcmp(border_style_str, "toggle") == 0) {
816             border_style++;
817             border_style %= 3;
818             if (border_style == BS_NORMAL)
819                 tmp_border_width = 2;
820             else if (border_style == BS_NONE)
821                 tmp_border_width = 0;
822             else if (border_style == BS_PIXEL)
823                 tmp_border_width = 1;
824         } else {
825             if (strcmp(border_style_str, "normal") == 0)
826                 border_style = BS_NORMAL;
827             else if (strcmp(border_style_str, "pixel") == 0)
828                 border_style = BS_PIXEL;
829             else if (strcmp(border_style_str, "1pixel") == 0){
830                 border_style = BS_PIXEL;
831                 tmp_border_width = 1;
832             } else if (strcmp(border_style_str, "none") == 0)
833                 border_style = BS_NONE;
834             else {
835                 ELOG("BUG: called with border_style=%s\n", border_style_str);
836                 ysuccess(false);
837                 return;
838             }
839         }
840         con_set_border_style(current->con, border_style, tmp_border_width);
841     }
842
843     cmd_output->needs_tree_render = true;
844     // XXX: default reply for now, make this a better reply
845     ysuccess(true);
846 }
847
848 /*
849  * Implementation of 'nop <comment>'.
850  *
851  */
852 void cmd_nop(I3_CMD, char *comment) {
853     LOG("-------------------------------------------------\n");
854     LOG("  NOP: %s\n", comment);
855     LOG("-------------------------------------------------\n");
856 }
857
858 /*
859  * Implementation of 'append_layout <path>'.
860  *
861  */
862 void cmd_append_layout(I3_CMD, char *path) {
863     LOG("Appending layout \"%s\"\n", path);
864     tree_append_json(path);
865
866     cmd_output->needs_tree_render = true;
867     // XXX: default reply for now, make this a better reply
868     ysuccess(true);
869 }
870
871 /*
872  * Implementation of 'workspace next|prev|next_on_output|prev_on_output'.
873  *
874  */
875 void cmd_workspace(I3_CMD, char *which) {
876     Con *ws;
877
878     DLOG("which=%s\n", which);
879
880     if (strcmp(which, "next") == 0)
881         ws = workspace_next();
882     else if (strcmp(which, "prev") == 0)
883         ws = workspace_prev();
884     else if (strcmp(which, "next_on_output") == 0)
885         ws = workspace_next_on_output();
886     else if (strcmp(which, "prev_on_output") == 0)
887         ws = workspace_prev_on_output();
888     else {
889         ELOG("BUG: called with which=%s\n", which);
890         ysuccess(false);
891         return;
892     }
893
894     workspace_show(ws);
895
896     cmd_output->needs_tree_render = true;
897     // XXX: default reply for now, make this a better reply
898     ysuccess(true);
899 }
900
901 /*
902  * Implementation of 'workspace number <name>'
903  *
904  */
905 void cmd_workspace_number(I3_CMD, char *which) {
906     Con *output, *workspace = NULL;
907
908     char *endptr = NULL;
909     long parsed_num = strtol(which, &endptr, 10);
910     if (parsed_num == LONG_MIN ||
911         parsed_num == LONG_MAX ||
912         parsed_num < 0 ||
913         endptr == which) {
914         LOG("Could not parse initial part of \"%s\" as a number.\n", which);
915         y(map_open);
916         ystr("success");
917         y(bool, false);
918         ystr("error");
919         // TODO: better error message
920         ystr("Could not parse number");
921         y(map_close);
922
923         return;
924     }
925
926     TAILQ_FOREACH(output, &(croot->nodes_head), nodes)
927         GREP_FIRST(workspace, output_get_content(output),
928             child->num == parsed_num);
929
930     if (!workspace) {
931         LOG("There is no workspace with number %ld, creating a new one.\n", parsed_num);
932         ysuccess(true);
933         workspace_show_by_name(which);
934         cmd_output->needs_tree_render = true;
935         return;
936     }
937     if (maybe_back_and_forth(cmd_output, workspace->name))
938         return;
939     workspace_show(workspace);
940
941     cmd_output->needs_tree_render = true;
942     // XXX: default reply for now, make this a better reply
943     ysuccess(true);
944 }
945
946 /*
947  * Implementation of 'workspace back_and_forth'.
948  *
949  */
950 void cmd_workspace_back_and_forth(I3_CMD) {
951     workspace_back_and_forth();
952
953     cmd_output->needs_tree_render = true;
954     // XXX: default reply for now, make this a better reply
955     ysuccess(true);
956 }
957
958 /*
959  * Implementation of 'workspace <name>'
960  *
961  */
962 void cmd_workspace_name(I3_CMD, char *name) {
963     if (strncasecmp(name, "__i3_", strlen("__i3_")) == 0) {
964         LOG("You cannot switch to the i3 internal workspaces.\n");
965         ysuccess(false);
966         return;
967     }
968
969     DLOG("should switch to workspace %s\n", name);
970     if (maybe_back_and_forth(cmd_output, name))
971        return;
972     workspace_show_by_name(name);
973
974     cmd_output->needs_tree_render = true;
975     // XXX: default reply for now, make this a better reply
976     ysuccess(true);
977 }
978
979 /*
980  * Implementation of 'mark <mark>'
981  *
982  */
983 void cmd_mark(I3_CMD, char *mark) {
984     DLOG("Clearing all windows which have that mark first\n");
985
986     Con *con;
987     TAILQ_FOREACH(con, &all_cons, all_cons) {
988         if (con->mark && strcmp(con->mark, mark) == 0)
989             FREE(con->mark);
990     }
991
992     DLOG("marking window with str %s\n", mark);
993     owindow *current;
994
995     HANDLE_EMPTY_MATCH;
996
997     TAILQ_FOREACH(current, &owindows, owindows) {
998         DLOG("matching: %p / %s\n", current->con, current->con->name);
999         current->con->mark = sstrdup(mark);
1000     }
1001
1002     cmd_output->needs_tree_render = true;
1003     // XXX: default reply for now, make this a better reply
1004     ysuccess(true);
1005 }
1006
1007 /*
1008  * Implementation of 'mode <string>'.
1009  *
1010  */
1011 void cmd_mode(I3_CMD, char *mode) {
1012     DLOG("mode=%s\n", mode);
1013     switch_mode(mode);
1014
1015     // XXX: default reply for now, make this a better reply
1016     ysuccess(true);
1017 }
1018
1019 /*
1020  * Implementation of 'move [window|container] [to] output <str>'.
1021  *
1022  */
1023 void cmd_move_con_to_output(I3_CMD, char *name) {
1024     owindow *current;
1025
1026     DLOG("should move window to output %s\n", name);
1027
1028     HANDLE_EMPTY_MATCH;
1029
1030     /* get the output */
1031     Output *current_output = NULL;
1032     Output *output;
1033
1034     // TODO: fix the handling of criteria
1035     TAILQ_FOREACH(current, &owindows, owindows)
1036         current_output = get_output_containing(current->con->rect.x, current->con->rect.y);
1037
1038     assert(current_output != NULL);
1039
1040     // TODO: clean this up with commands.spec as soon as we switched away from the lex/yacc command parser
1041     if (strcasecmp(name, "up") == 0)
1042         output = get_output_next(D_UP, current_output, CLOSEST_OUTPUT);
1043     else if (strcasecmp(name, "down") == 0)
1044         output = get_output_next(D_DOWN, current_output, CLOSEST_OUTPUT);
1045     else if (strcasecmp(name, "left") == 0)
1046         output = get_output_next(D_LEFT, current_output, CLOSEST_OUTPUT);
1047     else if (strcasecmp(name, "right") == 0)
1048         output = get_output_next(D_RIGHT, current_output, CLOSEST_OUTPUT);
1049     else
1050         output = get_output_by_name(name);
1051
1052     if (!output) {
1053         LOG("No such output found.\n");
1054         ysuccess(false);
1055         return;
1056     }
1057
1058     /* get visible workspace on output */
1059     Con *ws = NULL;
1060     GREP_FIRST(ws, output_get_content(output->con), workspace_is_visible(child));
1061     if (!ws) {
1062         ysuccess(false);
1063         return;
1064     }
1065
1066     TAILQ_FOREACH(current, &owindows, owindows) {
1067         DLOG("matching: %p / %s\n", current->con, current->con->name);
1068         con_move_to_workspace(current->con, ws, true, false);
1069     }
1070
1071     cmd_output->needs_tree_render = true;
1072     // XXX: default reply for now, make this a better reply
1073     ysuccess(true);
1074 }
1075
1076 /*
1077  * Implementation of 'floating enable|disable|toggle'
1078  *
1079  */
1080 void cmd_floating(I3_CMD, char *floating_mode) {
1081     owindow *current;
1082
1083     DLOG("floating_mode=%s\n", floating_mode);
1084
1085     HANDLE_EMPTY_MATCH;
1086
1087     TAILQ_FOREACH(current, &owindows, owindows) {
1088         DLOG("matching: %p / %s\n", current->con, current->con->name);
1089         if (strcmp(floating_mode, "toggle") == 0) {
1090             DLOG("should toggle mode\n");
1091             toggle_floating_mode(current->con, false);
1092         } else {
1093             DLOG("should switch mode to %s\n", floating_mode);
1094             if (strcmp(floating_mode, "enable") == 0) {
1095                 floating_enable(current->con, false);
1096             } else {
1097                 floating_disable(current->con, false);
1098             }
1099         }
1100     }
1101
1102     cmd_output->needs_tree_render = true;
1103     // XXX: default reply for now, make this a better reply
1104     ysuccess(true);
1105 }
1106
1107 /*
1108  * Implementation of 'move workspace to [output] <str>'.
1109  *
1110  */
1111 void cmd_move_workspace_to_output(I3_CMD, char *name) {
1112     DLOG("should move workspace to output %s\n", name);
1113
1114     HANDLE_EMPTY_MATCH;
1115
1116     owindow *current;
1117     TAILQ_FOREACH(current, &owindows, owindows) {
1118         Output *current_output = get_output_containing(current->con->rect.x,
1119                                                        current->con->rect.y);
1120         if (!current_output) {
1121             ELOG("Cannot get current output. This is a bug in i3.\n");
1122             ysuccess(false);
1123             return;
1124         }
1125         Output *output = get_output_from_string(current_output, name);
1126         if (!output) {
1127             ELOG("Could not get output from string \"%s\"\n", name);
1128             ysuccess(false);
1129             return;
1130         }
1131
1132         Con *content = output_get_content(output->con);
1133         LOG("got output %p with content %p\n", output, content);
1134
1135         Con *previously_visible_ws = TAILQ_FIRST(&(content->nodes_head));
1136         LOG("Previously visible workspace = %p / %s\n", previously_visible_ws, previously_visible_ws->name);
1137
1138         Con *ws = con_get_workspace(current->con);
1139         LOG("should move workspace %p / %s\n", ws, ws->name);
1140         bool workspace_was_visible = workspace_is_visible(ws);
1141
1142         if (con_num_children(ws->parent) == 1) {
1143             LOG("Creating a new workspace to replace \"%s\" (last on its output).\n", ws->name);
1144
1145             /* check if we can find a workspace assigned to this output */
1146             bool used_assignment = false;
1147             struct Workspace_Assignment *assignment;
1148             TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
1149                 if (strcmp(assignment->output, current_output->name) != 0)
1150                     continue;
1151
1152                 /* check if this workspace is already attached to the tree */
1153                 Con *workspace = NULL, *out;
1154                 TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
1155                     GREP_FIRST(workspace, output_get_content(out),
1156                                !strcasecmp(child->name, assignment->name));
1157                 if (workspace != NULL)
1158                     continue;
1159
1160                 /* so create the workspace referenced to by this assignment */
1161                 LOG("Creating workspace from assignment %s.\n", assignment->name);
1162                 workspace_get(assignment->name, NULL);
1163                 used_assignment = true;
1164                 break;
1165             }
1166
1167             /* if we couldn't create the workspace using an assignment, create
1168              * it on the output */
1169             if (!used_assignment)
1170                 create_workspace_on_output(current_output, ws->parent);
1171
1172             /* notify the IPC listeners */
1173             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"init\"}");
1174         }
1175         DLOG("Detaching\n");
1176
1177         /* detach from the old output and attach to the new output */
1178         Con *old_content = ws->parent;
1179         con_detach(ws);
1180         if (workspace_was_visible) {
1181             /* The workspace which we just detached was visible, so focus
1182              * the next one in the focus-stack. */
1183             Con *focus_ws = TAILQ_FIRST(&(old_content->focus_head));
1184             LOG("workspace was visible, focusing %p / %s now\n", focus_ws, focus_ws->name);
1185             workspace_show(focus_ws);
1186         }
1187         con_attach(ws, content, false);
1188
1189         /* fix the coordinates of the floating containers */
1190         Con *floating_con;
1191         TAILQ_FOREACH(floating_con, &(ws->floating_head), floating_windows)
1192             floating_fix_coordinates(floating_con, &(old_content->rect), &(content->rect));
1193
1194         ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"move\"}");
1195         if (workspace_was_visible) {
1196             /* Focus the moved workspace on the destination output. */
1197             workspace_show(ws);
1198         }
1199
1200         /* NB: We cannot simply work with previously_visible_ws since it might
1201          * have been cleaned up by workspace_show() already, depending on the
1202          * focus order/number of other workspaces on the output.
1203          * Instead, we loop through the available workspaces and only work with
1204          * previously_visible_ws if we still find it. */
1205         TAILQ_FOREACH(ws, &(content->nodes_head), nodes) {
1206             if (ws != previously_visible_ws)
1207                 continue;
1208
1209             /* Call the on_remove_child callback of the workspace which previously
1210              * was visible on the destination output. Since it is no longer
1211              * visible, it might need to get cleaned up. */
1212             CALL(previously_visible_ws, on_remove_child);
1213             break;
1214         }
1215     }
1216
1217     cmd_output->needs_tree_render = true;
1218     // XXX: default reply for now, make this a better reply
1219     ysuccess(true);
1220 }
1221
1222 /*
1223  * Implementation of 'split v|h|vertical|horizontal'.
1224  *
1225  */
1226 void cmd_split(I3_CMD, char *direction) {
1227     owindow *current;
1228     /* TODO: use matches */
1229     LOG("splitting in direction %c\n", direction[0]);
1230     if (match_is_empty(current_match))
1231         tree_split(focused, (direction[0] == 'v' ? VERT : HORIZ));
1232     else {
1233         TAILQ_FOREACH(current, &owindows, owindows) {
1234             DLOG("matching: %p / %s\n", current->con, current->con->name);
1235             tree_split(current->con, (direction[0] == 'v' ? VERT : HORIZ));
1236         }
1237     }
1238
1239     cmd_output->needs_tree_render = true;
1240     // XXX: default reply for now, make this a better reply
1241     ysuccess(true);
1242 }
1243
1244 /*
1245  * Implementaiton of 'kill [window|client]'.
1246  *
1247  */
1248 void cmd_kill(I3_CMD, char *kill_mode_str) {
1249     if (kill_mode_str == NULL)
1250         kill_mode_str = "window";
1251     owindow *current;
1252
1253     DLOG("kill_mode=%s\n", kill_mode_str);
1254
1255     int kill_mode;
1256     if (strcmp(kill_mode_str, "window") == 0)
1257         kill_mode = KILL_WINDOW;
1258     else if (strcmp(kill_mode_str, "client") == 0)
1259         kill_mode = KILL_CLIENT;
1260     else {
1261         ELOG("BUG: called with kill_mode=%s\n", kill_mode_str);
1262         ysuccess(false);
1263         return;
1264     }
1265
1266     /* check if the match is empty, not if the result is empty */
1267     if (match_is_empty(current_match))
1268         tree_close_con(kill_mode);
1269     else {
1270         TAILQ_FOREACH(current, &owindows, owindows) {
1271             DLOG("matching: %p / %s\n", current->con, current->con->name);
1272             tree_close(current->con, kill_mode, false, false);
1273         }
1274     }
1275
1276     cmd_output->needs_tree_render = true;
1277     // XXX: default reply for now, make this a better reply
1278     ysuccess(true);
1279 }
1280
1281 /*
1282  * Implementation of 'exec [--no-startup-id] <command>'.
1283  *
1284  */
1285 void cmd_exec(I3_CMD, char *nosn, char *command) {
1286     bool no_startup_id = (nosn != NULL);
1287
1288     DLOG("should execute %s, no_startup_id = %d\n", command, no_startup_id);
1289     start_application(command, no_startup_id);
1290
1291     // XXX: default reply for now, make this a better reply
1292     ysuccess(true);
1293 }
1294
1295 /*
1296  * Implementation of 'focus left|right|up|down'.
1297  *
1298  */
1299 void cmd_focus_direction(I3_CMD, char *direction) {
1300     if (focused &&
1301         focused->type != CT_WORKSPACE &&
1302         focused->fullscreen_mode != CF_NONE) {
1303         LOG("Cannot change focus while in fullscreen mode.\n");
1304         ysuccess(false);
1305         return;
1306     }
1307
1308     DLOG("direction = *%s*\n", direction);
1309
1310     if (strcmp(direction, "left") == 0)
1311         tree_next('p', HORIZ);
1312     else if (strcmp(direction, "right") == 0)
1313         tree_next('n', HORIZ);
1314     else if (strcmp(direction, "up") == 0)
1315         tree_next('p', VERT);
1316     else if (strcmp(direction, "down") == 0)
1317         tree_next('n', VERT);
1318     else {
1319         ELOG("Invalid focus direction (%s)\n", direction);
1320         ysuccess(false);
1321         return;
1322     }
1323
1324     cmd_output->needs_tree_render = true;
1325     // XXX: default reply for now, make this a better reply
1326     ysuccess(true);
1327 }
1328
1329 /*
1330  * Implementation of 'focus tiling|floating|mode_toggle'.
1331  *
1332  */
1333 void cmd_focus_window_mode(I3_CMD, char *window_mode) {
1334     if (focused &&
1335         focused->type != CT_WORKSPACE &&
1336         focused->fullscreen_mode != CF_NONE) {
1337         LOG("Cannot change focus while in fullscreen mode.\n");
1338         ysuccess(false);
1339         return;
1340     }
1341
1342     DLOG("window_mode = %s\n", window_mode);
1343
1344     Con *ws = con_get_workspace(focused);
1345     Con *current;
1346     if (ws != NULL) {
1347         if (strcmp(window_mode, "mode_toggle") == 0) {
1348             current = TAILQ_FIRST(&(ws->focus_head));
1349             if (current != NULL && current->type == CT_FLOATING_CON)
1350                 window_mode = "tiling";
1351             else window_mode = "floating";
1352         }
1353         TAILQ_FOREACH(current, &(ws->focus_head), focused) {
1354             if ((strcmp(window_mode, "floating") == 0 && current->type != CT_FLOATING_CON) ||
1355                 (strcmp(window_mode, "tiling") == 0 && current->type == CT_FLOATING_CON))
1356                 continue;
1357
1358             con_focus(con_descend_focused(current));
1359             break;
1360         }
1361     }
1362
1363     cmd_output->needs_tree_render = true;
1364     // XXX: default reply for now, make this a better reply
1365     ysuccess(true);
1366 }
1367
1368 /*
1369  * Implementation of 'focus parent|child'.
1370  *
1371  */
1372 void cmd_focus_level(I3_CMD, char *level) {
1373     DLOG("level = %s\n", level);
1374     bool success = false;
1375
1376     /* Focusing the parent can only be allowed if the newly
1377      * focused container won't escape the fullscreen container. */
1378     if (strcmp(level, "parent") == 0) {
1379         if (focused && focused->parent) {
1380             if (con_fullscreen_permits_focusing(focused->parent))
1381                 success = level_up();
1382             else
1383                 ELOG("'focus parent': Currently in fullscreen, not going up\n");
1384         }
1385     }
1386
1387     /* Focusing a child should always be allowed. */
1388     else success = level_down();
1389
1390     cmd_output->needs_tree_render = success;
1391     // XXX: default reply for now, make this a better reply
1392     ysuccess(success);
1393 }
1394
1395 /*
1396  * Implementation of 'focus'.
1397  *
1398  */
1399 void cmd_focus(I3_CMD) {
1400     DLOG("current_match = %p\n", current_match);
1401
1402     if (match_is_empty(current_match)) {
1403         ELOG("You have to specify which window/container should be focused.\n");
1404         ELOG("Example: [class=\"urxvt\" title=\"irssi\"] focus\n");
1405
1406         y(map_open);
1407         ystr("success");
1408         y(bool, false);
1409         ystr("error");
1410         ystr("You have to specify which window/container should be focused");
1411         y(map_close);
1412
1413         return;
1414     }
1415
1416     int count = 0;
1417     owindow *current;
1418     TAILQ_FOREACH(current, &owindows, owindows) {
1419         Con *ws = con_get_workspace(current->con);
1420         /* If no workspace could be found, this was a dock window.
1421          * Just skip it, you cannot focus dock windows. */
1422         if (!ws)
1423             continue;
1424
1425         /* Check the fullscreen focus constraints. */
1426         if (!con_fullscreen_permits_focusing(current->con)) {
1427             LOG("Cannot change focus while in fullscreen mode (fullscreen rules).\n");
1428             ysuccess(false);
1429             return;
1430         }
1431
1432         /* If the container is not on the current workspace,
1433          * workspace_show() will switch to a different workspace and (if
1434          * enabled) trigger a mouse pointer warp to the currently focused
1435          * container (!) on the target workspace.
1436          *
1437          * Therefore, before calling workspace_show(), we make sure that
1438          * 'current' will be focused on the workspace. However, we cannot
1439          * just con_focus(current) because then the pointer will not be
1440          * warped at all (the code thinks we are already there).
1441          *
1442          * So we focus 'current' to make it the currently focused window of
1443          * the target workspace, then revert focus. */
1444         Con *currently_focused = focused;
1445         con_focus(current->con);
1446         con_focus(currently_focused);
1447
1448         /* Now switch to the workspace, then focus */
1449         workspace_show(ws);
1450         LOG("focusing %p / %s\n", current->con, current->con->name);
1451         con_focus(current->con);
1452         count++;
1453     }
1454
1455     if (count > 1)
1456         LOG("WARNING: Your criteria for the focus command matches %d containers, "
1457             "while only exactly one container can be focused at a time.\n", count);
1458
1459     cmd_output->needs_tree_render = true;
1460     // XXX: default reply for now, make this a better reply
1461     ysuccess(true);
1462 }
1463
1464 /*
1465  * Implementation of 'fullscreen [global]'.
1466  *
1467  */
1468 void cmd_fullscreen(I3_CMD, char *fullscreen_mode) {
1469     if (fullscreen_mode == NULL)
1470         fullscreen_mode = "output";
1471     DLOG("toggling fullscreen, mode = %s\n", fullscreen_mode);
1472     owindow *current;
1473
1474     HANDLE_EMPTY_MATCH;
1475
1476     TAILQ_FOREACH(current, &owindows, owindows) {
1477         printf("matching: %p / %s\n", current->con, current->con->name);
1478         con_toggle_fullscreen(current->con, (strcmp(fullscreen_mode, "global") == 0 ? CF_GLOBAL : CF_OUTPUT));
1479     }
1480
1481     cmd_output->needs_tree_render = true;
1482     // XXX: default reply for now, make this a better reply
1483     ysuccess(true);
1484 }
1485
1486 /*
1487  * Implementation of 'move <direction> [<pixels> [px]]'.
1488  *
1489  */
1490 void cmd_move_direction(I3_CMD, char *direction, char *move_px) {
1491     // TODO: We could either handle this in the parser itself as a separate token (and make the stack typed) or we need a better way to convert a string to a number with error checking
1492     int px = atoi(move_px);
1493
1494     /* TODO: make 'move' work with criteria. */
1495     DLOG("moving in direction %s, px %s\n", direction, move_px);
1496     if (con_is_floating(focused)) {
1497         DLOG("floating move with %d pixels\n", px);
1498         Rect newrect = focused->parent->rect;
1499         if (strcmp(direction, "left") == 0) {
1500             newrect.x -= px;
1501         } else if (strcmp(direction, "right") == 0) {
1502             newrect.x += px;
1503         } else if (strcmp(direction, "up") == 0) {
1504             newrect.y -= px;
1505         } else if (strcmp(direction, "down") == 0) {
1506             newrect.y += px;
1507         }
1508         floating_reposition(focused->parent, newrect);
1509     } else {
1510         tree_move((strcmp(direction, "right") == 0 ? D_RIGHT :
1511                    (strcmp(direction, "left") == 0 ? D_LEFT :
1512                     (strcmp(direction, "up") == 0 ? D_UP :
1513                      D_DOWN))));
1514         cmd_output->needs_tree_render = true;
1515     }
1516
1517     // XXX: default reply for now, make this a better reply
1518     ysuccess(true);
1519 }
1520
1521 /*
1522  * Implementation of 'layout default|stacked|stacking|tabbed|splitv|splith'.
1523  *
1524  */
1525 void cmd_layout(I3_CMD, char *layout_str) {
1526     if (strcmp(layout_str, "stacking") == 0)
1527         layout_str = "stacked";
1528     owindow *current;
1529     int layout;
1530     /* default is a special case which will be handled in con_set_layout(). */
1531     if (strcmp(layout_str, "default") == 0)
1532         layout = L_DEFAULT;
1533     else if (strcmp(layout_str, "stacked") == 0)
1534         layout = L_STACKED;
1535     else if (strcmp(layout_str, "tabbed") == 0)
1536         layout = L_TABBED;
1537     else if (strcmp(layout_str, "splitv") == 0)
1538         layout = L_SPLITV;
1539     else if (strcmp(layout_str, "splith") == 0)
1540         layout = L_SPLITH;
1541     else {
1542         ELOG("Unknown layout \"%s\", this is a mismatch between code and parser spec.\n", layout_str);
1543         return;
1544     }
1545
1546     DLOG("changing layout to %s (%d)\n", layout_str, layout);
1547
1548     /* check if the match is empty, not if the result is empty */
1549     if (match_is_empty(current_match))
1550         con_set_layout(focused, layout);
1551     else {
1552         TAILQ_FOREACH(current, &owindows, owindows) {
1553             DLOG("matching: %p / %s\n", current->con, current->con->name);
1554             con_set_layout(current->con, layout);
1555         }
1556     }
1557
1558     cmd_output->needs_tree_render = true;
1559     // XXX: default reply for now, make this a better reply
1560     ysuccess(true);
1561 }
1562
1563 /*
1564  * Implementation of 'layout toggle [all|split]'.
1565  *
1566  */
1567 void cmd_layout_toggle(I3_CMD, char *toggle_mode) {
1568     owindow *current;
1569
1570     if (toggle_mode == NULL)
1571         toggle_mode = "default";
1572
1573     DLOG("toggling layout (mode = %s)\n", toggle_mode);
1574
1575     /* check if the match is empty, not if the result is empty */
1576     if (match_is_empty(current_match))
1577         con_toggle_layout(focused, toggle_mode);
1578     else {
1579         TAILQ_FOREACH(current, &owindows, owindows) {
1580             DLOG("matching: %p / %s\n", current->con, current->con->name);
1581             con_toggle_layout(current->con, toggle_mode);
1582         }
1583     }
1584
1585     cmd_output->needs_tree_render = true;
1586     // XXX: default reply for now, make this a better reply
1587     ysuccess(true);
1588 }
1589
1590 /*
1591  * Implementaiton of 'exit'.
1592  *
1593  */
1594 void cmd_exit(I3_CMD) {
1595     LOG("Exiting due to user command.\n");
1596     xcb_disconnect(conn);
1597     exit(0);
1598
1599     /* unreached */
1600 }
1601
1602 /*
1603  * Implementaiton of 'reload'.
1604  *
1605  */
1606 void cmd_reload(I3_CMD) {
1607     LOG("reloading\n");
1608     kill_configerror_nagbar(false);
1609     kill_commanderror_nagbar(false);
1610     load_configuration(conn, NULL, true);
1611     x_set_i3_atoms();
1612     /* Send an IPC event just in case the ws names have changed */
1613     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"reload\"}");
1614
1615     // XXX: default reply for now, make this a better reply
1616     ysuccess(true);
1617 }
1618
1619 /*
1620  * Implementaiton of 'restart'.
1621  *
1622  */
1623 void cmd_restart(I3_CMD) {
1624     LOG("restarting i3\n");
1625     i3_restart(false);
1626
1627     // XXX: default reply for now, make this a better reply
1628     ysuccess(true);
1629 }
1630
1631 /*
1632  * Implementaiton of 'open'.
1633  *
1634  */
1635 void cmd_open(I3_CMD) {
1636     LOG("opening new container\n");
1637     Con *con = tree_open_con(NULL, NULL);
1638     con->layout = L_SPLITH;
1639     con_focus(con);
1640
1641     y(map_open);
1642     ystr("success");
1643     y(bool, true);
1644     ystr("id");
1645     y(integer, (long int)con);
1646     y(map_close);
1647
1648     cmd_output->needs_tree_render = true;
1649 }
1650
1651 /*
1652  * Implementation of 'focus output <output>'.
1653  *
1654  */
1655 void cmd_focus_output(I3_CMD, char *name) {
1656     owindow *current;
1657
1658     DLOG("name = %s\n", name);
1659
1660     HANDLE_EMPTY_MATCH;
1661
1662     /* get the output */
1663     Output *current_output = NULL;
1664     Output *output;
1665
1666     TAILQ_FOREACH(current, &owindows, owindows)
1667         current_output = get_output_containing(current->con->rect.x, current->con->rect.y);
1668     assert(current_output != NULL);
1669
1670     output = get_output_from_string(current_output, name);
1671
1672     if (!output) {
1673         LOG("No such output found.\n");
1674         ysuccess(false);
1675         return;
1676     }
1677
1678     /* get visible workspace on output */
1679     Con *ws = NULL;
1680     GREP_FIRST(ws, output_get_content(output->con), workspace_is_visible(child));
1681     if (!ws) {
1682         ysuccess(false);
1683         return;
1684     }
1685
1686     workspace_show(ws);
1687
1688     cmd_output->needs_tree_render = true;
1689     // XXX: default reply for now, make this a better reply
1690     ysuccess(true);
1691 }
1692
1693 /*
1694  * Implementation of 'move [window|container] [to] [absolute] position <px> [px] <px> [px]
1695  *
1696  */
1697 void cmd_move_window_to_position(I3_CMD, char *method, char *cx, char *cy) {
1698
1699     int x = atoi(cx);
1700     int y = atoi(cy);
1701
1702     if (!con_is_floating(focused)) {
1703         ELOG("Cannot change position. The window/container is not floating\n");
1704         y(map_open);
1705         ystr("success");
1706         y(bool, false);
1707         ystr("error");
1708         ystr("Cannot change position. The window/container is not floating.");
1709         y(map_close);
1710         return;
1711     }
1712
1713     if (strcmp(method, "absolute") == 0) {
1714         focused->parent->rect.x = x;
1715         focused->parent->rect.y = y;
1716
1717         DLOG("moving to absolute position %d %d\n", x, y);
1718         floating_maybe_reassign_ws(focused->parent);
1719         cmd_output->needs_tree_render = true;
1720     }
1721
1722     if (strcmp(method, "position") == 0) {
1723         Rect newrect = focused->parent->rect;
1724
1725         DLOG("moving to position %d %d\n", x, y);
1726         newrect.x = x;
1727         newrect.y = y;
1728
1729         floating_reposition(focused->parent, newrect);
1730     }
1731
1732     // XXX: default reply for now, make this a better reply
1733     ysuccess(true);
1734 }
1735
1736 /*
1737  * Implementation of 'move [window|container] [to] [absolute] position center
1738  *
1739  */
1740 void cmd_move_window_to_center(I3_CMD, char *method) {
1741
1742     if (!con_is_floating(focused)) {
1743         ELOG("Cannot change position. The window/container is not floating\n");
1744         y(map_open);
1745         ystr("success");
1746         y(bool, false);
1747         ystr("error");
1748         ystr("Cannot change position. The window/container is not floating.");
1749         y(map_close);
1750     }
1751
1752     if (strcmp(method, "absolute") == 0) {
1753         Rect *rect = &focused->parent->rect;
1754
1755         DLOG("moving to absolute center\n");
1756         rect->x = croot->rect.width/2 - rect->width/2;
1757         rect->y = croot->rect.height/2 - rect->height/2;
1758
1759         floating_maybe_reassign_ws(focused->parent);
1760         cmd_output->needs_tree_render = true;
1761     }
1762
1763     if (strcmp(method, "position") == 0) {
1764         Rect *wsrect = &con_get_workspace(focused)->rect;
1765         Rect newrect = focused->parent->rect;
1766
1767         DLOG("moving to center\n");
1768         newrect.x = wsrect->width/2 - newrect.width/2;
1769         newrect.y = wsrect->height/2 - newrect.height/2;
1770
1771         floating_reposition(focused->parent, newrect);
1772     }
1773
1774     // XXX: default reply for now, make this a better reply
1775     ysuccess(true);
1776 }
1777
1778 /*
1779  * Implementation of 'move scratchpad'.
1780  *
1781  */
1782 void cmd_move_scratchpad(I3_CMD) {
1783     DLOG("should move window to scratchpad\n");
1784     owindow *current;
1785
1786     HANDLE_EMPTY_MATCH;
1787
1788     TAILQ_FOREACH(current, &owindows, owindows) {
1789         DLOG("matching: %p / %s\n", current->con, current->con->name);
1790         scratchpad_move(current->con);
1791     }
1792
1793     cmd_output->needs_tree_render = true;
1794     // XXX: default reply for now, make this a better reply
1795     ysuccess(true);
1796 }
1797
1798 /*
1799  * Implementation of 'scratchpad show'.
1800  *
1801  */
1802 void cmd_scratchpad_show(I3_CMD) {
1803     DLOG("should show scratchpad window\n");
1804     owindow *current;
1805
1806     if (match_is_empty(current_match)) {
1807         scratchpad_show(NULL);
1808     } else {
1809         TAILQ_FOREACH(current, &owindows, owindows) {
1810             DLOG("matching: %p / %s\n", current->con, current->con->name);
1811             scratchpad_show(current->con);
1812         }
1813     }
1814
1815     cmd_output->needs_tree_render = true;
1816     // XXX: default reply for now, make this a better reply
1817     ysuccess(true);
1818 }
1819
1820 /*
1821  * Implementation of 'rename workspace <name> to <name>'
1822  *
1823  */
1824 void cmd_rename_workspace(I3_CMD, char *old_name, char *new_name) {
1825     LOG("Renaming workspace \"%s\" to \"%s\"\n", old_name, new_name);
1826
1827     Con *output, *workspace = NULL;
1828     TAILQ_FOREACH(output, &(croot->nodes_head), nodes)
1829         GREP_FIRST(workspace, output_get_content(output),
1830             !strcasecmp(child->name, old_name));
1831
1832     if (!workspace) {
1833         // TODO: we should include the old workspace name here and use yajl for
1834         // generating the reply.
1835         y(map_open);
1836         ystr("success");
1837         y(bool, false);
1838         ystr("error");
1839         // TODO: better error message
1840         ystr("Old workspace not found");
1841         y(map_close);
1842         return;
1843     }
1844
1845     Con *check_dest = NULL;
1846     TAILQ_FOREACH(output, &(croot->nodes_head), nodes)
1847         GREP_FIRST(check_dest, output_get_content(output),
1848             !strcasecmp(child->name, new_name));
1849
1850     if (check_dest != NULL) {
1851         // TODO: we should include the new workspace name here and use yajl for
1852         // generating the reply.
1853         y(map_open);
1854         ystr("success");
1855         y(bool, false);
1856         ystr("error");
1857         // TODO: better error message
1858         ystr("New workspace already exists");
1859         y(map_close);
1860         return;
1861     }
1862
1863     /* Change the name and try to parse it as a number. */
1864     FREE(workspace->name);
1865     workspace->name = sstrdup(new_name);
1866     char *endptr = NULL;
1867     long parsed_num = strtol(new_name, &endptr, 10);
1868     if (parsed_num == LONG_MIN ||
1869         parsed_num == LONG_MAX ||
1870         parsed_num < 0 ||
1871         endptr == new_name)
1872         workspace->num = -1;
1873     else workspace->num = parsed_num;
1874     LOG("num = %d\n", workspace->num);
1875
1876     /* By re-attaching, the sort order will be correct afterwards. */
1877     Con *previously_focused = focused;
1878     Con *parent = workspace->parent;
1879     con_detach(workspace);
1880     con_attach(workspace, parent, false);
1881     /* Restore the previous focus since con_attach messes with the focus. */
1882     con_focus(previously_focused);
1883
1884     cmd_output->needs_tree_render = true;
1885     ysuccess(true);
1886
1887     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"rename\"}");
1888 }