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