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