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