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