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