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