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  * con.c: Functions which deal with containers directly (creating containers,
8  *        searching containers, getting specific properties from containers,
9  *        …).
10  *
11  */
12 #include "all.h"
13 #include "yajl_utils.h"
14 
15 static void con_on_remove_child(Con *con);
16 
17 /*
18  * force parent split containers to be redrawn
19  *
20  */
con_force_split_parents_redraw(Con * con)21 void con_force_split_parents_redraw(Con *con) {
22     Con *parent = con;
23 
24     while (parent != NULL && parent->type != CT_WORKSPACE && parent->type != CT_DOCKAREA) {
25         if (!con_is_leaf(parent)) {
26             FREE(parent->deco_render_params);
27         }
28 
29         parent = parent->parent;
30     }
31 }
32 
33 /*
34  * Create a new container (and attach it to the given parent, if not NULL).
35  * This function only initializes the data structures.
36  *
37  */
con_new_skeleton(Con * parent,i3Window * window)38 Con *con_new_skeleton(Con *parent, i3Window *window) {
39     Con *new = scalloc(1, sizeof(Con));
40     new->on_remove_child = con_on_remove_child;
41     TAILQ_INSERT_TAIL(&all_cons, new, all_cons);
42     new->type = CT_CON;
43     new->window = window;
44     new->border_style = config.default_border;
45     new->current_border_width = -1;
46     new->window_icon_padding = -1;
47     if (window) {
48         new->depth = window->depth;
49     } else {
50         new->depth = root_depth;
51     }
52     DLOG("opening window\n");
53 
54     TAILQ_INIT(&(new->floating_head));
55     TAILQ_INIT(&(new->nodes_head));
56     TAILQ_INIT(&(new->focus_head));
57     TAILQ_INIT(&(new->swallow_head));
58     TAILQ_INIT(&(new->marks_head));
59 
60     if (parent != NULL)
61         con_attach(new, parent, false);
62 
63     return new;
64 }
65 
66 /* A wrapper for con_new_skeleton, to retain the old con_new behaviour
67  *
68  */
con_new(Con * parent,i3Window * window)69 Con *con_new(Con *parent, i3Window *window) {
70     Con *new = con_new_skeleton(parent, window);
71     x_con_init(new);
72     return new;
73 }
74 
75 /*
76  * Frees the specified container.
77  *
78  */
con_free(Con * con)79 void con_free(Con *con) {
80     free(con->name);
81     FREE(con->deco_render_params);
82     TAILQ_REMOVE(&all_cons, con, all_cons);
83     while (!TAILQ_EMPTY(&(con->swallow_head))) {
84         Match *match = TAILQ_FIRST(&(con->swallow_head));
85         TAILQ_REMOVE(&(con->swallow_head), match, matches);
86         match_free(match);
87         free(match);
88     }
89     while (!TAILQ_EMPTY(&(con->marks_head))) {
90         mark_t *mark = TAILQ_FIRST(&(con->marks_head));
91         TAILQ_REMOVE(&(con->marks_head), mark, marks);
92         FREE(mark->name);
93         FREE(mark);
94     }
95     DLOG("con %p freed\n", con);
96     free(con);
97 }
98 
_con_attach(Con * con,Con * parent,Con * previous,bool ignore_focus)99 static void _con_attach(Con *con, Con *parent, Con *previous, bool ignore_focus) {
100     con->parent = parent;
101     Con *loop;
102     Con *current = previous;
103     struct nodes_head *nodes_head = &(parent->nodes_head);
104     struct focus_head *focus_head = &(parent->focus_head);
105 
106     /* Workspaces are handled differently: they need to be inserted at the
107      * right position. */
108     if (con->type == CT_WORKSPACE) {
109         DLOG("it's a workspace. num = %d\n", con->num);
110         if (con->num == -1 || TAILQ_EMPTY(nodes_head)) {
111             TAILQ_INSERT_TAIL(nodes_head, con, nodes);
112         } else {
113             current = TAILQ_FIRST(nodes_head);
114             if (con->num < current->num) {
115                 /* we need to insert the container at the beginning */
116                 TAILQ_INSERT_HEAD(nodes_head, con, nodes);
117             } else {
118                 while (current->num != -1 && con->num > current->num) {
119                     current = TAILQ_NEXT(current, nodes);
120                     if (current == TAILQ_END(nodes_head)) {
121                         current = NULL;
122                         break;
123                     }
124                 }
125                 /* we need to insert con after current, if current is not NULL */
126                 if (current)
127                     TAILQ_INSERT_BEFORE(current, con, nodes);
128                 else
129                     TAILQ_INSERT_TAIL(nodes_head, con, nodes);
130             }
131         }
132         goto add_to_focus_head;
133     }
134 
135     if (parent->type == CT_DOCKAREA) {
136         /* Insert dock client, sorting alphanumerically by class and then
137          * instance name. This makes dock client order deterministic. As a side
138          * effect, bars without a custom bar id will be sorted according to
139          * their declaration order in the config file. See #3491. */
140         current = NULL;
141         TAILQ_FOREACH (loop, nodes_head, nodes) {
142             int result = strcasecmp_nullable(con->window->class_class, loop->window->class_class);
143             if (result == 0) {
144                 result = strcasecmp_nullable(con->window->class_instance, loop->window->class_instance);
145             }
146             if (result < 0) {
147                 current = loop;
148                 break;
149             }
150         }
151         if (current) {
152             TAILQ_INSERT_BEFORE(loop, con, nodes);
153         } else {
154             TAILQ_INSERT_TAIL(nodes_head, con, nodes);
155         }
156         goto add_to_focus_head;
157     }
158 
159     if (con->type == CT_FLOATING_CON) {
160         DLOG("Inserting into floating containers\n");
161         TAILQ_INSERT_TAIL(&(parent->floating_head), con, floating_windows);
162     } else {
163         if (!ignore_focus) {
164             /* Get the first tiling container in focus stack */
165             TAILQ_FOREACH (loop, &(parent->focus_head), focused) {
166                 if (loop->type == CT_FLOATING_CON)
167                     continue;
168                 current = loop;
169                 break;
170             }
171         }
172 
173         /* When the container is not a split container (but contains a window)
174          * and is attached to a workspace, we check if the user configured a
175          * workspace_layout. This is done in workspace_attach_to, which will
176          * provide us with the container to which we should attach (either the
177          * workspace or a new split container with the configured
178          * workspace_layout).
179          */
180         if (con->window != NULL &&
181             parent->type == CT_WORKSPACE &&
182             parent->workspace_layout != L_DEFAULT) {
183             DLOG("Parent is a workspace. Applying default layout...\n");
184             Con *target = workspace_attach_to(parent);
185 
186             /* Attach the original con to this new split con instead */
187             nodes_head = &(target->nodes_head);
188             focus_head = &(target->focus_head);
189             con->parent = target;
190             current = NULL;
191 
192             DLOG("done\n");
193         }
194 
195         /* Insert the container after the tiling container, if found.
196          * When adding to a CT_OUTPUT, just append one after another. */
197         if (current != NULL && parent->type != CT_OUTPUT) {
198             DLOG("Inserting con = %p after con %p\n", con, current);
199             TAILQ_INSERT_AFTER(nodes_head, current, con, nodes);
200         } else
201             TAILQ_INSERT_TAIL(nodes_head, con, nodes);
202     }
203 
204 add_to_focus_head:
205     /* We insert to the TAIL because con_focus() will correct this.
206      * This way, we have the option to insert Cons without having
207      * to focus them. */
208     TAILQ_INSERT_TAIL(focus_head, con, focused);
209     con_force_split_parents_redraw(con);
210 }
211 
212 /*
213  * Attaches the given container to the given parent. This happens when moving
214  * a container or when inserting a new container at a specific place in the
215  * tree.
216  *
217  * ignore_focus is to just insert the Con at the end (useful when creating a
218  * new split container *around* some containers, that is, detaching and
219  * attaching them in order without wanting to mess with the focus in between).
220  *
221  */
con_attach(Con * con,Con * parent,bool ignore_focus)222 void con_attach(Con *con, Con *parent, bool ignore_focus) {
223     _con_attach(con, parent, NULL, ignore_focus);
224 }
225 
226 /*
227  * Detaches the given container from its current parent
228  *
229  */
con_detach(Con * con)230 void con_detach(Con *con) {
231     con_force_split_parents_redraw(con);
232     if (con->type == CT_FLOATING_CON) {
233         TAILQ_REMOVE(&(con->parent->floating_head), con, floating_windows);
234         TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
235     } else {
236         TAILQ_REMOVE(&(con->parent->nodes_head), con, nodes);
237         TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
238     }
239 }
240 
241 /*
242  * Sets input focus to the given container. Will be updated in X11 in the next
243  * run of x_push_changes().
244  *
245  */
con_focus(Con * con)246 void con_focus(Con *con) {
247     assert(con != NULL);
248     DLOG("con_focus = %p\n", con);
249 
250     /* 1: set focused-pointer to the new con */
251     /* 2: exchange the position of the container in focus stack of the parent all the way up */
252     TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
253     TAILQ_INSERT_HEAD(&(con->parent->focus_head), con, focused);
254     if (con->parent->parent != NULL)
255         con_focus(con->parent);
256 
257     focused = con;
258     /* We can't blindly reset non-leaf containers since they might have
259      * other urgent children. Therefore we only reset leafs and propagate
260      * the changes upwards via con_update_parents_urgency() which does proper
261      * checks before resetting the urgency.
262      */
263     if (con->urgent && con_is_leaf(con)) {
264         con_set_urgency(con, false);
265         con_update_parents_urgency(con);
266         workspace_update_urgent_flag(con_get_workspace(con));
267         ipc_send_window_event("urgent", con);
268     }
269 }
270 
271 /*
272  * Raise container to the top if it is floating or inside some floating
273  * container.
274  *
275  */
con_raise(Con * con)276 static void con_raise(Con *con) {
277     Con *floating = con_inside_floating(con);
278     if (floating) {
279         floating_raise_con(floating);
280     }
281 }
282 
283 /*
284  * Sets input focus to the given container and raises it to the top.
285  *
286  */
con_activate(Con * con)287 void con_activate(Con *con) {
288     con_focus(con);
289     con_raise(con);
290 }
291 
292 /*
293  * Activates the container like in con_activate but removes fullscreen
294  * restrictions and properly warps the pointer if needed.
295  *
296  */
con_activate_unblock(Con * con)297 void con_activate_unblock(Con *con) {
298     Con *ws = con_get_workspace(con);
299     Con *previous_focus = focused;
300     Con *fullscreen_on_ws = con_get_fullscreen_covering_ws(ws);
301 
302     if (fullscreen_on_ws && fullscreen_on_ws != con && !con_has_parent(con, fullscreen_on_ws)) {
303         con_disable_fullscreen(fullscreen_on_ws);
304     }
305 
306     con_activate(con);
307 
308     /* If the container is not on the current workspace, workspace_show() will
309      * switch to a different workspace and (if enabled) trigger a mouse pointer
310      * warp to the currently focused container (!) on the target workspace.
311      *
312      * Therefore, before calling workspace_show(), we make sure that 'con' will
313      * be focused on the workspace. However, we cannot just con_focus(con)
314      * because then the pointer will not be warped at all (the code thinks we
315      * are already there).
316      *
317      * So we focus 'con' to make it the currently focused window of the target
318      * workspace, then revert focus. */
319     if (ws != con_get_workspace(previous_focus)) {
320         con_activate(previous_focus);
321         /* Now switch to the workspace, then focus */
322         workspace_show(ws);
323         con_activate(con);
324     }
325 }
326 
327 /*
328  * Closes the given container.
329  *
330  */
con_close(Con * con,kill_window_t kill_window)331 void con_close(Con *con, kill_window_t kill_window) {
332     assert(con != NULL);
333     DLOG("Closing con = %p.\n", con);
334 
335     /* We never close output or root containers. */
336     if (con->type == CT_OUTPUT || con->type == CT_ROOT) {
337         DLOG("con = %p is of type %d, not closing anything.\n", con, con->type);
338         return;
339     }
340 
341     if (con->type == CT_WORKSPACE) {
342         DLOG("con = %p is a workspace, closing all children instead.\n", con);
343         Con *child, *nextchild;
344         for (child = TAILQ_FIRST(&(con->focus_head)); child;) {
345             nextchild = TAILQ_NEXT(child, focused);
346             DLOG("killing child = %p.\n", child);
347             tree_close_internal(child, kill_window, false);
348             child = nextchild;
349         }
350 
351         return;
352     }
353 
354     tree_close_internal(con, kill_window, false);
355 }
356 
357 /*
358  * Returns true when this node is a leaf node (has no children)
359  *
360  */
con_is_leaf(Con * con)361 bool con_is_leaf(Con *con) {
362     return TAILQ_EMPTY(&(con->nodes_head));
363 }
364 
365 /*
366  * Returns true when this con is a leaf node with a managed X11 window (e.g.,
367  * excluding dock containers)
368  */
con_has_managed_window(Con * con)369 bool con_has_managed_window(Con *con) {
370     return (con != NULL && con->window != NULL && con->window->id != XCB_WINDOW_NONE && con_get_workspace(con) != NULL);
371 }
372 
373 /*
374  * Returns true if this node has regular or floating children.
375  *
376  */
con_has_children(Con * con)377 bool con_has_children(Con *con) {
378     return (!con_is_leaf(con) || !TAILQ_EMPTY(&(con->floating_head)));
379 }
380 
381 /*
382  * Returns true if a container should be considered split.
383  *
384  */
con_is_split(Con * con)385 bool con_is_split(Con *con) {
386     if (con_is_leaf(con))
387         return false;
388 
389     switch (con->layout) {
390         case L_DOCKAREA:
391         case L_OUTPUT:
392             return false;
393 
394         default:
395             return true;
396     }
397 }
398 
399 /*
400  * This will only return true for containers which have some parent with
401  * a tabbed / stacked parent of which they are not the currently focused child.
402  *
403  */
con_is_hidden(Con * con)404 bool con_is_hidden(Con *con) {
405     Con *current = con;
406 
407     /* ascend to the workspace level and memorize the highest-up container
408      * which is stacked or tabbed. */
409     while (current != NULL && current->type != CT_WORKSPACE) {
410         Con *parent = current->parent;
411         if (parent != NULL && (parent->layout == L_TABBED || parent->layout == L_STACKED)) {
412             if (TAILQ_FIRST(&(parent->focus_head)) != current)
413                 return true;
414         }
415 
416         current = parent;
417     }
418 
419     return false;
420 }
421 
422 /*
423  * Returns whether the container or any of its children is sticky.
424  *
425  */
con_is_sticky(Con * con)426 bool con_is_sticky(Con *con) {
427     if (con->sticky)
428         return true;
429 
430     Con *child;
431     TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
432         if (con_is_sticky(child))
433             return true;
434     }
435 
436     return false;
437 }
438 
439 /*
440  * Returns true if this node accepts a window (if the node swallows windows,
441  * it might already have swallowed enough and cannot hold any more).
442  *
443  */
con_accepts_window(Con * con)444 bool con_accepts_window(Con *con) {
445     /* 1: workspaces never accept direct windows */
446     if (con->type == CT_WORKSPACE)
447         return false;
448 
449     if (con_is_split(con)) {
450         DLOG("container %p does not accept windows, it is a split container.\n", con);
451         return false;
452     }
453 
454     /* TODO: if this is a swallowing container, we need to check its max_clients */
455     return (con->window == NULL);
456 }
457 
458 /*
459  * Gets the output container (first container with CT_OUTPUT in hierarchy) this
460  * node is on.
461  *
462  */
con_get_output(Con * con)463 Con *con_get_output(Con *con) {
464     Con *result = con;
465     while (result != NULL && result->type != CT_OUTPUT)
466         result = result->parent;
467     /* We must be able to get an output because focus can never be set higher
468      * in the tree (root node cannot be focused). */
469     assert(result != NULL);
470     return result;
471 }
472 
473 /*
474  * Gets the workspace container this node is on.
475  *
476  */
con_get_workspace(Con * con)477 Con *con_get_workspace(Con *con) {
478     Con *result = con;
479     while (result != NULL && result->type != CT_WORKSPACE)
480         result = result->parent;
481     return result;
482 }
483 
484 /*
485  * Searches parents of the given 'con' until it reaches one with the specified
486  * 'orientation'. Aborts when it comes across a floating_con.
487  *
488  */
con_parent_with_orientation(Con * con,orientation_t orientation)489 Con *con_parent_with_orientation(Con *con, orientation_t orientation) {
490     DLOG("Searching for parent of Con %p with orientation %d\n", con, orientation);
491     Con *parent = con->parent;
492     if (parent->type == CT_FLOATING_CON)
493         return NULL;
494     while (con_orientation(parent) != orientation) {
495         DLOG("Need to go one level further up\n");
496         parent = parent->parent;
497         /* Abort when we reach a floating con, or an output con */
498         if (parent &&
499             (parent->type == CT_FLOATING_CON ||
500              parent->type == CT_OUTPUT ||
501              (parent->parent && parent->parent->type == CT_OUTPUT)))
502             parent = NULL;
503         if (parent == NULL)
504             break;
505     }
506     DLOG("Result: %p\n", parent);
507     return parent;
508 }
509 
510 /*
511  * helper data structure for the breadth-first-search in
512  * con_get_fullscreen_con()
513  *
514  */
515 struct bfs_entry {
516     Con *con;
517 
518     TAILQ_ENTRY(bfs_entry) entries;
519 };
520 
521 /*
522  * Returns the first fullscreen node below this node.
523  *
524  */
con_get_fullscreen_con(Con * con,fullscreen_mode_t fullscreen_mode)525 Con *con_get_fullscreen_con(Con *con, fullscreen_mode_t fullscreen_mode) {
526     Con *current, *child;
527 
528     /* TODO: is breadth-first-search really appropriate? (check as soon as
529      * fullscreen levels and fullscreen for containers is implemented) */
530     TAILQ_HEAD(bfs_head, bfs_entry) bfs_head = TAILQ_HEAD_INITIALIZER(bfs_head);
531     struct bfs_entry *entry = smalloc(sizeof(struct bfs_entry));
532     entry->con = con;
533     TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
534 
535     while (!TAILQ_EMPTY(&bfs_head)) {
536         entry = TAILQ_FIRST(&bfs_head);
537         current = entry->con;
538         if (current != con && current->fullscreen_mode == fullscreen_mode) {
539             /* empty the queue */
540             while (!TAILQ_EMPTY(&bfs_head)) {
541                 entry = TAILQ_FIRST(&bfs_head);
542                 TAILQ_REMOVE(&bfs_head, entry, entries);
543                 free(entry);
544             }
545             return current;
546         }
547 
548         TAILQ_REMOVE(&bfs_head, entry, entries);
549         free(entry);
550 
551         TAILQ_FOREACH (child, &(current->nodes_head), nodes) {
552             entry = smalloc(sizeof(struct bfs_entry));
553             entry->con = child;
554             TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
555         }
556 
557         TAILQ_FOREACH (child, &(current->floating_head), floating_windows) {
558             entry = smalloc(sizeof(struct bfs_entry));
559             entry->con = child;
560             TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
561         }
562     }
563 
564     return NULL;
565 }
566 
567 /*
568  * Returns the fullscreen node that covers the given workspace if it exists.
569  * This is either a CF_GLOBAL fullscreen container anywhere or a CF_OUTPUT
570  * fullscreen container in the workspace.
571  *
572  */
con_get_fullscreen_covering_ws(Con * ws)573 Con *con_get_fullscreen_covering_ws(Con *ws) {
574     if (!ws) {
575         return NULL;
576     }
577     Con *fs = con_get_fullscreen_con(croot, CF_GLOBAL);
578     if (!fs) {
579         return con_get_fullscreen_con(ws, CF_OUTPUT);
580     }
581     return fs;
582 }
583 
584 /*
585  * Returns true if the container is internal, such as __i3_scratch
586  *
587  */
con_is_internal(Con * con)588 bool con_is_internal(Con *con) {
589     return (con->name[0] == '_' && con->name[1] == '_');
590 }
591 
592 /*
593  * Returns true if the node is floating.
594  *
595  */
con_is_floating(Con * con)596 bool con_is_floating(Con *con) {
597     assert(con != NULL);
598     return (con->floating >= FLOATING_AUTO_ON);
599 }
600 
601 /*
602  * Returns true if the container is a docked container.
603  *
604  */
con_is_docked(Con * con)605 bool con_is_docked(Con *con) {
606     if (con->parent == NULL)
607         return false;
608 
609     if (con->parent->type == CT_DOCKAREA)
610         return true;
611 
612     return con_is_docked(con->parent);
613 }
614 
615 /*
616  * Checks if the given container is either floating or inside some floating
617  * container. It returns the FLOATING_CON container.
618  *
619  */
con_inside_floating(Con * con)620 Con *con_inside_floating(Con *con) {
621     assert(con != NULL);
622     if (con->type == CT_FLOATING_CON)
623         return con;
624 
625     if (con->floating >= FLOATING_AUTO_ON)
626         return con->parent;
627 
628     if (con->type == CT_WORKSPACE || con->type == CT_OUTPUT)
629         return NULL;
630 
631     return con_inside_floating(con->parent);
632 }
633 
634 /*
635  * Checks if the given container is inside a focused container.
636  *
637  */
con_inside_focused(Con * con)638 bool con_inside_focused(Con *con) {
639     if (con == focused)
640         return true;
641     if (!con->parent)
642         return false;
643     return con_inside_focused(con->parent);
644 }
645 
646 /*
647  * Checks if the container has the given parent as an actual parent.
648  *
649  */
con_has_parent(Con * con,Con * parent)650 bool con_has_parent(Con *con, Con *parent) {
651     Con *current = con->parent;
652     if (current == NULL) {
653         return false;
654     }
655 
656     if (current == parent) {
657         return true;
658     }
659 
660     return con_has_parent(current, parent);
661 }
662 
663 /*
664  * Returns the container with the given client window ID or NULL if no such
665  * container exists.
666  *
667  */
con_by_window_id(xcb_window_t window)668 Con *con_by_window_id(xcb_window_t window) {
669     Con *con;
670     TAILQ_FOREACH (con, &all_cons, all_cons) {
671         if (con->window != NULL && con->window->id == window) {
672             return con;
673         }
674     }
675     return NULL;
676 }
677 
678 /*
679  * Returns the container with the given container ID or NULL if no such
680  * container exists.
681  *
682  */
con_by_con_id(long target)683 Con *con_by_con_id(long target) {
684     Con *con;
685     TAILQ_FOREACH (con, &all_cons, all_cons) {
686         if (con == (Con *)target) {
687             return con;
688         }
689     }
690 
691     return NULL;
692 }
693 
694 /*
695  * Returns true if the given container (still) exists.
696  * This can be used, e.g., to make sure a container hasn't been closed in the meantime.
697  *
698  */
con_exists(Con * con)699 bool con_exists(Con *con) {
700     return con_by_con_id((long)con) != NULL;
701 }
702 
703 /*
704  * Returns the container with the given frame ID or NULL if no such container
705  * exists.
706  *
707  */
con_by_frame_id(xcb_window_t frame)708 Con *con_by_frame_id(xcb_window_t frame) {
709     Con *con;
710     TAILQ_FOREACH (con, &all_cons, all_cons) {
711         if (con->frame.id == frame) {
712             return con;
713         }
714     }
715     return NULL;
716 }
717 
718 /*
719  * Returns the container with the given mark or NULL if no such container
720  * exists.
721  *
722  */
con_by_mark(const char * mark)723 Con *con_by_mark(const char *mark) {
724     Con *con;
725     TAILQ_FOREACH (con, &all_cons, all_cons) {
726         if (con_has_mark(con, mark))
727             return con;
728     }
729 
730     return NULL;
731 }
732 
733 /*
734  * Returns true if and only if the given containers holds the mark.
735  *
736  */
con_has_mark(Con * con,const char * mark)737 bool con_has_mark(Con *con, const char *mark) {
738     mark_t *current;
739     TAILQ_FOREACH (current, &(con->marks_head), marks) {
740         if (strcmp(current->name, mark) == 0)
741             return true;
742     }
743 
744     return false;
745 }
746 
747 /*
748  * Toggles the mark on a container.
749  * If the container already has this mark, the mark is removed.
750  * Otherwise, the mark is assigned to the container.
751  *
752  */
con_mark_toggle(Con * con,const char * mark,mark_mode_t mode)753 void con_mark_toggle(Con *con, const char *mark, mark_mode_t mode) {
754     assert(con != NULL);
755     DLOG("Toggling mark \"%s\" on con = %p.\n", mark, con);
756 
757     if (con_has_mark(con, mark)) {
758         con_unmark(con, mark);
759     } else {
760         con_mark(con, mark, mode);
761     }
762 }
763 
764 /*
765  * Assigns a mark to the container.
766  *
767  */
con_mark(Con * con,const char * mark,mark_mode_t mode)768 void con_mark(Con *con, const char *mark, mark_mode_t mode) {
769     assert(con != NULL);
770     DLOG("Setting mark \"%s\" on con = %p.\n", mark, con);
771 
772     con_unmark(NULL, mark);
773     if (mode == MM_REPLACE) {
774         DLOG("Removing all existing marks on con = %p.\n", con);
775 
776         mark_t *current;
777         while (!TAILQ_EMPTY(&(con->marks_head))) {
778             current = TAILQ_FIRST(&(con->marks_head));
779             con_unmark(con, current->name);
780         }
781     }
782 
783     mark_t *new = scalloc(1, sizeof(mark_t));
784     new->name = sstrdup(mark);
785     TAILQ_INSERT_TAIL(&(con->marks_head), new, marks);
786     ipc_send_window_event("mark", con);
787 
788     con->mark_changed = true;
789 }
790 
791 /*
792  * Removes marks from containers.
793  * If con is NULL, all containers are considered.
794  * If name is NULL, this removes all existing marks.
795  * Otherwise, it will only remove the given mark (if it is present).
796  *
797  */
con_unmark(Con * con,const char * name)798 void con_unmark(Con *con, const char *name) {
799     Con *current;
800     if (name == NULL) {
801         DLOG("Unmarking all containers.\n");
802         TAILQ_FOREACH (current, &all_cons, all_cons) {
803             if (con != NULL && current != con)
804                 continue;
805 
806             if (TAILQ_EMPTY(&(current->marks_head)))
807                 continue;
808 
809             mark_t *mark;
810             while (!TAILQ_EMPTY(&(current->marks_head))) {
811                 mark = TAILQ_FIRST(&(current->marks_head));
812                 FREE(mark->name);
813                 TAILQ_REMOVE(&(current->marks_head), mark, marks);
814                 FREE(mark);
815 
816                 ipc_send_window_event("mark", current);
817             }
818 
819             current->mark_changed = true;
820         }
821     } else {
822         DLOG("Removing mark \"%s\".\n", name);
823         current = (con == NULL) ? con_by_mark(name) : con;
824         if (current == NULL) {
825             DLOG("No container found with this mark, so there is nothing to do.\n");
826             return;
827         }
828 
829         DLOG("Found mark on con = %p. Removing it now.\n", current);
830         current->mark_changed = true;
831 
832         mark_t *mark;
833         TAILQ_FOREACH (mark, &(current->marks_head), marks) {
834             if (strcmp(mark->name, name) != 0)
835                 continue;
836 
837             FREE(mark->name);
838             TAILQ_REMOVE(&(current->marks_head), mark, marks);
839             FREE(mark);
840 
841             ipc_send_window_event("mark", current);
842             break;
843         }
844     }
845 }
846 
847 /*
848  * Returns the first container below 'con' which wants to swallow this window
849  * TODO: priority
850  *
851  */
con_for_window(Con * con,i3Window * window,Match ** store_match)852 Con *con_for_window(Con *con, i3Window *window, Match **store_match) {
853     Con *child;
854     Match *match;
855     //DLOG("searching con for window %p starting at con %p\n", window, con);
856     //DLOG("class == %s\n", window->class_class);
857 
858     TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
859         TAILQ_FOREACH (match, &(child->swallow_head), matches) {
860             if (!match_matches_window(match, window))
861                 continue;
862             if (store_match != NULL)
863                 *store_match = match;
864             return child;
865         }
866         Con *result = con_for_window(child, window, store_match);
867         if (result != NULL)
868             return result;
869     }
870 
871     TAILQ_FOREACH (child, &(con->floating_head), floating_windows) {
872         TAILQ_FOREACH (match, &(child->swallow_head), matches) {
873             if (!match_matches_window(match, window))
874                 continue;
875             if (store_match != NULL)
876                 *store_match = match;
877             return child;
878         }
879         Con *result = con_for_window(child, window, store_match);
880         if (result != NULL)
881             return result;
882     }
883 
884     return NULL;
885 }
886 
num_focus_heads(Con * con)887 static int num_focus_heads(Con *con) {
888     int focus_heads = 0;
889 
890     Con *current;
891     TAILQ_FOREACH (current, &(con->focus_head), focused) {
892         focus_heads++;
893     }
894 
895     return focus_heads;
896 }
897 
898 /*
899  * Iterate over the container's focus stack and return an array with the
900  * containers inside it, ordered from higher focus order to lowest.
901  *
902  */
get_focus_order(Con * con)903 Con **get_focus_order(Con *con) {
904     const int focus_heads = num_focus_heads(con);
905     Con **focus_order = smalloc(focus_heads * sizeof(Con *));
906     Con *current;
907     int idx = 0;
908     TAILQ_FOREACH (current, &(con->focus_head), focused) {
909         assert(idx < focus_heads);
910         focus_order[idx++] = current;
911     }
912 
913     return focus_order;
914 }
915 
916 /*
917  * Clear the container's focus stack and re-add it using the provided container
918  * array. The function doesn't check if the provided array contains the same
919  * containers with the previous focus stack but will not add floating containers
920  * in the new focus stack if container is not a workspace.
921  *
922  */
set_focus_order(Con * con,Con ** focus_order)923 void set_focus_order(Con *con, Con **focus_order) {
924     int focus_heads = 0;
925     while (!TAILQ_EMPTY(&(con->focus_head))) {
926         Con *current = TAILQ_FIRST(&(con->focus_head));
927 
928         TAILQ_REMOVE(&(con->focus_head), current, focused);
929         focus_heads++;
930     }
931 
932     for (int idx = 0; idx < focus_heads; idx++) {
933         /* Useful when encapsulating a workspace. */
934         if (con->type != CT_WORKSPACE && con_inside_floating(focus_order[idx])) {
935             focus_heads++;
936             continue;
937         }
938 
939         TAILQ_INSERT_TAIL(&(con->focus_head), focus_order[idx], focused);
940     }
941 }
942 
943 /*
944  * Returns the number of children of this container.
945  *
946  */
con_num_children(Con * con)947 int con_num_children(Con *con) {
948     Con *child;
949     int children = 0;
950 
951     TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
952         children++;
953     }
954 
955     return children;
956 }
957 
958 /*
959  * Returns the number of visible non-floating children of this container.
960  * For example, if the container contains a hsplit which has two children,
961  * this will return 2 instead of 1.
962  */
con_num_visible_children(Con * con)963 int con_num_visible_children(Con *con) {
964     if (con == NULL)
965         return 0;
966 
967     int children = 0;
968     Con *current = NULL;
969     TAILQ_FOREACH (current, &(con->nodes_head), nodes) {
970         /* Visible leaf nodes are a child. */
971         if (!con_is_hidden(current) && con_is_leaf(current))
972             children++;
973         /* All other containers need to be recursed. */
974         else
975             children += con_num_visible_children(current);
976     }
977 
978     return children;
979 }
980 
981 /*
982  * Count the number of windows (i.e., leaf containers).
983  *
984  */
con_num_windows(Con * con)985 int con_num_windows(Con *con) {
986     if (con == NULL)
987         return 0;
988 
989     if (con_has_managed_window(con))
990         return 1;
991 
992     int num = 0;
993     Con *current = NULL;
994     TAILQ_FOREACH (current, &(con->nodes_head), nodes) {
995         num += con_num_windows(current);
996     }
997 
998     TAILQ_FOREACH (current, &(con->floating_head), floating_windows) {
999         num += con_num_windows(current);
1000     }
1001 
1002     return num;
1003 }
1004 
1005 /*
1006  * Updates the percent attribute of the children of the given container. This
1007  * function needs to be called when a window is added or removed from a
1008  * container.
1009  *
1010  */
con_fix_percent(Con * con)1011 void con_fix_percent(Con *con) {
1012     Con *child;
1013     int children = con_num_children(con);
1014 
1015     // calculate how much we have distributed and how many containers
1016     // with a percentage set we have
1017     double total = 0.0;
1018     int children_with_percent = 0;
1019     TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
1020         if (child->percent > 0.0) {
1021             total += child->percent;
1022             ++children_with_percent;
1023         }
1024     }
1025 
1026     // if there were children without a percentage set, set to a value that
1027     // will make those children proportional to all others
1028     if (children_with_percent != children) {
1029         TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
1030             if (child->percent <= 0.0) {
1031                 if (children_with_percent == 0) {
1032                     total += (child->percent = 1.0);
1033                 } else {
1034                     total += (child->percent = total / children_with_percent);
1035                 }
1036             }
1037         }
1038     }
1039 
1040     // if we got a zero, just distribute the space equally, otherwise
1041     // distribute according to the proportions we got
1042     if (total == 0.0) {
1043         TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
1044             child->percent = 1.0 / children;
1045         }
1046     } else if (total != 1.0) {
1047         TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
1048             child->percent /= total;
1049         }
1050     }
1051 }
1052 
1053 /*
1054  * Toggles fullscreen mode for the given container. If there already is a
1055  * fullscreen container on this workspace, fullscreen will be disabled and then
1056  * enabled for the container the user wants to have in fullscreen mode.
1057  *
1058  */
con_toggle_fullscreen(Con * con,int fullscreen_mode)1059 void con_toggle_fullscreen(Con *con, int fullscreen_mode) {
1060     if (con->type == CT_WORKSPACE) {
1061         DLOG("You cannot make a workspace fullscreen.\n");
1062         return;
1063     }
1064 
1065     DLOG("toggling fullscreen for %p / %s\n", con, con->name);
1066 
1067     if (con->fullscreen_mode == CF_NONE)
1068         con_enable_fullscreen(con, fullscreen_mode);
1069     else
1070         con_disable_fullscreen(con);
1071 }
1072 
1073 /*
1074  * Sets the specified fullscreen mode for the given container, sends the
1075  * “fullscreen_mode” event and changes the XCB fullscreen property of the
1076  * container’s window, if any.
1077  *
1078  */
con_set_fullscreen_mode(Con * con,fullscreen_mode_t fullscreen_mode)1079 static void con_set_fullscreen_mode(Con *con, fullscreen_mode_t fullscreen_mode) {
1080     con->fullscreen_mode = fullscreen_mode;
1081 
1082     DLOG("mode now: %d\n", con->fullscreen_mode);
1083 
1084     /* Send an ipc window "fullscreen_mode" event */
1085     ipc_send_window_event("fullscreen_mode", con);
1086 
1087     /* update _NET_WM_STATE if this container has a window */
1088     /* TODO: when a window is assigned to a container which is already
1089      * fullscreened, this state needs to be pushed to the client, too */
1090     if (con->window == NULL)
1091         return;
1092 
1093     if (con->fullscreen_mode != CF_NONE) {
1094         DLOG("Setting _NET_WM_STATE_FULLSCREEN for con = %p / window = %d.\n", con, con->window->id);
1095         xcb_add_property_atom(conn, con->window->id, A__NET_WM_STATE, A__NET_WM_STATE_FULLSCREEN);
1096     } else {
1097         DLOG("Removing _NET_WM_STATE_FULLSCREEN for con = %p / window = %d.\n", con, con->window->id);
1098         xcb_remove_property_atom(conn, con->window->id, A__NET_WM_STATE, A__NET_WM_STATE_FULLSCREEN);
1099     }
1100 }
1101 
1102 /*
1103  * Enables fullscreen mode for the given container, if necessary.
1104  *
1105  * If the container’s mode is already CF_OUTPUT or CF_GLOBAL, the container is
1106  * kept fullscreen but its mode is set to CF_GLOBAL and CF_OUTPUT,
1107  * respectively.
1108  *
1109  * Other fullscreen containers will be disabled first, if they hide the new
1110  * one.
1111  *
1112  */
con_enable_fullscreen(Con * con,fullscreen_mode_t fullscreen_mode)1113 void con_enable_fullscreen(Con *con, fullscreen_mode_t fullscreen_mode) {
1114     if (con->type == CT_WORKSPACE) {
1115         DLOG("You cannot make a workspace fullscreen.\n");
1116         return;
1117     }
1118 
1119     assert(fullscreen_mode == CF_GLOBAL || fullscreen_mode == CF_OUTPUT);
1120 
1121     if (fullscreen_mode == CF_GLOBAL)
1122         DLOG("enabling global fullscreen for %p / %s\n", con, con->name);
1123     else
1124         DLOG("enabling fullscreen for %p / %s\n", con, con->name);
1125 
1126     if (con->fullscreen_mode == fullscreen_mode) {
1127         DLOG("fullscreen already enabled for %p / %s\n", con, con->name);
1128         return;
1129     }
1130 
1131     Con *con_ws = con_get_workspace(con);
1132 
1133     /* Disable any fullscreen container that would conflict the new one. */
1134     Con *fullscreen = con_get_fullscreen_con(croot, CF_GLOBAL);
1135     if (fullscreen == NULL)
1136         fullscreen = con_get_fullscreen_con(con_ws, CF_OUTPUT);
1137     if (fullscreen != NULL)
1138         con_disable_fullscreen(fullscreen);
1139 
1140     /* Set focus to new fullscreen container. Unless in global fullscreen mode
1141      * and on another workspace restore focus afterwards.
1142      * Switch to the container’s workspace if mode is global. */
1143     Con *cur_ws = con_get_workspace(focused);
1144     Con *old_focused = focused;
1145     if (fullscreen_mode == CF_GLOBAL && cur_ws != con_ws)
1146         workspace_show(con_ws);
1147     con_activate(con);
1148     if (fullscreen_mode != CF_GLOBAL && cur_ws != con_ws)
1149         con_activate(old_focused);
1150 
1151     con_set_fullscreen_mode(con, fullscreen_mode);
1152 }
1153 
1154 /*
1155  * Disables fullscreen mode for the given container regardless of the mode, if
1156  * necessary.
1157  *
1158  */
con_disable_fullscreen(Con * con)1159 void con_disable_fullscreen(Con *con) {
1160     if (con->type == CT_WORKSPACE) {
1161         DLOG("You cannot make a workspace fullscreen.\n");
1162         return;
1163     }
1164 
1165     DLOG("disabling fullscreen for %p / %s\n", con, con->name);
1166 
1167     if (con->fullscreen_mode == CF_NONE) {
1168         DLOG("fullscreen already disabled for %p / %s\n", con, con->name);
1169         return;
1170     }
1171 
1172     con_set_fullscreen_mode(con, CF_NONE);
1173 }
1174 
_con_move_to_con(Con * con,Con * target,bool behind_focused,bool fix_coordinates,bool dont_warp,bool ignore_focus,bool fix_percentage)1175 static bool _con_move_to_con(Con *con, Con *target, bool behind_focused, bool fix_coordinates, bool dont_warp, bool ignore_focus, bool fix_percentage) {
1176     Con *orig_target = target;
1177 
1178     /* Prevent moving if this would violate the fullscreen focus restrictions. */
1179     Con *target_ws = con_get_workspace(target);
1180     if (!ignore_focus && !con_fullscreen_permits_focusing(target_ws)) {
1181         LOG("Cannot move out of a fullscreen container.\n");
1182         return false;
1183     }
1184 
1185     if (con_is_floating(con)) {
1186         DLOG("Container is floating, using parent instead.\n");
1187         con = con->parent;
1188     }
1189 
1190     Con *source_ws = con_get_workspace(con);
1191 
1192     if (con->type == CT_WORKSPACE) {
1193         /* Re-parent all of the old workspace's floating windows. */
1194         Con *child;
1195         while (!TAILQ_EMPTY(&(source_ws->floating_head))) {
1196             child = TAILQ_FIRST(&(source_ws->floating_head));
1197             con_move_to_workspace(child, target_ws, true, true, false);
1198         }
1199 
1200         /* If there are no non-floating children, ignore the workspace. */
1201         if (con_is_leaf(con))
1202             return false;
1203 
1204         con = workspace_encapsulate(con);
1205         if (con == NULL) {
1206             ELOG("Workspace failed to move its contents into a container!\n");
1207             return false;
1208         }
1209     }
1210 
1211     /* Save the urgency state so that we can restore it. */
1212     bool urgent = con->urgent;
1213 
1214     /* Save the current workspace. So we can call workspace_show() by the end
1215      * of this function. */
1216     Con *current_ws = con_get_workspace(focused);
1217 
1218     Con *source_output = con_get_output(con),
1219         *dest_output = con_get_output(target_ws);
1220 
1221     /* 1: save the container which is going to be focused after the current
1222      * container is moved away */
1223     Con *focus_next = NULL;
1224     if (!ignore_focus && source_ws == current_ws && target_ws != source_ws) {
1225         focus_next = con_descend_focused(source_ws);
1226         if (focus_next == con || con_has_parent(focus_next, con)) {
1227             focus_next = con_next_focused(con);
1228         }
1229     }
1230 
1231     /* 2: we go up one level, but only when target is a normal container */
1232     if (target->type != CT_WORKSPACE) {
1233         DLOG("target originally = %p / %s / type %d\n", target, target->name, target->type);
1234         target = target->parent;
1235     }
1236 
1237     /* 3: if the original target is the direct child of a floating container, we
1238      * can't move con next to it - floating containers have only one child - so
1239      * we get the workspace instead. */
1240     if (target->type == CT_FLOATING_CON) {
1241         DLOG("floatingcon, going up even further\n");
1242         orig_target = target;
1243         target = target->parent;
1244     }
1245 
1246     if (con->type == CT_FLOATING_CON) {
1247         Con *ws = con_get_workspace(target);
1248         DLOG("This is a floating window, using workspace %p / %s\n", ws, ws->name);
1249         target = ws;
1250     }
1251 
1252     if (source_output != dest_output) {
1253         /* Take the relative coordinates of the current output, then add them
1254          * to the coordinate space of the correct output */
1255         if (fix_coordinates && con->type == CT_FLOATING_CON) {
1256             floating_fix_coordinates(con, &(source_output->rect), &(dest_output->rect));
1257         } else
1258             DLOG("Not fixing coordinates, fix_coordinates flag = %d\n", fix_coordinates);
1259     }
1260 
1261     /* If moving a fullscreen container and the destination already has a
1262      * fullscreen window on it, un-fullscreen the target's fullscreen con.
1263      * con->fullscreen_mode is not enough in some edge cases:
1264      * 1. con is CT_FLOATING_CON, child is fullscreen.
1265      * 2. con is the parent of a fullscreen container, can be triggered by
1266      * moving the parent with command criteria.
1267      */
1268     Con *fullscreen = con_get_fullscreen_con(target_ws, CF_OUTPUT);
1269     const bool con_has_fullscreen = con->fullscreen_mode != CF_NONE ||
1270                                     con_get_fullscreen_con(con, CF_GLOBAL) ||
1271                                     con_get_fullscreen_con(con, CF_OUTPUT);
1272     if (con_has_fullscreen && fullscreen != NULL) {
1273         con_toggle_fullscreen(fullscreen, CF_OUTPUT);
1274         fullscreen = NULL;
1275     }
1276 
1277     DLOG("Re-attaching container to %p / %s\n", target, target->name);
1278     /* 4: re-attach the con to the parent of this focused container */
1279     Con *parent = con->parent;
1280     con_detach(con);
1281     _con_attach(con, target, behind_focused ? NULL : orig_target, !behind_focused);
1282 
1283     /* 5: fix the percentages */
1284     if (fix_percentage) {
1285         con_fix_percent(parent);
1286         con->percent = 0.0;
1287         con_fix_percent(target);
1288     }
1289 
1290     /* 6: focus the con on the target workspace, but only within that
1291      * workspace, that is, don’t move focus away if the target workspace is
1292      * invisible.
1293      * We don’t focus the con for i3 pseudo workspaces like __i3_scratch and
1294      * we don’t focus when there is a fullscreen con on that workspace. We
1295      * also don't do it if the caller requested to ignore focus. */
1296     if (!ignore_focus && !con_is_internal(target_ws) && !fullscreen) {
1297         /* We need to save the focused workspace on the output in case the
1298          * new workspace is hidden and it's necessary to immediately switch
1299          * back to the originally-focused workspace. */
1300         Con *old_focus_ws = TAILQ_FIRST(&(output_get_content(dest_output)->focus_head));
1301         Con *old_focus = focused;
1302         con_activate(con_descend_focused(con));
1303 
1304         if (old_focus_ws == current_ws && old_focus->type != CT_WORKSPACE) {
1305             /* Restore focus to the currently focused container. */
1306             con_activate(old_focus);
1307         } else if (con_get_workspace(focused) != old_focus_ws) {
1308             /* Restore focus if the output's focused workspace has changed. */
1309             con_focus(con_descend_focused(old_focus_ws));
1310         }
1311     }
1312 
1313     /* 7: when moving to another workspace, we leave the focus on the current
1314      * workspace. (see also #809) */
1315     if (!ignore_focus) {
1316         workspace_show(current_ws);
1317         if (dont_warp) {
1318             DLOG("x_set_warp_to(NULL) because dont_warp is set\n");
1319             x_set_warp_to(NULL);
1320         }
1321     }
1322 
1323     /* Set focus only if con was on current workspace before moving.
1324      * Otherwise we would give focus to some window on different workspace. */
1325     if (focus_next)
1326         con_activate(con_descend_focused(focus_next));
1327 
1328     /* 8. If anything within the container is associated with a startup sequence,
1329      * delete it so child windows won't be created on the old workspace. */
1330     if (!con_is_leaf(con)) {
1331         Con *child;
1332         TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
1333             if (!child->window)
1334                 continue;
1335             startup_sequence_delete_by_window(child->window);
1336         }
1337     }
1338 
1339     if (con->window) {
1340         startup_sequence_delete_by_window(con->window);
1341     }
1342 
1343     /* 9. If the container was marked urgent, move the urgency hint. */
1344     if (urgent) {
1345         workspace_update_urgent_flag(source_ws);
1346         con_set_urgency(con, true);
1347     }
1348 
1349     /* Ensure the container will be redrawn. */
1350     FREE(con->deco_render_params);
1351 
1352     CALL(parent, on_remove_child);
1353 
1354     ipc_send_window_event("move", con);
1355     ewmh_update_wm_desktop();
1356     return true;
1357 }
1358 
1359 /*
1360  * Moves the given container to the given mark.
1361  *
1362  */
con_move_to_mark(Con * con,const char * mark)1363 bool con_move_to_mark(Con *con, const char *mark) {
1364     Con *target = con_by_mark(mark);
1365     if (target == NULL) {
1366         DLOG("found no container with mark \"%s\"\n", mark);
1367         return false;
1368     }
1369 
1370     /* For target containers in the scratchpad, we just send the window to the scratchpad. */
1371     if (con_get_workspace(target) == workspace_get("__i3_scratch")) {
1372         DLOG("target container is in the scratchpad, moving container to scratchpad.\n");
1373         scratchpad_move(con);
1374         return true;
1375     }
1376 
1377     /* For floating target containers, we just send the window to the same workspace. */
1378     if (con_is_floating(target)) {
1379         DLOG("target container is floating, moving container to target's workspace.\n");
1380         con_move_to_workspace(con, con_get_workspace(target), true, false, false);
1381         return true;
1382     }
1383 
1384     if (target->type == CT_WORKSPACE && con_is_leaf(target)) {
1385         DLOG("target container is an empty workspace, simply moving the container there.\n");
1386         con_move_to_workspace(con, target, true, false, false);
1387         return true;
1388     }
1389 
1390     /* For split containers, we use the currently focused container within it.
1391      * This allows setting marks on, e.g., tabbed containers which will move
1392      * con to a new tab behind the focused tab. */
1393     if (con_is_split(target)) {
1394         DLOG("target is a split container, descending to the currently focused child.\n");
1395         target = TAILQ_FIRST(&(target->focus_head));
1396     }
1397 
1398     if (con == target || con_has_parent(target, con)) {
1399         DLOG("cannot move the container to or inside itself, aborting.\n");
1400         return false;
1401     }
1402 
1403     return _con_move_to_con(con, target, false, true, false, false, true);
1404 }
1405 
1406 /*
1407  * Moves the given container to the currently focused container on the given
1408  * workspace.
1409  *
1410  * The fix_coordinates flag will translate the current coordinates (offset from
1411  * the monitor position basically) to appropriate coordinates on the
1412  * destination workspace.
1413  * Not enabling this behaviour comes in handy when this function gets called by
1414  * floating_maybe_reassign_ws, which will only "move" a floating window when it
1415  * *already* changed its coordinates to a different output.
1416  *
1417  * The dont_warp flag disables pointer warping and will be set when this
1418  * function is called while dragging a floating window.
1419  *
1420  * If ignore_focus is set, the container will be moved without modifying focus
1421  * at all.
1422  *
1423  * TODO: is there a better place for this function?
1424  *
1425  */
con_move_to_workspace(Con * con,Con * workspace,bool fix_coordinates,bool dont_warp,bool ignore_focus)1426 void con_move_to_workspace(Con *con, Con *workspace, bool fix_coordinates, bool dont_warp, bool ignore_focus) {
1427     assert(workspace->type == CT_WORKSPACE);
1428 
1429     Con *source_ws = con_get_workspace(con);
1430     if (workspace == source_ws) {
1431         DLOG("Not moving, already there\n");
1432         return;
1433     }
1434 
1435     Con *target = con_descend_focused(workspace);
1436     _con_move_to_con(con, target, true, fix_coordinates, dont_warp, ignore_focus, true);
1437 }
1438 
1439 /*
1440  * Moves the given container to the currently focused container on the
1441  * visible workspace on the given output.
1442  *
1443  */
con_move_to_output(Con * con,Output * output,bool fix_coordinates)1444 void con_move_to_output(Con *con, Output *output, bool fix_coordinates) {
1445     Con *ws = NULL;
1446     GREP_FIRST(ws, output_get_content(output->con), workspace_is_visible(child));
1447     assert(ws != NULL);
1448     DLOG("Moving con %p to output %s\n", con, output_primary_name(output));
1449     con_move_to_workspace(con, ws, fix_coordinates, false, false);
1450 }
1451 
1452 /*
1453  * Moves the given container to the currently focused container on the
1454  * visible workspace on the output specified by the given name.
1455  * The current output for the container is used to resolve relative names
1456  * such as left, right, up, down.
1457  *
1458  */
con_move_to_output_name(Con * con,const char * name,bool fix_coordinates)1459 bool con_move_to_output_name(Con *con, const char *name, bool fix_coordinates) {
1460     Output *current_output = get_output_for_con(con);
1461     Output *output = get_output_from_string(current_output, name);
1462     if (output == NULL) {
1463         ELOG("Could not find output \"%s\"\n", name);
1464         return false;
1465     }
1466 
1467     con_move_to_output(con, output, fix_coordinates);
1468     return true;
1469 }
1470 
1471 /*
1472  * Returns the orientation of the given container (for stacked containers,
1473  * vertical orientation is used regardless of the actual orientation of the
1474  * container).
1475  *
1476  */
con_orientation(Con * con)1477 orientation_t con_orientation(Con *con) {
1478     switch (con->layout) {
1479         case L_SPLITV:
1480         /* stacking containers behave like they are in vertical orientation */
1481         case L_STACKED:
1482             return VERT;
1483 
1484         case L_SPLITH:
1485         /* tabbed containers behave like they are in vertical orientation */
1486         case L_TABBED:
1487             return HORIZ;
1488 
1489         case L_DEFAULT:
1490             ELOG("Someone called con_orientation() on a con with L_DEFAULT, this is a bug in the code.\n");
1491             assert(false);
1492 
1493         case L_DOCKAREA:
1494         case L_OUTPUT:
1495             ELOG("con_orientation() called on dockarea/output (%d) container %p\n", con->layout, con);
1496             assert(false);
1497     }
1498     /* should not be reached */
1499     assert(false);
1500 }
1501 
1502 /*
1503  * Returns the container which will be focused next when the given container
1504  * is not available anymore. Called in tree_close_internal and con_move_to_workspace
1505  * to properly restore focus.
1506  *
1507  */
con_next_focused(Con * con)1508 Con *con_next_focused(Con *con) {
1509     /* dock clients cannot be focused, so we focus the workspace instead */
1510     if (con->parent->type == CT_DOCKAREA) {
1511         DLOG("selecting workspace for dock client\n");
1512         return con_descend_focused(output_get_content(con->parent->parent));
1513     }
1514     if (con_is_floating(con)) {
1515         con = con->parent;
1516     }
1517 
1518     /* if 'con' is not the first entry in the focus stack, use the first one as
1519      * it’s currently focused already */
1520     Con *next = TAILQ_FIRST(&(con->parent->focus_head));
1521     if (next != con) {
1522         DLOG("Using first entry %p\n", next);
1523     } else {
1524         /* try to focus the next container on the same level as this one or fall
1525          * back to its parent */
1526         if (!(next = TAILQ_NEXT(con, focused))) {
1527             next = con->parent;
1528         }
1529     }
1530 
1531     /* now go down the focus stack as far as
1532      * possible, excluding the current container */
1533     while (!TAILQ_EMPTY(&(next->focus_head)) && TAILQ_FIRST(&(next->focus_head)) != con) {
1534         next = TAILQ_FIRST(&(next->focus_head));
1535     }
1536 
1537     if (con->type == CT_FLOATING_CON && next != con->parent) {
1538         next = con_descend_focused(next);
1539     }
1540 
1541     return next;
1542 }
1543 
1544 /*
1545  * Returns the focused con inside this client, descending the tree as far as
1546  * possible. This comes in handy when attaching a con to a workspace at the
1547  * currently focused position, for example.
1548  *
1549  */
con_descend_focused(Con * con)1550 Con *con_descend_focused(Con *con) {
1551     Con *next = con;
1552     while (next != focused && !TAILQ_EMPTY(&(next->focus_head)))
1553         next = TAILQ_FIRST(&(next->focus_head));
1554     return next;
1555 }
1556 
1557 /*
1558  * Returns the focused con inside this client, descending the tree as far as
1559  * possible. This comes in handy when attaching a con to a workspace at the
1560  * currently focused position, for example.
1561  *
1562  * Works like con_descend_focused but considers only tiling cons.
1563  *
1564  */
con_descend_tiling_focused(Con * con)1565 Con *con_descend_tiling_focused(Con *con) {
1566     Con *next = con;
1567     Con *before;
1568     Con *child;
1569     if (next == focused)
1570         return next;
1571     do {
1572         before = next;
1573         TAILQ_FOREACH (child, &(next->focus_head), focused) {
1574             if (child->type == CT_FLOATING_CON)
1575                 continue;
1576 
1577             next = child;
1578             break;
1579         }
1580     } while (before != next && next != focused);
1581     return next;
1582 }
1583 
1584 /*
1585  * Returns the leftmost, rightmost, etc. container in sub-tree. For example, if
1586  * direction is D_LEFT, then we return the rightmost container and if direction
1587  * is D_RIGHT, we return the leftmost container.  This is because if we are
1588  * moving D_LEFT, and thus want the rightmost container.
1589  *
1590  */
con_descend_direction(Con * con,direction_t direction)1591 Con *con_descend_direction(Con *con, direction_t direction) {
1592     Con *most = NULL;
1593     Con *current;
1594     int orientation = con_orientation(con);
1595     DLOG("con_descend_direction(%p, orientation %d, direction %d)\n", con, orientation, direction);
1596     if (direction == D_LEFT || direction == D_RIGHT) {
1597         if (orientation == HORIZ) {
1598             /* If the direction is horizontal, we can use either the first
1599              * (D_RIGHT) or the last con (D_LEFT) */
1600             if (direction == D_RIGHT)
1601                 most = TAILQ_FIRST(&(con->nodes_head));
1602             else
1603                 most = TAILQ_LAST(&(con->nodes_head), nodes_head);
1604         } else if (orientation == VERT) {
1605             /* Wrong orientation. We use the last focused con. Within that con,
1606              * we recurse to chose the left/right con or at least the last
1607              * focused one. */
1608             TAILQ_FOREACH (current, &(con->focus_head), focused) {
1609                 if (current->type != CT_FLOATING_CON) {
1610                     most = current;
1611                     break;
1612                 }
1613             }
1614         } else {
1615             /* If the con has no orientation set, it’s not a split container
1616              * but a container with a client window, so stop recursing */
1617             return con;
1618         }
1619     }
1620 
1621     if (direction == D_UP || direction == D_DOWN) {
1622         if (orientation == VERT) {
1623             /* If the direction is vertical, we can use either the first
1624              * (D_DOWN) or the last con (D_UP) */
1625             if (direction == D_UP)
1626                 most = TAILQ_LAST(&(con->nodes_head), nodes_head);
1627             else
1628                 most = TAILQ_FIRST(&(con->nodes_head));
1629         } else if (orientation == HORIZ) {
1630             /* Wrong orientation. We use the last focused con. Within that con,
1631              * we recurse to chose the top/bottom con or at least the last
1632              * focused one. */
1633             TAILQ_FOREACH (current, &(con->focus_head), focused) {
1634                 if (current->type != CT_FLOATING_CON) {
1635                     most = current;
1636                     break;
1637                 }
1638             }
1639         } else {
1640             /* If the con has no orientation set, it’s not a split container
1641              * but a container with a client window, so stop recursing */
1642             return con;
1643         }
1644     }
1645 
1646     if (!most)
1647         return con;
1648     return con_descend_direction(most, direction);
1649 }
1650 
has_outer_gaps(gaps_t gaps)1651 static bool has_outer_gaps(gaps_t gaps) {
1652     return gaps.top > 0 ||
1653            gaps.right > 0 ||
1654            gaps.bottom > 0 ||
1655            gaps.left > 0;
1656 }
1657 
1658 /*
1659  * Returns a "relative" Rect which contains the amount of pixels that need to
1660  * be added to the original Rect to get the final position (obviously the
1661  * amount of pixels for normal, 1pixel and borderless are different).
1662  *
1663  */
con_border_style_rect(Con * con)1664 Rect con_border_style_rect(Con *con) {
1665     if ((config.smart_borders == SMART_BORDERS_ON && con_num_visible_children(con_get_workspace(con)) <= 1) ||
1666         (config.smart_borders == SMART_BORDERS_NO_GAPS && !has_outer_gaps(calculate_effective_gaps(con))) ||
1667         (config.hide_edge_borders == HEBM_SMART && con_num_visible_children(con_get_workspace(con)) <= 1) ||
1668         (config.hide_edge_borders == HEBM_SMART_NO_GAPS && con_num_visible_children(con_get_workspace(con)) <= 1 && !has_outer_gaps(calculate_effective_gaps(con)))) {
1669         if (!con_is_floating(con))
1670             return (Rect){0, 0, 0, 0};
1671     }
1672 
1673     adjacent_t borders_to_hide = ADJ_NONE;
1674     int border_width = con->current_border_width;
1675     DLOG("The border width for con is set to: %d\n", con->current_border_width);
1676     Rect result;
1677     if (con->current_border_width < 0) {
1678         if (con_is_floating(con)) {
1679             border_width = config.default_floating_border_width;
1680         } else {
1681             border_width = config.default_border_width;
1682         }
1683     }
1684     DLOG("Effective border width is set to: %d\n", border_width);
1685     /* Shortcut to avoid calling con_adjacent_borders() on dock containers. */
1686     int border_style = con_border_style(con);
1687     if (border_style == BS_NONE)
1688         return (Rect){0, 0, 0, 0};
1689     if (border_style == BS_NORMAL) {
1690         result = (Rect){border_width, 0, -(2 * border_width), -(border_width)};
1691     } else {
1692         result = (Rect){border_width, border_width, -(2 * border_width), -(2 * border_width)};
1693     }
1694 
1695     /* If hide_edge_borders is set to no_gaps and it did not pass the no border check, show all borders */
1696     if (config.hide_edge_borders == HEBM_SMART_NO_GAPS) {
1697         borders_to_hide = con_adjacent_borders(con) & HEBM_NONE;
1698     } else {
1699         borders_to_hide = con_adjacent_borders(con) & config.hide_edge_borders;
1700     }
1701 
1702     if (borders_to_hide & ADJ_LEFT_SCREEN_EDGE) {
1703         result.x -= border_width;
1704         result.width += border_width;
1705     }
1706     if (borders_to_hide & ADJ_RIGHT_SCREEN_EDGE) {
1707         result.width += border_width;
1708     }
1709     if (borders_to_hide & ADJ_UPPER_SCREEN_EDGE && (border_style != BS_NORMAL)) {
1710         result.y -= border_width;
1711         result.height += border_width;
1712     }
1713     if (borders_to_hide & ADJ_LOWER_SCREEN_EDGE) {
1714         result.height += border_width;
1715     }
1716     return result;
1717 }
1718 
1719 /*
1720  * Returns adjacent borders of the window. We need this if hide_edge_borders is
1721  * enabled.
1722  */
con_adjacent_borders(Con * con)1723 adjacent_t con_adjacent_borders(Con *con) {
1724     adjacent_t result = ADJ_NONE;
1725     /* Floating windows are never adjacent to any other window, so
1726        don’t hide their border(s). This prevents bug #998. */
1727     if (con_is_floating(con))
1728         return result;
1729 
1730     Con *workspace = con_get_workspace(con);
1731     if (con->rect.x == workspace->rect.x)
1732         result |= ADJ_LEFT_SCREEN_EDGE;
1733     if (con->rect.x + con->rect.width == workspace->rect.x + workspace->rect.width)
1734         result |= ADJ_RIGHT_SCREEN_EDGE;
1735     if (con->rect.y == workspace->rect.y)
1736         result |= ADJ_UPPER_SCREEN_EDGE;
1737     if (con->rect.y + con->rect.height == workspace->rect.y + workspace->rect.height)
1738         result |= ADJ_LOWER_SCREEN_EDGE;
1739     return result;
1740 }
1741 
1742 /*
1743  * Use this function to get a container’s border style. This is important
1744  * because when inside a stack, the border style is always BS_NORMAL.
1745  * For tabbed mode, the same applies, with one exception: when the container is
1746  * borderless and the only element in the tabbed container, the border is not
1747  * rendered.
1748  *
1749  * For children of a CT_DOCKAREA, the border style is always none.
1750  *
1751  */
con_border_style(Con * con)1752 int con_border_style(Con *con) {
1753     if (con->fullscreen_mode == CF_OUTPUT || con->fullscreen_mode == CF_GLOBAL) {
1754         DLOG("this one is fullscreen! overriding BS_NONE\n");
1755         return BS_NONE;
1756     }
1757 
1758     if (con->parent->layout == L_STACKED)
1759         return (con_num_children(con->parent) == 1 ? con->border_style : BS_NORMAL);
1760 
1761     if (con->parent->layout == L_TABBED && con->border_style != BS_NORMAL)
1762         return (con_num_children(con->parent) == 1 ? con->border_style : BS_NORMAL);
1763 
1764     if (con->parent->type == CT_DOCKAREA)
1765         return BS_NONE;
1766 
1767     return con->border_style;
1768 }
1769 
1770 /*
1771  * Sets the given border style on con, correctly keeping the position/size of a
1772  * floating window.
1773  *
1774  */
con_set_border_style(Con * con,int border_style,int border_width)1775 void con_set_border_style(Con *con, int border_style, int border_width) {
1776     /* Handle the simple case: non-floating containerns */
1777     if (!con_is_floating(con)) {
1778         con->border_style = border_style;
1779         con->current_border_width = border_width;
1780         return;
1781     }
1782 
1783     /* For floating containers, we want to keep the position/size of the
1784      * *window* itself. We first add the border pixels to con->rect to make
1785      * con->rect represent the absolute position of the window (same for
1786      * parent). Then, we change the border style and subtract the new border
1787      * pixels. For the parent, we do the same also for the decoration. */
1788     DLOG("This is a floating container\n");
1789 
1790     Con *parent = con->parent;
1791     Rect bsr = con_border_style_rect(con);
1792     int deco_height = (con->border_style == BS_NORMAL ? render_deco_height() : 0);
1793 
1794     con->rect = rect_add(con->rect, bsr);
1795     parent->rect = rect_add(parent->rect, bsr);
1796     parent->rect.y += deco_height;
1797     parent->rect.height -= deco_height;
1798 
1799     /* Change the border style, get new border/decoration values. */
1800     con->border_style = border_style;
1801     con->current_border_width = border_width;
1802     bsr = con_border_style_rect(con);
1803     deco_height = (con->border_style == BS_NORMAL ? render_deco_height() : 0);
1804 
1805     con->rect = rect_sub(con->rect, bsr);
1806     parent->rect = rect_sub(parent->rect, bsr);
1807     parent->rect.y -= deco_height;
1808     parent->rect.height += deco_height;
1809 }
1810 
1811 /*
1812  * This function changes the layout of a given container. Use it to handle
1813  * special cases like changing a whole workspace to stacked/tabbed (creates a
1814  * new split container before).
1815  *
1816  */
con_set_layout(Con * con,layout_t layout)1817 void con_set_layout(Con *con, layout_t layout) {
1818     DLOG("con_set_layout(%p, %d), con->type = %d\n",
1819          con, layout, con->type);
1820 
1821     /* Users can focus workspaces, but not any higher in the hierarchy.
1822      * Focus on the workspace is a special case, since in every other case, the
1823      * user means "change the layout of the parent split container". */
1824     if (con->type != CT_WORKSPACE)
1825         con = con->parent;
1826 
1827     /* We fill in last_split_layout when switching to a different layout
1828      * since there are many places in the code that don’t use
1829      * con_set_layout(). */
1830     if (con->layout == L_SPLITH || con->layout == L_SPLITV)
1831         con->last_split_layout = con->layout;
1832 
1833     /* When the container type is CT_WORKSPACE, the user wants to change the
1834      * whole workspace into stacked/tabbed mode. To do this and still allow
1835      * intuitive operations (like level-up and then opening a new window), we
1836      * need to create a new split container. */
1837     if (con->type == CT_WORKSPACE) {
1838         if (con_num_children(con) == 0) {
1839             layout_t ws_layout = (layout == L_STACKED || layout == L_TABBED) ? layout : L_DEFAULT;
1840             DLOG("Setting workspace_layout to %d\n", ws_layout);
1841             con->workspace_layout = ws_layout;
1842             DLOG("Setting layout to %d\n", layout);
1843             con->layout = layout;
1844         } else if (layout == L_STACKED || layout == L_TABBED || layout == L_SPLITV || layout == L_SPLITH) {
1845             DLOG("Creating new split container\n");
1846             /* 1: create a new split container */
1847             Con *new = con_new(NULL, NULL);
1848             new->parent = con;
1849 
1850             /* 2: Set the requested layout on the split container and mark it as
1851              * split. */
1852             new->layout = layout;
1853             new->last_split_layout = con->last_split_layout;
1854 
1855             /* 3: move the existing cons of this workspace below the new con */
1856             Con **focus_order = get_focus_order(con);
1857 
1858             DLOG("Moving cons\n");
1859             Con *child;
1860             while (!TAILQ_EMPTY(&(con->nodes_head))) {
1861                 child = TAILQ_FIRST(&(con->nodes_head));
1862                 con_detach(child);
1863                 con_attach(child, new, true);
1864             }
1865 
1866             set_focus_order(new, focus_order);
1867             free(focus_order);
1868 
1869             /* 4: attach the new split container to the workspace */
1870             DLOG("Attaching new split to ws\n");
1871             con_attach(new, con, false);
1872 
1873             tree_flatten(croot);
1874             con_force_split_parents_redraw(con);
1875             return;
1876         }
1877     }
1878 
1879     if (layout == L_DEFAULT) {
1880         /* Special case: the layout formerly known as "default" (in combination
1881          * with an orientation). Since we switched to splith/splitv layouts,
1882          * using the "default" layout (which "only" should happen when using
1883          * legacy configs) is using the last split layout (either splith or
1884          * splitv) in order to still do the same thing. */
1885         con->layout = con->last_split_layout;
1886         /* In case last_split_layout was not initialized… */
1887         if (con->layout == L_DEFAULT)
1888             con->layout = L_SPLITH;
1889     } else {
1890         con->layout = layout;
1891     }
1892     con_force_split_parents_redraw(con);
1893 }
1894 
1895 /*
1896  * This function toggles the layout of a given container. toggle_mode can be
1897  * either 'default' (toggle only between stacked/tabbed/last_split_layout),
1898  * 'split' (toggle only between splitv/splith) or 'all' (toggle between all
1899  * layouts).
1900  *
1901  */
con_toggle_layout(Con * con,const char * toggle_mode)1902 void con_toggle_layout(Con *con, const char *toggle_mode) {
1903     Con *parent = con;
1904     /* Users can focus workspaces, but not any higher in the hierarchy.
1905      * Focus on the workspace is a special case, since in every other case, the
1906      * user means "change the layout of the parent split container". */
1907     if (con->type != CT_WORKSPACE)
1908         parent = con->parent;
1909     DLOG("con_toggle_layout(%p, %s), parent = %p\n", con, toggle_mode, parent);
1910 
1911     const char delim[] = " ";
1912 
1913     if (strcasecmp(toggle_mode, "split") == 0 || strstr(toggle_mode, delim)) {
1914         /* L_DEFAULT is used as a placeholder value to distinguish if
1915          * the first layout has already been saved. (it can never be L_DEFAULT) */
1916         layout_t new_layout = L_DEFAULT;
1917         bool current_layout_found = false;
1918         char *tm_dup = sstrdup(toggle_mode);
1919         char *cur_tok = strtok(tm_dup, delim);
1920 
1921         for (layout_t layout; cur_tok != NULL; cur_tok = strtok(NULL, delim)) {
1922             if (strcasecmp(cur_tok, "split") == 0) {
1923                 /* Toggle between splits. When the current layout is not a split
1924                  * layout, we just switch back to last_split_layout. Otherwise, we
1925                  * change to the opposite split layout. */
1926                 if (parent->layout != L_SPLITH && parent->layout != L_SPLITV) {
1927                     layout = parent->last_split_layout;
1928                     /* In case last_split_layout was not initialized… */
1929                     if (layout == L_DEFAULT) {
1930                         layout = L_SPLITH;
1931                     }
1932                 } else {
1933                     layout = (parent->layout == L_SPLITH) ? L_SPLITV : L_SPLITH;
1934                 }
1935             } else {
1936                 bool success = layout_from_name(cur_tok, &layout);
1937                 if (!success || layout == L_DEFAULT) {
1938                     ELOG("The token '%s' was not recognized and has been skipped.\n", cur_tok);
1939                     continue;
1940                 }
1941             }
1942 
1943             /* If none of the specified layouts match the current,
1944              * fall back to the first layout in the list */
1945             if (new_layout == L_DEFAULT) {
1946                 new_layout = layout;
1947             }
1948 
1949             /* We found the active layout in the last iteration, so
1950              * now let's activate the current layout (next in list) */
1951             if (current_layout_found) {
1952                 new_layout = layout;
1953                 break;
1954             }
1955 
1956             if (parent->layout == layout) {
1957                 current_layout_found = true;
1958             }
1959         }
1960         free(tm_dup);
1961 
1962         if (new_layout != L_DEFAULT) {
1963             con_set_layout(con, new_layout);
1964         }
1965     } else if (strcasecmp(toggle_mode, "all") == 0 || strcasecmp(toggle_mode, "default") == 0) {
1966         if (parent->layout == L_STACKED)
1967             con_set_layout(con, L_TABBED);
1968         else if (parent->layout == L_TABBED) {
1969             if (strcasecmp(toggle_mode, "all") == 0)
1970                 con_set_layout(con, L_SPLITH);
1971             else
1972                 con_set_layout(con, parent->last_split_layout);
1973         } else if (parent->layout == L_SPLITH || parent->layout == L_SPLITV) {
1974             if (strcasecmp(toggle_mode, "all") == 0) {
1975                 /* When toggling through all modes, we toggle between
1976                  * splith/splitv, whereas normally we just directly jump to
1977                  * stacked. */
1978                 if (parent->layout == L_SPLITH)
1979                     con_set_layout(con, L_SPLITV);
1980                 else
1981                     con_set_layout(con, L_STACKED);
1982             } else {
1983                 con_set_layout(con, L_STACKED);
1984             }
1985         }
1986     }
1987 }
1988 
1989 /*
1990  * Callback which will be called when removing a child from the given con.
1991  * Kills the container if it is empty and replaces it with the child if there
1992  * is exactly one child.
1993  *
1994  */
con_on_remove_child(Con * con)1995 static void con_on_remove_child(Con *con) {
1996     DLOG("on_remove_child\n");
1997 
1998     /* Every container 'above' (in the hierarchy) the workspace content should
1999      * not be closed when the last child was removed */
2000     if (con->type == CT_OUTPUT ||
2001         con->type == CT_ROOT ||
2002         con->type == CT_DOCKAREA ||
2003         (con->parent != NULL && con->parent->type == CT_OUTPUT)) {
2004         DLOG("not handling, type = %d, name = %s\n", con->type, con->name);
2005         return;
2006     }
2007 
2008     /* For workspaces, close them only if they're not visible anymore */
2009     if (con->type == CT_WORKSPACE) {
2010         if (TAILQ_EMPTY(&(con->focus_head)) && !workspace_is_visible(con)) {
2011             LOG("Closing old workspace (%p / %s), it is empty\n", con, con->name);
2012             yajl_gen gen = ipc_marshal_workspace_event("empty", con, NULL);
2013             tree_close_internal(con, DONT_KILL_WINDOW, false);
2014 
2015             const unsigned char *payload;
2016             ylength length;
2017             y(get_buf, &payload, &length);
2018             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, (const char *)payload);
2019 
2020             y(free);
2021         }
2022         return;
2023     }
2024 
2025     con_force_split_parents_redraw(con);
2026     con->urgent = con_has_urgent_child(con);
2027     con_update_parents_urgency(con);
2028 
2029     /* TODO: check if this container would swallow any other client and
2030      * don’t close it automatically. */
2031     int children = con_num_children(con);
2032     if (children == 0) {
2033         DLOG("Container empty, closing\n");
2034         tree_close_internal(con, DONT_KILL_WINDOW, false);
2035         return;
2036     }
2037 }
2038 
2039 /*
2040  * Determines the minimum size of the given con by looking at its children (for
2041  * split/stacked/tabbed cons). Will be called when resizing floating cons
2042  *
2043  */
con_minimum_size(Con * con)2044 Rect con_minimum_size(Con *con) {
2045     DLOG("Determining minimum size for con %p\n", con);
2046 
2047     if (con_is_leaf(con)) {
2048         DLOG("leaf node, returning 75x50\n");
2049         return (Rect){0, 0, 75, 50};
2050     }
2051 
2052     if (con->type == CT_FLOATING_CON) {
2053         DLOG("floating con\n");
2054         Con *child = TAILQ_FIRST(&(con->nodes_head));
2055         return con_minimum_size(child);
2056     }
2057 
2058     if (con->layout == L_STACKED || con->layout == L_TABBED) {
2059         uint32_t max_width = 0, max_height = 0, deco_height = 0;
2060         Con *child;
2061         TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
2062             Rect min = con_minimum_size(child);
2063             deco_height += child->deco_rect.height;
2064             max_width = max(max_width, min.width);
2065             max_height = max(max_height, min.height);
2066         }
2067         DLOG("stacked/tabbed now, returning %d x %d + deco_rect = %d\n",
2068              max_width, max_height, deco_height);
2069         return (Rect){0, 0, max_width, max_height + deco_height};
2070     }
2071 
2072     /* For horizontal/vertical split containers we sum up the width (h-split)
2073      * or height (v-split) and use the maximum of the height (h-split) or width
2074      * (v-split) as minimum size. */
2075     if (con_is_split(con)) {
2076         uint32_t width = 0, height = 0;
2077         Con *child;
2078         TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
2079             Rect min = con_minimum_size(child);
2080             if (con->layout == L_SPLITH) {
2081                 width += min.width;
2082                 height = max(height, min.height);
2083             } else {
2084                 height += min.height;
2085                 width = max(width, min.width);
2086             }
2087         }
2088         DLOG("split container, returning width = %d x height = %d\n", width, height);
2089         return (Rect){0, 0, width, height};
2090     }
2091 
2092     ELOG("Unhandled case, type = %d, layout = %d, split = %d\n",
2093          con->type, con->layout, con_is_split(con));
2094     assert(false);
2095 }
2096 
2097 /*
2098  * Returns true if changing the focus to con would be allowed considering
2099  * the fullscreen focus constraints. Specifically, if a fullscreen container or
2100  * any of its descendants is focused, this function returns true if and only if
2101  * focusing con would mean that focus would still be visible on screen, i.e.,
2102  * the newly focused container would not be obscured by a fullscreen container.
2103  *
2104  * In the simplest case, if a fullscreen container or any of its descendants is
2105  * fullscreen, this functions returns true if con is the fullscreen container
2106  * itself or any of its descendants, as this means focus wouldn't escape the
2107  * boundaries of the fullscreen container.
2108  *
2109  * In case the fullscreen container is of type CF_OUTPUT, this function returns
2110  * true if con is on a different workspace, as focus wouldn't be obscured by
2111  * the fullscreen container that is constrained to a different workspace.
2112  *
2113  * Note that this same logic can be applied to moving containers. If a
2114  * container can be focused under the fullscreen focus constraints, it can also
2115  * become a parent or sibling to the currently focused container.
2116  *
2117  */
con_fullscreen_permits_focusing(Con * con)2118 bool con_fullscreen_permits_focusing(Con *con) {
2119     /* No focus, no problem. */
2120     if (!focused)
2121         return true;
2122 
2123     /* Find the first fullscreen ascendent. */
2124     Con *fs = focused;
2125     while (fs && fs->fullscreen_mode == CF_NONE)
2126         fs = fs->parent;
2127 
2128     /* fs must be non-NULL since the workspace con doesn’t have CF_NONE and
2129      * there always has to be a workspace con in the hierarchy. */
2130     assert(fs != NULL);
2131     /* The most common case is we hit the workspace level. In this
2132      * situation, changing focus is also harmless. */
2133     assert(fs->fullscreen_mode != CF_NONE);
2134     if (fs->type == CT_WORKSPACE)
2135         return true;
2136 
2137     /* Allow it if the container itself is the fullscreen container. */
2138     if (con == fs)
2139         return true;
2140 
2141     /* If fullscreen is per-output, the focus being in a different workspace is
2142      * sufficient to guarantee that change won't leave fullscreen in bad shape. */
2143     if (fs->fullscreen_mode == CF_OUTPUT &&
2144         con_get_workspace(con) != con_get_workspace(fs)) {
2145         return true;
2146     }
2147 
2148     /* Allow it only if the container to be focused is contained within the
2149      * current fullscreen container. */
2150     return con_has_parent(con, fs);
2151 }
2152 
2153 /*
2154  *
2155  * Checks if the given container has an urgent child.
2156  *
2157  */
con_has_urgent_child(Con * con)2158 bool con_has_urgent_child(Con *con) {
2159     Con *child;
2160 
2161     if (con_is_leaf(con))
2162         return con->urgent;
2163 
2164     /* We are not interested in floating windows since they can only be
2165      * attached to a workspace → nodes_head instead of focus_head */
2166     TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
2167         if (con_has_urgent_child(child))
2168             return true;
2169     }
2170 
2171     return false;
2172 }
2173 
2174 /*
2175  * Make all parent containers urgent if con is urgent or clear the urgent flag
2176  * of all parent containers if there are no more urgent children left.
2177  *
2178  */
con_update_parents_urgency(Con * con)2179 void con_update_parents_urgency(Con *con) {
2180     Con *parent = con->parent;
2181 
2182     /* Urgency hints should not be set on any container higher up in the
2183      * hierarchy than the workspace level. Unfortunately, since the content
2184      * container has type == CT_CON, that’s not easy to verify in the loop
2185      * below, so we need another condition to catch that case: */
2186     if (con->type == CT_WORKSPACE)
2187         return;
2188 
2189     bool new_urgency_value = con->urgent;
2190     while (parent && parent->type != CT_WORKSPACE && parent->type != CT_DOCKAREA) {
2191         if (new_urgency_value) {
2192             parent->urgent = true;
2193         } else {
2194             /* We can only reset the urgency when the parent
2195              * has no other urgent children */
2196             if (!con_has_urgent_child(parent))
2197                 parent->urgent = false;
2198         }
2199         parent = parent->parent;
2200     }
2201 }
2202 
2203 /*
2204  * Set urgency flag to the container, all the parent containers and the workspace.
2205  *
2206  */
con_set_urgency(Con * con,bool urgent)2207 void con_set_urgency(Con *con, bool urgent) {
2208     if (urgent && focused == con) {
2209         DLOG("Ignoring urgency flag for current client\n");
2210         return;
2211     }
2212 
2213     const bool old_urgent = con->urgent;
2214 
2215     if (con->urgency_timer == NULL) {
2216         con->urgent = urgent;
2217     } else
2218         DLOG("Discarding urgency WM_HINT because timer is running\n");
2219 
2220     //CLIENT_LOG(con);
2221     if (con->window) {
2222         if (con->urgent) {
2223             gettimeofday(&con->window->urgent, NULL);
2224         } else {
2225             con->window->urgent.tv_sec = 0;
2226             con->window->urgent.tv_usec = 0;
2227         }
2228     }
2229 
2230     con_update_parents_urgency(con);
2231 
2232     Con *ws;
2233     /* Set the urgency flag on the workspace, if a workspace could be found
2234      * (for dock clients, that is not the case). */
2235     if ((ws = con_get_workspace(con)) != NULL)
2236         workspace_update_urgent_flag(ws);
2237 
2238     if (con->urgent != old_urgent) {
2239         LOG("Urgency flag changed to %d\n", con->urgent);
2240         ipc_send_window_event("urgent", con);
2241     }
2242 }
2243 
2244 /*
2245  * Create a string representing the subtree under con.
2246  *
2247  */
con_get_tree_representation(Con * con)2248 char *con_get_tree_representation(Con *con) {
2249     /* this code works as follows:
2250      *  1) create a string with the layout type (D/V/H/T/S) and an opening bracket
2251      *  2) append the tree representation of the children to the string
2252      *  3) add closing bracket
2253      *
2254      * The recursion ends when we hit a leaf, in which case we return the
2255      * class_instance of the contained window.
2256      */
2257 
2258     /* end of recursion */
2259     if (con_is_leaf(con)) {
2260         if (!con->window)
2261             return sstrdup("nowin");
2262 
2263         if (!con->window->class_instance)
2264             return sstrdup("noinstance");
2265 
2266         return sstrdup(con->window->class_instance);
2267     }
2268 
2269     char *buf;
2270     /* 1) add the Layout type to buf */
2271     if (con->layout == L_DEFAULT)
2272         buf = sstrdup("D[");
2273     else if (con->layout == L_SPLITV)
2274         buf = sstrdup("V[");
2275     else if (con->layout == L_SPLITH)
2276         buf = sstrdup("H[");
2277     else if (con->layout == L_TABBED)
2278         buf = sstrdup("T[");
2279     else if (con->layout == L_STACKED)
2280         buf = sstrdup("S[");
2281     else {
2282         ELOG("BUG: Code not updated to account for new layout type\n");
2283         assert(false);
2284     }
2285 
2286     /* 2) append representation of children */
2287     Con *child;
2288     TAILQ_FOREACH (child, &(con->nodes_head), nodes) {
2289         char *child_txt = con_get_tree_representation(child);
2290 
2291         char *tmp_buf;
2292         sasprintf(&tmp_buf, "%s%s%s", buf,
2293                   (TAILQ_FIRST(&(con->nodes_head)) == child ? "" : " "), child_txt);
2294         free(buf);
2295         buf = tmp_buf;
2296         free(child_txt);
2297     }
2298 
2299     /* 3) close the brackets */
2300     char *complete_buf;
2301     sasprintf(&complete_buf, "%s]", buf);
2302     free(buf);
2303 
2304     return complete_buf;
2305 }
2306 
2307 /**
2308  * Calculates the effective gap sizes for a container.
2309  */
calculate_effective_gaps(Con * con)2310 gaps_t calculate_effective_gaps(Con *con) {
2311     Con *workspace = con_get_workspace(con);
2312     if (workspace == NULL)
2313         return (gaps_t){0, 0, 0, 0, 0};
2314 
2315     bool one_child = con_num_visible_children(workspace) <= 1 ||
2316                      (con_num_children(workspace) == 1 &&
2317                       (TAILQ_FIRST(&(workspace->nodes_head))->layout == L_TABBED ||
2318                        TAILQ_FIRST(&(workspace->nodes_head))->layout == L_STACKED));
2319 
2320     if (config.smart_gaps == SMART_GAPS_ON && one_child)
2321         return (gaps_t){0, 0, 0, 0, 0};
2322 
2323     gaps_t gaps = {
2324         .inner = (workspace->gaps.inner + config.gaps.inner) / 2,
2325         .top = 0,
2326         .right = 0,
2327         .bottom = 0,
2328         .left = 0};
2329 
2330     if (config.smart_gaps != SMART_GAPS_INVERSE_OUTER || one_child) {
2331         gaps.top = workspace->gaps.top + config.gaps.top;
2332         gaps.right = workspace->gaps.right + config.gaps.right;
2333         gaps.bottom = workspace->gaps.bottom + config.gaps.bottom;
2334         gaps.left = workspace->gaps.left + config.gaps.left;
2335     }
2336 
2337     /* Outer gaps are added on top of inner gaps. */
2338     gaps.top += 2 * gaps.inner;
2339     gaps.right += 2 * gaps.inner;
2340     gaps.bottom += 2 * gaps.inner;
2341     gaps.left += 2 * gaps.inner;
2342 
2343     return gaps;
2344 }
2345 
2346 /*
2347  * Returns the container's title considering the current title format.
2348  *
2349  */
con_parse_title_format(Con * con)2350 i3String *con_parse_title_format(Con *con) {
2351     assert(con->title_format != NULL);
2352 
2353     i3Window *win = con->window;
2354 
2355     /* We need to ensure that we only escape the window title if pango
2356      * is used by the current font. */
2357     const bool pango_markup = font_is_pango();
2358 
2359     char *title;
2360     char *class;
2361     char *instance;
2362     char *machine;
2363     if (win == NULL) {
2364         title = pango_escape_markup(con_get_tree_representation(con));
2365         class = sstrdup("i3-frame");
2366         instance = sstrdup("i3-frame");
2367         machine = sstrdup("");
2368     } else {
2369         title = pango_escape_markup(sstrdup((win->name == NULL) ? "" : i3string_as_utf8(win->name)));
2370         class = pango_escape_markup(sstrdup((win->class_class == NULL) ? "" : win->class_class));
2371         instance = pango_escape_markup(sstrdup((win->class_instance == NULL) ? "" : win->class_instance));
2372         machine = pango_escape_markup(sstrdup((win->machine == NULL) ? "" : win->machine));
2373     }
2374 
2375     placeholder_t placeholders[] = {
2376         {.name = "%title", .value = title},
2377         {.name = "%class", .value = class},
2378         {.name = "%instance", .value = instance},
2379         {.name = "%machine", .value = machine},
2380     };
2381     const size_t num = sizeof(placeholders) / sizeof(placeholder_t);
2382 
2383     char *formatted_str = format_placeholders(con->title_format, &placeholders[0], num);
2384     i3String *formatted = i3string_from_utf8(formatted_str);
2385     i3string_set_markup(formatted, pango_markup);
2386 
2387     free(formatted_str);
2388     free(title);
2389     free(class);
2390     free(instance);
2391 
2392     return formatted;
2393 }
2394 
2395 /*
2396  * Swaps the two containers.
2397  *
2398  */
con_swap(Con * first,Con * second)2399 bool con_swap(Con *first, Con *second) {
2400     assert(first != NULL);
2401     assert(second != NULL);
2402     DLOG("Swapping containers %p / %p\n", first, second);
2403 
2404     if (first->type != CT_CON) {
2405         ELOG("Only regular containers can be swapped, but found con = %p with type = %d.\n", first, first->type);
2406         return false;
2407     }
2408 
2409     if (second->type != CT_CON) {
2410         ELOG("Only regular containers can be swapped, but found con = %p with type = %d.\n", second, second->type);
2411         return false;
2412     }
2413 
2414     if (first == second) {
2415         DLOG("Swapping container %p with itself, nothing to do.\n", first);
2416         return false;
2417     }
2418 
2419     if (con_has_parent(first, second) || con_has_parent(second, first)) {
2420         ELOG("Cannot swap containers %p and %p because they are in a parent-child relationship.\n", first, second);
2421         return false;
2422     }
2423 
2424     Con *ws1 = con_get_workspace(first);
2425     Con *ws2 = con_get_workspace(second);
2426     Con *restore_focus = NULL;
2427     if (ws1 == ws2 && ws1 == con_get_workspace(focused)) {
2428         /* Preserve focus in the current workspace. */
2429         restore_focus = focused;
2430     } else if (first == focused || con_has_parent(focused, first)) {
2431         restore_focus = second;
2432     } else if (second == focused || con_has_parent(focused, second)) {
2433         restore_focus = first;
2434     }
2435 
2436 #define SWAP_CONS_IN_TREE(headname, field)                            \
2437     do {                                                              \
2438         struct headname *head1 = &(first->parent->headname);          \
2439         struct headname *head2 = &(second->parent->headname);         \
2440         Con *first_prev = TAILQ_PREV(first, headname, field);         \
2441         Con *second_prev = TAILQ_PREV(second, headname, field);       \
2442         if (second_prev == first) {                                   \
2443             TAILQ_SWAP(first, second, head1, field);                  \
2444         } else if (first_prev == second) {                            \
2445             TAILQ_SWAP(second, first, head1, field);                  \
2446         } else {                                                      \
2447             TAILQ_REMOVE(head1, first, field);                        \
2448             TAILQ_REMOVE(head2, second, field);                       \
2449             if (second_prev == NULL) {                                \
2450                 TAILQ_INSERT_HEAD(head2, first, field);               \
2451             } else {                                                  \
2452                 TAILQ_INSERT_AFTER(head2, second_prev, first, field); \
2453             }                                                         \
2454             if (first_prev == NULL) {                                 \
2455                 TAILQ_INSERT_HEAD(head1, second, field);              \
2456             } else {                                                  \
2457                 TAILQ_INSERT_AFTER(head1, first_prev, second, field); \
2458             }                                                         \
2459         }                                                             \
2460     } while (0)
2461 
2462     SWAP_CONS_IN_TREE(nodes_head, nodes);
2463     SWAP_CONS_IN_TREE(focus_head, focused);
2464     SWAP(first->parent, second->parent, Con *);
2465 
2466     /* Floating nodes are children of CT_FLOATING_CONs, they are listed in
2467      * nodes_head and focus_head like all other containers. Thus, we don't need
2468      * to do anything special other than swapping the floating status and the
2469      * relevant rects. */
2470     SWAP(first->floating, second->floating, int);
2471     SWAP(first->rect, second->rect, Rect);
2472     SWAP(first->window_rect, second->window_rect, Rect);
2473 
2474     /* We need to copy each other's percentages to ensure that the geometry
2475      * doesn't change during the swap. */
2476     SWAP(first->percent, second->percent, double);
2477 
2478     if (restore_focus) {
2479         con_focus(restore_focus);
2480     }
2481 
2482     /* Update new parents' & workspaces' urgency. */
2483     con_set_urgency(first, first->urgent);
2484     con_set_urgency(second, second->urgent);
2485 
2486     /* Exchange fullscreen modes, can't use SWAP because we need to call the
2487      * correct functions. */
2488     fullscreen_mode_t second_fullscreen_mode = second->fullscreen_mode;
2489     if (first->fullscreen_mode == CF_NONE) {
2490         con_disable_fullscreen(second);
2491     } else {
2492         con_enable_fullscreen(second, first->fullscreen_mode);
2493     }
2494     if (second_fullscreen_mode == CF_NONE) {
2495         con_disable_fullscreen(first);
2496     } else {
2497         con_enable_fullscreen(first, second_fullscreen_mode);
2498     }
2499 
2500     /* We don't actually need this since percentages-wise we haven't changed
2501      * anything, but we'll better be safe than sorry and just make sure as we'd
2502      * otherwise crash i3. */
2503     con_fix_percent(first->parent);
2504     con_fix_percent(second->parent);
2505 
2506     FREE(first->deco_render_params);
2507     FREE(second->deco_render_params);
2508     con_force_split_parents_redraw(first);
2509     con_force_split_parents_redraw(second);
2510 
2511     return true;
2512 }
2513 
2514 /*
2515  * Returns container's rect size depending on its orientation.
2516  * i.e. its width when horizontal, its height when vertical.
2517  *
2518  */
con_rect_size_in_orientation(Con * con)2519 uint32_t con_rect_size_in_orientation(Con *con) {
2520     return (con_orientation(con) == HORIZ ? con->rect.width : con->rect.height);
2521 }
2522 
2523 /*
2524  * Merges container specific data that should move with the window (e.g. marks,
2525  * title format, and the window itself) into another container, and closes the
2526  * old container.
2527  *
2528  */
con_merge_into(Con * old,Con * new)2529 void con_merge_into(Con *old, Con *new) {
2530     new->window = old->window;
2531     old->window = NULL;
2532 
2533     if (old->title_format) {
2534         FREE(new->title_format);
2535         new->title_format = old->title_format;
2536         old->title_format = NULL;
2537     }
2538 
2539     if (old->sticky_group) {
2540         FREE(new->sticky_group);
2541         new->sticky_group = old->sticky_group;
2542         old->sticky_group = NULL;
2543     }
2544 
2545     new->sticky = old->sticky;
2546 
2547     con_set_urgency(new, old->urgent);
2548 
2549     mark_t *mark;
2550     TAILQ_FOREACH (mark, &(old->marks_head), marks) {
2551         TAILQ_INSERT_TAIL(&(new->marks_head), mark, marks);
2552         ipc_send_window_event("mark", new);
2553     }
2554     new->mark_changed = (TAILQ_FIRST(&(old->marks_head)) != NULL);
2555     TAILQ_INIT(&(old->marks_head));
2556 
2557     tree_close_internal(old, DONT_KILL_WINDOW, false);
2558 }
2559