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