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