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