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