]> git.sur5r.net Git - i3/i3/blob - src/tree.c
82a4756ca2fb9d95543c12537ee941a83e2e12ce
[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     while (!TAILQ_EMPTY(&(con->marks_head))) {
333         mark_t *mark = TAILQ_FIRST(&(con->marks_head));
334         TAILQ_REMOVE(&(con->marks_head), mark, marks);
335         FREE(mark->name);
336         FREE(mark);
337     }
338     free(con);
339
340     /* in the case of floating windows, we already focused another container
341      * when closing the parent, so we can exit now. */
342     if (!next) {
343         DLOG("No next container, i will just exit now\n");
344         return true;
345     }
346
347     if (was_mapped || con == focused) {
348         if ((kill_window != DONT_KILL_WINDOW) || !dont_kill_parent || con == focused) {
349             DLOG("focusing %p / %s\n", next, next->name);
350             if (next->type == CT_DOCKAREA) {
351                 /* Instead of focusing the dockarea, we need to restore focus to the workspace */
352                 con_focus(con_descend_focused(output_get_content(next->parent)));
353             } else {
354                 if (!force_set_focus && con != focused)
355                     DLOG("not changing focus, the container was not focused before\n");
356                 else
357                     con_focus(next);
358             }
359         } else {
360             DLOG("not focusing because we're not killing anybody\n");
361         }
362     } else {
363         DLOG("not focusing, was not mapped\n");
364     }
365
366     /* check if the parent container is empty now and close it */
367     if (!dont_kill_parent)
368         CALL(parent, on_remove_child);
369
370     return true;
371 }
372
373 /*
374  * Splits (horizontally or vertically) the given container by creating a new
375  * container which contains the old one and the future ones.
376  *
377  */
378 void tree_split(Con *con, orientation_t orientation) {
379     if (con_is_floating(con)) {
380         DLOG("Floating containers can't be split.\n");
381         return;
382     }
383
384     if (con->type == CT_WORKSPACE) {
385         if (con_num_children(con) < 2) {
386             if (con_num_children(con) == 0) {
387                 DLOG("Changing workspace_layout to L_DEFAULT\n");
388                 con->workspace_layout = L_DEFAULT;
389             }
390             DLOG("Changing orientation of workspace\n");
391             con->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
392             return;
393         } else {
394             /* if there is more than one container on the workspace
395              * move them into a new container and handle this instead */
396             con = workspace_encapsulate(con);
397         }
398     }
399
400     Con *parent = con->parent;
401
402     /* Force re-rendering to make the indicator border visible. */
403     con_force_split_parents_redraw(con);
404
405     /* if we are in a container whose parent contains only one
406      * child (its split functionality is unused so far), we just change the
407      * orientation (more intuitive than splitting again) */
408     if (con_num_children(parent) == 1 &&
409         (parent->layout == L_SPLITH ||
410          parent->layout == L_SPLITV)) {
411         parent->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
412         DLOG("Just changing orientation of existing container\n");
413         return;
414     }
415
416     DLOG("Splitting in orientation %d\n", orientation);
417
418     /* 2: replace it with a new Con */
419     Con *new = con_new(NULL, NULL);
420     TAILQ_REPLACE(&(parent->nodes_head), con, new, nodes);
421     TAILQ_REPLACE(&(parent->focus_head), con, new, focused);
422     new->parent = parent;
423     new->layout = (orientation == HORIZ) ? L_SPLITH : L_SPLITV;
424
425     /* 3: swap 'percent' (resize factor) */
426     new->percent = con->percent;
427     con->percent = 0.0;
428
429     /* 4: add it as a child to the new Con */
430     con_attach(con, new, false);
431 }
432
433 /*
434  * Moves focus one level up. Returns true if focus changed.
435  *
436  */
437 bool level_up(void) {
438     /* Skip over floating containers and go directly to the grandparent
439      * (which should always be a workspace) */
440     if (focused->parent->type == CT_FLOATING_CON) {
441         con_focus(focused->parent->parent);
442         return true;
443     }
444
445     /* We can focus up to the workspace, but not any higher in the tree */
446     if ((focused->parent->type != CT_CON &&
447          focused->parent->type != CT_WORKSPACE) ||
448         focused->type == CT_WORKSPACE) {
449         ELOG("'focus parent': Focus is already on the workspace, cannot go higher than that.\n");
450         return false;
451     }
452     con_focus(focused->parent);
453     return true;
454 }
455
456 /*
457  * Moves focus one level down. Returns true if focus changed.
458  *
459  */
460 bool level_down(void) {
461     /* Go down the focus stack of the current node */
462     Con *next = TAILQ_FIRST(&(focused->focus_head));
463     if (next == TAILQ_END(&(focused->focus_head))) {
464         DLOG("cannot go down\n");
465         return false;
466     } else if (next->type == CT_FLOATING_CON) {
467         /* Floating cons shouldn't be directly focused; try immediately
468          * going to the grandchild of the focused con. */
469         Con *child = TAILQ_FIRST(&(next->focus_head));
470         if (child == TAILQ_END(&(next->focus_head))) {
471             DLOG("cannot go down\n");
472             return false;
473         } else
474             next = TAILQ_FIRST(&(next->focus_head));
475     }
476
477     con_focus(next);
478     return true;
479 }
480
481 static void mark_unmapped(Con *con) {
482     Con *current;
483
484     con->mapped = false;
485     TAILQ_FOREACH(current, &(con->nodes_head), nodes)
486     mark_unmapped(current);
487     if (con->type == CT_WORKSPACE) {
488         /* We need to call mark_unmapped on floating nodes as well since we can
489          * make containers floating. */
490         TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
491         mark_unmapped(current);
492     }
493 }
494
495 /*
496  * Renders the tree, that is rendering all outputs using render_con() and
497  * pushing the changes to X11 using x_push_changes().
498  *
499  */
500 void tree_render(void) {
501     if (croot == NULL)
502         return;
503
504     DLOG("-- BEGIN RENDERING --\n");
505     /* Reset map state for all nodes in tree */
506     /* TODO: a nicer method to walk all nodes would be good, maybe? */
507     mark_unmapped(croot);
508     croot->mapped = true;
509
510     render_con(croot, false);
511
512     x_push_changes(croot);
513     DLOG("-- END RENDERING --\n");
514 }
515
516 /*
517  * Recursive function to walk the tree until a con can be found to focus.
518  *
519  */
520 static bool _tree_next(Con *con, char way, orientation_t orientation, bool wrap) {
521     /* When dealing with fullscreen containers, it's necessary to go up to the
522      * workspace level, because 'focus $dir' will start at the con's real
523      * position in the tree, and it may not be possible to get to the edge
524      * normally due to fullscreen focusing restrictions. */
525     if (con->fullscreen_mode == CF_OUTPUT && con->type != CT_WORKSPACE)
526         con = con_get_workspace(con);
527
528     /* Stop recursing at workspaces after attempting to switch to next
529      * workspace if possible. */
530     if (con->type == CT_WORKSPACE) {
531         if (con_get_fullscreen_con(con, CF_GLOBAL)) {
532             DLOG("Cannot change workspace while in global fullscreen mode.\n");
533             return false;
534         }
535         Output *current_output = get_output_containing(con->rect.x, con->rect.y);
536         Output *next_output;
537
538         if (!current_output)
539             return false;
540         DLOG("Current output is %s\n", output_primary_name(current_output));
541
542         /* Try to find next output */
543         direction_t direction;
544         if (way == 'n' && orientation == HORIZ)
545             direction = D_RIGHT;
546         else if (way == 'p' && orientation == HORIZ)
547             direction = D_LEFT;
548         else if (way == 'n' && orientation == VERT)
549             direction = D_DOWN;
550         else if (way == 'p' && orientation == VERT)
551             direction = D_UP;
552         else
553             return false;
554
555         next_output = get_output_next(direction, current_output, CLOSEST_OUTPUT);
556         if (!next_output)
557             return false;
558         DLOG("Next output is %s\n", output_primary_name(next_output));
559
560         /* Find visible workspace on next output */
561         Con *workspace = NULL;
562         GREP_FIRST(workspace, output_get_content(next_output->con), workspace_is_visible(child));
563
564         /* Show next workspace and focus appropriate container if possible. */
565         if (!workspace)
566             return false;
567
568         workspace_show(workspace);
569
570         /* If a workspace has an active fullscreen container, one of its
571          * children should always be focused. The above workspace_show()
572          * should be adequate for that, so return. */
573         if (con_get_fullscreen_con(workspace, CF_OUTPUT))
574             return true;
575
576         Con *focus = con_descend_direction(workspace, direction);
577
578         /* special case: if there was no tiling con to focus and the workspace
579          * has a floating con in the focus stack, focus the top of the focus
580          * stack (which may be floating) */
581         if (focus == workspace)
582             focus = con_descend_focused(workspace);
583
584         if (focus) {
585             con_focus(focus);
586             x_set_warp_to(&(focus->rect));
587         }
588         return true;
589     }
590
591     Con *parent = con->parent;
592
593     if (con->type == CT_FLOATING_CON) {
594         if (orientation != HORIZ)
595             return false;
596
597         /* left/right focuses the previous/next floating container */
598         Con *next;
599         if (way == 'n')
600             next = TAILQ_NEXT(con, floating_windows);
601         else
602             next = TAILQ_PREV(con, floating_head, floating_windows);
603
604         /* If there is no next/previous container, wrap */
605         if (!next) {
606             if (way == 'n')
607                 next = TAILQ_FIRST(&(parent->floating_head));
608             else
609                 next = TAILQ_LAST(&(parent->floating_head), floating_head);
610         }
611
612         /* Still no next/previous container? bail out */
613         if (!next)
614             return false;
615
616         /* Raise the floating window on top of other windows preserving
617          * relative stack order */
618         while (TAILQ_LAST(&(parent->floating_head), floating_head) != next) {
619             Con *last = TAILQ_LAST(&(parent->floating_head), floating_head);
620             TAILQ_REMOVE(&(parent->floating_head), last, floating_windows);
621             TAILQ_INSERT_HEAD(&(parent->floating_head), last, floating_windows);
622         }
623
624         con_focus(con_descend_focused(next));
625         return true;
626     }
627
628     /* If the orientation does not match or there is no other con to focus, we
629      * need to go higher in the hierarchy */
630     if (con_orientation(parent) != orientation ||
631         con_num_children(parent) == 1)
632         return _tree_next(parent, way, orientation, wrap);
633
634     Con *current = TAILQ_FIRST(&(parent->focus_head));
635     /* TODO: when can the following happen (except for floating windows, which
636      * are handled above)? */
637     if (TAILQ_EMPTY(&(parent->nodes_head))) {
638         DLOG("nothing to focus\n");
639         return false;
640     }
641
642     Con *next;
643     if (way == 'n')
644         next = TAILQ_NEXT(current, nodes);
645     else
646         next = TAILQ_PREV(current, nodes_head, nodes);
647
648     if (!next) {
649         if (!config.force_focus_wrapping) {
650             /* If there is no next/previous container, we check if we can focus one
651              * when going higher (without wrapping, though). If so, we are done, if
652              * not, we wrap */
653             if (_tree_next(parent, way, orientation, false))
654                 return true;
655
656             if (!wrap)
657                 return false;
658         }
659
660         if (way == 'n')
661             next = TAILQ_FIRST(&(parent->nodes_head));
662         else
663             next = TAILQ_LAST(&(parent->nodes_head), nodes_head);
664     }
665
666     /* Don't violate fullscreen focus restrictions. */
667     if (!con_fullscreen_permits_focusing(next))
668         return false;
669
670     /* 3: focus choice comes in here. at the moment we will go down
671      * until we find a window */
672     /* TODO: check for window, atm we only go down as far as possible */
673     con_focus(con_descend_focused(next));
674     return true;
675 }
676
677 /*
678  * Changes focus in the given way (next/previous) and given orientation
679  * (horizontal/vertical).
680  *
681  */
682 void tree_next(char way, orientation_t orientation) {
683     _tree_next(focused, way, orientation, true);
684 }
685
686 /*
687  * tree_flatten() removes pairs of redundant split containers, e.g.:
688  *       [workspace, horizontal]
689  *   [v-split]           [child3]
690  *   [h-split]
691  * [child1] [child2]
692  * In this example, the v-split and h-split container are redundant.
693  * Such a situation can be created by moving containers in a direction which is
694  * not the orientation of their parent container. i3 needs to create a new
695  * split container then and if you move containers this way multiple times,
696  * redundant chains of split-containers can be the result.
697  *
698  */
699 void tree_flatten(Con *con) {
700     Con *current, *child, *parent = con->parent;
701     DLOG("Checking if I can flatten con = %p / %s\n", con, con->name);
702
703     /* We only consider normal containers without windows */
704     if (con->type != CT_CON ||
705         parent->layout == L_OUTPUT || /* con == "content" */
706         con->window != NULL)
707         goto recurse;
708
709     /* Ensure it got only one child */
710     child = TAILQ_FIRST(&(con->nodes_head));
711     if (child == NULL || TAILQ_NEXT(child, nodes) != NULL)
712         goto recurse;
713
714     DLOG("child = %p, con = %p, parent = %p\n", child, con, parent);
715
716     /* The child must have a different orientation than the con but the same as
717      * the con’s parent to be redundant */
718     if (!con_is_split(con) ||
719         !con_is_split(child) ||
720         (con->layout != L_SPLITH && con->layout != L_SPLITV) ||
721         (child->layout != L_SPLITH && child->layout != L_SPLITV) ||
722         con_orientation(con) == con_orientation(child) ||
723         con_orientation(child) != con_orientation(parent))
724         goto recurse;
725
726     DLOG("Alright, I have to flatten this situation now. Stay calm.\n");
727     /* 1: save focus */
728     Con *focus_next = TAILQ_FIRST(&(child->focus_head));
729
730     DLOG("detaching...\n");
731     /* 2: re-attach the children to the parent before con */
732     while (!TAILQ_EMPTY(&(child->nodes_head))) {
733         current = TAILQ_FIRST(&(child->nodes_head));
734         DLOG("detaching current=%p / %s\n", current, current->name);
735         con_detach(current);
736         DLOG("re-attaching\n");
737         /* We don’t use con_attach() here because for a CT_CON, the special
738          * case handling of con_attach() does not trigger. So all it would do
739          * is calling TAILQ_INSERT_AFTER, but with the wrong container. So we
740          * directly use the TAILQ macros. */
741         current->parent = parent;
742         TAILQ_INSERT_BEFORE(con, current, nodes);
743         DLOG("attaching to focus list\n");
744         TAILQ_INSERT_TAIL(&(parent->focus_head), current, focused);
745         current->percent = con->percent;
746     }
747     DLOG("re-attached all\n");
748
749     /* 3: restore focus, if con was focused */
750     if (focus_next != NULL &&
751         TAILQ_FIRST(&(parent->focus_head)) == con) {
752         DLOG("restoring focus to focus_next=%p\n", focus_next);
753         TAILQ_REMOVE(&(parent->focus_head), focus_next, focused);
754         TAILQ_INSERT_HEAD(&(parent->focus_head), focus_next, focused);
755         DLOG("restored focus.\n");
756     }
757
758     /* 4: close the redundant cons */
759     DLOG("closing redundant cons\n");
760     tree_close_internal(con, DONT_KILL_WINDOW, true, false);
761
762     /* Well, we got to abort the recursion here because we destroyed the
763      * container. However, if tree_flatten() is called sufficiently often,
764      * there can’t be the situation of having two pairs of redundant containers
765      * at once. Therefore, we can safely abort the recursion on this level
766      * after flattening. */
767     return;
768
769 recurse:
770     /* We cannot use normal foreach here because tree_flatten might close the
771      * current container. */
772     current = TAILQ_FIRST(&(con->nodes_head));
773     while (current != NULL) {
774         Con *next = TAILQ_NEXT(current, nodes);
775         tree_flatten(current);
776         current = next;
777     }
778
779     current = TAILQ_FIRST(&(con->floating_head));
780     while (current != NULL) {
781         Con *next = TAILQ_NEXT(current, floating_windows);
782         tree_flatten(current);
783         current = next;
784     }
785 }