]> git.sur5r.net Git - i3/i3/blob - src/tree.c
Validate matched containers for "kill" command correctly.
[i3/i3] / src / tree.c
1 #undef I3__FILE__
2 #define I3__FILE__ "tree.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * tree.c: Everything that primarily modifies the layout tree data structure.
10  *
11  */
12 #include "all.h"
13
14 struct Con *croot;
15 struct Con *focused;
16
17 struct all_cons_head all_cons = TAILQ_HEAD_INITIALIZER(all_cons);
18
19 /*
20  * Create the pseudo-output __i3. Output-independent workspaces such as
21  * __i3_scratch will live there.
22  *
23  */
24 static Con *_create___i3(void) {
25     Con *__i3 = con_new(croot, NULL);
26     FREE(__i3->name);
27     __i3->name = sstrdup("__i3");
28     __i3->type = CT_OUTPUT;
29     __i3->layout = L_OUTPUT;
30     con_fix_percent(croot);
31     x_set_name(__i3, "[i3 con] pseudo-output __i3");
32     /* For retaining the correct position/size of a scratchpad window, the
33      * dimensions of the real outputs should be multiples of the __i3
34      * pseudo-output. Ensuring that is the job of scratchpad_fix_resolution()
35      * which gets called after this function and after detecting all the
36      * outputs (or whenever an output changes). */
37     __i3->rect.width = 1280;
38     __i3->rect.height = 1024;
39
40     /* Add a content container. */
41     DLOG("adding main content container\n");
42     Con *content = con_new(NULL, NULL);
43     content->type = CT_CON;
44     FREE(content->name);
45     content->name = sstrdup("content");
46     content->layout = L_SPLITH;
47
48     x_set_name(content, "[i3 con] content __i3");
49     con_attach(content, __i3, false);
50
51     /* Attach the __i3_scratch workspace. */
52     Con *ws = con_new(NULL, NULL);
53     ws->type = CT_WORKSPACE;
54     ws->num = -1;
55     ws->name = sstrdup("__i3_scratch");
56     ws->layout = L_SPLITH;
57     con_attach(ws, content, false);
58     x_set_name(ws, "[i3 con] workspace __i3_scratch");
59     ws->fullscreen_mode = CF_OUTPUT;
60
61     return __i3;
62 }
63
64 /*
65  * Loads tree from 'path' (used for in-place restarts).
66  *
67  */
68 bool tree_restore(const char *path, xcb_get_geometry_reply_t *geometry) {
69     char *globbed = resolve_tilde(path);
70
71     if (!path_exists(globbed)) {
72         LOG("%s does not exist, not restoring tree\n", globbed);
73         free(globbed);
74         return false;
75     }
76
77     /* TODO: refactor the following */
78     croot = con_new(NULL, NULL);
79     croot->rect = (Rect){
80         geometry->x,
81         geometry->y,
82         geometry->width,
83         geometry->height};
84     focused = croot;
85
86     tree_append_json(focused, globbed, NULL);
87
88     DLOG("appended tree, using new root\n");
89     croot = TAILQ_FIRST(&(croot->nodes_head));
90     DLOG("new root = %p\n", croot);
91     Con *out = TAILQ_FIRST(&(croot->nodes_head));
92     DLOG("out = %p\n", out);
93     Con *ws = TAILQ_FIRST(&(out->nodes_head));
94     DLOG("ws = %p\n", ws);
95
96     /* For in-place restarting into v4.2, we need to make sure the new
97      * pseudo-output __i3 is present. */
98     if (strcmp(out->name, "__i3") != 0) {
99         DLOG("Adding pseudo-output __i3 during inplace restart\n");
100         Con *__i3 = _create___i3();
101         /* Ensure that it is the first output, other places in the code make
102          * that assumption. */
103         TAILQ_REMOVE(&(croot->nodes_head), __i3, nodes);
104         TAILQ_INSERT_HEAD(&(croot->nodes_head), __i3, nodes);
105     }
106
107     restore_open_placeholder_windows(croot);
108
109     return true;
110 }
111
112 /*
113  * Initializes the tree by creating the root node. The CT_OUTPUT Cons below the
114  * root node are created in randr.c for each Output.
115  *
116  */
117 void tree_init(xcb_get_geometry_reply_t *geometry) {
118     croot = con_new(NULL, NULL);
119     FREE(croot->name);
120     croot->name = "root";
121     croot->type = CT_ROOT;
122     croot->layout = L_SPLITH;
123     croot->rect = (Rect){
124         geometry->x,
125         geometry->y,
126         geometry->width,
127         geometry->height};
128
129     _create___i3();
130 }
131
132 /*
133  * Opens an empty container in the current container
134  *
135  */
136 Con *tree_open_con(Con *con, i3Window *window) {
137     if (con == NULL) {
138         /* every focusable Con has a parent (outputs have parent root) */
139         con = focused->parent;
140         /* If the parent is an output, we are on a workspace. In this case,
141          * the new container needs to be opened as a leaf of the workspace. */
142         if (con->parent->type == CT_OUTPUT && con->type != CT_DOCKAREA) {
143             con = focused;
144         }
145
146         /* If the currently focused container is a floating container, we
147          * attach the new container to the currently focused spot in its
148          * workspace. */
149         if (con->type == CT_FLOATING_CON) {
150             con = con_descend_tiling_focused(con->parent);
151             if (con->type != CT_WORKSPACE)
152                 con = con->parent;
153         }
154         DLOG("con = %p\n", con);
155     }
156
157     assert(con != NULL);
158
159     /* 3. create the container and attach it to its parent */
160     Con *new = con_new(con, window);
161     new->layout = L_SPLITH;
162
163     /* 4: re-calculate child->percent for each child */
164     con_fix_percent(con);
165
166     return new;
167 }
168
169 static bool _is_con_mapped(Con *con) {
170     Con *child;
171
172     TAILQ_FOREACH(child, &(con->nodes_head), nodes)
173     if (_is_con_mapped(child))
174         return true;
175
176     return con->mapped;
177 }
178
179 /*
180  * Closes the given container including all children.
181  * Returns true if the container was killed or false if just WM_DELETE was sent
182  * and the window is expected to kill itself.
183  *
184  * The dont_kill_parent flag is specified when the function calls itself
185  * recursively while deleting a containers children.
186  *
187  * The force_set_focus flag is specified in the case of killing a floating
188  * window: tree_close_internal() will be invoked for the CT_FLOATINGCON (the parent
189  * container) and focus should be set there.
190  *
191  */
192 bool tree_close_internal(Con *con, kill_window_t kill_window, bool dont_kill_parent, bool force_set_focus) {
193     bool was_mapped = con->mapped;
194     Con *parent = con->parent;
195
196     if (!was_mapped) {
197         /* Even if the container itself is not mapped, its children may be
198          * mapped (for example split containers don't have a mapped window on
199          * their own but usually contain mapped children). */
200         was_mapped = _is_con_mapped(con);
201     }
202
203     /* remove the urgency hint of the workspace (if set) */
204     if (con->urgent) {
205         con_set_urgency(con, false);
206         con_update_parents_urgency(con);
207         workspace_update_urgent_flag(con_get_workspace(con));
208     }
209
210     /* Get the container which is next focused */
211     Con *next = con_next_focused(con);
212     DLOG("next = %p, focused = %p\n", next, focused);
213
214     DLOG("closing %p, kill_window = %d\n", con, kill_window);
215     Con *child, *nextchild;
216     bool abort_kill = false;
217     /* We cannot use TAILQ_FOREACH because the children get deleted
218      * in their parent’s nodes_head */
219     for (child = TAILQ_FIRST(&(con->nodes_head)); child;) {
220         nextchild = TAILQ_NEXT(child, nodes);
221         DLOG("killing child=%p\n", child);
222         if (!tree_close_internal(child, kill_window, true, false))
223             abort_kill = true;
224         child = nextchild;
225     }
226
227     if (abort_kill) {
228         DLOG("One of the children could not be killed immediately (WM_DELETE sent), aborting.\n");
229         return false;
230     }
231
232     if (con->window != NULL) {
233         if (kill_window != DONT_KILL_WINDOW) {
234             x_window_kill(con->window->id, kill_window);
235             return false;
236         } else {
237             xcb_void_cookie_t cookie;
238             /* Ignore any further events by clearing the event mask,
239              * unmap the window,
240              * then reparent it to the root window. */
241             xcb_change_window_attributes(conn, con->window->id,
242                                          XCB_CW_EVENT_MASK, (uint32_t[]){XCB_NONE});
243             xcb_unmap_window(conn, con->window->id);
244             cookie = xcb_reparent_window(conn, con->window->id, root, 0, 0);
245
246             /* Ignore X11 errors for the ReparentWindow request.
247              * X11 Errors are returned when the window was already destroyed */
248             add_ignore_event(cookie.sequence, 0);
249
250             /* We are no longer handling this window, thus set WM_STATE to
251              * WM_STATE_WITHDRAWN (see ICCCM 4.1.3.1) */
252             long data[] = {XCB_ICCCM_WM_STATE_WITHDRAWN, XCB_NONE};
253             cookie = xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
254                                          con->window->id, A_WM_STATE, A_WM_STATE, 32, 2, data);
255
256             /* Remove the window from the save set. All windows in the save set
257              * will be mapped when i3 closes its connection (e.g. when
258              * restarting). This is not what we want, since some apps keep
259              * unmapped windows around and don’t expect them to suddenly be
260              * mapped. See http://bugs.i3wm.org/1617 */
261             xcb_change_save_set(conn, XCB_SET_MODE_DELETE, con->window->id);
262
263             /* Ignore X11 errors for the ReparentWindow request.
264              * X11 Errors are returned when the window was already destroyed */
265             add_ignore_event(cookie.sequence, 0);
266         }
267         ipc_send_window_event("close", con);
268         FREE(con->window->class_class);
269         FREE(con->window->class_instance);
270         i3string_free(con->window->name);
271         FREE(con->window->ran_assignments);
272         FREE(con->window);
273     }
274
275     Con *ws = con_get_workspace(con);
276
277     /* Figure out which container to focus next before detaching 'con'. */
278     if (con_is_floating(con)) {
279         if (con == focused) {
280             DLOG("This is the focused container, i need to find another one to focus. I start looking at ws = %p\n", ws);
281             next = con_next_focused(parent);
282
283             dont_kill_parent = true;
284             DLOG("Alright, focusing %p\n", next);
285         } else {
286             next = NULL;
287         }
288     }
289
290     /* Detach the container so that it will not be rendered anymore. */
291     con_detach(con);
292
293     /* disable urgency timer, if needed */
294     if (con->urgency_timer != NULL) {
295         DLOG("Removing urgency timer of con %p\n", con);
296         workspace_update_urgent_flag(ws);
297         ev_timer_stop(main_loop, con->urgency_timer);
298         FREE(con->urgency_timer);
299     }
300
301     if (con->type != CT_FLOATING_CON) {
302         /* If the container is *not* floating, we might need to re-distribute
303          * percentage values for the resized containers. */
304         con_fix_percent(parent);
305     }
306
307     /* Render the tree so that the surrounding containers take up the space
308      * which 'con' does no longer occupy. If we don’t render here, there will
309      * be a gap in our containers and that could trigger an EnterNotify for an
310      * underlying container, see ticket #660.
311      *
312      * Rendering has to be avoided when dont_kill_parent is set (when
313      * tree_close_internal calls itself recursively) because the tree is in a
314      * non-renderable state during that time. */
315     if (!dont_kill_parent)
316         tree_render();
317
318     /* kill the X11 part of this container */
319     x_con_kill(con);
320
321     if (con_is_floating(con)) {
322         DLOG("Container was floating, killing floating container\n");
323         tree_close_internal(parent, DONT_KILL_WINDOW, false, (con == focused));
324         DLOG("parent container killed\n");
325     }
326
327     free(con->name);
328     FREE(con->deco_render_params);
329     TAILQ_REMOVE(&all_cons, con, all_cons);
330     free(con);
331
332     /* in the case of floating windows, we already focused another container
333      * when closing the parent, so we can exit now. */
334     if (!next) {
335         DLOG("No next container, i will just exit now\n");
336         return true;
337     }
338
339     if (was_mapped || con == focused) {
340         if ((kill_window != DONT_KILL_WINDOW) || !dont_kill_parent || con == focused) {
341             DLOG("focusing %p / %s\n", next, next->name);
342             if (next->type == CT_DOCKAREA) {
343                 /* Instead of focusing the dockarea, we need to restore focus to the workspace */
344                 con_focus(con_descend_focused(output_get_content(next->parent)));
345             } else {
346                 if (!force_set_focus && con != focused)
347                     DLOG("not changing focus, the container was not focused before\n");
348                 else
349                     con_focus(next);
350             }
351         } else {
352             DLOG("not focusing because we're not killing anybody\n");
353         }
354     } else {
355         DLOG("not focusing, was not mapped\n");
356     }
357
358     /* check if the parent container is empty now and close it */
359     if (!dont_kill_parent)
360         CALL(parent, on_remove_child);
361
362     return true;
363 }
364
365 /*
366  * Splits (horizontally or vertically) the given container by creating a new
367  * container which contains the old one and the future ones.
368  *
369  */
370 void tree_split(Con *con, orientation_t orientation) {
371     if (con_is_floating(con)) {
372         DLOG("Floating containers can't be split.\n");
373         return;
374     }
375
376     if (con->type == CT_WORKSPACE) {
377         if (con_num_children(con) < 2) {
378             DLOG("Just changing orientation of workspace\n");
379             con->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
380             return;
381         } else {
382             /* if there is more than one container on the workspace
383              * move them into a new container and handle this instead */
384             con = workspace_encapsulate(con);
385         }
386     }
387
388     Con *parent = con->parent;
389
390     /* Force re-rendering to make the indicator border visible. */
391     con_force_split_parents_redraw(con);
392
393     /* if we are in a container whose parent contains only one
394      * child (its split functionality is unused so far), we just change the
395      * orientation (more intuitive than splitting again) */
396     if (con_num_children(parent) == 1 &&
397         (parent->layout == L_SPLITH ||
398          parent->layout == L_SPLITV)) {
399         parent->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
400         DLOG("Just changing orientation of existing container\n");
401         return;
402     }
403
404     DLOG("Splitting in orientation %d\n", orientation);
405
406     /* 2: replace it with a new Con */
407     Con *new = con_new(NULL, NULL);
408     TAILQ_REPLACE(&(parent->nodes_head), con, new, nodes);
409     TAILQ_REPLACE(&(parent->focus_head), con, new, focused);
410     new->parent = parent;
411     new->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
412
413     /* 3: swap 'percent' (resize factor) */
414     new->percent = con->percent;
415     con->percent = 0.0;
416
417     /* 4: add it as a child to the new Con */
418     con_attach(con, new, false);
419 }
420
421 /*
422  * Moves focus one level up. Returns true if focus changed.
423  *
424  */
425 bool level_up(void) {
426     /* Skip over floating containers and go directly to the grandparent
427      * (which should always be a workspace) */
428     if (focused->parent->type == CT_FLOATING_CON) {
429         con_focus(focused->parent->parent);
430         return true;
431     }
432
433     /* We can focus up to the workspace, but not any higher in the tree */
434     if ((focused->parent->type != CT_CON &&
435          focused->parent->type != CT_WORKSPACE) ||
436         focused->type == CT_WORKSPACE) {
437         ELOG("'focus parent': Focus is already on the workspace, cannot go higher than that.\n");
438         return false;
439     }
440     con_focus(focused->parent);
441     return true;
442 }
443
444 /*
445  * Moves focus one level down. Returns true if focus changed.
446  *
447  */
448 bool level_down(void) {
449     /* Go down the focus stack of the current node */
450     Con *next = TAILQ_FIRST(&(focused->focus_head));
451     if (next == TAILQ_END(&(focused->focus_head))) {
452         DLOG("cannot go down\n");
453         return false;
454     } else if (next->type == CT_FLOATING_CON) {
455         /* Floating cons shouldn't be directly focused; try immediately
456          * going to the grandchild of the focused con. */
457         Con *child = TAILQ_FIRST(&(next->focus_head));
458         if (child == TAILQ_END(&(next->focus_head))) {
459             DLOG("cannot go down\n");
460             return false;
461         } else
462             next = TAILQ_FIRST(&(next->focus_head));
463     }
464
465     con_focus(next);
466     return true;
467 }
468
469 static void mark_unmapped(Con *con) {
470     Con *current;
471
472     con->mapped = false;
473     TAILQ_FOREACH(current, &(con->nodes_head), nodes)
474     mark_unmapped(current);
475     if (con->type == CT_WORKSPACE) {
476         /* We need to call mark_unmapped on floating nodes aswell since we can
477          * make containers floating. */
478         TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
479         mark_unmapped(current);
480     }
481 }
482
483 /*
484  * Renders the tree, that is rendering all outputs using render_con() and
485  * pushing the changes to X11 using x_push_changes().
486  *
487  */
488 void tree_render(void) {
489     if (croot == NULL)
490         return;
491
492     DLOG("-- BEGIN RENDERING --\n");
493     /* Reset map state for all nodes in tree */
494     /* TODO: a nicer method to walk all nodes would be good, maybe? */
495     mark_unmapped(croot);
496     croot->mapped = true;
497
498     render_con(croot, false);
499
500     x_push_changes(croot);
501     DLOG("-- END RENDERING --\n");
502 }
503
504 /*
505  * Recursive function to walk the tree until a con can be found to focus.
506  *
507  */
508 static bool _tree_next(Con *con, char way, orientation_t orientation, bool wrap) {
509     /* When dealing with fullscreen containers, it's necessary to go up to the
510      * workspace level, because 'focus $dir' will start at the con's real
511      * position in the tree, and it may not be possible to get to the edge
512      * normally due to fullscreen focusing restrictions. */
513     if (con->fullscreen_mode == CF_OUTPUT && con->type != CT_WORKSPACE)
514         con = con_get_workspace(con);
515
516     /* Stop recursing at workspaces after attempting to switch to next
517      * workspace if possible. */
518     if (con->type == CT_WORKSPACE) {
519         if (con_get_fullscreen_con(con, CF_GLOBAL)) {
520             DLOG("Cannot change workspace while in global fullscreen mode.\n");
521             return false;
522         }
523         Output *current_output = get_output_containing(con->rect.x, con->rect.y);
524         Output *next_output;
525
526         if (!current_output)
527             return false;
528         DLOG("Current output is %s\n", current_output->name);
529
530         /* Try to find next output */
531         direction_t direction;
532         if (way == 'n' && orientation == HORIZ)
533             direction = D_RIGHT;
534         else if (way == 'p' && orientation == HORIZ)
535             direction = D_LEFT;
536         else if (way == 'n' && orientation == VERT)
537             direction = D_DOWN;
538         else if (way == 'p' && orientation == VERT)
539             direction = D_UP;
540         else
541             return false;
542
543         next_output = get_output_next(direction, current_output, CLOSEST_OUTPUT);
544         if (!next_output)
545             return false;
546         DLOG("Next output is %s\n", next_output->name);
547
548         /* Find visible workspace on next output */
549         Con *workspace = NULL;
550         GREP_FIRST(workspace, output_get_content(next_output->con), workspace_is_visible(child));
551
552         /* Show next workspace and focus appropriate container if possible. */
553         if (!workspace)
554             return false;
555
556         workspace_show(workspace);
557
558         /* If a workspace has an active fullscreen container, one of its
559          * children should always be focused. The above workspace_show()
560          * should be adequate for that, so return. */
561         if (con_get_fullscreen_con(workspace, CF_OUTPUT))
562             return true;
563
564         Con *focus = con_descend_direction(workspace, direction);
565
566         /* special case: if there was no tiling con to focus and the workspace
567          * has a floating con in the focus stack, focus the top of the focus
568          * stack (which may be floating) */
569         if (focus == workspace)
570             focus = con_descend_focused(workspace);
571
572         if (focus) {
573             con_focus(focus);
574             x_set_warp_to(&(focus->rect));
575         }
576         return true;
577     }
578
579     Con *parent = con->parent;
580
581     if (con->type == CT_FLOATING_CON) {
582         if (orientation != HORIZ)
583             return false;
584
585         /* left/right focuses the previous/next floating container */
586         Con *next;
587         if (way == 'n')
588             next = TAILQ_NEXT(con, floating_windows);
589         else
590             next = TAILQ_PREV(con, floating_head, floating_windows);
591
592         /* If there is no next/previous container, wrap */
593         if (!next) {
594             if (way == 'n')
595                 next = TAILQ_FIRST(&(parent->floating_head));
596             else
597                 next = TAILQ_LAST(&(parent->floating_head), floating_head);
598         }
599
600         /* Still no next/previous container? bail out */
601         if (!next)
602             return false;
603
604         /* Raise the floating window on top of other windows preserving
605          * relative stack order */
606         while (TAILQ_LAST(&(parent->floating_head), floating_head) != next) {
607             Con *last = TAILQ_LAST(&(parent->floating_head), floating_head);
608             TAILQ_REMOVE(&(parent->floating_head), last, floating_windows);
609             TAILQ_INSERT_HEAD(&(parent->floating_head), last, floating_windows);
610         }
611
612         con_focus(con_descend_focused(next));
613         return true;
614     }
615
616     /* If the orientation does not match or there is no other con to focus, we
617      * need to go higher in the hierarchy */
618     if (con_orientation(parent) != orientation ||
619         con_num_children(parent) == 1)
620         return _tree_next(parent, way, orientation, wrap);
621
622     Con *current = TAILQ_FIRST(&(parent->focus_head));
623     /* TODO: when can the following happen (except for floating windows, which
624      * are handled above)? */
625     if (TAILQ_EMPTY(&(parent->nodes_head))) {
626         DLOG("nothing to focus\n");
627         return false;
628     }
629
630     Con *next;
631     if (way == 'n')
632         next = TAILQ_NEXT(current, nodes);
633     else
634         next = TAILQ_PREV(current, nodes_head, nodes);
635
636     if (!next) {
637         if (!config.force_focus_wrapping) {
638             /* If there is no next/previous container, we check if we can focus one
639              * when going higher (without wrapping, though). If so, we are done, if
640              * not, we wrap */
641             if (_tree_next(parent, way, orientation, false))
642                 return true;
643
644             if (!wrap)
645                 return false;
646         }
647
648         if (way == 'n')
649             next = TAILQ_FIRST(&(parent->nodes_head));
650         else
651             next = TAILQ_LAST(&(parent->nodes_head), nodes_head);
652     }
653
654     /* Don't violate fullscreen focus restrictions. */
655     if (!con_fullscreen_permits_focusing(next))
656         return false;
657
658     /* 3: focus choice comes in here. at the moment we will go down
659      * until we find a window */
660     /* TODO: check for window, atm we only go down as far as possible */
661     con_focus(con_descend_focused(next));
662     return true;
663 }
664
665 /*
666  * Changes focus in the given way (next/previous) and given orientation
667  * (horizontal/vertical).
668  *
669  */
670 void tree_next(char way, orientation_t orientation) {
671     _tree_next(focused, way, orientation, true);
672 }
673
674 /*
675  * tree_flatten() removes pairs of redundant split containers, e.g.:
676  *       [workspace, horizontal]
677  *   [v-split]           [child3]
678  *   [h-split]
679  * [child1] [child2]
680  * In this example, the v-split and h-split container are redundant.
681  * Such a situation can be created by moving containers in a direction which is
682  * not the orientation of their parent container. i3 needs to create a new
683  * split container then and if you move containers this way multiple times,
684  * redundant chains of split-containers can be the result.
685  *
686  */
687 void tree_flatten(Con *con) {
688     Con *current, *child, *parent = con->parent;
689     DLOG("Checking if I can flatten con = %p / %s\n", con, con->name);
690
691     /* We only consider normal containers without windows */
692     if (con->type != CT_CON ||
693         parent->layout == L_OUTPUT || /* con == "content" */
694         con->window != NULL)
695         goto recurse;
696
697     /* Ensure it got only one child */
698     child = TAILQ_FIRST(&(con->nodes_head));
699     if (child == NULL || TAILQ_NEXT(child, nodes) != NULL)
700         goto recurse;
701
702     DLOG("child = %p, con = %p, parent = %p\n", child, con, parent);
703
704     /* The child must have a different orientation than the con but the same as
705      * the con’s parent to be redundant */
706     if (!con_is_split(con) ||
707         !con_is_split(child) ||
708         (con->layout != L_SPLITH && con->layout != L_SPLITV) ||
709         (child->layout != L_SPLITH && child->layout != L_SPLITV) ||
710         con_orientation(con) == con_orientation(child) ||
711         con_orientation(child) != con_orientation(parent))
712         goto recurse;
713
714     DLOG("Alright, I have to flatten this situation now. Stay calm.\n");
715     /* 1: save focus */
716     Con *focus_next = TAILQ_FIRST(&(child->focus_head));
717
718     DLOG("detaching...\n");
719     /* 2: re-attach the children to the parent before con */
720     while (!TAILQ_EMPTY(&(child->nodes_head))) {
721         current = TAILQ_FIRST(&(child->nodes_head));
722         DLOG("detaching current=%p / %s\n", current, current->name);
723         con_detach(current);
724         DLOG("re-attaching\n");
725         /* We don’t use con_attach() here because for a CT_CON, the special
726          * case handling of con_attach() does not trigger. So all it would do
727          * is calling TAILQ_INSERT_AFTER, but with the wrong container. So we
728          * directly use the TAILQ macros. */
729         current->parent = parent;
730         TAILQ_INSERT_BEFORE(con, current, nodes);
731         DLOG("attaching to focus list\n");
732         TAILQ_INSERT_TAIL(&(parent->focus_head), current, focused);
733         current->percent = con->percent;
734     }
735     DLOG("re-attached all\n");
736
737     /* 3: restore focus, if con was focused */
738     if (focus_next != NULL &&
739         TAILQ_FIRST(&(parent->focus_head)) == con) {
740         DLOG("restoring focus to focus_next=%p\n", focus_next);
741         TAILQ_REMOVE(&(parent->focus_head), focus_next, focused);
742         TAILQ_INSERT_HEAD(&(parent->focus_head), focus_next, focused);
743         DLOG("restored focus.\n");
744     }
745
746     /* 4: close the redundant cons */
747     DLOG("closing redundant cons\n");
748     tree_close_internal(con, DONT_KILL_WINDOW, true, false);
749
750     /* Well, we got to abort the recursion here because we destroyed the
751      * container. However, if tree_flatten() is called sufficiently often,
752      * there can’t be the situation of having two pairs of redundant containers
753      * at once. Therefore, we can safely abort the recursion on this level
754      * after flattening. */
755     return;
756
757 recurse:
758     /* We cannot use normal foreach here because tree_flatten might close the
759      * current container. */
760     current = TAILQ_FIRST(&(con->nodes_head));
761     while (current != NULL) {
762         Con *next = TAILQ_NEXT(current, nodes);
763         tree_flatten(current);
764         current = next;
765     }
766
767     current = TAILQ_FIRST(&(con->floating_head));
768     while (current != NULL) {
769         Con *next = TAILQ_NEXT(current, floating_windows);
770         tree_flatten(current);
771         current = next;
772     }
773 }