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