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