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