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