1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * commands.c: all command functions (see commands_parser.c)
8  *
9  */
10 #include "all.h"
11 #include "shmlog.h"
12 
13 #include <fcntl.h>
14 #include <stdint.h>
15 #include <unistd.h>
16 
17 // Macros to make the YAJL API a bit easier to use.
18 #define y(x, ...) (cmd_output->json_gen != NULL ? yajl_gen_##x(cmd_output->json_gen, ##__VA_ARGS__) : 0)
19 #define ystr(str) (cmd_output->json_gen != NULL ? yajl_gen_string(cmd_output->json_gen, (unsigned char *)str, strlen(str)) : 0)
20 #define ysuccess(success)                   \
21     do {                                    \
22         if (cmd_output->json_gen != NULL) { \
23             y(map_open);                    \
24             ystr("success");                \
25             y(bool, success);               \
26             y(map_close);                   \
27         }                                   \
28     } while (0)
29 #define yerror(format, ...)                             \
30     do {                                                \
31         if (cmd_output->json_gen != NULL) {             \
32             char *message;                              \
33             sasprintf(&message, format, ##__VA_ARGS__); \
34             y(map_open);                                \
35             ystr("success");                            \
36             y(bool, false);                             \
37             ystr("error");                              \
38             ystr(message);                              \
39             y(map_close);                               \
40             free(message);                              \
41         }                                               \
42     } while (0)
43 
44 /** If an error occurred during parsing of the criteria, we want to exit instead
45  * of relying on fallback behavior. See #2091. */
46 #define HANDLE_INVALID_MATCH                                   \
47     do {                                                       \
48         if (current_match->error != NULL) {                    \
49             yerror("Invalid match: %s", current_match->error); \
50             return;                                            \
51         }                                                      \
52     } while (0)
53 
54 /** When the command did not include match criteria (!), we use the currently
55  * focused container. Do not confuse this case with a command which included
56  * criteria but which did not match any windows. This macro has to be called in
57  * every command.
58  */
59 #define HANDLE_EMPTY_MATCH                              \
60     do {                                                \
61         HANDLE_INVALID_MATCH;                           \
62                                                         \
63         if (match_is_empty(current_match)) {            \
64             while (!TAILQ_EMPTY(&owindows)) {           \
65                 owindow *ow = TAILQ_FIRST(&owindows);   \
66                 TAILQ_REMOVE(&owindows, ow, owindows);  \
67                 free(ow);                               \
68             }                                           \
69             owindow *ow = smalloc(sizeof(owindow));     \
70             ow->con = focused;                          \
71             TAILQ_INIT(&owindows);                      \
72             TAILQ_INSERT_TAIL(&owindows, ow, owindows); \
73         }                                               \
74     } while (0)
75 
76 /*
77  * Checks whether we switched to a new workspace and returns false in that case,
78  * signaling that further workspace switching should be done by the calling function
79  * If not, calls workspace_back_and_forth() if workspace_auto_back_and_forth is set
80  * and return true, signaling that no further workspace switching should occur in the calling function.
81  *
82  */
maybe_back_and_forth(struct CommandResultIR * cmd_output,const char * name)83 static bool maybe_back_and_forth(struct CommandResultIR *cmd_output, const char *name) {
84     Con *ws = con_get_workspace(focused);
85 
86     /* If we switched to a different workspace, do nothing */
87     if (strcmp(ws->name, name) != 0)
88         return false;
89 
90     DLOG("This workspace is already focused.\n");
91     if (config.workspace_auto_back_and_forth) {
92         workspace_back_and_forth();
93         cmd_output->needs_tree_render = true;
94     }
95     return true;
96 }
97 
98 /*
99  * Return the passed workspace unless it is the current one and auto back and
100  * forth is enabled, in which case the back_and_forth workspace is returned.
101  */
maybe_auto_back_and_forth_workspace(Con * workspace)102 static Con *maybe_auto_back_and_forth_workspace(Con *workspace) {
103     Con *current, *baf;
104 
105     if (!config.workspace_auto_back_and_forth)
106         return workspace;
107 
108     current = con_get_workspace(focused);
109 
110     if (current == workspace) {
111         baf = workspace_back_and_forth_get();
112         if (baf != NULL) {
113             DLOG("Substituting workspace with back_and_forth, as it is focused.\n");
114             return baf;
115         }
116     }
117 
118     return workspace;
119 }
120 
121 /*******************************************************************************
122  * Criteria functions.
123  ******************************************************************************/
124 
125 /*
126  * Helper data structure for an operation window (window on which the operation
127  * will be performed). Used to build the TAILQ owindows.
128  *
129  */
130 typedef struct owindow {
131     Con *con;
132     TAILQ_ENTRY(owindow) owindows;
133 } owindow;
134 
135 typedef TAILQ_HEAD(owindows_head, owindow) owindows_head;
136 
137 static owindows_head owindows;
138 
139 /*
140  * Initializes the specified 'Match' data structure and the initial state of
141  * commands.c for matching target windows of a command.
142  *
143  */
cmd_criteria_init(I3_CMD)144 void cmd_criteria_init(I3_CMD) {
145     Con *con;
146     owindow *ow;
147 
148     DLOG("Initializing criteria, current_match = %p\n", current_match);
149     match_free(current_match);
150     match_init(current_match);
151     while (!TAILQ_EMPTY(&owindows)) {
152         ow = TAILQ_FIRST(&owindows);
153         TAILQ_REMOVE(&owindows, ow, owindows);
154         free(ow);
155     }
156     TAILQ_INIT(&owindows);
157     /* copy all_cons */
158     TAILQ_FOREACH (con, &all_cons, all_cons) {
159         ow = smalloc(sizeof(owindow));
160         ow->con = con;
161         TAILQ_INSERT_TAIL(&owindows, ow, owindows);
162     }
163 }
164 
165 /*
166  * A match specification just finished (the closing square bracket was found),
167  * so we filter the list of owindows.
168  *
169  */
cmd_criteria_match_windows(I3_CMD)170 void cmd_criteria_match_windows(I3_CMD) {
171     owindow *next, *current;
172 
173     DLOG("match specification finished, matching...\n");
174     /* copy the old list head to iterate through it and start with a fresh
175      * list which will contain only matching windows */
176     struct owindows_head old = owindows;
177     TAILQ_INIT(&owindows);
178     for (next = TAILQ_FIRST(&old); next != TAILQ_END(&old);) {
179         /* make a copy of the next pointer and advance the pointer to the
180          * next element as we are going to invalidate the element’s
181          * next/prev pointers by calling TAILQ_INSERT_TAIL later */
182         current = next;
183         next = TAILQ_NEXT(next, owindows);
184 
185         DLOG("checking if con %p / %s matches\n", current->con, current->con->name);
186 
187         /* We use this flag to prevent matching on window-less containers if
188          * only window-specific criteria were specified. */
189         bool accept_match = false;
190 
191         if (current_match->con_id != NULL) {
192             accept_match = true;
193 
194             if (current_match->con_id == current->con) {
195                 DLOG("con_id matched.\n");
196             } else {
197                 DLOG("con_id does not match.\n");
198                 FREE(current);
199                 continue;
200             }
201         }
202 
203         if (current_match->mark != NULL && !TAILQ_EMPTY(&(current->con->marks_head))) {
204             accept_match = true;
205             bool matched_by_mark = false;
206 
207             mark_t *mark;
208             TAILQ_FOREACH (mark, &(current->con->marks_head), marks) {
209                 if (!regex_matches(current_match->mark, mark->name))
210                     continue;
211 
212                 DLOG("match by mark\n");
213                 matched_by_mark = true;
214                 break;
215             }
216 
217             if (!matched_by_mark) {
218                 DLOG("mark does not match.\n");
219                 FREE(current);
220                 continue;
221             }
222         }
223 
224         if (current->con->window != NULL) {
225             if (match_matches_window(current_match, current->con->window)) {
226                 DLOG("matches window!\n");
227                 accept_match = true;
228             } else {
229                 DLOG("doesn't match\n");
230                 FREE(current);
231                 continue;
232             }
233         }
234 
235         if (accept_match) {
236             TAILQ_INSERT_TAIL(&owindows, current, owindows);
237         } else {
238             FREE(current);
239             continue;
240         }
241     }
242 
243     TAILQ_FOREACH (current, &owindows, owindows) {
244         DLOG("matching: %p / %s\n", current->con, current->con->name);
245     }
246 }
247 
248 /*
249  * Interprets a ctype=cvalue pair and adds it to the current match
250  * specification.
251  *
252  */
cmd_criteria_add(I3_CMD,const char * ctype,const char * cvalue)253 void cmd_criteria_add(I3_CMD, const char *ctype, const char *cvalue) {
254     match_parse_property(current_match, ctype, cvalue);
255 }
256 
move_matches_to_workspace(Con * ws)257 static void move_matches_to_workspace(Con *ws) {
258     owindow *current;
259     TAILQ_FOREACH (current, &owindows, owindows) {
260         DLOG("matching: %p / %s\n", current->con, current->con->name);
261         con_move_to_workspace(current->con, ws, true, false, false);
262     }
263 }
264 
265 #define CHECK_MOVE_CON_TO_WORKSPACE                                                          \
266     do {                                                                                     \
267         HANDLE_EMPTY_MATCH;                                                                  \
268         if (TAILQ_EMPTY(&owindows)) {                                                        \
269             yerror("Nothing to move: specified criteria don't match any window");            \
270             return;                                                                          \
271         } else {                                                                             \
272             bool found = false;                                                              \
273             owindow *current = TAILQ_FIRST(&owindows);                                       \
274             while (current) {                                                                \
275                 owindow *next = TAILQ_NEXT(current, owindows);                               \
276                                                                                              \
277                 if (current->con->type == CT_WORKSPACE && !con_has_children(current->con)) { \
278                     TAILQ_REMOVE(&owindows, current, owindows);                              \
279                 } else {                                                                     \
280                     found = true;                                                            \
281                 }                                                                            \
282                                                                                              \
283                 current = next;                                                              \
284             }                                                                                \
285             if (!found) {                                                                    \
286                 yerror("Nothing to move: workspace empty");                                  \
287                 return;                                                                      \
288             }                                                                                \
289         }                                                                                    \
290     } while (0)
291 
292 /*
293  * Implementation of 'move [window|container] [to] workspace
294  * next|prev|next_on_output|prev_on_output|current'.
295  *
296  */
cmd_move_con_to_workspace(I3_CMD,const char * which)297 void cmd_move_con_to_workspace(I3_CMD, const char *which) {
298     DLOG("which=%s\n", which);
299 
300     CHECK_MOVE_CON_TO_WORKSPACE;
301 
302     /* get the workspace */
303     Con *ws;
304     if (strcmp(which, "next") == 0)
305         ws = workspace_next();
306     else if (strcmp(which, "prev") == 0)
307         ws = workspace_prev();
308     else if (strcmp(which, "next_on_output") == 0)
309         ws = workspace_next_on_output();
310     else if (strcmp(which, "prev_on_output") == 0)
311         ws = workspace_prev_on_output();
312     else if (strcmp(which, "current") == 0)
313         ws = con_get_workspace(focused);
314     else {
315         yerror("BUG: called with which=%s", which);
316         return;
317     }
318 
319     move_matches_to_workspace(ws);
320 
321     cmd_output->needs_tree_render = true;
322     // XXX: default reply for now, make this a better reply
323     ysuccess(true);
324 }
325 
326 /*
327  * Implementation of 'move [window|container] [to] workspace back_and_forth'.
328  *
329  */
cmd_move_con_to_workspace_back_and_forth(I3_CMD)330 void cmd_move_con_to_workspace_back_and_forth(I3_CMD) {
331     Con *ws = workspace_back_and_forth_get();
332     if (ws == NULL) {
333         yerror("No workspace was previously active.");
334         return;
335     }
336 
337     HANDLE_EMPTY_MATCH;
338 
339     move_matches_to_workspace(ws);
340 
341     cmd_output->needs_tree_render = true;
342     // XXX: default reply for now, make this a better reply
343     ysuccess(true);
344 }
345 
346 /*
347  * Implementation of 'move [--no-auto-back-and-forth] [window|container] [to] workspace <name>'.
348  *
349  */
cmd_move_con_to_workspace_name(I3_CMD,const char * name,const char * no_auto_back_and_forth)350 void cmd_move_con_to_workspace_name(I3_CMD, const char *name, const char *no_auto_back_and_forth) {
351     if (strncasecmp(name, "__", strlen("__")) == 0) {
352         yerror("You cannot move containers to i3-internal workspaces (\"%s\").", name);
353         return;
354     }
355 
356     CHECK_MOVE_CON_TO_WORKSPACE;
357 
358     LOG("should move window to workspace %s\n", name);
359     /* get the workspace */
360     Con *ws = workspace_get(name);
361 
362     if (no_auto_back_and_forth == NULL) {
363         ws = maybe_auto_back_and_forth_workspace(ws);
364     }
365 
366     move_matches_to_workspace(ws);
367 
368     cmd_output->needs_tree_render = true;
369     // XXX: default reply for now, make this a better reply
370     ysuccess(true);
371 }
372 
373 /*
374  * Implementation of 'move [--no-auto-back-and-forth] [window|container] [to] workspace number <name>'.
375  *
376  */
cmd_move_con_to_workspace_number(I3_CMD,const char * which,const char * no_auto_back_and_forth)377 void cmd_move_con_to_workspace_number(I3_CMD, const char *which, const char *no_auto_back_and_forth) {
378     CHECK_MOVE_CON_TO_WORKSPACE;
379 
380     LOG("should move window to workspace %s\n", which);
381 
382     long parsed_num = ws_name_to_number(which);
383     if (parsed_num == -1) {
384         LOG("Could not parse initial part of \"%s\" as a number.\n", which);
385         yerror("Could not parse number \"%s\"", which);
386         return;
387     }
388 
389     Con *ws = get_existing_workspace_by_num(parsed_num);
390     if (!ws) {
391         ws = workspace_get(which);
392     }
393 
394     if (no_auto_back_and_forth == NULL) {
395         ws = maybe_auto_back_and_forth_workspace(ws);
396     }
397 
398     move_matches_to_workspace(ws);
399 
400     cmd_output->needs_tree_render = true;
401     // XXX: default reply for now, make this a better reply
402     ysuccess(true);
403 }
404 
405 /*
406  * Convert a string direction ("left", "right", etc.) to a direction_t. Assumes
407  * valid direction string.
408  */
parse_direction(const char * str)409 static direction_t parse_direction(const char *str) {
410     if (strcmp(str, "left") == 0) {
411         return D_LEFT;
412     } else if (strcmp(str, "right") == 0) {
413         return D_RIGHT;
414     } else if (strcmp(str, "up") == 0) {
415         return D_UP;
416     } else if (strcmp(str, "down") == 0) {
417         return D_DOWN;
418     } else {
419         ELOG("Invalid direction. This is a parser bug.\n");
420         assert(false);
421     }
422 }
423 
cmd_resize_floating(I3_CMD,const char * direction_str,Con * floating_con,int px)424 static void cmd_resize_floating(I3_CMD, const char *direction_str, Con *floating_con, int px) {
425     Rect old_rect = floating_con->rect;
426     Con *focused_con = con_descend_focused(floating_con);
427 
428     direction_t direction;
429     if (strcmp(direction_str, "height") == 0) {
430         direction = D_DOWN;
431     } else if (strcmp(direction_str, "width") == 0) {
432         direction = D_RIGHT;
433     } else {
434         direction = parse_direction(direction_str);
435     }
436     orientation_t orientation = orientation_from_direction(direction);
437 
438     /* ensure that resize will take place even if pixel increment is smaller than
439      * height increment or width increment.
440      * fixes #1011 */
441     const i3Window *window = focused_con->window;
442     if (window != NULL) {
443         if (orientation == VERT) {
444             if (px < 0) {
445                 px = (-px < window->height_increment) ? -window->height_increment : px;
446             } else {
447                 px = (px < window->height_increment) ? window->height_increment : px;
448             }
449         } else {
450             if (px < 0) {
451                 px = (-px < window->width_increment) ? -window->width_increment : px;
452             } else {
453                 px = (px < window->width_increment) ? window->width_increment : px;
454             }
455         }
456     }
457 
458     if (orientation == VERT) {
459         floating_con->rect.height += px;
460     } else {
461         floating_con->rect.width += px;
462     }
463     floating_check_size(floating_con, orientation == VERT);
464 
465     /* Did we actually resize anything or did the size constraints prevent us?
466      * If we could not resize, exit now to not move the window. */
467     if (rect_equals(old_rect, floating_con->rect)) {
468         return;
469     }
470 
471     if (direction == D_UP) {
472         floating_con->rect.y -= (floating_con->rect.height - old_rect.height);
473     } else if (direction == D_LEFT) {
474         floating_con->rect.x -= (floating_con->rect.width - old_rect.width);
475     }
476 
477     /* If this is a scratchpad window, don't auto center it from now on. */
478     if (floating_con->scratchpad_state == SCRATCHPAD_FRESH) {
479         floating_con->scratchpad_state = SCRATCHPAD_CHANGED;
480     }
481 }
482 
cmd_resize_tiling_direction(I3_CMD,Con * current,const char * direction,int px,int ppt)483 static bool cmd_resize_tiling_direction(I3_CMD, Con *current, const char *direction, int px, int ppt) {
484     Con *second = NULL;
485     Con *first = current;
486     direction_t search_direction = parse_direction(direction);
487 
488     bool res = resize_find_tiling_participants(&first, &second, search_direction, false);
489     if (!res) {
490         yerror("No second container found in this direction.");
491         return false;
492     }
493 
494     if (ppt) {
495         /* For backwards compatibility, 'X px or Y ppt' means that ppt is
496          * preferred. */
497         px = 0;
498     }
499     return resize_neighboring_cons(first, second, px, ppt);
500 }
501 
cmd_resize_tiling_width_height(I3_CMD,Con * current,const char * direction,int px,double ppt)502 static bool cmd_resize_tiling_width_height(I3_CMD, Con *current, const char *direction, int px, double ppt) {
503     LOG("width/height resize\n");
504 
505     /* get the appropriate current container (skip stacked/tabbed cons) */
506     Con *dummy = NULL;
507     direction_t search_direction = (strcmp(direction, "width") == 0 ? D_LEFT : D_DOWN);
508     bool search_result = resize_find_tiling_participants(&current, &dummy, search_direction, true);
509     if (search_result == false) {
510         yerror("Failed to find appropriate tiling containers for resize operation");
511         return false;
512     }
513 
514     /* get the default percentage */
515     int children = con_num_children(current->parent);
516     LOG("ins. %d children\n", children);
517     double percentage = 1.0 / children;
518     LOG("default percentage = %f\n", percentage);
519 
520     /* Ensure all the other children have a percentage set. */
521     Con *child;
522     TAILQ_FOREACH (child, &(current->parent->nodes_head), nodes) {
523         LOG("child->percent = %f (child %p)\n", child->percent, child);
524         if (child->percent == 0.0)
525             child->percent = percentage;
526     }
527 
528     double new_current_percent;
529     double subtract_percent;
530     if (ppt != 0.0) {
531         new_current_percent = current->percent + ppt;
532     } else {
533         /* Convert px change to change in percentages */
534         ppt = (double)px / (double)con_rect_size_in_orientation(current->parent);
535         new_current_percent = current->percent + ppt;
536     }
537     subtract_percent = ppt / (children - 1);
538     if (ppt < 0.0 && new_current_percent < percent_for_1px(current)) {
539         yerror("Not resizing, container would end with less than 1px");
540         return false;
541     }
542 
543     LOG("new_current_percent = %f\n", new_current_percent);
544     LOG("subtract_percent = %f\n", subtract_percent);
545     /* Ensure that the new percentages are positive. */
546     if (subtract_percent >= 0.0) {
547         TAILQ_FOREACH (child, &(current->parent->nodes_head), nodes) {
548             if (child == current) {
549                 continue;
550             }
551             if (child->percent - subtract_percent < percent_for_1px(child)) {
552                 yerror("Not resizing, already at minimum size (child %p would end up with a size of %.f", child, child->percent - subtract_percent);
553                 return false;
554             }
555         }
556     }
557 
558     current->percent = new_current_percent;
559     LOG("current->percent after = %f\n", current->percent);
560 
561     TAILQ_FOREACH (child, &(current->parent->nodes_head), nodes) {
562         if (child == current)
563             continue;
564         child->percent -= subtract_percent;
565         LOG("child->percent after (%p) = %f\n", child, child->percent);
566     }
567 
568     return true;
569 }
570 
571 /*
572  * Implementation of 'resize grow|shrink <direction> [<px> px] [or <ppt> ppt]'.
573  *
574  */
cmd_resize(I3_CMD,const char * way,const char * direction,long resize_px,long resize_ppt)575 void cmd_resize(I3_CMD, const char *way, const char *direction, long resize_px, long resize_ppt) {
576     DLOG("resizing in way %s, direction %s, px %ld or ppt %ld\n", way, direction, resize_px, resize_ppt);
577     if (strcmp(way, "shrink") == 0) {
578         resize_px *= -1;
579         resize_ppt *= -1;
580     }
581 
582     HANDLE_EMPTY_MATCH;
583 
584     owindow *current;
585     TAILQ_FOREACH (current, &owindows, owindows) {
586         /* Don't handle dock windows (issue #1201) */
587         if (current->con->window && current->con->window->dock) {
588             DLOG("This is a dock window. Not resizing (con = %p)\n)", current->con);
589             continue;
590         }
591 
592         Con *floating_con;
593         if ((floating_con = con_inside_floating(current->con))) {
594             cmd_resize_floating(current_match, cmd_output, direction, floating_con, resize_px);
595         } else {
596             if (strcmp(direction, "width") == 0 ||
597                 strcmp(direction, "height") == 0) {
598                 const double ppt = (double)resize_ppt / 100.0;
599                 if (!cmd_resize_tiling_width_height(current_match, cmd_output,
600                                                     current->con, direction,
601                                                     resize_px, ppt)) {
602                     yerror("Cannot resize.");
603                     return;
604                 }
605             } else {
606                 if (!cmd_resize_tiling_direction(current_match, cmd_output,
607                                                  current->con, direction,
608                                                  resize_px, resize_ppt)) {
609                     yerror("Cannot resize.");
610                     return;
611                 }
612             }
613         }
614     }
615 
616     cmd_output->needs_tree_render = true;
617     // XXX: default reply for now, make this a better reply
618     ysuccess(true);
619 }
620 
resize_set_tiling(I3_CMD,Con * target,orientation_t resize_orientation,bool is_ppt,long target_size)621 static bool resize_set_tiling(I3_CMD, Con *target, orientation_t resize_orientation, bool is_ppt, long target_size) {
622     direction_t search_direction;
623     char *mode;
624     if (resize_orientation == HORIZ) {
625         search_direction = D_LEFT;
626         mode = "width";
627     } else {
628         search_direction = D_DOWN;
629         mode = "height";
630     }
631 
632     /* Get the appropriate current container (skip stacked/tabbed cons) */
633     Con *dummy;
634     resize_find_tiling_participants(&target, &dummy, search_direction, true);
635 
636     /* Calculate new size for the target container */
637     double ppt = 0.0;
638     int px = 0;
639     if (is_ppt) {
640         ppt = (double)target_size / 100.0 - target->percent;
641     } else {
642         px = target_size - (resize_orientation == HORIZ ? target->rect.width : target->rect.height);
643     }
644 
645     /* Perform resizing and report failure if not possible */
646     return cmd_resize_tiling_width_height(current_match, cmd_output,
647                                           target, mode, px, ppt);
648 }
649 
650 /*
651  * Implementation of 'resize set <width> [px | ppt] <height> [px | ppt]'.
652  *
653  */
cmd_resize_set(I3_CMD,long cwidth,const char * mode_width,long cheight,const char * mode_height)654 void cmd_resize_set(I3_CMD, long cwidth, const char *mode_width, long cheight, const char *mode_height) {
655     DLOG("resizing to %ld %s x %ld %s\n", cwidth, mode_width, cheight, mode_height);
656     if (cwidth < 0 || cheight < 0) {
657         yerror("Dimensions cannot be negative.");
658         return;
659     }
660 
661     HANDLE_EMPTY_MATCH;
662 
663     owindow *current;
664     bool success = true;
665     TAILQ_FOREACH (current, &owindows, owindows) {
666         Con *floating_con;
667         if ((floating_con = con_inside_floating(current->con))) {
668             Con *output = con_get_output(floating_con);
669             if (cwidth == 0) {
670                 cwidth = floating_con->rect.width;
671             } else if (mode_width && strcmp(mode_width, "ppt") == 0) {
672                 cwidth = output->rect.width * ((double)cwidth / 100.0);
673             }
674             if (cheight == 0) {
675                 cheight = floating_con->rect.height;
676             } else if (mode_height && strcmp(mode_height, "ppt") == 0) {
677                 cheight = output->rect.height * ((double)cheight / 100.0);
678             }
679             floating_resize(floating_con, cwidth, cheight);
680         } else {
681             if (current->con->window && current->con->window->dock) {
682                 DLOG("This is a dock window. Not resizing (con = %p)\n)", current->con);
683                 continue;
684             }
685 
686             if (cwidth > 0) {
687                 bool is_ppt = mode_width && strcmp(mode_width, "ppt") == 0;
688                 success &= resize_set_tiling(current_match, cmd_output, current->con,
689                                              HORIZ, is_ppt, cwidth);
690             }
691             if (cheight > 0) {
692                 bool is_ppt = mode_height && strcmp(mode_height, "ppt") == 0;
693                 success &= resize_set_tiling(current_match, cmd_output, current->con,
694                                              VERT, is_ppt, cheight);
695             }
696         }
697     }
698 
699     cmd_output->needs_tree_render = true;
700     ysuccess(success);
701 }
702 
border_width_from_style(border_style_t border_style,long border_width,Con * con)703 static int border_width_from_style(border_style_t border_style, long border_width, Con *con) {
704     if (border_style == BS_NONE) {
705         return 0;
706     }
707     if (border_width >= 0) {
708         return logical_px(border_width);
709     }
710 
711     const bool is_floating = con_inside_floating(con) != NULL;
712     /* Load the configured defaults. */
713     if (is_floating && border_style == config.default_floating_border) {
714         return config.default_floating_border_width;
715     } else if (!is_floating && border_style == config.default_border) {
716         return config.default_border_width;
717     } else {
718         /* Use some hardcoded values. */
719         return logical_px(border_style == BS_NORMAL ? 2 : 1);
720     }
721 }
722 
723 /*
724  * Implementation of 'border normal|pixel [<n>]', 'border none|1pixel|toggle'.
725  *
726  */
cmd_border(I3_CMD,const char * border_style_str,long border_width)727 void cmd_border(I3_CMD, const char *border_style_str, long border_width) {
728     DLOG("border style should be changed to %s with border width %ld\n", border_style_str, border_width);
729     owindow *current;
730 
731     HANDLE_EMPTY_MATCH;
732 
733     TAILQ_FOREACH (current, &owindows, owindows) {
734         DLOG("matching: %p / %s\n", current->con, current->con->name);
735 
736         border_style_t border_style;
737         if (strcmp(border_style_str, "toggle") == 0) {
738             border_style = (current->con->border_style + 1) % 3;
739         } else if (strcmp(border_style_str, "normal") == 0) {
740             border_style = BS_NORMAL;
741         } else if (strcmp(border_style_str, "pixel") == 0) {
742             border_style = BS_PIXEL;
743         } else if (strcmp(border_style_str, "none") == 0) {
744             border_style = BS_NONE;
745         } else {
746             yerror("BUG: called with border_style=%s", border_style_str);
747             return;
748         }
749 
750         const int con_border_width = border_width_from_style(border_style, border_width, current->con);
751         con_set_border_style(current->con, border_style, con_border_width);
752     }
753 
754     cmd_output->needs_tree_render = true;
755     ysuccess(true);
756 }
757 
758 /*
759  * Implementation of 'nop <comment>'.
760  *
761  */
cmd_nop(I3_CMD,const char * comment)762 void cmd_nop(I3_CMD, const char *comment) {
763     LOG("-------------------------------------------------\n");
764     LOG("  NOP: %.4000s\n", comment);
765     LOG("-------------------------------------------------\n");
766     ysuccess(true);
767 }
768 
769 /*
770  * Implementation of 'append_layout <path>'.
771  *
772  */
cmd_append_layout(I3_CMD,const char * cpath)773 void cmd_append_layout(I3_CMD, const char *cpath) {
774     LOG("Appending layout \"%s\"\n", cpath);
775 
776     /* Make sure we allow paths like '~/.i3/layout.json' */
777     char *path = resolve_tilde(cpath);
778 
779     char *buf = NULL;
780     ssize_t len;
781     if ((len = slurp(path, &buf)) < 0) {
782         yerror("Could not slurp \"%s\".", path);
783         /* slurp already logged an error. */
784         goto out;
785     }
786 
787     if (!json_validate(buf, len)) {
788         ELOG("Could not parse \"%s\" as JSON, not loading.\n", path);
789         yerror("Could not parse \"%s\" as JSON.", path);
790         goto out;
791     }
792 
793     json_content_t content = json_determine_content(buf, len);
794     LOG("JSON content = %d\n", content);
795     if (content == JSON_CONTENT_UNKNOWN) {
796         ELOG("Could not determine the contents of \"%s\", not loading.\n", path);
797         yerror("Could not determine the contents of \"%s\".", path);
798         goto out;
799     }
800 
801     Con *parent = focused;
802     if (content == JSON_CONTENT_WORKSPACE) {
803         parent = output_get_content(con_get_output(parent));
804     } else {
805         /* We need to append the layout to a split container, since a leaf
806          * container must not have any children (by definition).
807          * Note that we explicitly check for workspaces, since they are okay for
808          * this purpose, but con_accepts_window() returns false for workspaces. */
809         while (parent->type != CT_WORKSPACE && !con_accepts_window(parent))
810             parent = parent->parent;
811     }
812     DLOG("Appending to parent=%p instead of focused=%p\n", parent, focused);
813     char *errormsg = NULL;
814     tree_append_json(parent, buf, len, &errormsg);
815     if (errormsg != NULL) {
816         yerror(errormsg);
817         free(errormsg);
818         /* Note that we continue executing since tree_append_json() has
819          * side-effects — user-provided layouts can be partly valid, partly
820          * invalid, leading to half of the placeholder containers being
821          * created. */
822     } else {
823         ysuccess(true);
824     }
825 
826     // XXX: This is a bit of a kludge. Theoretically, render_con(parent,
827     // false); should be enough, but when sending 'workspace 4; append_layout
828     // /tmp/foo.json', the needs_tree_render == true of the workspace command
829     // is not executed yet and will be batched with append_layout’s
830     // needs_tree_render after the parser finished. We should check if that is
831     // necessary at all.
832     render_con(croot, false);
833 
834     restore_open_placeholder_windows(parent);
835 
836     if (content == JSON_CONTENT_WORKSPACE)
837         ipc_send_workspace_event("restored", parent, NULL);
838 
839     cmd_output->needs_tree_render = true;
840 out:
841     free(path);
842     free(buf);
843 }
844 
845 /*
846  * Implementation of 'workspace next|prev|next_on_output|prev_on_output'.
847  *
848  */
cmd_workspace(I3_CMD,const char * which)849 void cmd_workspace(I3_CMD, const char *which) {
850     Con *ws;
851 
852     DLOG("which=%s\n", which);
853 
854     if (con_get_fullscreen_con(croot, CF_GLOBAL)) {
855         yerror("Cannot switch workspace while in global fullscreen");
856         return;
857     }
858 
859     if (strcmp(which, "next") == 0)
860         ws = workspace_next();
861     else if (strcmp(which, "prev") == 0)
862         ws = workspace_prev();
863     else if (strcmp(which, "next_on_output") == 0)
864         ws = workspace_next_on_output();
865     else if (strcmp(which, "prev_on_output") == 0)
866         ws = workspace_prev_on_output();
867     else {
868         yerror("BUG: called with which=%s", which);
869         return;
870     }
871 
872     workspace_show(ws);
873 
874     cmd_output->needs_tree_render = true;
875     // XXX: default reply for now, make this a better reply
876     ysuccess(true);
877 }
878 
879 /*
880  * Implementation of 'workspace [--no-auto-back-and-forth] number <name>'
881  *
882  */
cmd_workspace_number(I3_CMD,const char * which,const char * _no_auto_back_and_forth)883 void cmd_workspace_number(I3_CMD, const char *which, const char *_no_auto_back_and_forth) {
884     const bool no_auto_back_and_forth = (_no_auto_back_and_forth != NULL);
885 
886     if (con_get_fullscreen_con(croot, CF_GLOBAL)) {
887         yerror("Cannot switch workspace while in global fullscreen");
888         return;
889     }
890 
891     long parsed_num = ws_name_to_number(which);
892     if (parsed_num == -1) {
893         yerror("Could not parse initial part of \"%s\" as a number.", which);
894         return;
895     }
896 
897     Con *workspace = get_existing_workspace_by_num(parsed_num);
898     if (!workspace) {
899         LOG("There is no workspace with number %ld, creating a new one.\n", parsed_num);
900         ysuccess(true);
901         workspace_show_by_name(which);
902         cmd_output->needs_tree_render = true;
903         return;
904     }
905     if (!no_auto_back_and_forth && maybe_back_and_forth(cmd_output, workspace->name)) {
906         ysuccess(true);
907         return;
908     }
909     workspace_show(workspace);
910 
911     cmd_output->needs_tree_render = true;
912     // XXX: default reply for now, make this a better reply
913     ysuccess(true);
914 }
915 
916 /*
917  * Implementation of 'workspace back_and_forth'.
918  *
919  */
cmd_workspace_back_and_forth(I3_CMD)920 void cmd_workspace_back_and_forth(I3_CMD) {
921     if (con_get_fullscreen_con(croot, CF_GLOBAL)) {
922         yerror("Cannot switch workspace while in global fullscreen");
923         return;
924     }
925 
926     workspace_back_and_forth();
927 
928     cmd_output->needs_tree_render = true;
929     // XXX: default reply for now, make this a better reply
930     ysuccess(true);
931 }
932 
933 /*
934  * Implementation of 'workspace [--no-auto-back-and-forth] <name>'
935  *
936  */
cmd_workspace_name(I3_CMD,const char * name,const char * _no_auto_back_and_forth)937 void cmd_workspace_name(I3_CMD, const char *name, const char *_no_auto_back_and_forth) {
938     const bool no_auto_back_and_forth = (_no_auto_back_and_forth != NULL);
939 
940     if (strncasecmp(name, "__", strlen("__")) == 0) {
941         yerror("You cannot switch to the i3-internal workspaces (\"%s\").", name);
942         return;
943     }
944 
945     if (con_get_fullscreen_con(croot, CF_GLOBAL)) {
946         yerror("Cannot switch workspace while in global fullscreen");
947         return;
948     }
949 
950     DLOG("should switch to workspace %s\n", name);
951     if (!no_auto_back_and_forth && maybe_back_and_forth(cmd_output, name)) {
952         ysuccess(true);
953         return;
954     }
955     workspace_show_by_name(name);
956 
957     cmd_output->needs_tree_render = true;
958     // XXX: default reply for now, make this a better reply
959     ysuccess(true);
960 }
961 
962 /*
963  * Implementation of 'mark [--add|--replace] [--toggle] <mark>'
964  *
965  */
cmd_mark(I3_CMD,const char * mark,const char * mode,const char * toggle)966 void cmd_mark(I3_CMD, const char *mark, const char *mode, const char *toggle) {
967     HANDLE_EMPTY_MATCH;
968 
969     owindow *current = TAILQ_FIRST(&owindows);
970     if (current == NULL) {
971         yerror("Given criteria don't match a window");
972         return;
973     }
974 
975     /* Marks must be unique, i.e., no two windows must have the same mark. */
976     if (current != TAILQ_LAST(&owindows, owindows_head)) {
977         yerror("A mark must not be put onto more than one window");
978         return;
979     }
980 
981     DLOG("matching: %p / %s\n", current->con, current->con->name);
982 
983     mark_mode_t mark_mode = (mode == NULL || strcmp(mode, "--replace") == 0) ? MM_REPLACE : MM_ADD;
984     if (toggle != NULL) {
985         con_mark_toggle(current->con, mark, mark_mode);
986     } else {
987         con_mark(current->con, mark, mark_mode);
988     }
989 
990     cmd_output->needs_tree_render = true;
991     // XXX: default reply for now, make this a better reply
992     ysuccess(true);
993 }
994 
995 /*
996  * Implementation of 'unmark [mark]'
997  *
998  */
cmd_unmark(I3_CMD,const char * mark)999 void cmd_unmark(I3_CMD, const char *mark) {
1000     if (match_is_empty(current_match)) {
1001         con_unmark(NULL, mark);
1002     } else {
1003         owindow *current;
1004         TAILQ_FOREACH (current, &owindows, owindows) {
1005             con_unmark(current->con, mark);
1006         }
1007     }
1008 
1009     cmd_output->needs_tree_render = true;
1010     // XXX: default reply for now, make this a better reply
1011     ysuccess(true);
1012 }
1013 
1014 /*
1015  * Implementation of 'mode <string>'.
1016  *
1017  */
cmd_mode(I3_CMD,const char * mode)1018 void cmd_mode(I3_CMD, const char *mode) {
1019     DLOG("mode=%s\n", mode);
1020     switch_mode(mode);
1021 
1022     // XXX: default reply for now, make this a better reply
1023     ysuccess(true);
1024 }
1025 
1026 /*
1027  * Implementation of 'move [window|container|workspace] [to] output <strings>'.
1028  *
1029  */
cmd_move_con_to_output(I3_CMD,const char * name,bool move_workspace)1030 void cmd_move_con_to_output(I3_CMD, const char *name, bool move_workspace) {
1031     /* Initialize a data structure that is used to save multiple user-specified
1032      * output names since this function is called multiple types for each
1033      * command call. */
1034     typedef struct user_output_name {
1035         char *name;
1036         TAILQ_ENTRY(user_output_name) user_output_names;
1037     } user_output_name;
1038     static TAILQ_HEAD(user_output_names_head, user_output_name) user_output_names = TAILQ_HEAD_INITIALIZER(user_output_names);
1039 
1040     if (name) {
1041         if (strcmp(name, "next") == 0) {
1042             /* "next" here works like a wildcard: It "expands" to all available
1043              * outputs. */
1044             Output *output;
1045             TAILQ_FOREACH (output, &outputs, outputs) {
1046                 user_output_name *co = scalloc(sizeof(user_output_name), 1);
1047                 co->name = sstrdup(output_primary_name(output));
1048                 TAILQ_INSERT_TAIL(&user_output_names, co, user_output_names);
1049             }
1050             return;
1051         }
1052 
1053         user_output_name *co = scalloc(sizeof(user_output_name), 1);
1054         co->name = sstrdup(name);
1055         TAILQ_INSERT_TAIL(&user_output_names, co, user_output_names);
1056         return;
1057     }
1058 
1059     HANDLE_EMPTY_MATCH;
1060 
1061     if (TAILQ_EMPTY(&user_output_names)) {
1062         yerror("At least one output must be specified");
1063         return;
1064     }
1065 
1066     bool success = false;
1067     user_output_name *uo;
1068     owindow *current;
1069     TAILQ_FOREACH (current, &owindows, owindows) {
1070         Con *ws = con_get_workspace(current->con);
1071         if (con_is_internal(ws)) {
1072             continue;
1073         }
1074 
1075         Output *current_output = get_output_for_con(ws);
1076 
1077         Output *target_output = NULL;
1078         TAILQ_FOREACH (uo, &user_output_names, user_output_names) {
1079             if (strcasecmp(output_primary_name(current_output), uo->name) == 0) {
1080                 /* The current output is in the user list */
1081                 while (true) {
1082                     /* This corrupts the outer loop but it is ok since we are
1083                      * going to break anyway. */
1084                     uo = TAILQ_NEXT(uo, user_output_names);
1085                     if (!uo) {
1086                         /* We reached the end of the list. We should use the
1087                          * first available output that, if it exists, is
1088                          * already saved in target_output. */
1089                         break;
1090                     }
1091                     Output *out = get_output_from_string(current_output, uo->name);
1092                     if (out) {
1093                         DLOG("Found next target for workspace %s from user list: %s\n", ws->name, uo->name);
1094                         target_output = out;
1095                         break;
1096                     }
1097                 }
1098                 break;
1099             }
1100             if (!target_output) {
1101                 /* The first available output from the list is used in 2 cases:
1102                  * 1. When we must wrap around the user list. For example, if
1103                  * user specifies outputs A B C and C is `current_output`.
1104                  * 2. When the current output is not in the user list. For
1105                  * example, user specifies A B C and D is `current_output`.
1106                  */
1107                 DLOG("Found first target for workspace %s from user list: %s\n", ws->name, uo->name);
1108                 target_output = get_output_from_string(current_output, uo->name);
1109             }
1110         }
1111         if (target_output) {
1112             if (move_workspace) {
1113                 workspace_move_to_output(ws, target_output);
1114             } else {
1115                 con_move_to_output(current->con, target_output, true);
1116             }
1117             success = true;
1118         }
1119     }
1120 
1121     while (!TAILQ_EMPTY(&user_output_names)) {
1122         uo = TAILQ_FIRST(&user_output_names);
1123         free(uo->name);
1124         TAILQ_REMOVE(&user_output_names, uo, user_output_names);
1125         free(uo);
1126     }
1127 
1128     cmd_output->needs_tree_render = success;
1129     if (success) {
1130         ysuccess(true);
1131     } else {
1132         yerror("No output matched");
1133     }
1134 }
1135 
1136 /*
1137  * Implementation of 'move [container|window] [to] mark <str>'.
1138  *
1139  */
cmd_move_con_to_mark(I3_CMD,const char * mark)1140 void cmd_move_con_to_mark(I3_CMD, const char *mark) {
1141     DLOG("moving window to mark \"%s\"\n", mark);
1142 
1143     HANDLE_EMPTY_MATCH;
1144 
1145     bool result = true;
1146     owindow *current;
1147     TAILQ_FOREACH (current, &owindows, owindows) {
1148         DLOG("moving matched window %p / %s to mark \"%s\"\n", current->con, current->con->name, mark);
1149         result &= con_move_to_mark(current->con, mark);
1150     }
1151 
1152     cmd_output->needs_tree_render = true;
1153     ysuccess(result);
1154 }
1155 
1156 /*
1157  * Implementation of 'floating enable|disable|toggle'
1158  *
1159  */
cmd_floating(I3_CMD,const char * floating_mode)1160 void cmd_floating(I3_CMD, const char *floating_mode) {
1161     owindow *current;
1162 
1163     DLOG("floating_mode=%s\n", floating_mode);
1164 
1165     HANDLE_EMPTY_MATCH;
1166 
1167     TAILQ_FOREACH (current, &owindows, owindows) {
1168         DLOG("matching: %p / %s\n", current->con, current->con->name);
1169         if (strcmp(floating_mode, "toggle") == 0) {
1170             DLOG("should toggle mode\n");
1171             toggle_floating_mode(current->con, false);
1172         } else {
1173             DLOG("should switch mode to %s\n", floating_mode);
1174             if (strcmp(floating_mode, "enable") == 0) {
1175                 floating_enable(current->con, false);
1176             } else {
1177                 floating_disable(current->con);
1178             }
1179         }
1180     }
1181 
1182     cmd_output->needs_tree_render = true;
1183     // XXX: default reply for now, make this a better reply
1184     ysuccess(true);
1185 }
1186 
1187 /*
1188  * Implementation of 'split v|h|t|vertical|horizontal|toggle'.
1189  *
1190  */
cmd_split(I3_CMD,const char * direction)1191 void cmd_split(I3_CMD, const char *direction) {
1192     HANDLE_EMPTY_MATCH;
1193 
1194     owindow *current;
1195     LOG("splitting in direction %c\n", direction[0]);
1196     TAILQ_FOREACH (current, &owindows, owindows) {
1197         if (con_is_docked(current->con)) {
1198             ELOG("Cannot split a docked container, skipping.\n");
1199             continue;
1200         }
1201 
1202         DLOG("matching: %p / %s\n", current->con, current->con->name);
1203         if (direction[0] == 't') {
1204             layout_t current_layout;
1205             if (current->con->type == CT_WORKSPACE) {
1206                 current_layout = current->con->layout;
1207             } else {
1208                 current_layout = current->con->parent->layout;
1209             }
1210             /* toggling split orientation */
1211             if (current_layout == L_SPLITH) {
1212                 tree_split(current->con, VERT);
1213             } else {
1214                 tree_split(current->con, HORIZ);
1215             }
1216         } else {
1217             tree_split(current->con, (direction[0] == 'v' ? VERT : HORIZ));
1218         }
1219     }
1220 
1221     cmd_output->needs_tree_render = true;
1222     // XXX: default reply for now, make this a better reply
1223     ysuccess(true);
1224 }
1225 
1226 /*
1227  * Implementation of 'kill [window|client]'.
1228  *
1229  */
cmd_kill(I3_CMD,const char * kill_mode_str)1230 void cmd_kill(I3_CMD, const char *kill_mode_str) {
1231     if (kill_mode_str == NULL)
1232         kill_mode_str = "window";
1233 
1234     DLOG("kill_mode=%s\n", kill_mode_str);
1235 
1236     int kill_mode;
1237     if (strcmp(kill_mode_str, "window") == 0)
1238         kill_mode = KILL_WINDOW;
1239     else if (strcmp(kill_mode_str, "client") == 0)
1240         kill_mode = KILL_CLIENT;
1241     else {
1242         yerror("BUG: called with kill_mode=%s", kill_mode_str);
1243         return;
1244     }
1245 
1246     HANDLE_EMPTY_MATCH;
1247 
1248     owindow *current;
1249     TAILQ_FOREACH (current, &owindows, owindows) {
1250         con_close(current->con, kill_mode);
1251     }
1252 
1253     cmd_output->needs_tree_render = true;
1254     // XXX: default reply for now, make this a better reply
1255     ysuccess(true);
1256 }
1257 
1258 /*
1259  * Implementation of 'exec [--no-startup-id] <command>'.
1260  *
1261  */
cmd_exec(I3_CMD,const char * nosn,const char * command)1262 void cmd_exec(I3_CMD, const char *nosn, const char *command) {
1263     bool no_startup_id = (nosn != NULL);
1264 
1265     HANDLE_EMPTY_MATCH;
1266 
1267     int count = 0;
1268     owindow *current;
1269     TAILQ_FOREACH (current, &owindows, owindows) {
1270         count++;
1271     }
1272 
1273     if (count > 1) {
1274         LOG("WARNING: Your criteria for the exec command match %d containers, "
1275             "so the command will execute this many times.\n",
1276             count);
1277     }
1278 
1279     TAILQ_FOREACH (current, &owindows, owindows) {
1280         DLOG("should execute %s, no_startup_id = %d\n", command, no_startup_id);
1281         start_application(command, no_startup_id);
1282     }
1283 
1284     ysuccess(true);
1285 }
1286 
1287 #define CMD_FOCUS_WARN_CHILDREN                                                        \
1288     do {                                                                               \
1289         int count = 0;                                                                 \
1290         owindow *current;                                                              \
1291         TAILQ_FOREACH (current, &owindows, owindows) {                                 \
1292             count++;                                                                   \
1293         }                                                                              \
1294                                                                                        \
1295         if (count > 1) {                                                               \
1296             LOG("WARNING: Your criteria for the focus command matches %d containers, " \
1297                 "while only exactly one container can be focused at a time.\n",        \
1298                 count);                                                                \
1299         }                                                                              \
1300     } while (0)
1301 
1302 /*
1303  * Implementation of 'focus left|right|up|down|next|prev'.
1304  *
1305  */
cmd_focus_direction(I3_CMD,const char * direction_str)1306 void cmd_focus_direction(I3_CMD, const char *direction_str) {
1307     HANDLE_EMPTY_MATCH;
1308     CMD_FOCUS_WARN_CHILDREN;
1309 
1310     direction_t direction;
1311     position_t position;
1312     bool auto_direction = true;
1313     if (strcmp(direction_str, "prev") == 0) {
1314         position = BEFORE;
1315     } else if (strcmp(direction_str, "next") == 0) {
1316         position = AFTER;
1317     } else {
1318         auto_direction = false;
1319         direction = parse_direction(direction_str);
1320     }
1321 
1322     owindow *current;
1323     TAILQ_FOREACH (current, &owindows, owindows) {
1324         Con *ws = con_get_workspace(current->con);
1325         if (!ws || con_is_internal(ws)) {
1326             continue;
1327         }
1328         if (auto_direction) {
1329             orientation_t o = con_orientation(current->con->parent);
1330             direction = direction_from_orientation_position(o, position);
1331         }
1332         tree_next(current->con, direction);
1333     }
1334 
1335     cmd_output->needs_tree_render = true;
1336     // XXX: default reply for now, make this a better reply
1337     ysuccess(true);
1338 }
1339 
1340 /*
1341  * Implementation of 'focus next|prev sibling'
1342  *
1343  */
cmd_focus_sibling(I3_CMD,const char * direction_str)1344 void cmd_focus_sibling(I3_CMD, const char *direction_str) {
1345     HANDLE_EMPTY_MATCH;
1346     CMD_FOCUS_WARN_CHILDREN;
1347 
1348     const position_t direction = (STARTS_WITH(direction_str, "prev")) ? BEFORE : AFTER;
1349     owindow *current;
1350     TAILQ_FOREACH (current, &owindows, owindows) {
1351         Con *ws = con_get_workspace(current->con);
1352         if (!ws || con_is_internal(ws)) {
1353             continue;
1354         }
1355         Con *next = get_tree_next_sibling(current->con, direction);
1356         if (next) {
1357             if (next->type == CT_WORKSPACE) {
1358                 /* On the workspace level, we need to make sure that the
1359                  * workspace change happens properly. However, workspace_show
1360                  * descends focus so we also have to put focus on the workspace
1361                  * itself to maintain consistency. See #3997. */
1362                 workspace_show(next);
1363                 con_focus(next);
1364             } else {
1365                 con_activate(next);
1366             }
1367         }
1368     }
1369 
1370     cmd_output->needs_tree_render = true;
1371     // XXX: default reply for now, make this a better reply
1372     ysuccess(true);
1373 }
1374 
1375 /*
1376  * Implementation of 'focus tiling|floating|mode_toggle'.
1377  *
1378  */
cmd_focus_window_mode(I3_CMD,const char * window_mode)1379 void cmd_focus_window_mode(I3_CMD, const char *window_mode) {
1380     DLOG("window_mode = %s\n", window_mode);
1381 
1382     bool to_floating = false;
1383     if (strcmp(window_mode, "mode_toggle") == 0) {
1384         to_floating = !con_inside_floating(focused);
1385     } else if (strcmp(window_mode, "floating") == 0) {
1386         to_floating = true;
1387     } else if (strcmp(window_mode, "tiling") == 0) {
1388         to_floating = false;
1389     }
1390 
1391     Con *ws = con_get_workspace(focused);
1392     Con *current;
1393     bool success = false;
1394     TAILQ_FOREACH (current, &(ws->focus_head), focused) {
1395         if ((to_floating && current->type != CT_FLOATING_CON) ||
1396             (!to_floating && current->type == CT_FLOATING_CON))
1397             continue;
1398 
1399         con_activate_unblock(con_descend_focused(current));
1400         success = true;
1401         break;
1402     }
1403 
1404     if (success) {
1405         cmd_output->needs_tree_render = true;
1406         ysuccess(true);
1407     } else {
1408         yerror("Failed to find a %s container in workspace.", to_floating ? "floating" : "tiling");
1409     }
1410 }
1411 
1412 /*
1413  * Implementation of 'focus parent|child'.
1414  *
1415  */
cmd_focus_level(I3_CMD,const char * level)1416 void cmd_focus_level(I3_CMD, const char *level) {
1417     DLOG("level = %s\n", level);
1418     bool success = false;
1419 
1420     /* Focusing the parent can only be allowed if the newly
1421      * focused container won't escape the fullscreen container. */
1422     if (strcmp(level, "parent") == 0) {
1423         if (focused && focused->parent) {
1424             if (con_fullscreen_permits_focusing(focused->parent))
1425                 success = level_up();
1426             else
1427                 ELOG("'focus parent': Currently in fullscreen, not going up\n");
1428         }
1429     }
1430 
1431     /* Focusing a child should always be allowed. */
1432     else
1433         success = level_down();
1434 
1435     cmd_output->needs_tree_render = success;
1436     // XXX: default reply for now, make this a better reply
1437     ysuccess(success);
1438 }
1439 
1440 /*
1441  * Implementation of 'focus'.
1442  *
1443  */
cmd_focus(I3_CMD)1444 void cmd_focus(I3_CMD) {
1445     DLOG("current_match = %p\n", current_match);
1446 
1447     if (match_is_empty(current_match)) {
1448         ELOG("You have to specify which window/container should be focused.\n");
1449         ELOG("Example: [class=\"urxvt\" title=\"irssi\"] focus\n");
1450 
1451         yerror("You have to specify which window/container should be focused");
1452         return;
1453     } else if (TAILQ_EMPTY(&owindows)) {
1454         yerror("No window matches given criteria");
1455         return;
1456     }
1457 
1458     CMD_FOCUS_WARN_CHILDREN;
1459 
1460     Con *__i3_scratch = workspace_get("__i3_scratch");
1461     owindow *current;
1462     TAILQ_FOREACH (current, &owindows, owindows) {
1463         Con *ws = con_get_workspace(current->con);
1464         /* If no workspace could be found, this was a dock window.
1465          * Just skip it, you cannot focus dock windows. */
1466         if (!ws)
1467             continue;
1468 
1469         /* In case this is a scratchpad window, call scratchpad_show(). */
1470         if (ws == __i3_scratch) {
1471             scratchpad_show(current->con);
1472             /* While for the normal focus case we can change focus multiple
1473              * times and only a single window ends up focused, we could show
1474              * multiple scratchpad windows. So, rather break here. */
1475             break;
1476         }
1477 
1478         LOG("focusing %p / %s\n", current->con, current->con->name);
1479         con_activate_unblock(current->con);
1480     }
1481 
1482     cmd_output->needs_tree_render = true;
1483     ysuccess(true);
1484 }
1485 
1486 /*
1487  * Implementation of 'fullscreen enable|toggle [global]' and
1488  *                   'fullscreen disable'
1489  *
1490  */
cmd_fullscreen(I3_CMD,const char * action,const char * fullscreen_mode)1491 void cmd_fullscreen(I3_CMD, const char *action, const char *fullscreen_mode) {
1492     fullscreen_mode_t mode = strcmp(fullscreen_mode, "global") == 0 ? CF_GLOBAL : CF_OUTPUT;
1493     DLOG("%s fullscreen, mode = %s\n", action, fullscreen_mode);
1494     owindow *current;
1495 
1496     HANDLE_EMPTY_MATCH;
1497 
1498     TAILQ_FOREACH (current, &owindows, owindows) {
1499         DLOG("matching: %p / %s\n", current->con, current->con->name);
1500         if (strcmp(action, "toggle") == 0) {
1501             con_toggle_fullscreen(current->con, mode);
1502         } else if (strcmp(action, "enable") == 0) {
1503             con_enable_fullscreen(current->con, mode);
1504         } else if (strcmp(action, "disable") == 0) {
1505             con_disable_fullscreen(current->con);
1506         }
1507     }
1508 
1509     cmd_output->needs_tree_render = true;
1510     // XXX: default reply for now, make this a better reply
1511     ysuccess(true);
1512 }
1513 
1514 /*
1515  * Implementation of 'sticky enable|disable|toggle'.
1516  *
1517  */
cmd_sticky(I3_CMD,const char * action)1518 void cmd_sticky(I3_CMD, const char *action) {
1519     DLOG("%s sticky on window\n", action);
1520     HANDLE_EMPTY_MATCH;
1521 
1522     owindow *current;
1523     TAILQ_FOREACH (current, &owindows, owindows) {
1524         if (current->con->window == NULL) {
1525             ELOG("only containers holding a window can be made sticky, skipping con = %p\n", current->con);
1526             continue;
1527         }
1528         DLOG("setting sticky for container = %p / %s\n", current->con, current->con->name);
1529 
1530         bool sticky = false;
1531         if (strcmp(action, "enable") == 0)
1532             sticky = true;
1533         else if (strcmp(action, "disable") == 0)
1534             sticky = false;
1535         else if (strcmp(action, "toggle") == 0)
1536             sticky = !current->con->sticky;
1537 
1538         current->con->sticky = sticky;
1539         ewmh_update_sticky(current->con->window->id, sticky);
1540     }
1541 
1542     /* A window we made sticky might not be on a visible workspace right now, so we need to make
1543      * sure it gets pushed to the front now. */
1544     output_push_sticky_windows(focused);
1545 
1546     ewmh_update_wm_desktop();
1547 
1548     cmd_output->needs_tree_render = true;
1549     ysuccess(true);
1550 }
1551 
1552 /*
1553  * Implementation of 'move <direction> [<amount> [px|ppt]]'.
1554  *
1555  */
cmd_move_direction(I3_CMD,const char * direction_str,long amount,const char * mode)1556 void cmd_move_direction(I3_CMD, const char *direction_str, long amount, const char *mode) {
1557     owindow *current;
1558     HANDLE_EMPTY_MATCH;
1559 
1560     Con *initially_focused = focused;
1561     direction_t direction = parse_direction(direction_str);
1562 
1563     const bool is_ppt = mode && strcmp(mode, "ppt") == 0;
1564 
1565     DLOG("moving in direction %s, %ld %s\n", direction_str, amount, mode);
1566     TAILQ_FOREACH (current, &owindows, owindows) {
1567         if (con_is_floating(current->con)) {
1568             DLOG("floating move with %ld %s\n", amount, mode);
1569             Rect newrect = current->con->parent->rect;
1570             Con *output = con_get_output(current->con);
1571 
1572             switch (direction) {
1573                 case D_LEFT:
1574                     newrect.x -= is_ppt ? output->rect.width * ((double)amount / 100.0) : amount;
1575                     break;
1576                 case D_RIGHT:
1577                     newrect.x += is_ppt ? output->rect.width * ((double)amount / 100.0) : amount;
1578                     break;
1579                 case D_UP:
1580                     newrect.y -= is_ppt ? output->rect.height * ((double)amount / 100.0) : amount;
1581                     break;
1582                 case D_DOWN:
1583                     newrect.y += is_ppt ? output->rect.height * ((double)amount / 100.0) : amount;
1584                     break;
1585             }
1586 
1587             cmd_output->needs_tree_render = floating_reposition(current->con->parent, newrect);
1588         } else {
1589             tree_move(current->con, direction);
1590             cmd_output->needs_tree_render = true;
1591         }
1592     }
1593 
1594     /* The move command should not disturb focus. con_exists is called because
1595      * tree_move calls tree_flatten. */
1596     if (focused != initially_focused && con_exists(initially_focused)) {
1597         con_activate(initially_focused);
1598     }
1599 
1600     // XXX: default reply for now, make this a better reply
1601     ysuccess(true);
1602 }
1603 
1604 /*
1605  * Implementation of 'layout default|stacked|stacking|tabbed|splitv|splith'.
1606  *
1607  */
cmd_layout(I3_CMD,const char * layout_str)1608 void cmd_layout(I3_CMD, const char *layout_str) {
1609     HANDLE_EMPTY_MATCH;
1610 
1611     layout_t layout;
1612     if (!layout_from_name(layout_str, &layout)) {
1613         yerror("Unknown layout \"%s\", this is a mismatch between code and parser spec.", layout_str);
1614         return;
1615     }
1616 
1617     DLOG("changing layout to %s (%d)\n", layout_str, layout);
1618 
1619     owindow *current;
1620     TAILQ_FOREACH (current, &owindows, owindows) {
1621         if (con_is_docked(current->con)) {
1622             ELOG("cannot change layout of a docked container, skipping it.\n");
1623             continue;
1624         }
1625 
1626         DLOG("matching: %p / %s\n", current->con, current->con->name);
1627         con_set_layout(current->con, layout);
1628     }
1629 
1630     cmd_output->needs_tree_render = true;
1631     // XXX: default reply for now, make this a better reply
1632     ysuccess(true);
1633 }
1634 
1635 /*
1636  * Implementation of 'layout toggle [all|split]'.
1637  *
1638  */
cmd_layout_toggle(I3_CMD,const char * toggle_mode)1639 void cmd_layout_toggle(I3_CMD, const char *toggle_mode) {
1640     owindow *current;
1641 
1642     if (toggle_mode == NULL)
1643         toggle_mode = "default";
1644 
1645     DLOG("toggling layout (mode = %s)\n", toggle_mode);
1646 
1647     /* check if the match is empty, not if the result is empty */
1648     if (match_is_empty(current_match))
1649         con_toggle_layout(focused, toggle_mode);
1650     else {
1651         TAILQ_FOREACH (current, &owindows, owindows) {
1652             DLOG("matching: %p / %s\n", current->con, current->con->name);
1653             con_toggle_layout(current->con, toggle_mode);
1654         }
1655     }
1656 
1657     cmd_output->needs_tree_render = true;
1658     // XXX: default reply for now, make this a better reply
1659     ysuccess(true);
1660 }
1661 
1662 /*
1663  * Implementation of 'exit'.
1664  *
1665  */
cmd_exit(I3_CMD)1666 void cmd_exit(I3_CMD) {
1667     LOG("Exiting due to user command.\n");
1668     exit(EXIT_SUCCESS);
1669 
1670     /* unreached */
1671 }
1672 
1673 /*
1674  * Implementation of 'reload'.
1675  *
1676  */
cmd_reload(I3_CMD)1677 void cmd_reload(I3_CMD) {
1678     LOG("reloading\n");
1679 
1680     kill_nagbar(config_error_nagbar_pid, false);
1681     kill_nagbar(command_error_nagbar_pid, false);
1682     /* start_nagbar() will refuse to start a new process if the passed pid is
1683      * set. This will happen when our child watcher is triggered by libev when
1684      * the loop re-starts. However, config errors might be detected before
1685      * that since we will read the config right now with load_configuration.
1686      * See #4104. */
1687     config_error_nagbar_pid = command_error_nagbar_pid = -1;
1688 
1689     load_configuration(NULL, C_RELOAD);
1690     x_set_i3_atoms();
1691     /* Send an IPC event just in case the ws names have changed */
1692     ipc_send_workspace_event("reload", NULL, NULL);
1693     /* Send an update event for each barconfig just in case it has changed */
1694     Barconfig *current;
1695     TAILQ_FOREACH (current, &barconfigs, configs) {
1696         ipc_send_barconfig_update_event(current);
1697     }
1698 
1699     // XXX: default reply for now, make this a better reply
1700     ysuccess(true);
1701 }
1702 
1703 /*
1704  * Implementation of 'restart'.
1705  *
1706  */
cmd_restart(I3_CMD)1707 void cmd_restart(I3_CMD) {
1708     LOG("restarting i3\n");
1709     int exempt_fd = -1;
1710     if (cmd_output->client != NULL) {
1711         exempt_fd = cmd_output->client->fd;
1712         LOG("Carrying file descriptor %d across restart\n", exempt_fd);
1713         int flags;
1714         if ((flags = fcntl(exempt_fd, F_GETFD)) < 0 ||
1715             fcntl(exempt_fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
1716             ELOG("Could not disable FD_CLOEXEC on fd %d\n", exempt_fd);
1717         }
1718         char *fdstr = NULL;
1719         sasprintf(&fdstr, "%d", exempt_fd);
1720         setenv("_I3_RESTART_FD", fdstr, 1);
1721     }
1722     ipc_shutdown(SHUTDOWN_REASON_RESTART, exempt_fd);
1723     unlink(config.ipc_socket_path);
1724     if (current_log_stream_socket_path != NULL) {
1725         unlink(current_log_stream_socket_path);
1726     }
1727     /* We need to call this manually since atexit handlers don’t get called
1728      * when exec()ing */
1729     purge_zerobyte_logfile();
1730     i3_restart(false);
1731     /* unreached */
1732     assert(false);
1733 }
1734 
1735 /*
1736  * Implementation of 'open'.
1737  *
1738  */
cmd_open(I3_CMD)1739 void cmd_open(I3_CMD) {
1740     LOG("opening new container\n");
1741     Con *con = tree_open_con(NULL, NULL);
1742     con->layout = L_SPLITH;
1743     con_activate(con);
1744 
1745     y(map_open);
1746     ystr("success");
1747     y(bool, true);
1748     ystr("id");
1749     y(integer, (uintptr_t)con);
1750     y(map_close);
1751 
1752     cmd_output->needs_tree_render = true;
1753 }
1754 
1755 /*
1756  * Implementation of 'focus output <output>'.
1757  *
1758  */
cmd_focus_output(I3_CMD,const char * name)1759 void cmd_focus_output(I3_CMD, const char *name) {
1760     HANDLE_EMPTY_MATCH;
1761 
1762     if (TAILQ_EMPTY(&owindows)) {
1763         ysuccess(true);
1764         return;
1765     }
1766 
1767     Output *current_output = get_output_for_con(TAILQ_FIRST(&owindows)->con);
1768     Output *output = get_output_from_string(current_output, name);
1769 
1770     if (!output) {
1771         yerror("Output %s not found.", name);
1772         return;
1773     }
1774 
1775     /* get visible workspace on output */
1776     Con *ws = NULL;
1777     GREP_FIRST(ws, output_get_content(output->con), workspace_is_visible(child));
1778     if (!ws) {
1779         yerror("BUG: No workspace found on output.");
1780         return;
1781     }
1782 
1783     workspace_show(ws);
1784 
1785     cmd_output->needs_tree_render = true;
1786     ysuccess(true);
1787 }
1788 
1789 /*
1790  * Implementation of 'move [window|container] [to] [absolute] position [<pos_x> [px|ppt] <pos_y> [px|ppt]]
1791  *
1792  */
cmd_move_window_to_position(I3_CMD,long x,const char * mode_x,long y,const char * mode_y)1793 void cmd_move_window_to_position(I3_CMD, long x, const char *mode_x, long y, const char *mode_y) {
1794     bool has_error = false;
1795 
1796     owindow *current;
1797     HANDLE_EMPTY_MATCH;
1798 
1799     TAILQ_FOREACH (current, &owindows, owindows) {
1800         if (!con_is_floating(current->con)) {
1801             ELOG("Cannot change position. The window/container is not floating\n");
1802 
1803             if (!has_error) {
1804                 yerror("Cannot change position of a window/container because it is not floating.");
1805                 has_error = true;
1806             }
1807 
1808             continue;
1809         }
1810 
1811         Rect newrect = current->con->parent->rect;
1812         Con *output = con_get_output(current->con);
1813 
1814         newrect.x = mode_x && strcmp(mode_x, "ppt") == 0 ? output->rect.width * ((double)x / 100.0) : x;
1815         newrect.y = mode_y && strcmp(mode_y, "ppt") == 0 ? output->rect.height * ((double)y / 100.0) : y;
1816         DLOG("moving to position %d %s %d %s\n", newrect.x, mode_x, newrect.y, mode_y);
1817 
1818         if (!floating_reposition(current->con->parent, newrect)) {
1819             yerror("Cannot move window/container out of bounds.");
1820             has_error = true;
1821         }
1822     }
1823 
1824     if (!has_error)
1825         ysuccess(true);
1826 }
1827 
1828 /*
1829  * Implementation of 'move [window|container] [to] [absolute] position center
1830  *
1831  */
cmd_move_window_to_center(I3_CMD,const char * method)1832 void cmd_move_window_to_center(I3_CMD, const char *method) {
1833     bool has_error = false;
1834     HANDLE_EMPTY_MATCH;
1835 
1836     owindow *current;
1837     TAILQ_FOREACH (current, &owindows, owindows) {
1838         Con *floating_con = con_inside_floating(current->con);
1839         if (floating_con == NULL) {
1840             ELOG("con %p / %s is not floating, cannot move it to the center.\n",
1841                  current->con, current->con->name);
1842 
1843             if (!has_error) {
1844                 yerror("Cannot change position of a window/container because it is not floating.");
1845                 has_error = true;
1846             }
1847 
1848             continue;
1849         }
1850 
1851         if (strcmp(method, "absolute") == 0) {
1852             DLOG("moving to absolute center\n");
1853             floating_center(floating_con, croot->rect);
1854 
1855             floating_maybe_reassign_ws(floating_con);
1856             cmd_output->needs_tree_render = true;
1857         }
1858 
1859         if (strcmp(method, "position") == 0) {
1860             DLOG("moving to center\n");
1861             floating_center(floating_con, con_get_workspace(floating_con)->rect);
1862 
1863             cmd_output->needs_tree_render = true;
1864         }
1865     }
1866 
1867     // XXX: default reply for now, make this a better reply
1868     if (!has_error)
1869         ysuccess(true);
1870 }
1871 
1872 /*
1873  * Implementation of 'move [window|container] [to] position mouse'
1874  *
1875  */
cmd_move_window_to_mouse(I3_CMD)1876 void cmd_move_window_to_mouse(I3_CMD) {
1877     HANDLE_EMPTY_MATCH;
1878 
1879     owindow *current;
1880     TAILQ_FOREACH (current, &owindows, owindows) {
1881         Con *floating_con = con_inside_floating(current->con);
1882         if (floating_con == NULL) {
1883             DLOG("con %p / %s is not floating, cannot move it to the mouse position.\n",
1884                  current->con, current->con->name);
1885             continue;
1886         }
1887 
1888         DLOG("moving floating container %p / %s to cursor position\n", floating_con, floating_con->name);
1889         floating_move_to_pointer(floating_con);
1890     }
1891 
1892     cmd_output->needs_tree_render = true;
1893     ysuccess(true);
1894 }
1895 
1896 /*
1897  * Implementation of 'move scratchpad'.
1898  *
1899  */
cmd_move_scratchpad(I3_CMD)1900 void cmd_move_scratchpad(I3_CMD) {
1901     DLOG("should move window to scratchpad\n");
1902     owindow *current;
1903 
1904     HANDLE_EMPTY_MATCH;
1905 
1906     TAILQ_FOREACH (current, &owindows, owindows) {
1907         DLOG("matching: %p / %s\n", current->con, current->con->name);
1908         scratchpad_move(current->con);
1909     }
1910 
1911     cmd_output->needs_tree_render = true;
1912     // XXX: default reply for now, make this a better reply
1913     ysuccess(true);
1914 }
1915 
1916 /*
1917  * Implementation of 'scratchpad show'.
1918  *
1919  */
cmd_scratchpad_show(I3_CMD)1920 void cmd_scratchpad_show(I3_CMD) {
1921     DLOG("should show scratchpad window\n");
1922     owindow *current;
1923     bool result = false;
1924 
1925     if (match_is_empty(current_match)) {
1926         result = scratchpad_show(NULL);
1927     } else {
1928         TAILQ_FOREACH (current, &owindows, owindows) {
1929             DLOG("matching: %p / %s\n", current->con, current->con->name);
1930             result |= scratchpad_show(current->con);
1931         }
1932     }
1933 
1934     cmd_output->needs_tree_render = true;
1935 
1936     ysuccess(result);
1937 }
1938 
1939 /*
1940  * Implementation of 'swap [container] [with] id|con_id|mark <arg>'.
1941  *
1942  */
cmd_swap(I3_CMD,const char * mode,const char * arg)1943 void cmd_swap(I3_CMD, const char *mode, const char *arg) {
1944     HANDLE_EMPTY_MATCH;
1945 
1946     owindow *match = TAILQ_FIRST(&owindows);
1947     if (match == NULL) {
1948         yerror("No match found for swapping.");
1949         return;
1950     }
1951     if (match->con == NULL) {
1952         yerror("Match %p has no container.", match);
1953         return;
1954     }
1955 
1956     Con *con;
1957     if (strcmp(mode, "id") == 0) {
1958         long target;
1959         if (!parse_long(arg, &target, 0)) {
1960             yerror("Failed to parse %s into a window id.", arg);
1961             return;
1962         }
1963 
1964         con = con_by_window_id(target);
1965     } else if (strcmp(mode, "con_id") == 0) {
1966         long target;
1967         if (!parse_long(arg, &target, 0)) {
1968             yerror("Failed to parse %s into a container id.", arg);
1969             return;
1970         }
1971 
1972         con = con_by_con_id(target);
1973     } else if (strcmp(mode, "mark") == 0) {
1974         con = con_by_mark(arg);
1975     } else {
1976         yerror("Unhandled swap mode \"%s\". This is a bug.", mode);
1977         return;
1978     }
1979 
1980     if (con == NULL) {
1981         yerror("Could not find container for %s = %s", mode, arg);
1982         return;
1983     }
1984 
1985     if (match != TAILQ_LAST(&owindows, owindows_head)) {
1986         LOG("More than one container matched the swap command, only using the first one.");
1987     }
1988 
1989     DLOG("Swapping %p with %p.\n", match->con, con);
1990     bool result = con_swap(match->con, con);
1991 
1992     cmd_output->needs_tree_render = true;
1993     // XXX: default reply for now, make this a better reply
1994     ysuccess(result);
1995 }
1996 
1997 /*
1998  * Implementation of 'title_format <format>'
1999  *
2000  */
cmd_title_format(I3_CMD,const char * format)2001 void cmd_title_format(I3_CMD, const char *format) {
2002     DLOG("setting title_format to \"%s\"\n", format);
2003     HANDLE_EMPTY_MATCH;
2004 
2005     owindow *current;
2006     TAILQ_FOREACH (current, &owindows, owindows) {
2007         DLOG("setting title_format for %p / %s\n", current->con, current->con->name);
2008         FREE(current->con->title_format);
2009 
2010         /* If we only display the title without anything else, we can skip the parsing step,
2011          * so we remove the title format altogether. */
2012         if (strcasecmp(format, "%title") != 0) {
2013             current->con->title_format = sstrdup(format);
2014 
2015             if (current->con->window != NULL) {
2016                 i3String *formatted_title = con_parse_title_format(current->con);
2017                 ewmh_update_visible_name(current->con->window->id, i3string_as_utf8(formatted_title));
2018                 I3STRING_FREE(formatted_title);
2019             }
2020         } else {
2021             if (current->con->window != NULL) {
2022                 /* We can remove _NET_WM_VISIBLE_NAME since we don't display a custom title. */
2023                 ewmh_update_visible_name(current->con->window->id, NULL);
2024             }
2025         }
2026 
2027         if (current->con->window != NULL) {
2028             /* Make sure the window title is redrawn immediately. */
2029             current->con->window->name_x_changed = true;
2030         } else {
2031             /* For windowless containers we also need to force the redrawing. */
2032             FREE(current->con->deco_render_params);
2033         }
2034     }
2035 
2036     cmd_output->needs_tree_render = true;
2037     ysuccess(true);
2038 }
2039 
2040 /*
2041  * Implementation of 'title_window_icon <yes|no>' and 'title_window_icon padding <px>'
2042  *
2043  */
cmd_title_window_icon(I3_CMD,const char * enable,int padding)2044 void cmd_title_window_icon(I3_CMD, const char *enable, int padding) {
2045     if (enable != NULL && !boolstr(enable)) {
2046         padding = -1;
2047     }
2048     DLOG("setting window_icon=%d\n", padding);
2049     HANDLE_EMPTY_MATCH;
2050 
2051     owindow *current;
2052     TAILQ_FOREACH (current, &owindows, owindows) {
2053         DLOG("setting window_icon for %p / %s\n", current->con, current->con->name);
2054         current->con->window_icon_padding = padding;
2055 
2056         if (current->con->window != NULL) {
2057             /* Make sure the window title is redrawn immediately. */
2058             current->con->window->name_x_changed = true;
2059         } else {
2060             /* For windowless containers we also need to force the redrawing. */
2061             FREE(current->con->deco_render_params);
2062         }
2063     }
2064 
2065     cmd_output->needs_tree_render = true;
2066     ysuccess(true);
2067 }
2068 
2069 /*
2070  * Implementation of 'rename workspace [<name>] to <name>'
2071  *
2072  */
cmd_rename_workspace(I3_CMD,const char * old_name,const char * new_name)2073 void cmd_rename_workspace(I3_CMD, const char *old_name, const char *new_name) {
2074     if (strncasecmp(new_name, "__", strlen("__")) == 0) {
2075         yerror("Cannot rename workspace to \"%s\": names starting with __ are i3-internal.", new_name);
2076         return;
2077     }
2078     if (old_name) {
2079         LOG("Renaming workspace \"%s\" to \"%s\"\n", old_name, new_name);
2080     } else {
2081         LOG("Renaming current workspace to \"%s\"\n", new_name);
2082     }
2083 
2084     Con *workspace;
2085     if (old_name) {
2086         workspace = get_existing_workspace_by_name(old_name);
2087     } else {
2088         workspace = con_get_workspace(focused);
2089         old_name = workspace->name;
2090     }
2091 
2092     if (!workspace) {
2093         yerror("Old workspace \"%s\" not found", old_name);
2094         return;
2095     }
2096 
2097     Con *check_dest = get_existing_workspace_by_name(new_name);
2098 
2099     /* If check_dest == workspace, the user might be changing the case of the
2100      * workspace, or it might just be a no-op. */
2101     if (check_dest != NULL && check_dest != workspace) {
2102         yerror("New workspace \"%s\" already exists", new_name);
2103         return;
2104     }
2105 
2106     /* Change the name and try to parse it as a number. */
2107     /* old_name might refer to workspace->name, so copy it before free()ing */
2108     char *old_name_copy = sstrdup(old_name);
2109     FREE(workspace->name);
2110     workspace->name = sstrdup(new_name);
2111 
2112     workspace->num = ws_name_to_number(new_name);
2113     LOG("num = %d\n", workspace->num);
2114 
2115     /* By re-attaching, the sort order will be correct afterwards. */
2116     Con *previously_focused = focused;
2117     Con *previously_focused_content = focused->type == CT_WORKSPACE ? focused->parent : NULL;
2118     Con *parent = workspace->parent;
2119     con_detach(workspace);
2120     con_attach(workspace, parent, false);
2121     ipc_send_workspace_event("rename", workspace, NULL);
2122 
2123     Con *assigned = get_assigned_output(workspace->name, workspace->num);
2124     if (assigned) {
2125         workspace_move_to_output(workspace, get_output_for_con(assigned));
2126     }
2127 
2128     bool can_restore_focus = previously_focused != NULL;
2129     /* NB: If previously_focused is a workspace we can't work directly with it
2130      * since it might have been cleaned up by workspace_show() already,
2131      * depending on the focus order/number of other workspaces on the output.
2132      * Instead, we loop through the available workspaces and only focus
2133      * previously_focused if we still find it. */
2134     if (previously_focused_content) {
2135         Con *workspace = NULL;
2136         GREP_FIRST(workspace, previously_focused_content, child == previously_focused);
2137         can_restore_focus &= (workspace != NULL);
2138     }
2139 
2140     if (can_restore_focus) {
2141         /* Restore the previous focus since con_attach messes with the focus. */
2142         workspace_show(con_get_workspace(previously_focused));
2143         con_focus(previously_focused);
2144     }
2145 
2146     /* Let back-and-forth work after renaming the previous workspace.
2147      * See #3694. */
2148     if (previous_workspace_name && !strcmp(previous_workspace_name, old_name_copy)) {
2149         FREE(previous_workspace_name);
2150         previous_workspace_name = sstrdup(new_name);
2151     }
2152 
2153     cmd_output->needs_tree_render = true;
2154     ysuccess(true);
2155 
2156     ewmh_update_desktop_properties();
2157 
2158     startup_sequence_rename_workspace(old_name_copy, new_name);
2159     free(old_name_copy);
2160 }
2161 
2162 /*
2163  * Implementation of 'bar mode dock|hide|invisible|toggle [<bar_id>]'
2164  *
2165  */
cmd_bar_mode(I3_CMD,const char * bar_mode,const char * bar_id)2166 void cmd_bar_mode(I3_CMD, const char *bar_mode, const char *bar_id) {
2167     int mode = M_DOCK;
2168     bool toggle = false;
2169     if (strcmp(bar_mode, "dock") == 0)
2170         mode = M_DOCK;
2171     else if (strcmp(bar_mode, "hide") == 0)
2172         mode = M_HIDE;
2173     else if (strcmp(bar_mode, "invisible") == 0)
2174         mode = M_INVISIBLE;
2175     else if (strcmp(bar_mode, "toggle") == 0)
2176         toggle = true;
2177     else {
2178         ELOG("Unknown bar mode \"%s\", this is a mismatch between code and parser spec.\n", bar_mode);
2179         assert(false);
2180     }
2181 
2182     if (TAILQ_EMPTY(&barconfigs)) {
2183         yerror("No bars found\n");
2184         return;
2185     }
2186 
2187     Barconfig *current = NULL;
2188     TAILQ_FOREACH (current, &barconfigs, configs) {
2189         if (bar_id && strcmp(current->id, bar_id) != 0) {
2190             continue;
2191         }
2192 
2193         if (toggle) {
2194             mode = (current->mode + 1) % 2;
2195         }
2196 
2197         DLOG("Changing bar mode of bar_id '%s' from '%d' to '%s (%d)'\n",
2198              current->id, current->mode, bar_mode, mode);
2199         if ((int)current->mode != mode) {
2200             current->mode = mode;
2201             ipc_send_barconfig_update_event(current);
2202         }
2203 
2204         if (bar_id) {
2205             /* We are looking for a specific bar and we found it */
2206             ysuccess(true);
2207             return;
2208         }
2209     }
2210 
2211     if (bar_id) {
2212         /* We are looking for a specific bar and we did not find it */
2213         yerror("Changing bar mode of bar_id %s failed, bar_id not found.\n", bar_id);
2214     } else {
2215         /* We have already handled the case of no bars, so we must have
2216          * updated all active bars now. */
2217         ysuccess(true);
2218     }
2219 }
2220 
2221 /*
2222  * Implementation of 'bar hidden_state hide|show|toggle [<bar_id>]'
2223  *
2224  */
cmd_bar_hidden_state(I3_CMD,const char * bar_hidden_state,const char * bar_id)2225 void cmd_bar_hidden_state(I3_CMD, const char *bar_hidden_state, const char *bar_id) {
2226     int hidden_state = S_SHOW;
2227     bool toggle = false;
2228     if (strcmp(bar_hidden_state, "hide") == 0)
2229         hidden_state = S_HIDE;
2230     else if (strcmp(bar_hidden_state, "show") == 0)
2231         hidden_state = S_SHOW;
2232     else if (strcmp(bar_hidden_state, "toggle") == 0)
2233         toggle = true;
2234     else {
2235         ELOG("Unknown bar state \"%s\", this is a mismatch between code and parser spec.\n", bar_hidden_state);
2236         assert(false);
2237     }
2238 
2239     if (TAILQ_EMPTY(&barconfigs)) {
2240         yerror("No bars found\n");
2241         return;
2242     }
2243 
2244     Barconfig *current = NULL;
2245     TAILQ_FOREACH (current, &barconfigs, configs) {
2246         if (bar_id && strcmp(current->id, bar_id) != 0) {
2247             continue;
2248         }
2249 
2250         if (toggle) {
2251             hidden_state = (current->hidden_state + 1) % 2;
2252         }
2253 
2254         DLOG("Changing bar hidden_state of bar_id '%s' from '%d' to '%s (%d)'\n",
2255              current->id, current->hidden_state, bar_hidden_state, hidden_state);
2256         if ((int)current->hidden_state != hidden_state) {
2257             current->hidden_state = hidden_state;
2258             ipc_send_barconfig_update_event(current);
2259         }
2260 
2261         if (bar_id) {
2262             /* We are looking for a specific bar and we found it */
2263             ysuccess(true);
2264             return;
2265         }
2266     }
2267 
2268     if (bar_id) {
2269         /* We are looking for a specific bar and we did not find it */
2270         yerror("Changing bar hidden_state of bar_id %s failed, bar_id not found.\n", bar_id);
2271     } else {
2272         /* We have already handled the case of no bars, so we must have
2273          * updated all active bars now. */
2274         ysuccess(true);
2275     }
2276 }
2277 
2278 /*
2279  * Implementation of 'shmlog <size>|toggle|on|off'
2280  *
2281  */
cmd_shmlog(I3_CMD,const char * argument)2282 void cmd_shmlog(I3_CMD, const char *argument) {
2283     if (!strcmp(argument, "toggle"))
2284         /* Toggle shm log, if size is not 0. If it is 0, set it to default. */
2285         shmlog_size = shmlog_size ? -shmlog_size : default_shmlog_size;
2286     else if (!strcmp(argument, "on"))
2287         shmlog_size = default_shmlog_size;
2288     else if (!strcmp(argument, "off"))
2289         shmlog_size = 0;
2290     else {
2291         long new_size = 0;
2292         if (!parse_long(argument, &new_size, 0)) {
2293             yerror("Failed to parse %s into a shmlog size.", argument);
2294             return;
2295         }
2296         /* If shm logging now, restart logging with the new size. */
2297         if (shmlog_size > 0) {
2298             shmlog_size = 0;
2299             LOG("Restarting shm logging...\n");
2300             init_logging();
2301         }
2302         shmlog_size = (int)new_size;
2303     }
2304     LOG("%s shm logging\n", shmlog_size > 0 ? "Enabling" : "Disabling");
2305     init_logging();
2306     update_shmlog_atom();
2307     ysuccess(true);
2308 }
2309 
2310 /*
2311  * Implementation of 'debuglog toggle|on|off'
2312  *
2313  */
cmd_debuglog(I3_CMD,const char * argument)2314 void cmd_debuglog(I3_CMD, const char *argument) {
2315     bool logging = get_debug_logging();
2316     if (!strcmp(argument, "toggle")) {
2317         LOG("%s debug logging\n", logging ? "Disabling" : "Enabling");
2318         set_debug_logging(!logging);
2319     } else if (!strcmp(argument, "on") && !logging) {
2320         LOG("Enabling debug logging\n");
2321         set_debug_logging(true);
2322     } else if (!strcmp(argument, "off") && logging) {
2323         LOG("Disabling debug logging\n");
2324         set_debug_logging(false);
2325     }
2326     // XXX: default reply for now, make this a better reply
2327     ysuccess(true);
2328 }
2329 
2330 /**
2331  * Implementation of 'gaps inner|outer|top|right|bottom|left|horizontal|vertical current|all set|plus|minus|toggle <px>'
2332  *
2333  */
cmd_gaps(I3_CMD,const char * type,const char * scope,const char * mode,const char * value)2334 void cmd_gaps(I3_CMD, const char *type, const char *scope, const char *mode, const char *value) {
2335     int pixels = logical_px(atoi(value));
2336     Con *workspace = con_get_workspace(focused);
2337 
2338 #define CMD_SET_GAPS_VALUE(type, value, reset)                          \
2339     do {                                                                \
2340         if (!strcmp(scope, "all")) {                                    \
2341             Con *output, *cur_ws = NULL;                                \
2342             TAILQ_FOREACH (output, &(croot->nodes_head), nodes) {       \
2343                 Con *content = output_get_content(output);              \
2344                 TAILQ_FOREACH (cur_ws, &(content->nodes_head), nodes) { \
2345                     if (reset)                                          \
2346                         cur_ws->gaps.type = 0;                          \
2347                     else if (value + cur_ws->gaps.type < 0)             \
2348                         cur_ws->gaps.type = -value;                     \
2349                 }                                                       \
2350             }                                                           \
2351                                                                         \
2352             config.gaps.type = value;                                   \
2353         } else {                                                        \
2354             workspace->gaps.type = value - config.gaps.type;            \
2355         }                                                               \
2356     } while (0)
2357 
2358 #define CMD_GAPS(type)                                                                                          \
2359     do {                                                                                                        \
2360         int current_value = config.gaps.type;                                                                   \
2361         if (strcmp(scope, "current") == 0)                                                                      \
2362             current_value += workspace->gaps.type;                                                              \
2363                                                                                                                 \
2364         bool reset = false;                                                                                     \
2365         if (!strcmp(mode, "plus"))                                                                              \
2366             current_value += pixels;                                                                            \
2367         else if (!strcmp(mode, "minus"))                                                                        \
2368             current_value -= pixels;                                                                            \
2369         else if (!strcmp(mode, "set")) {                                                                        \
2370             current_value = pixels;                                                                             \
2371             reset = true;                                                                                       \
2372         } else if (!strcmp(mode, "toggle")) {                                                                   \
2373             current_value = !current_value * pixels;                                                            \
2374             reset = true;                                                                                       \
2375         } else {                                                                                                \
2376             ELOG("Invalid mode %s when changing gaps", mode);                                                   \
2377             ysuccess(false);                                                                                    \
2378             return;                                                                                             \
2379         }                                                                                                       \
2380                                                                                                                 \
2381         /* see issue 262 */                                                                                     \
2382         int min_value = 0;                                                                                      \
2383         if (strcmp(#type, "inner") != 0) {                                                                      \
2384             min_value = strcmp(scope, "all") ? -config.gaps.inner - workspace->gaps.inner : -config.gaps.inner; \
2385         }                                                                                                       \
2386                                                                                                                 \
2387         if (current_value < min_value)                                                                          \
2388             current_value = min_value;                                                                          \
2389                                                                                                                 \
2390         CMD_SET_GAPS_VALUE(type, current_value, reset);                                                         \
2391     } while (0)
2392 
2393 #define CMD_UPDATE_GAPS(type)                                                                              \
2394     do {                                                                                                   \
2395         if (!strcmp(scope, "all")) {                                                                       \
2396             if (config.gaps.type + config.gaps.inner < 0)                                                  \
2397                 CMD_SET_GAPS_VALUE(type, -config.gaps.inner, true);                                        \
2398         } else {                                                                                           \
2399             if (config.gaps.type + workspace->gaps.type + config.gaps.inner + workspace->gaps.inner < 0) { \
2400                 CMD_SET_GAPS_VALUE(type, -config.gaps.inner - workspace->gaps.inner, true);                \
2401             }                                                                                              \
2402         }                                                                                                  \
2403     } while (0)
2404 
2405     if (!strcmp(type, "inner")) {
2406         CMD_GAPS(inner);
2407         // update inconsistent values
2408         CMD_UPDATE_GAPS(top);
2409         CMD_UPDATE_GAPS(bottom);
2410         CMD_UPDATE_GAPS(right);
2411         CMD_UPDATE_GAPS(left);
2412     } else if (!strcmp(type, "outer")) {
2413         CMD_GAPS(top);
2414         CMD_GAPS(bottom);
2415         CMD_GAPS(right);
2416         CMD_GAPS(left);
2417     } else if (!strcmp(type, "vertical")) {
2418         CMD_GAPS(top);
2419         CMD_GAPS(bottom);
2420     } else if (!strcmp(type, "horizontal")) {
2421         CMD_GAPS(right);
2422         CMD_GAPS(left);
2423     } else if (!strcmp(type, "top")) {
2424         CMD_GAPS(top);
2425     } else if (!strcmp(type, "bottom")) {
2426         CMD_GAPS(bottom);
2427     } else if (!strcmp(type, "right")) {
2428         CMD_GAPS(right);
2429     } else if (!strcmp(type, "left")) {
2430         CMD_GAPS(left);
2431     } else {
2432         ELOG("Invalid type %s when changing gaps", type);
2433         ysuccess(false);
2434         return;
2435     }
2436 
2437     cmd_output->needs_tree_render = true;
2438     // XXX: default reply for now, make this a better reply
2439     ysuccess(true);
2440 }
2441