]> git.sur5r.net Git - i3/i3/blob - src/commands.c
da8bccbae19e962f2b43392b514ab396cedbcbe6
[i3/i3] / src / commands.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * commands.c: all command functions (see commands_parser.c)
8  *
9  */
10 #include <float.h>
11 #include <stdarg.h>
12
13 #include "all.h"
14
15 /** When the command did not include match criteria (!), we use the currently
16  * focused command. Do not confuse this case with a command which included
17  * criteria but which did not match any windows. This macro has to be called in
18  * every command.
19  */
20 #define HANDLE_EMPTY_MATCH do { \
21     if (match_is_empty(current_match)) { \
22         owindow *ow = smalloc(sizeof(owindow)); \
23         ow->con = focused; \
24         TAILQ_INIT(&owindows); \
25         TAILQ_INSERT_TAIL(&owindows, ow, owindows); \
26     } \
27 } while (0)
28
29 static owindows_head owindows;
30
31 /*
32  * Returns true if a is definitely greater than b (using the given epsilon)
33  *
34  */
35 static bool definitelyGreaterThan(float a, float b, float epsilon) {
36     return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
37 }
38
39 /*
40  * Returns an 'output' corresponding to one of left/right/down/up or a specific
41  * output name.
42  *
43  */
44 static Output *get_output_from_string(Output *current_output, const char *output_str) {
45     Output *output;
46
47     if (strcasecmp(output_str, "left") == 0) {
48         output = get_output_next(D_LEFT, current_output);
49         if (!output)
50             output = get_output_most(D_RIGHT, current_output);
51     } else if (strcasecmp(output_str, "right") == 0) {
52         output = get_output_next(D_RIGHT, current_output);
53         if (!output)
54             output = get_output_most(D_LEFT, current_output);
55     } else if (strcasecmp(output_str, "up") == 0) {
56         output = get_output_next(D_UP, current_output);
57         if (!output)
58             output = get_output_most(D_DOWN, current_output);
59     } else if (strcasecmp(output_str, "down") == 0) {
60         output = get_output_next(D_DOWN, current_output);
61         if (!output)
62             output = get_output_most(D_UP, current_output);
63     } else output = get_output_by_name(output_str);
64
65     return output;
66 }
67
68 // This code is commented out because we might recycle it for popping up error
69 // messages on parser errors.
70 #if 0
71 static pid_t migration_pid = -1;
72
73 /*
74  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
75  * it exited (or could not be started, depending on the exit code).
76  *
77  */
78 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
79     ev_child_stop(EV_A_ watcher);
80     if (!WIFEXITED(watcher->rstatus)) {
81         fprintf(stderr, "ERROR: i3-nagbar did not exit normally.\n");
82         return;
83     }
84
85     int exitcode = WEXITSTATUS(watcher->rstatus);
86     printf("i3-nagbar process exited with status %d\n", exitcode);
87     if (exitcode == 2) {
88         fprintf(stderr, "ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
89     }
90
91     migration_pid = -1;
92 }
93
94 /* We need ev >= 4 for the following code. Since it is not *that* important (it
95  * only makes sure that there are no i3-nagbar instances left behind) we still
96  * support old systems with libev 3. */
97 #if EV_VERSION_MAJOR >= 4
98 /*
99  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
100  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
101  *
102  */
103 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
104     if (migration_pid != -1) {
105         LOG("Sending SIGKILL (9) to i3-nagbar with PID %d\n", migration_pid);
106         kill(migration_pid, SIGKILL);
107     }
108 }
109 #endif
110
111 void cmd_MIGRATION_start_nagbar() {
112     if (migration_pid != -1) {
113         fprintf(stderr, "i3-nagbar already running.\n");
114         return;
115     }
116     fprintf(stderr, "Starting i3-nagbar, command parsing differs from expected output.\n");
117     ELOG("Please report this on IRC or in the bugtracker. Make sure to include the full debug level logfile:\n");
118     ELOG("i3-dump-log | gzip -9c > /tmp/i3.log.gz\n");
119     ELOG("FYI: Your i3 version is " I3_VERSION "\n");
120     migration_pid = fork();
121     if (migration_pid == -1) {
122         warn("Could not fork()");
123         return;
124     }
125
126     /* child */
127     if (migration_pid == 0) {
128         char *pageraction;
129         sasprintf(&pageraction, "i3-sensible-terminal -e i3-sensible-pager \"%s\"", errorfilename);
130         char *argv[] = {
131             NULL, /* will be replaced by the executable path */
132             "-t",
133             "error",
134             "-m",
135             "You found a parsing error. Please, please, please, report it!",
136             "-b",
137             "show errors",
138             pageraction,
139             NULL
140         };
141         exec_i3_utility("i3-nagbar", argv);
142     }
143
144     /* parent */
145     /* install a child watcher */
146     ev_child *child = smalloc(sizeof(ev_child));
147     ev_child_init(child, &nagbar_exited, migration_pid, 0);
148     ev_child_start(main_loop, child);
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     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
155      * still running) */
156     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
157     ev_cleanup_init(cleanup, nagbar_cleanup);
158     ev_cleanup_start(main_loop, cleanup);
159 #endif
160 }
161
162 #endif
163
164 /*******************************************************************************
165  * Criteria functions.
166  ******************************************************************************/
167
168 /*
169  * Initializes the specified 'Match' data structure and the initial state of
170  * commands.c for matching target windows of a command.
171  *
172  */
173 char *cmd_criteria_init(Match *current_match) {
174     Con *con;
175     owindow *ow;
176
177     DLOG("Initializing criteria, current_match = %p\n", current_match);
178     match_init(current_match);
179     while (!TAILQ_EMPTY(&owindows)) {
180         ow = TAILQ_FIRST(&owindows);
181         TAILQ_REMOVE(&owindows, ow, owindows);
182         free(ow);
183     }
184     TAILQ_INIT(&owindows);
185     /* copy all_cons */
186     TAILQ_FOREACH(con, &all_cons, all_cons) {
187         ow = smalloc(sizeof(owindow));
188         ow->con = con;
189         TAILQ_INSERT_TAIL(&owindows, ow, owindows);
190     }
191
192     /* This command is internal and does not generate a JSON reply. */
193     return NULL;
194 }
195
196 /*
197  * A match specification just finished (the closing square bracket was found),
198  * so we filter the list of owindows.
199  *
200  */
201 char *cmd_criteria_match_windows(Match *current_match) {
202     owindow *next, *current;
203
204     DLOG("match specification finished, matching...\n");
205     /* copy the old list head to iterate through it and start with a fresh
206      * list which will contain only matching windows */
207     struct owindows_head old = owindows;
208     TAILQ_INIT(&owindows);
209     for (next = TAILQ_FIRST(&old); next != TAILQ_END(&old);) {
210         /* make a copy of the next pointer and advance the pointer to the
211          * next element as we are going to invalidate the element’s
212          * next/prev pointers by calling TAILQ_INSERT_TAIL later */
213         current = next;
214         next = TAILQ_NEXT(next, owindows);
215
216         DLOG("checking if con %p / %s matches\n", current->con, current->con->name);
217         if (current_match->con_id != NULL) {
218             if (current_match->con_id == current->con) {
219                 DLOG("matches container!\n");
220                 TAILQ_INSERT_TAIL(&owindows, current, owindows);
221             }
222         } else if (current_match->mark != NULL && current->con->mark != NULL &&
223                    regex_matches(current_match->mark, current->con->mark)) {
224             DLOG("match by mark\n");
225             TAILQ_INSERT_TAIL(&owindows, current, owindows);
226         } else {
227             if (current->con->window == NULL)
228                 continue;
229             if (match_matches_window(current_match, current->con->window)) {
230                 DLOG("matches window!\n");
231                 TAILQ_INSERT_TAIL(&owindows, current, owindows);
232             } else {
233                 DLOG("doesnt match\n");
234                 free(current);
235             }
236         }
237     }
238
239     TAILQ_FOREACH(current, &owindows, owindows) {
240         DLOG("matching: %p / %s\n", current->con, current->con->name);
241     }
242
243     /* This command is internal and does not generate a JSON reply. */
244     return NULL;
245 }
246
247 /*
248  * Interprets a ctype=cvalue pair and adds it to the current match
249  * specification.
250  *
251  */
252 char *cmd_criteria_add(Match *current_match, char *ctype, char *cvalue) {
253     DLOG("ctype=*%s*, cvalue=*%s*\n", ctype, cvalue);
254
255     if (strcmp(ctype, "class") == 0) {
256         current_match->class = regex_new(cvalue);
257         return NULL;
258     }
259
260     if (strcmp(ctype, "instance") == 0) {
261         current_match->instance = regex_new(cvalue);
262         return NULL;
263     }
264
265     if (strcmp(ctype, "window_role") == 0) {
266         current_match->role = regex_new(cvalue);
267         return NULL;
268     }
269
270     if (strcmp(ctype, "con_id") == 0) {
271         char *end;
272         long parsed = strtol(cvalue, &end, 10);
273         if (parsed == LONG_MIN ||
274             parsed == LONG_MAX ||
275             parsed < 0 ||
276             (end && *end != '\0')) {
277             ELOG("Could not parse con id \"%s\"\n", cvalue);
278         } else {
279             current_match->con_id = (Con*)parsed;
280             printf("id as int = %p\n", current_match->con_id);
281         }
282         return NULL;
283     }
284
285     if (strcmp(ctype, "id") == 0) {
286         char *end;
287         long parsed = strtol(cvalue, &end, 10);
288         if (parsed == LONG_MIN ||
289             parsed == LONG_MAX ||
290             parsed < 0 ||
291             (end && *end != '\0')) {
292             ELOG("Could not parse window id \"%s\"\n", cvalue);
293         } else {
294             current_match->id = parsed;
295             printf("window id as int = %d\n", current_match->id);
296         }
297         return NULL;
298     }
299
300     if (strcmp(ctype, "con_mark") == 0) {
301         current_match->mark = regex_new(cvalue);
302         return NULL;
303     }
304
305     if (strcmp(ctype, "title") == 0) {
306         current_match->title = regex_new(cvalue);
307         return NULL;
308     }
309
310     if (strcmp(ctype, "urgent") == 0) {
311         if (strcasecmp(cvalue, "latest") == 0 ||
312             strcasecmp(cvalue, "newest") == 0 ||
313             strcasecmp(cvalue, "recent") == 0 ||
314             strcasecmp(cvalue, "last") == 0) {
315             current_match->urgent = U_LATEST;
316         } else if (strcasecmp(cvalue, "oldest") == 0 ||
317                    strcasecmp(cvalue, "first") == 0) {
318             current_match->urgent = U_OLDEST;
319         }
320         return NULL;
321     }
322
323     ELOG("Unknown criterion: %s\n", ctype);
324
325     /* This command is internal and does not generate a JSON reply. */
326     return NULL;
327 }
328
329 /*
330  * Implementation of 'move [window|container] [to] workspace
331  * next|prev|next_on_output|prev_on_output'.
332  *
333  */
334 char *cmd_move_con_to_workspace(Match *current_match, char *which) {
335     owindow *current;
336
337     DLOG("which=%s\n", which);
338
339     HANDLE_EMPTY_MATCH;
340
341     /* get the workspace */
342     Con *ws;
343     if (strcmp(which, "next") == 0)
344         ws = workspace_next();
345     else if (strcmp(which, "prev") == 0)
346         ws = workspace_prev();
347     else if (strcmp(which, "next_on_output") == 0)
348         ws = workspace_next_on_output();
349     else if (strcmp(which, "prev_on_output") == 0)
350         ws = workspace_prev_on_output();
351     else {
352         ELOG("BUG: called with which=%s\n", which);
353         return sstrdup("{\"sucess\": false}");
354     }
355
356     TAILQ_FOREACH(current, &owindows, owindows) {
357         DLOG("matching: %p / %s\n", current->con, current->con->name);
358         con_move_to_workspace(current->con, ws, true, false);
359     }
360
361     tree_render();
362
363     // XXX: default reply for now, make this a better reply
364     return sstrdup("{\"success\": true}");
365 }
366
367 /*
368  * Implementation of 'move [window|container] [to] workspace <name>'.
369  *
370  */
371 char *cmd_move_con_to_workspace_name(Match *current_match, char *name) {
372     if (strncasecmp(name, "__i3_", strlen("__i3_")) == 0) {
373         LOG("You cannot switch to the i3 internal workspaces.\n");
374         return sstrdup("{\"sucess\": false}");
375     }
376
377     owindow *current;
378
379     /* Error out early to not create a non-existing workspace (in
380      * workspace_get()) if we are not actually able to move anything. */
381     if (match_is_empty(current_match) && focused->type == CT_WORKSPACE)
382         return sstrdup("{\"sucess\": false}");
383
384     LOG("should move window to workspace %s\n", name);
385     /* get the workspace */
386     Con *ws = workspace_get(name, NULL);
387
388     HANDLE_EMPTY_MATCH;
389
390     TAILQ_FOREACH(current, &owindows, owindows) {
391         DLOG("matching: %p / %s\n", current->con, current->con->name);
392         con_move_to_workspace(current->con, ws, true, false);
393     }
394
395     tree_render();
396
397     // XXX: default reply for now, make this a better reply
398     return sstrdup("{\"success\": true}");
399 }
400
401 /*
402  * Implementation of 'resize grow|shrink <direction> [<px> px] [or <ppt> ppt]'.
403  *
404  */
405 char *cmd_resize(Match *current_match, char *way, char *direction, char *resize_px, char *resize_ppt) {
406     /* resize <grow|shrink> <direction> [<px> px] [or <ppt> ppt] */
407     DLOG("resizing in way %s, direction %s, px %s or ppt %s\n", way, direction, resize_px, resize_ppt);
408     // 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
409     int px = atoi(resize_px);
410     int ppt = atoi(resize_ppt);
411     if (strcmp(way, "shrink") == 0) {
412         px *= -1;
413         ppt *= -1;
414     }
415
416     Con *floating_con;
417     if ((floating_con = con_inside_floating(focused))) {
418         printf("floating resize\n");
419         if (strcmp(direction, "up") == 0) {
420             floating_con->rect.y -= px;
421             floating_con->rect.height += px;
422         } else if (strcmp(direction, "down") == 0) {
423             floating_con->rect.height += px;
424         } else if (strcmp(direction, "left") == 0) {
425             floating_con->rect.x -= px;
426             floating_con->rect.width += px;
427         } else {
428             floating_con->rect.width += px;
429         }
430     } else {
431         LOG("tiling resize\n");
432         /* get the appropriate current container (skip stacked/tabbed cons) */
433         Con *current = focused;
434         while (current->parent->layout == L_STACKED ||
435                current->parent->layout == L_TABBED)
436             current = current->parent;
437
438         /* Then further go up until we find one with the matching orientation. */
439         orientation_t search_orientation =
440             (strcmp(direction, "left") == 0 || strcmp(direction, "right") == 0 ? HORIZ : VERT);
441
442         while (current->type != CT_WORKSPACE &&
443                current->type != CT_FLOATING_CON &&
444                current->parent->orientation != search_orientation)
445             current = current->parent;
446
447         /* get the default percentage */
448         int children = con_num_children(current->parent);
449         Con *other;
450         LOG("ins. %d children\n", children);
451         double percentage = 1.0 / children;
452         LOG("default percentage = %f\n", percentage);
453
454         orientation_t orientation = current->parent->orientation;
455
456         if ((orientation == HORIZ &&
457              (strcmp(direction, "up") == 0 || strcmp(direction, "down") == 0)) ||
458             (orientation == VERT &&
459              (strcmp(direction, "left") == 0 || strcmp(direction, "right") == 0))) {
460             LOG("You cannot resize in that direction. Your focus is in a %s split container currently.\n",
461                 (orientation == HORIZ ? "horizontal" : "vertical"));
462             return sstrdup("{\"sucess\": false}");
463         }
464
465         if (strcmp(direction, "up") == 0 || strcmp(direction, "left") == 0) {
466             other = TAILQ_PREV(current, nodes_head, nodes);
467         } else {
468             other = TAILQ_NEXT(current, nodes);
469         }
470         if (other == TAILQ_END(workspaces)) {
471             LOG("No other container in this direction found, cannot resize.\n");
472             return sstrdup("{\"sucess\": false}");
473         }
474         LOG("other->percent = %f\n", other->percent);
475         LOG("current->percent before = %f\n", current->percent);
476         if (current->percent == 0.0)
477             current->percent = percentage;
478         if (other->percent == 0.0)
479             other->percent = percentage;
480         double new_current_percent = current->percent + ((double)ppt / 100.0);
481         double new_other_percent = other->percent - ((double)ppt / 100.0);
482         LOG("new_current_percent = %f\n", new_current_percent);
483         LOG("new_other_percent = %f\n", new_other_percent);
484         /* Ensure that the new percentages are positive and greater than
485          * 0.05 to have a reasonable minimum size. */
486         if (definitelyGreaterThan(new_current_percent, 0.05, DBL_EPSILON) &&
487             definitelyGreaterThan(new_other_percent, 0.05, DBL_EPSILON)) {
488             current->percent += ((double)ppt / 100.0);
489             other->percent -= ((double)ppt / 100.0);
490             LOG("current->percent after = %f\n", current->percent);
491             LOG("other->percent after = %f\n", other->percent);
492         } else {
493             LOG("Not resizing, already at minimum size\n");
494         }
495     }
496
497     tree_render();
498
499     // XXX: default reply for now, make this a better reply
500     return sstrdup("{\"success\": true}");
501 }
502
503 /*
504  * Implementation of 'border normal|none|1pixel|toggle'.
505  *
506  */
507 char *cmd_border(Match *current_match, char *border_style_str) {
508     DLOG("border style should be changed to %s\n", border_style_str);
509     owindow *current;
510
511     HANDLE_EMPTY_MATCH;
512
513     TAILQ_FOREACH(current, &owindows, owindows) {
514         DLOG("matching: %p / %s\n", current->con, current->con->name);
515         int border_style = current->con->border_style;
516         if (strcmp(border_style_str, "toggle") == 0) {
517             border_style++;
518             border_style %= 3;
519         } else {
520             if (strcmp(border_style_str, "normal") == 0)
521                 border_style = BS_NORMAL;
522             else if (strcmp(border_style_str, "none") == 0)
523                 border_style = BS_NONE;
524             else if (strcmp(border_style_str, "1pixel") == 0)
525                 border_style = BS_1PIXEL;
526             else {
527                 ELOG("BUG: called with border_style=%s\n", border_style_str);
528                 return sstrdup("{\"sucess\": false}");
529             }
530         }
531         con_set_border_style(current->con, border_style);
532     }
533
534     tree_render();
535
536     // XXX: default reply for now, make this a better reply
537     return sstrdup("{\"success\": true}");
538 }
539
540 /*
541  * Implementation of 'nop <comment>'.
542  *
543  */
544 char *cmd_nop(Match *current_match, char *comment) {
545     LOG("-------------------------------------------------\n");
546     LOG("  NOP: %s\n", comment);
547     LOG("-------------------------------------------------\n");
548
549     return NULL;
550 }
551
552 /*
553  * Implementation of 'append_layout <path>'.
554  *
555  */
556 char *cmd_append_layout(Match *current_match, char *path) {
557     LOG("Appending layout \"%s\"\n", path);
558     tree_append_json(path);
559     tree_render();
560
561     // XXX: default reply for now, make this a better reply
562     return sstrdup("{\"success\": true}");
563 }
564
565 /*
566  * Implementation of 'workspace next|prev|next_on_output|prev_on_output'.
567  *
568  */
569 char *cmd_workspace(Match *current_match, char *which) {
570     Con *ws;
571
572     DLOG("which=%s\n", which);
573
574     if (strcmp(which, "next") == 0)
575         ws = workspace_next();
576     else if (strcmp(which, "prev") == 0)
577         ws = workspace_prev();
578     else if (strcmp(which, "next_on_output") == 0)
579         ws = workspace_next_on_output();
580     else if (strcmp(which, "prev_on_output") == 0)
581         ws = workspace_prev_on_output();
582     else {
583         ELOG("BUG: called with which=%s\n", which);
584         return sstrdup("{\"sucess\": false}");
585     }
586
587     workspace_show(ws);
588     tree_render();
589
590     // XXX: default reply for now, make this a better reply
591     return sstrdup("{\"success\": true}");
592 }
593
594 /*
595  * Implementation of 'workspace back_and_forth'.
596  *
597  */
598 char *cmd_workspace_back_and_forth(Match *current_match) {
599     workspace_back_and_forth();
600     tree_render();
601
602     // XXX: default reply for now, make this a better reply
603     return sstrdup("{\"success\": true}");
604 }
605
606 /*
607  * Implementation of 'workspace <name>'
608  *
609  */
610 char *cmd_workspace_name(Match *current_match, char *name) {
611     if (strncasecmp(name, "__i3_", strlen("__i3_")) == 0) {
612         LOG("You cannot switch to the i3 internal workspaces.\n");
613         return sstrdup("{\"sucess\": false}");
614     }
615
616     DLOG("should switch to workspace %s\n", name);
617
618     Con *ws = con_get_workspace(focused);
619
620     /* Check if the command wants to switch to the current workspace */
621     if (strcmp(ws->name, name) == 0) {
622         DLOG("This workspace is already focused.\n");
623         if (config.workspace_auto_back_and_forth) {
624             workspace_back_and_forth();
625             tree_render();
626         }
627         return sstrdup("{\"sucess\": false}");
628     }
629
630     workspace_show_by_name(name);
631
632     tree_render();
633
634     // XXX: default reply for now, make this a better reply
635     return sstrdup("{\"success\": true}");
636 }
637
638 /*
639  * Implementation of 'mark <mark>'
640  *
641  */
642 char *cmd_mark(Match *current_match, char *mark) {
643     DLOG("Clearing all windows which have that mark first\n");
644
645     Con *con;
646     TAILQ_FOREACH(con, &all_cons, all_cons) {
647         if (con->mark && strcmp(con->mark, mark) == 0)
648             FREE(con->mark);
649     }
650
651     DLOG("marking window with str %s\n", mark);
652     owindow *current;
653
654     HANDLE_EMPTY_MATCH;
655
656     TAILQ_FOREACH(current, &owindows, owindows) {
657         DLOG("matching: %p / %s\n", current->con, current->con->name);
658         current->con->mark = sstrdup(mark);
659     }
660
661     tree_render();
662
663     // XXX: default reply for now, make this a better reply
664     return sstrdup("{\"success\": true}");
665 }
666
667 /*
668  * Implementation of 'mode <string>'.
669  *
670  */
671 char *cmd_mode(Match *current_match, char *mode) {
672     DLOG("mode=%s\n", mode);
673     switch_mode(mode);
674
675     // XXX: default reply for now, make this a better reply
676     return sstrdup("{\"success\": true}");
677 }
678
679 /*
680  * Implementation of 'move [window|container] [to] output <str>'.
681  *
682  */
683 char *cmd_move_con_to_output(Match *current_match, char *name) {
684     owindow *current;
685
686     DLOG("should move window to output %s\n", name);
687
688     HANDLE_EMPTY_MATCH;
689
690     /* get the output */
691     Output *current_output = NULL;
692     Output *output;
693
694     // TODO: fix the handling of criteria
695     TAILQ_FOREACH(current, &owindows, owindows)
696         current_output = get_output_containing(current->con->rect.x, current->con->rect.y);
697
698     assert(current_output != NULL);
699
700     // TODO: clean this up with commands.spec as soon as we switched away from the lex/yacc command parser
701     if (strcasecmp(name, "up") == 0)
702         output = get_output_next(D_UP, current_output);
703     else if (strcasecmp(name, "down") == 0)
704         output = get_output_next(D_DOWN, current_output);
705     else if (strcasecmp(name, "left") == 0)
706         output = get_output_next(D_LEFT, current_output);
707     else if (strcasecmp(name, "right") == 0)
708         output = get_output_next(D_RIGHT, current_output);
709     else
710         output = get_output_by_name(name);
711
712     if (!output) {
713         LOG("No such output found.\n");
714         return sstrdup("{\"sucess\": false}");
715     }
716
717     /* get visible workspace on output */
718     Con *ws = NULL;
719     GREP_FIRST(ws, output_get_content(output->con), workspace_is_visible(child));
720     if (!ws)
721         return sstrdup("{\"sucess\": false}");
722
723     TAILQ_FOREACH(current, &owindows, owindows) {
724         DLOG("matching: %p / %s\n", current->con, current->con->name);
725         con_move_to_workspace(current->con, ws, true, false);
726     }
727
728     tree_render();
729
730     // XXX: default reply for now, make this a better reply
731     return sstrdup("{\"success\": true}");
732 }
733
734 /*
735  * Implementation of 'floating enable|disable|toggle'
736  *
737  */
738 char *cmd_floating(Match *current_match, char *floating_mode) {
739     owindow *current;
740
741     DLOG("floating_mode=%s\n", floating_mode);
742
743     HANDLE_EMPTY_MATCH;
744
745     TAILQ_FOREACH(current, &owindows, owindows) {
746         DLOG("matching: %p / %s\n", current->con, current->con->name);
747         if (strcmp(floating_mode, "toggle") == 0) {
748             DLOG("should toggle mode\n");
749             toggle_floating_mode(current->con, false);
750         } else {
751             DLOG("should switch mode to %s\n", floating_mode);
752             if (strcmp(floating_mode, "enable") == 0) {
753                 floating_enable(current->con, false);
754             } else {
755                 floating_disable(current->con, false);
756             }
757         }
758     }
759
760     tree_render();
761
762     // XXX: default reply for now, make this a better reply
763     return sstrdup("{\"success\": true}");
764 }
765
766 /*
767  * Implementation of 'move workspace to [output] <str>'.
768  *
769  */
770 char *cmd_move_workspace_to_output(Match *current_match, char *name) {
771     DLOG("should move workspace to output %s\n", name);
772
773     HANDLE_EMPTY_MATCH;
774
775     owindow *current;
776     TAILQ_FOREACH(current, &owindows, owindows) {
777         Output *current_output = get_output_containing(current->con->rect.x,
778                                                        current->con->rect.y);
779         Output *output = get_output_from_string(current_output, name);
780         if (!output) {
781             LOG("No such output\n");
782             return sstrdup("{\"sucess\": false}");
783         }
784
785         Con *content = output_get_content(output->con);
786         LOG("got output %p with content %p\n", output, content);
787
788         Con *ws = con_get_workspace(current->con);
789         LOG("should move workspace %p / %s\n", ws, ws->name);
790
791         if (con_num_children(ws->parent) == 1) {
792             LOG("Creating a new workspace to replace \"%s\" (last on its output).\n", ws->name);
793
794             /* check if we can find a workspace assigned to this output */
795             bool used_assignment = false;
796             struct Workspace_Assignment *assignment;
797             TAILQ_FOREACH(assignment, &ws_assignments, ws_assignments) {
798                 if (strcmp(assignment->output, current_output->name) != 0)
799                     continue;
800
801                 /* check if this workspace is already attached to the tree */
802                 Con *workspace = NULL, *out;
803                 TAILQ_FOREACH(out, &(croot->nodes_head), nodes)
804                     GREP_FIRST(workspace, output_get_content(out),
805                                !strcasecmp(child->name, assignment->name));
806                 if (workspace != NULL)
807                     continue;
808
809                 /* so create the workspace referenced to by this assignment */
810                 LOG("Creating workspace from assignment %s.\n", assignment->name);
811                 workspace_get(assignment->name, NULL);
812                 used_assignment = true;
813                 break;
814             }
815
816             /* if we couldn't create the workspace using an assignment, create
817              * it on the output */
818             if (!used_assignment)
819                 create_workspace_on_output(current_output, ws->parent);
820
821             /* notify the IPC listeners */
822             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"init\"}");
823         }
824
825         /* detach from the old output and attach to the new output */
826         bool workspace_was_visible = workspace_is_visible(ws);
827         Con *old_content = ws->parent;
828         con_detach(ws);
829         if (workspace_was_visible) {
830             /* The workspace which we just detached was visible, so focus
831              * the next one in the focus-stack. */
832             Con *focus_ws = TAILQ_FIRST(&(old_content->focus_head));
833             LOG("workspace was visible, focusing %p / %s now\n", focus_ws, focus_ws->name);
834             workspace_show(focus_ws);
835         }
836         con_attach(ws, content, false);
837
838         /* fix the coordinates of the floating containers */
839         Con *floating_con;
840         TAILQ_FOREACH(floating_con, &(ws->floating_head), floating_windows)
841             floating_fix_coordinates(floating_con, &(old_content->rect), &(content->rect));
842
843         ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"move\"}");
844         if (workspace_was_visible) {
845             /* Focus the moved workspace on the destination output. */
846             workspace_show(ws);
847         }
848     }
849
850     tree_render();
851
852     // XXX: default reply for now, make this a better reply
853     return sstrdup("{\"success\": true}");
854 }
855
856 /*
857  * Implementation of 'split v|h|vertical|horizontal'.
858  *
859  */
860 char *cmd_split(Match *current_match, char *direction) {
861     /* TODO: use matches */
862     LOG("splitting in direction %c\n", direction[0]);
863     tree_split(focused, (direction[0] == 'v' ? VERT : HORIZ));
864
865     tree_render();
866
867     // XXX: default reply for now, make this a better reply
868     return sstrdup("{\"success\": true}");
869 }
870
871 /*
872  * Implementaiton of 'kill [window|client]'.
873  *
874  */
875 char *cmd_kill(Match *current_match, char *kill_mode_str) {
876     if (kill_mode_str == NULL)
877         kill_mode_str = "window";
878     owindow *current;
879
880     DLOG("kill_mode=%s\n", kill_mode_str);
881
882     int kill_mode;
883     if (strcmp(kill_mode_str, "window") == 0)
884         kill_mode = KILL_WINDOW;
885     else if (strcmp(kill_mode_str, "client") == 0)
886         kill_mode = KILL_CLIENT;
887     else {
888         ELOG("BUG: called with kill_mode=%s\n", kill_mode_str);
889         return sstrdup("{\"sucess\": false}");
890     }
891
892     /* check if the match is empty, not if the result is empty */
893     if (match_is_empty(current_match))
894         tree_close_con(kill_mode);
895     else {
896         TAILQ_FOREACH(current, &owindows, owindows) {
897             DLOG("matching: %p / %s\n", current->con, current->con->name);
898             tree_close(current->con, kill_mode, false, false);
899         }
900     }
901
902     tree_render();
903
904     // XXX: default reply for now, make this a better reply
905     return sstrdup("{\"success\": true}");
906 }
907
908 /*
909  * Implementation of 'exec [--no-startup-id] <command>'.
910  *
911  */
912 char *cmd_exec(Match *current_match, char *nosn, char *command) {
913     bool no_startup_id = (nosn != NULL);
914
915     DLOG("should execute %s, no_startup_id = %d\n", command, no_startup_id);
916     start_application(command, no_startup_id);
917
918     // XXX: default reply for now, make this a better reply
919     return sstrdup("{\"success\": true}");
920 }
921
922 /*
923  * Implementation of 'focus left|right|up|down'.
924  *
925  */
926 char *cmd_focus_direction(Match *current_match, char *direction) {
927     if (focused &&
928         focused->type != CT_WORKSPACE &&
929         focused->fullscreen_mode != CF_NONE) {
930         LOG("Cannot change focus while in fullscreen mode.\n");
931         return sstrdup("{\"sucess\": false}");
932     }
933
934     DLOG("direction = *%s*\n", direction);
935
936     if (strcmp(direction, "left") == 0)
937         tree_next('p', HORIZ);
938     else if (strcmp(direction, "right") == 0)
939         tree_next('n', HORIZ);
940     else if (strcmp(direction, "up") == 0)
941         tree_next('p', VERT);
942     else if (strcmp(direction, "down") == 0)
943         tree_next('n', VERT);
944     else {
945         ELOG("Invalid focus direction (%s)\n", direction);
946         return sstrdup("{\"sucess\": false}");
947     }
948
949     tree_render();
950
951     // XXX: default reply for now, make this a better reply
952     return sstrdup("{\"success\": true}");
953 }
954
955 /*
956  * Implementation of 'focus tiling|floating|mode_toggle'.
957  *
958  */
959 char *cmd_focus_window_mode(Match *current_match, char *window_mode) {
960     if (focused &&
961         focused->type != CT_WORKSPACE &&
962         focused->fullscreen_mode != CF_NONE) {
963         LOG("Cannot change focus while in fullscreen mode.\n");
964         return sstrdup("{\"sucess\": false}");
965     }
966
967     DLOG("window_mode = %s\n", window_mode);
968
969     Con *ws = con_get_workspace(focused);
970     Con *current;
971     if (ws != NULL) {
972         if (strcmp(window_mode, "mode_toggle") == 0) {
973             current = TAILQ_FIRST(&(ws->focus_head));
974             if (current != NULL && current->type == CT_FLOATING_CON)
975                 window_mode = "tiling";
976             else window_mode = "floating";
977         }
978         TAILQ_FOREACH(current, &(ws->focus_head), focused) {
979             if ((strcmp(window_mode, "floating") == 0 && current->type != CT_FLOATING_CON) ||
980                 (strcmp(window_mode, "tiling") == 0 && current->type == CT_FLOATING_CON))
981                 continue;
982
983             con_focus(con_descend_focused(current));
984             break;
985         }
986     }
987
988     tree_render();
989
990     // XXX: default reply for now, make this a better reply
991     return sstrdup("{\"success\": true}");
992 }
993
994 /*
995  * Implementation of 'focus parent|child'.
996  *
997  */
998 char *cmd_focus_level(Match *current_match, char *level) {
999     if (focused &&
1000         focused->type != CT_WORKSPACE &&
1001         focused->fullscreen_mode != CF_NONE) {
1002         LOG("Cannot change focus while in fullscreen mode.\n");
1003         return sstrdup("{\"sucess\": false}");
1004     }
1005
1006     DLOG("level = %s\n", level);
1007
1008     if (strcmp(level, "parent") == 0)
1009         level_up();
1010     else level_down();
1011
1012     tree_render();
1013
1014     // XXX: default reply for now, make this a better reply
1015     return sstrdup("{\"success\": true}");
1016 }
1017
1018 /*
1019  * Implementation of 'focus'.
1020  *
1021  */
1022 char *cmd_focus(Match *current_match) {
1023     DLOG("current_match = %p\n", current_match);
1024     if (focused &&
1025         focused->type != CT_WORKSPACE &&
1026         focused->fullscreen_mode != CF_NONE) {
1027         LOG("Cannot change focus while in fullscreen mode.\n");
1028         return sstrdup("{\"sucess\": false}");
1029     }
1030
1031     owindow *current;
1032
1033     if (match_is_empty(current_match)) {
1034         ELOG("You have to specify which window/container should be focused.\n");
1035         ELOG("Example: [class=\"urxvt\" title=\"irssi\"] focus\n");
1036
1037         char *json_output;
1038         sasprintf(&json_output, "{\"success\":false, \"error\":\"You have to "
1039                   "specify which window/container should be focused\"}");
1040         return json_output;
1041     }
1042
1043     int count = 0;
1044     TAILQ_FOREACH(current, &owindows, owindows) {
1045         Con *ws = con_get_workspace(current->con);
1046         /* If no workspace could be found, this was a dock window.
1047          * Just skip it, you cannot focus dock windows. */
1048         if (!ws)
1049             continue;
1050
1051         /* If the container is not on the current workspace,
1052          * workspace_show() will switch to a different workspace and (if
1053          * enabled) trigger a mouse pointer warp to the currently focused
1054          * container (!) on the target workspace.
1055          *
1056          * Therefore, before calling workspace_show(), we make sure that
1057          * 'current' will be focused on the workspace. However, we cannot
1058          * just con_focus(current) because then the pointer will not be
1059          * warped at all (the code thinks we are already there).
1060          *
1061          * So we focus 'current' to make it the currently focused window of
1062          * the target workspace, then revert focus. */
1063         Con *currently_focused = focused;
1064         con_focus(current->con);
1065         con_focus(currently_focused);
1066
1067         /* Now switch to the workspace, then focus */
1068         workspace_show(ws);
1069         LOG("focusing %p / %s\n", current->con, current->con->name);
1070         con_focus(current->con);
1071         count++;
1072     }
1073
1074     if (count > 1)
1075         LOG("WARNING: Your criteria for the focus command matches %d containers, "
1076             "while only exactly one container can be focused at a time.\n", count);
1077
1078     tree_render();
1079
1080     // XXX: default reply for now, make this a better reply
1081     return sstrdup("{\"success\": true}");
1082 }
1083
1084 /*
1085  * Implementation of 'fullscreen [global]'.
1086  *
1087  */
1088 char *cmd_fullscreen(Match *current_match, char *fullscreen_mode) {
1089     if (fullscreen_mode == NULL)
1090         fullscreen_mode = "output";
1091     DLOG("toggling fullscreen, mode = %s\n", fullscreen_mode);
1092     owindow *current;
1093
1094     HANDLE_EMPTY_MATCH;
1095
1096     TAILQ_FOREACH(current, &owindows, owindows) {
1097         printf("matching: %p / %s\n", current->con, current->con->name);
1098         con_toggle_fullscreen(current->con, (strcmp(fullscreen_mode, "global") == 0 ? CF_GLOBAL : CF_OUTPUT));
1099     }
1100
1101     tree_render();
1102
1103     // XXX: default reply for now, make this a better reply
1104     return sstrdup("{\"success\": true}");
1105 }
1106
1107 /*
1108  * Implementation of 'move <direction> [<pixels> [px]]'.
1109  *
1110  */
1111 char *cmd_move_direction(Match *current_match, char *direction, char *move_px) {
1112     // 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
1113     int px = atoi(move_px);
1114
1115     /* TODO: make 'move' work with criteria. */
1116     DLOG("moving in direction %s, px %s\n", direction, move_px);
1117     if (con_is_floating(focused)) {
1118         DLOG("floating move with %d pixels\n", px);
1119         Rect newrect = focused->parent->rect;
1120         if (strcmp(direction, "left") == 0) {
1121             newrect.x -= px;
1122         } else if (strcmp(direction, "right") == 0) {
1123             newrect.x += px;
1124         } else if (strcmp(direction, "up") == 0) {
1125             newrect.y -= px;
1126         } else if (strcmp(direction, "down") == 0) {
1127             newrect.y += px;
1128         }
1129         floating_reposition(focused->parent, newrect);
1130     } else {
1131         tree_move((strcmp(direction, "right") == 0 ? D_RIGHT :
1132                    (strcmp(direction, "left") == 0 ? D_LEFT :
1133                     (strcmp(direction, "up") == 0 ? D_UP :
1134                      D_DOWN))));
1135         tree_render();
1136     }
1137
1138
1139     // XXX: default reply for now, make this a better reply
1140     return sstrdup("{\"success\": true}");
1141 }
1142
1143 /*
1144  * Implementation of 'layout default|stacked|stacking|tabbed'.
1145  *
1146  */
1147 char *cmd_layout(Match *current_match, char *layout_str) {
1148     if (strcmp(layout_str, "stacking") == 0)
1149         layout_str = "stacked";
1150     DLOG("changing layout to %s\n", layout_str);
1151     owindow *current;
1152     int layout = (strcmp(layout_str, "default") == 0 ? L_DEFAULT :
1153                   (strcmp(layout_str, "stacked") == 0 ? L_STACKED :
1154                    L_TABBED));
1155
1156     /* check if the match is empty, not if the result is empty */
1157     if (match_is_empty(current_match))
1158         con_set_layout(focused->parent, layout);
1159     else {
1160         TAILQ_FOREACH(current, &owindows, owindows) {
1161             DLOG("matching: %p / %s\n", current->con, current->con->name);
1162             con_set_layout(current->con, layout);
1163         }
1164     }
1165
1166     tree_render();
1167
1168     // XXX: default reply for now, make this a better reply
1169     return sstrdup("{\"success\": true}");
1170 }
1171
1172 /*
1173  * Implementaiton of 'exit'.
1174  *
1175  */
1176 char *cmd_exit(Match *current_match) {
1177     LOG("Exiting due to user command.\n");
1178     exit(0);
1179
1180     /* unreached */
1181 }
1182
1183 /*
1184  * Implementaiton of 'reload'.
1185  *
1186  */
1187 char *cmd_reload(Match *current_match) {
1188     LOG("reloading\n");
1189     kill_configerror_nagbar(false);
1190     load_configuration(conn, NULL, true);
1191     x_set_i3_atoms();
1192     /* Send an IPC event just in case the ws names have changed */
1193     ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"reload\"}");
1194
1195     // XXX: default reply for now, make this a better reply
1196     return sstrdup("{\"success\": true}");
1197 }
1198
1199 /*
1200  * Implementaiton of 'restart'.
1201  *
1202  */
1203 char *cmd_restart(Match *current_match) {
1204     LOG("restarting i3\n");
1205     i3_restart(false);
1206
1207     // XXX: default reply for now, make this a better reply
1208     return sstrdup("{\"success\": true}");
1209 }
1210
1211 /*
1212  * Implementaiton of 'open'.
1213  *
1214  */
1215 char *cmd_open(Match *current_match) {
1216     LOG("opening new container\n");
1217     Con *con = tree_open_con(NULL, NULL);
1218     con_focus(con);
1219     char *json_output;
1220     sasprintf(&json_output, "{\"success\":true, \"id\":%ld}", (long int)con);
1221
1222     tree_render();
1223
1224     return json_output;
1225 }
1226
1227 /*
1228  * Implementation of 'focus output <output>'.
1229  *
1230  */
1231 char *cmd_focus_output(Match *current_match, char *name) {
1232     owindow *current;
1233
1234     DLOG("name = %s\n", name);
1235
1236     HANDLE_EMPTY_MATCH;
1237
1238     /* get the output */
1239     Output *current_output = NULL;
1240     Output *output;
1241
1242     TAILQ_FOREACH(current, &owindows, owindows)
1243         current_output = get_output_containing(current->con->rect.x, current->con->rect.y);
1244     assert(current_output != NULL);
1245
1246     output = get_output_from_string(current_output, name);
1247
1248     if (!output) {
1249         LOG("No such output found.\n");
1250         return sstrdup("{\"sucess\": false}");
1251     }
1252
1253     /* get visible workspace on output */
1254     Con *ws = NULL;
1255     GREP_FIRST(ws, output_get_content(output->con), workspace_is_visible(child));
1256     if (!ws)
1257         return sstrdup("{\"sucess\": false}");
1258
1259     workspace_show(ws);
1260     tree_render();
1261
1262     // XXX: default reply for now, make this a better reply
1263     return sstrdup("{\"success\": true}");
1264 }
1265
1266 /*
1267  * Implementation of 'move scratchpad'.
1268  *
1269  */
1270 char *cmd_move_scratchpad(Match *current_match) {
1271     DLOG("should move window to scratchpad\n");
1272     owindow *current;
1273
1274     HANDLE_EMPTY_MATCH;
1275
1276     TAILQ_FOREACH(current, &owindows, owindows) {
1277         DLOG("matching: %p / %s\n", current->con, current->con->name);
1278         scratchpad_move(current->con);
1279     }
1280
1281     tree_render();
1282
1283     // XXX: default reply for now, make this a better reply
1284     return sstrdup("{\"success\": true}");
1285 }
1286
1287 /*
1288  * Implementation of 'scratchpad show'.
1289  *
1290  */
1291 char *cmd_scratchpad_show(Match *current_match) {
1292     DLOG("should show scratchpad window\n");
1293     owindow *current;
1294
1295     if (match_is_empty(current_match)) {
1296         scratchpad_show(NULL);
1297     } else {
1298         TAILQ_FOREACH(current, &owindows, owindows) {
1299             DLOG("matching: %p / %s\n", current->con, current->con->name);
1300             scratchpad_show(current->con);
1301         }
1302     }
1303
1304     tree_render();
1305
1306     // XXX: default reply for now, make this a better reply
1307     return sstrdup("{\"success\": true}");
1308 }