]> git.sur5r.net Git - i3/i3/blob - src/con.c
Merge branch 'master' into next
[i3/i3] / src / con.c
1 #undef I3__FILE__
2 #define I3__FILE__ "con.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  * con.c: Functions which deal with containers directly (creating containers,
10  *        searching containers, getting specific properties from containers,
11  *        …).
12  *
13  */
14 #include "all.h"
15
16 char *colors[] = {
17     "#ff0000",
18     "#00FF00",
19     "#0000FF",
20     "#ff00ff",
21     "#00ffff",
22     "#ffff00",
23     "#aa0000",
24     "#00aa00",
25     "#0000aa",
26     "#aa00aa"
27 };
28
29 static void con_on_remove_child(Con *con);
30
31 /*
32  * Create a new container (and attach it to the given parent, if not NULL).
33  * This function initializes the data structures and creates the appropriate
34  * X11 IDs using x_con_init().
35  *
36  */
37 Con *con_new(Con *parent, i3Window *window) {
38     Con *new = scalloc(sizeof(Con));
39     new->on_remove_child = con_on_remove_child;
40     TAILQ_INSERT_TAIL(&all_cons, new, all_cons);
41     new->type = CT_CON;
42     new->window = window;
43     new->border_style = config.default_border;
44     static int cnt = 0;
45     DLOG("opening window %d\n", cnt);
46
47     /* TODO: remove window coloring after test-phase */
48     DLOG("color %s\n", colors[cnt]);
49     new->name = strdup(colors[cnt]);
50     //uint32_t cp = get_colorpixel(colors[cnt]);
51     cnt++;
52     if ((cnt % (sizeof(colors) / sizeof(char*))) == 0)
53         cnt = 0;
54     if (window)
55         x_con_init(new, window->depth);
56     else
57         x_con_init(new, XCB_COPY_FROM_PARENT);
58
59     TAILQ_INIT(&(new->floating_head));
60     TAILQ_INIT(&(new->nodes_head));
61     TAILQ_INIT(&(new->focus_head));
62     TAILQ_INIT(&(new->swallow_head));
63
64     if (parent != NULL)
65         con_attach(new, parent, false);
66
67     return new;
68 }
69
70 /*
71  * Attaches the given container to the given parent. This happens when moving
72  * a container or when inserting a new container at a specific place in the
73  * tree.
74  *
75  * ignore_focus is to just insert the Con at the end (useful when creating a
76  * new split container *around* some containers, that is, detaching and
77  * attaching them in order without wanting to mess with the focus in between).
78  *
79  */
80 void con_attach(Con *con, Con *parent, bool ignore_focus) {
81     con->parent = parent;
82     Con *loop;
83     Con *current = NULL;
84     struct nodes_head *nodes_head = &(parent->nodes_head);
85     struct focus_head *focus_head = &(parent->focus_head);
86
87     /* Workspaces are handled differently: they need to be inserted at the
88      * right position. */
89     if (con->type == CT_WORKSPACE) {
90         DLOG("it's a workspace. num = %d\n", con->num);
91         if (con->num == -1 || TAILQ_EMPTY(nodes_head)) {
92             TAILQ_INSERT_TAIL(nodes_head, con, nodes);
93         } else {
94             current = TAILQ_FIRST(nodes_head);
95             if (con->num < current->num) {
96                 /* we need to insert the container at the beginning */
97                 TAILQ_INSERT_HEAD(nodes_head, con, nodes);
98             } else {
99                 while (current->num != -1 && con->num > current->num) {
100                     current = TAILQ_NEXT(current, nodes);
101                     if (current == TAILQ_END(nodes_head)) {
102                         current = NULL;
103                         break;
104                     }
105                 }
106                 /* we need to insert con after current, if current is not NULL */
107                 if (current)
108                     TAILQ_INSERT_BEFORE(current, con, nodes);
109                 else TAILQ_INSERT_TAIL(nodes_head, con, nodes);
110             }
111         }
112         goto add_to_focus_head;
113     }
114
115     if (con->type == CT_FLOATING_CON) {
116         DLOG("Inserting into floating containers\n");
117         TAILQ_INSERT_TAIL(&(parent->floating_head), con, floating_windows);
118     } else {
119         if (!ignore_focus) {
120             /* Get the first tiling container in focus stack */
121             TAILQ_FOREACH(loop, &(parent->focus_head), focused) {
122                 if (loop->type == CT_FLOATING_CON)
123                     continue;
124                 current = loop;
125                 break;
126             }
127         }
128
129         /* When the container is not a split container (but contains a window)
130          * and is attached to a workspace, we check if the user configured a
131          * workspace_layout. This is done in workspace_attach_to, which will
132          * provide us with the container to which we should attach (either the
133          * workspace or a new split container with the configured
134          * workspace_layout).
135          */
136         if (con->window != NULL &&
137             parent->type == CT_WORKSPACE &&
138             config.default_layout != L_DEFAULT) {
139             DLOG("Parent is a workspace. Applying default layout...\n");
140             Con *target = workspace_attach_to(parent);
141
142             /* Attach the original con to this new split con instead */
143             nodes_head = &(target->nodes_head);
144             focus_head = &(target->focus_head);
145             con->parent = target;
146             current = NULL;
147
148             DLOG("done\n");
149         }
150
151         /* Insert the container after the tiling container, if found.
152          * When adding to a CT_OUTPUT, just append one after another. */
153         if (current && parent->type != CT_OUTPUT) {
154             DLOG("Inserting con = %p after last focused tiling con %p\n",
155                  con, current);
156             TAILQ_INSERT_AFTER(nodes_head, current, con, nodes);
157         } else TAILQ_INSERT_TAIL(nodes_head, con, nodes);
158     }
159
160 add_to_focus_head:
161     /* We insert to the TAIL because con_focus() will correct this.
162      * This way, we have the option to insert Cons without having
163      * to focus them. */
164     TAILQ_INSERT_TAIL(focus_head, con, focused);
165 }
166
167 /*
168  * Detaches the given container from its current parent
169  *
170  */
171 void con_detach(Con *con) {
172     if (con->type == CT_FLOATING_CON) {
173         TAILQ_REMOVE(&(con->parent->floating_head), con, floating_windows);
174         TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
175     } else {
176         TAILQ_REMOVE(&(con->parent->nodes_head), con, nodes);
177         TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
178     }
179 }
180
181 /*
182  * Sets input focus to the given container. Will be updated in X11 in the next
183  * run of x_push_changes().
184  *
185  */
186 void con_focus(Con *con) {
187     assert(con != NULL);
188     DLOG("con_focus = %p\n", con);
189
190     /* 1: set focused-pointer to the new con */
191     /* 2: exchange the position of the container in focus stack of the parent all the way up */
192     TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
193     TAILQ_INSERT_HEAD(&(con->parent->focus_head), con, focused);
194     if (con->parent->parent != NULL)
195         con_focus(con->parent);
196
197     focused = con;
198     if (con->urgent) {
199         con->urgent = false;
200         workspace_update_urgent_flag(con_get_workspace(con));
201     }
202 }
203
204 /*
205  * Returns true when this node is a leaf node (has no children)
206  *
207  */
208 bool con_is_leaf(Con *con) {
209     return TAILQ_EMPTY(&(con->nodes_head));
210 }
211
212 /*
213  * Returns true if this node accepts a window (if the node swallows windows,
214  * it might already have swallowed enough and cannot hold any more).
215  *
216  */
217 bool con_accepts_window(Con *con) {
218     /* 1: workspaces never accept direct windows */
219     if (con->type == CT_WORKSPACE)
220         return false;
221
222     if (con->split) {
223         DLOG("container %p does not accept windows, it is a split container.\n", con);
224         return false;
225     }
226
227     /* TODO: if this is a swallowing container, we need to check its max_clients */
228     return (con->window == NULL);
229 }
230
231 /*
232  * Gets the output container (first container with CT_OUTPUT in hierarchy) this
233  * node is on.
234  *
235  */
236 Con *con_get_output(Con *con) {
237     Con *result = con;
238     while (result != NULL && result->type != CT_OUTPUT)
239         result = result->parent;
240     /* We must be able to get an output because focus can never be set higher
241      * in the tree (root node cannot be focused). */
242     assert(result != NULL);
243     return result;
244 }
245
246 /*
247  * Gets the workspace container this node is on.
248  *
249  */
250 Con *con_get_workspace(Con *con) {
251     Con *result = con;
252     while (result != NULL && result->type != CT_WORKSPACE)
253         result = result->parent;
254     return result;
255 }
256
257 /*
258  * Searches parenst of the given 'con' until it reaches one with the specified
259  * 'orientation'. Aborts when it comes across a floating_con.
260  *
261  */
262 Con *con_parent_with_orientation(Con *con, orientation_t orientation) {
263     DLOG("Searching for parent of Con %p with orientation %d\n", con, orientation);
264     Con *parent = con->parent;
265     if (parent->type == CT_FLOATING_CON)
266         return NULL;
267     while (con_orientation(parent) != orientation) {
268         DLOG("Need to go one level further up\n");
269         parent = parent->parent;
270         /* Abort when we reach a floating con, or an output con */
271         if (parent &&
272             (parent->type == CT_FLOATING_CON ||
273              parent->type == CT_OUTPUT ||
274              (parent->parent && parent->parent->type == CT_OUTPUT)))
275             parent = NULL;
276         if (parent == NULL)
277             break;
278     }
279     DLOG("Result: %p\n", parent);
280     return parent;
281 }
282
283 /*
284  * helper data structure for the breadth-first-search in
285  * con_get_fullscreen_con()
286  *
287  */
288 struct bfs_entry {
289     Con *con;
290
291     TAILQ_ENTRY(bfs_entry) entries;
292 };
293
294 /*
295  * Returns the first fullscreen node below this node.
296  *
297  */
298 Con *con_get_fullscreen_con(Con *con, int fullscreen_mode) {
299     Con *current, *child;
300
301     /* TODO: is breadth-first-search really appropriate? (check as soon as
302      * fullscreen levels and fullscreen for containers is implemented) */
303     TAILQ_HEAD(bfs_head, bfs_entry) bfs_head = TAILQ_HEAD_INITIALIZER(bfs_head);
304     struct bfs_entry *entry = smalloc(sizeof(struct bfs_entry));
305     entry->con = con;
306     TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
307
308     while (!TAILQ_EMPTY(&bfs_head)) {
309         entry = TAILQ_FIRST(&bfs_head);
310         current = entry->con;
311         if (current != con && current->fullscreen_mode == fullscreen_mode) {
312             /* empty the queue */
313             while (!TAILQ_EMPTY(&bfs_head)) {
314                 entry = TAILQ_FIRST(&bfs_head);
315                 TAILQ_REMOVE(&bfs_head, entry, entries);
316                 free(entry);
317             }
318             return current;
319         }
320
321         TAILQ_REMOVE(&bfs_head, entry, entries);
322         free(entry);
323
324         TAILQ_FOREACH(child, &(current->nodes_head), nodes) {
325             entry = smalloc(sizeof(struct bfs_entry));
326             entry->con = child;
327             TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
328         }
329
330         TAILQ_FOREACH(child, &(current->floating_head), floating_windows) {
331             entry = smalloc(sizeof(struct bfs_entry));
332             entry->con = child;
333             TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
334         }
335     }
336
337     return NULL;
338 }
339
340 /*
341  * Returns true if the node is floating.
342  *
343  */
344 bool con_is_floating(Con *con) {
345     assert(con != NULL);
346     DLOG("checking if con %p is floating\n", con);
347     return (con->floating >= FLOATING_AUTO_ON);
348 }
349
350 /*
351  * Checks if the given container is either floating or inside some floating
352  * container. It returns the FLOATING_CON container.
353  *
354  */
355 Con *con_inside_floating(Con *con) {
356     assert(con != NULL);
357     if (con->type == CT_FLOATING_CON)
358         return con;
359
360     if (con->floating >= FLOATING_AUTO_ON)
361         return con->parent;
362
363     if (con->type == CT_WORKSPACE || con->type == CT_OUTPUT)
364         return NULL;
365
366     return con_inside_floating(con->parent);
367 }
368
369 /*
370  * Checks if the given container is inside a focused container.
371  *
372  */
373 bool con_inside_focused(Con *con) {
374     if (con == focused)
375         return true;
376     if (!con->parent)
377         return false;
378     return con_inside_focused(con->parent);
379 }
380
381 /*
382  * Returns the container with the given client window ID or NULL if no such
383  * container exists.
384  *
385  */
386 Con *con_by_window_id(xcb_window_t window) {
387     Con *con;
388     TAILQ_FOREACH(con, &all_cons, all_cons)
389         if (con->window != NULL && con->window->id == window)
390             return con;
391     return NULL;
392 }
393
394 /*
395  * Returns the container with the given frame ID or NULL if no such container
396  * exists.
397  *
398  */
399 Con *con_by_frame_id(xcb_window_t frame) {
400     Con *con;
401     TAILQ_FOREACH(con, &all_cons, all_cons)
402         if (con->frame == frame)
403             return con;
404     return NULL;
405 }
406
407 /*
408  * Returns the first container below 'con' which wants to swallow this window
409  * TODO: priority
410  *
411  */
412 Con *con_for_window(Con *con, i3Window *window, Match **store_match) {
413     Con *child;
414     Match *match;
415     //DLOG("searching con for window %p starting at con %p\n", window, con);
416     //DLOG("class == %s\n", window->class_class);
417
418     TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
419         TAILQ_FOREACH(match, &(child->swallow_head), matches) {
420             if (!match_matches_window(match, window))
421                 continue;
422             if (store_match != NULL)
423                 *store_match = match;
424             return child;
425         }
426         Con *result = con_for_window(child, window, store_match);
427         if (result != NULL)
428             return result;
429     }
430
431     TAILQ_FOREACH(child, &(con->floating_head), floating_windows) {
432         TAILQ_FOREACH(match, &(child->swallow_head), matches) {
433             if (!match_matches_window(match, window))
434                 continue;
435             if (store_match != NULL)
436                 *store_match = match;
437             return child;
438         }
439         Con *result = con_for_window(child, window, store_match);
440         if (result != NULL)
441             return result;
442     }
443
444     return NULL;
445 }
446
447 /*
448  * Returns the number of children of this container.
449  *
450  */
451 int con_num_children(Con *con) {
452     Con *child;
453     int children = 0;
454
455     TAILQ_FOREACH(child, &(con->nodes_head), nodes)
456         children++;
457
458     return children;
459 }
460
461 /*
462  * Updates the percent attribute of the children of the given container. This
463  * function needs to be called when a window is added or removed from a
464  * container.
465  *
466  */
467 void con_fix_percent(Con *con) {
468     Con *child;
469     int children = con_num_children(con);
470
471     // calculate how much we have distributed and how many containers
472     // with a percentage set we have
473     double total = 0.0;
474     int children_with_percent = 0;
475     TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
476         if (child->percent > 0.0) {
477             total += child->percent;
478             ++children_with_percent;
479         }
480     }
481
482     // if there were children without a percentage set, set to a value that
483     // will make those children proportional to all others
484     if (children_with_percent != children) {
485         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
486             if (child->percent <= 0.0) {
487                 if (children_with_percent == 0)
488                     total += (child->percent = 1.0);
489                 else total += (child->percent = total / children_with_percent);
490             }
491         }
492     }
493
494     // if we got a zero, just distribute the space equally, otherwise
495     // distribute according to the proportions we got
496     if (total == 0.0) {
497         TAILQ_FOREACH(child, &(con->nodes_head), nodes)
498             child->percent = 1.0 / children;
499     } else if (total != 1.0) {
500         TAILQ_FOREACH(child, &(con->nodes_head), nodes)
501             child->percent /= total;
502     }
503 }
504
505 /*
506  * Toggles fullscreen mode for the given container. Fullscreen mode will not be
507  * entered when there already is a fullscreen container on this workspace.
508  *
509  */
510 void con_toggle_fullscreen(Con *con, int fullscreen_mode) {
511     Con *workspace, *fullscreen;
512
513     if (con->type == CT_WORKSPACE) {
514         DLOG("You cannot make a workspace fullscreen.\n");
515         return;
516     }
517
518     DLOG("toggling fullscreen for %p / %s\n", con, con->name);
519     if (con->fullscreen_mode == CF_NONE) {
520         /* 1: check if there already is a fullscreen con */
521         if (fullscreen_mode == CF_GLOBAL)
522             fullscreen = con_get_fullscreen_con(croot, CF_GLOBAL);
523         else {
524             workspace = con_get_workspace(con);
525             fullscreen = con_get_fullscreen_con(workspace, CF_OUTPUT);
526         }
527         if (fullscreen != NULL) {
528             /* Disable fullscreen for the currently fullscreened
529              * container and enable it for the one the user wants
530              * to have in fullscreen mode. */
531             LOG("Disabling fullscreen for (%p/%s) upon user request\n",
532                 fullscreen, fullscreen->name);
533             fullscreen->fullscreen_mode = CF_NONE;
534         }
535
536         /* 2: enable fullscreen */
537         con->fullscreen_mode = fullscreen_mode;
538     } else {
539         /* 1: disable fullscreen */
540         con->fullscreen_mode = CF_NONE;
541     }
542
543     DLOG("mode now: %d\n", con->fullscreen_mode);
544
545     /* update _NET_WM_STATE if this container has a window */
546     /* TODO: when a window is assigned to a container which is already
547      * fullscreened, this state needs to be pushed to the client, too */
548     if (con->window == NULL)
549         return;
550
551     uint32_t values[1];
552     unsigned int num = 0;
553
554     if (con->fullscreen_mode != CF_NONE)
555         values[num++] = A__NET_WM_STATE_FULLSCREEN;
556
557     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
558                         A__NET_WM_STATE, XCB_ATOM_ATOM, 32, num, values);
559 }
560
561 /*
562  * Moves the given container to the currently focused container on the given
563  * workspace.
564  *
565  * The fix_coordinates flag will translate the current coordinates (offset from
566  * the monitor position basically) to appropriate coordinates on the
567  * destination workspace.
568  * Not enabling this behaviour comes in handy when this function gets called by
569  * floating_maybe_reassign_ws, which will only "move" a floating window when it
570  * *already* changed its coordinates to a different output.
571  *
572  * The dont_warp flag disables pointer warping and will be set when this
573  * function is called while dragging a floating window.
574  *
575  * TODO: is there a better place for this function?
576  *
577  */
578 void con_move_to_workspace(Con *con, Con *workspace, bool fix_coordinates, bool dont_warp) {
579     if (con->type == CT_WORKSPACE) {
580         DLOG("Moving workspaces is not yet implemented.\n");
581         return;
582     }
583
584     /* Prevent moving if this would violate the fullscreen focus restrictions. */
585     if (!con_fullscreen_permits_focusing(workspace)) {
586         LOG("Cannot move out of a fullscreen container");
587         return;
588     }
589
590     if (con_is_floating(con)) {
591         DLOG("Using FLOATINGCON instead\n");
592         con = con->parent;
593     }
594
595     Con *source_ws = con_get_workspace(con);
596     if (workspace == source_ws) {
597         DLOG("Not moving, already there\n");
598         return;
599     }
600
601     /* Save the current workspace. So we can call workspace_show() by the end
602      * of this function. */
603     Con *current_ws = con_get_workspace(focused);
604
605     Con *source_output = con_get_output(con),
606         *dest_output = con_get_output(workspace);
607
608     /* 1: save the container which is going to be focused after the current
609      * container is moved away */
610     Con *focus_next = con_next_focused(con);
611
612     /* 2: get the focused container of this workspace */
613     Con *next = con_descend_focused(workspace);
614
615     /* 3: we go up one level, but only when next is a normal container */
616     if (next->type != CT_WORKSPACE) {
617         DLOG("next originally = %p / %s / type %d\n", next, next->name, next->type);
618         next = next->parent;
619     }
620
621     /* 4: if the target container is floating, we get the workspace instead.
622      * Only tiling windows need to get inserted next to the current container.
623      * */
624     Con *floatingcon = con_inside_floating(next);
625     if (floatingcon != NULL) {
626         DLOG("floatingcon, going up even further\n");
627         next = floatingcon->parent;
628     }
629
630     if (con->type == CT_FLOATING_CON) {
631         Con *ws = con_get_workspace(next);
632         DLOG("This is a floating window, using workspace %p / %s\n", ws, ws->name);
633         next = ws;
634     }
635
636     if (source_output != dest_output) {
637         /* Take the relative coordinates of the current output, then add them
638          * to the coordinate space of the correct output */
639         if (fix_coordinates && con->type == CT_FLOATING_CON) {
640             floating_fix_coordinates(con, &(source_output->rect), &(dest_output->rect));
641         } else DLOG("Not fixing coordinates, fix_coordinates flag = %d\n", fix_coordinates);
642
643         /* If moving to a visible workspace, call show so it can be considered
644          * focused. Must do before attaching because workspace_show checks to see
645          * if focused container is in its area. */
646         if (workspace_is_visible(workspace)) {
647             workspace_show(workspace);
648
649             /* Don’t warp if told so (when dragging floating windows with the
650              * mouse for example) */
651             if (dont_warp)
652                 x_set_warp_to(NULL);
653             else
654                 x_set_warp_to(&(con->rect));
655         }
656     }
657
658     DLOG("Re-attaching container to %p / %s\n", next, next->name);
659     /* 5: re-attach the con to the parent of this focused container */
660     Con *parent = con->parent;
661     con_detach(con);
662     con_attach(con, next, false);
663
664     /* 6: fix the percentages */
665     con_fix_percent(parent);
666     con->percent = 0.0;
667     con_fix_percent(next);
668
669     /* 7: focus the con on the target workspace (the X focus is only updated by
670      * calling tree_render(), so for the "real" focus this is a no-op).
671      * We don’t focus the con for i3 pseudo workspaces like __i3_scratch and
672      * we don’t focus when there is a fullscreen con on that workspace. */
673     if ((workspace->name[0] != '_' || workspace->name[1] != '_') &&
674         con_get_fullscreen_con(workspace, CF_OUTPUT) == NULL)
675         con_focus(con_descend_focused(con));
676
677     /* 8: when moving to a visible workspace on a different output, we keep the
678      * con focused. Otherwise, we leave the focus on the current workspace as we
679      * don’t want to focus invisible workspaces */
680     if (source_output != dest_output &&
681         workspace_is_visible(workspace) &&
682         workspace->name[0] != '_' &&
683         workspace->name[1] != '_') {
684         DLOG("Moved to a different output, focusing target\n");
685     } else {
686         /* Descend focus stack in case focus_next is a workspace which can
687          * occur if we move to the same workspace.  Also show current workspace
688          * to ensure it is focused. */
689         workspace_show(current_ws);
690
691         /* Set focus only if con was on current workspace before moving.
692          * Otherwise we would give focus to some window on different workspace. */
693         if (source_ws == current_ws)
694             con_focus(con_descend_focused(focus_next));
695     }
696
697     CALL(parent, on_remove_child);
698 }
699
700 /*
701  * Returns the orientation of the given container (for stacked containers,
702  * vertical orientation is used regardless of the actual orientation of the
703  * container).
704  *
705  */
706 int con_orientation(Con *con) {
707     switch (con->layout) {
708         case L_SPLITV:
709         /* stacking containers behave like they are in vertical orientation */
710         case L_STACKED:
711             return VERT;
712
713         case L_SPLITH:
714         /* tabbed containers behave like they are in vertical orientation */
715         case L_TABBED:
716             return HORIZ;
717
718         case L_DEFAULT:
719             DLOG("Someone called con_orientation() on a con with L_DEFAULT, this is a bug in the code.\n");
720             assert(false);
721             return HORIZ;
722
723         case L_DOCKAREA:
724         case L_OUTPUT:
725             DLOG("con_orientation() called on dockarea/output (%d) container %p\n", con->layout, con);
726             assert(false);
727             return HORIZ;
728
729         default:
730             DLOG("con_orientation() ran into default\n");
731             assert(false);
732     }
733 }
734
735 /*
736  * Returns the container which will be focused next when the given container
737  * is not available anymore. Called in tree_close and con_move_to_workspace
738  * to properly restore focus.
739  *
740  */
741 Con *con_next_focused(Con *con) {
742     Con *next;
743     /* floating containers are attached to a workspace, so we focus either the
744      * next floating container (if any) or the workspace itself. */
745     if (con->type == CT_FLOATING_CON) {
746         DLOG("selecting next for CT_FLOATING_CON\n");
747         next = TAILQ_NEXT(con, floating_windows);
748         DLOG("next = %p\n", next);
749         if (!next) {
750             next = TAILQ_PREV(con, floating_head, floating_windows);
751             DLOG("using prev, next = %p\n", next);
752         }
753         if (!next) {
754             Con *ws = con_get_workspace(con);
755             next = ws;
756             DLOG("no more floating containers for next = %p, restoring workspace focus\n", next);
757             while (next != TAILQ_END(&(ws->focus_head)) && !TAILQ_EMPTY(&(next->focus_head))) {
758                 next = TAILQ_FIRST(&(next->focus_head));
759                 if (next == con) {
760                     DLOG("skipping container itself, we want the next client\n");
761                     next = TAILQ_NEXT(next, focused);
762                 }
763             }
764             if (next == TAILQ_END(&(ws->focus_head))) {
765                 DLOG("Focus list empty, returning ws\n");
766                 next = ws;
767             }
768         } else {
769             /* Instead of returning the next CT_FLOATING_CON, we descend it to
770              * get an actual window to focus. */
771             next = con_descend_focused(next);
772         }
773         return next;
774     }
775
776     /* dock clients cannot be focused, so we focus the workspace instead */
777     if (con->parent->type == CT_DOCKAREA) {
778         DLOG("selecting workspace for dock client\n");
779         return con_descend_focused(output_get_content(con->parent->parent));
780     }
781
782     /* if 'con' is not the first entry in the focus stack, use the first one as
783      * it’s currently focused already */
784     Con *first = TAILQ_FIRST(&(con->parent->focus_head));
785     if (first != con) {
786         DLOG("Using first entry %p\n", first);
787         next = first;
788     } else {
789         /* try to focus the next container on the same level as this one or fall
790          * back to its parent */
791         if (!(next = TAILQ_NEXT(con, focused)))
792             next = con->parent;
793     }
794
795     /* now go down the focus stack as far as
796      * possible, excluding the current container */
797     while (!TAILQ_EMPTY(&(next->focus_head)) &&
798            TAILQ_FIRST(&(next->focus_head)) != con)
799         next = TAILQ_FIRST(&(next->focus_head));
800
801     return next;
802 }
803
804 /*
805  * Get the next/previous container in the specified orientation. This may
806  * travel up until it finds a container with suitable orientation.
807  *
808  */
809 Con *con_get_next(Con *con, char way, orientation_t orientation) {
810     DLOG("con_get_next(way=%c, orientation=%d)\n", way, orientation);
811     /* 1: get the first parent with the same orientation */
812     Con *cur = con;
813     while (con_orientation(cur->parent) != orientation) {
814         DLOG("need to go one level further up\n");
815         if (cur->parent->type == CT_WORKSPACE) {
816             LOG("that's a workspace, we can't go further up\n");
817             return NULL;
818         }
819         cur = cur->parent;
820     }
821
822     /* 2: chose next (or previous) */
823     Con *next;
824     if (way == 'n') {
825         next = TAILQ_NEXT(cur, nodes);
826         /* if we are at the end of the list, we need to wrap */
827         if (next == TAILQ_END(&(parent->nodes_head)))
828             return NULL;
829     } else {
830         next = TAILQ_PREV(cur, nodes_head, nodes);
831         /* if we are at the end of the list, we need to wrap */
832         if (next == TAILQ_END(&(cur->nodes_head)))
833             return NULL;
834     }
835     DLOG("next = %p\n", next);
836
837     return next;
838 }
839
840 /*
841  * Returns the focused con inside this client, descending the tree as far as
842  * possible. This comes in handy when attaching a con to a workspace at the
843  * currently focused position, for example.
844  *
845  */
846 Con *con_descend_focused(Con *con) {
847     Con *next = con;
848     while (next != focused && !TAILQ_EMPTY(&(next->focus_head)))
849         next = TAILQ_FIRST(&(next->focus_head));
850     return next;
851 }
852
853 /*
854  * Returns the focused con inside this client, descending the tree as far as
855  * possible. This comes in handy when attaching a con to a workspace at the
856  * currently focused position, for example.
857  *
858  * Works like con_descend_focused but considers only tiling cons.
859  *
860  */
861 Con *con_descend_tiling_focused(Con *con) {
862     Con *next = con;
863     Con *before;
864     Con *child;
865     if (next == focused)
866         return next;
867     do {
868         before = next;
869         TAILQ_FOREACH(child, &(next->focus_head), focused) {
870             if (child->type == CT_FLOATING_CON)
871                 continue;
872
873             next = child;
874             break;
875         }
876     } while (before != next && next != focused);
877     return next;
878 }
879
880 /*
881  * Returns the leftmost, rightmost, etc. container in sub-tree. For example, if
882  * direction is D_LEFT, then we return the rightmost container and if direction
883  * is D_RIGHT, we return the leftmost container.  This is because if we are
884  * moving D_LEFT, and thus want the rightmost container.
885  *
886  */
887 Con *con_descend_direction(Con *con, direction_t direction) {
888     Con *most = NULL;
889     int orientation = con_orientation(con);
890     DLOG("con_descend_direction(%p, orientation %d, direction %d)\n", con, orientation, direction);
891     if (direction == D_LEFT || direction == D_RIGHT) {
892         if (orientation == HORIZ) {
893             /* If the direction is horizontal, we can use either the first
894              * (D_RIGHT) or the last con (D_LEFT) */
895             if (direction == D_RIGHT)
896                 most = TAILQ_FIRST(&(con->nodes_head));
897             else most = TAILQ_LAST(&(con->nodes_head), nodes_head);
898         } else if (orientation == VERT) {
899             /* Wrong orientation. We use the last focused con. Within that con,
900              * we recurse to chose the left/right con or at least the last
901              * focused one. */
902             most = TAILQ_FIRST(&(con->focus_head));
903         } else {
904             /* If the con has no orientation set, it’s not a split container
905              * but a container with a client window, so stop recursing */
906             return con;
907         }
908     }
909
910     if (direction == D_UP || direction == D_DOWN) {
911         if (orientation == VERT) {
912             /* If the direction is vertical, we can use either the first
913              * (D_DOWN) or the last con (D_UP) */
914             if (direction == D_UP)
915                 most = TAILQ_LAST(&(con->nodes_head), nodes_head);
916             else most = TAILQ_FIRST(&(con->nodes_head));
917         } else if (orientation == HORIZ) {
918             /* Wrong orientation. We use the last focused con. Within that con,
919              * we recurse to chose the top/bottom con or at least the last
920              * focused one. */
921             most = TAILQ_FIRST(&(con->focus_head));
922         } else {
923             /* If the con has no orientation set, it’s not a split container
924              * but a container with a client window, so stop recursing */
925             return con;
926         }
927     }
928
929     if (!most)
930         return con;
931     return con_descend_direction(most, direction);
932 }
933
934 /*
935  * Returns a "relative" Rect which contains the amount of pixels that need to
936  * be added to the original Rect to get the final position (obviously the
937  * amount of pixels for normal, 1pixel and borderless are different).
938  *
939  */
940 Rect con_border_style_rect(Con *con) {
941     adjacent_t borders_to_hide = ADJ_NONE;
942     Rect result;
943     /* Shortcut to avoid calling con_adjacent_borders() on dock containers. */
944     int border_style = con_border_style(con);
945     if (border_style == BS_NONE)
946         return (Rect){ 0, 0, 0, 0 };
947     borders_to_hide = con_adjacent_borders(con) & config.hide_edge_borders;
948     switch (border_style) {
949     case BS_NORMAL:
950         result = (Rect){2, 0, -(2 * 2), -2};
951         if (borders_to_hide & ADJ_LEFT_SCREEN_EDGE) {
952             result.x -= 2;
953             result.width += 2;
954         }
955         if (borders_to_hide & ADJ_RIGHT_SCREEN_EDGE) {
956             result.width += 2;
957         }
958         /* With normal borders we never hide the upper border */
959         if (borders_to_hide & ADJ_LOWER_SCREEN_EDGE) {
960             result.height += 2;
961         }
962         return result;
963
964     case BS_1PIXEL:
965         result = (Rect){1, 1, -2, -2};
966         if (borders_to_hide & ADJ_LEFT_SCREEN_EDGE) {
967             result.x -= 1;
968             result.width += 1;
969         }
970         if (borders_to_hide & ADJ_RIGHT_SCREEN_EDGE) {
971             result.width += 1;
972         }
973         if (borders_to_hide & ADJ_UPPER_SCREEN_EDGE) {
974             result.y -= 1;
975             result.height += 1;
976         }
977         if (borders_to_hide & ADJ_LOWER_SCREEN_EDGE) {
978             result.height += 1;
979         }
980         return result;
981
982     case BS_NONE:
983         return (Rect){0, 0, 0, 0};
984
985     default:
986         assert(false);
987     }
988 }
989
990 /*
991  * Returns adjacent borders of the window. We need this if hide_edge_borders is
992  * enabled.
993  */
994 adjacent_t con_adjacent_borders(Con *con) {
995     adjacent_t result = ADJ_NONE;
996     Con *workspace = con_get_workspace(con);
997     if (con->rect.x == workspace->rect.x)
998         result |= ADJ_LEFT_SCREEN_EDGE;
999     if (con->rect.x + con->rect.width == workspace->rect.x + workspace->rect.width)
1000         result |= ADJ_RIGHT_SCREEN_EDGE;
1001     if (con->rect.y == workspace->rect.y)
1002         result |= ADJ_UPPER_SCREEN_EDGE;
1003     if (con->rect.y + con->rect.height == workspace->rect.y + workspace->rect.height)
1004         result |= ADJ_LOWER_SCREEN_EDGE;
1005     return result;
1006 }
1007
1008 /*
1009  * Use this function to get a container’s border style. This is important
1010  * because when inside a stack, the border style is always BS_NORMAL.
1011  * For tabbed mode, the same applies, with one exception: when the container is
1012  * borderless and the only element in the tabbed container, the border is not
1013  * rendered.
1014  *
1015  * For children of a CT_DOCKAREA, the border style is always none.
1016  *
1017  */
1018 int con_border_style(Con *con) {
1019     Con *fs = con_get_fullscreen_con(con->parent, CF_OUTPUT);
1020     if (fs == con) {
1021         DLOG("this one is fullscreen! overriding BS_NONE\n");
1022         return BS_NONE;
1023     }
1024
1025     if (con->parent->layout == L_STACKED)
1026         return (con_num_children(con->parent) == 1 ? con->border_style : BS_NORMAL);
1027
1028     if (con->parent->layout == L_TABBED && con->border_style != BS_NORMAL)
1029         return (con_num_children(con->parent) == 1 ? con->border_style : BS_NORMAL);
1030
1031     if (con->parent->type == CT_DOCKAREA)
1032         return BS_NONE;
1033
1034     return con->border_style;
1035 }
1036
1037 /*
1038  * Sets the given border style on con, correctly keeping the position/size of a
1039  * floating window.
1040  *
1041  */
1042 void con_set_border_style(Con *con, int border_style) {
1043     /* Handle the simple case: non-floating containerns */
1044     if (!con_is_floating(con)) {
1045         con->border_style = border_style;
1046         return;
1047     }
1048
1049     /* For floating containers, we want to keep the position/size of the
1050      * *window* itself. We first add the border pixels to con->rect to make
1051      * con->rect represent the absolute position of the window. Then, we change
1052      * the border and subtract the new border pixels. Afterwards, we update
1053      * parent->rect to contain con. */
1054     DLOG("This is a floating container\n");
1055
1056     Rect bsr = con_border_style_rect(con);
1057     con->rect.x += bsr.x;
1058     con->rect.y += bsr.y;
1059     con->rect.width += bsr.width;
1060     con->rect.height += bsr.height;
1061
1062     /* Change the border style, get new border/decoration values. */
1063     con->border_style = border_style;
1064     bsr = con_border_style_rect(con);
1065     int deco_height =
1066         (con->border_style == BS_NORMAL ? config.font.height + 5 : 0);
1067
1068     con->rect.x -= bsr.x;
1069     con->rect.y -= bsr.y;
1070     con->rect.width -= bsr.width;
1071     con->rect.height -= bsr.height;
1072
1073     Con *parent = con->parent;
1074     parent->rect.x = con->rect.x;
1075     parent->rect.y = con->rect.y - deco_height;
1076     parent->rect.width = con->rect.width;
1077     parent->rect.height = con->rect.height + deco_height;
1078 }
1079
1080 /*
1081  * This function changes the layout of a given container. Use it to handle
1082  * special cases like changing a whole workspace to stacked/tabbed (creates a
1083  * new split container before).
1084  *
1085  */
1086 void con_set_layout(Con *con, int layout) {
1087     DLOG("con_set_layout(%p, %d), con->type = %d\n",
1088          con, layout, con->type);
1089
1090     /* Users can focus workspaces, but not any higher in the hierarchy.
1091      * Focus on the workspace is a special case, since in every other case, the
1092      * user means "change the layout of the parent split container". */
1093     if (con->type != CT_WORKSPACE)
1094         con = con->parent;
1095
1096     /* We fill in last_split_layout when switching to a different layout
1097      * since there are many places in the code that don’t use
1098      * con_set_layout(). */
1099     if (con->layout == L_SPLITH || con->layout == L_SPLITV)
1100         con->last_split_layout = con->layout;
1101
1102     /* When the container type is CT_WORKSPACE, the user wants to change the
1103      * whole workspace into stacked/tabbed mode. To do this and still allow
1104      * intuitive operations (like level-up and then opening a new window), we
1105      * need to create a new split container. */
1106     if (con->type == CT_WORKSPACE &&
1107         (layout == L_STACKED || layout == L_TABBED)) {
1108         DLOG("Creating new split container\n");
1109         /* 1: create a new split container */
1110         Con *new = con_new(NULL, NULL);
1111         new->parent = con;
1112
1113         /* 2: Set the requested layout on the split container and mark it as
1114          * split. */
1115         new->layout = layout;
1116         new->last_split_layout = con->last_split_layout;
1117         new->split = true;
1118
1119         Con *old_focused = TAILQ_FIRST(&(con->focus_head));
1120         if (old_focused == TAILQ_END(&(con->focus_head)))
1121             old_focused = NULL;
1122
1123         /* 3: move the existing cons of this workspace below the new con */
1124         DLOG("Moving cons\n");
1125         Con *child;
1126         while (!TAILQ_EMPTY(&(con->nodes_head))) {
1127             child = TAILQ_FIRST(&(con->nodes_head));
1128             con_detach(child);
1129             con_attach(child, new, true);
1130         }
1131
1132         /* 4: attach the new split container to the workspace */
1133         DLOG("Attaching new split to ws\n");
1134         con_attach(new, con, false);
1135
1136         if (old_focused)
1137             con_focus(old_focused);
1138
1139         tree_flatten(croot);
1140
1141         return;
1142     }
1143
1144     if (layout == L_DEFAULT) {
1145         /* Special case: the layout formerly known as "default" (in combination
1146          * with an orientation). Since we switched to splith/splitv layouts,
1147          * using the "default" layout (which "only" should happen when using
1148          * legacy configs) is using the last split layout (either splith or
1149          * splitv) in order to still do the same thing.
1150          *
1151          * Starting from v4.6 though, we will nag users about using "layout
1152          * default", and in v4.9 we will remove it entirely (with an
1153          * appropriate i3-migrate-config mechanism). */
1154         con->layout = con->last_split_layout;
1155         /* In case last_split_layout was not initialized… */
1156         if (con->layout == L_DEFAULT)
1157             con->layout = L_SPLITH;
1158     } else {
1159         con->layout = layout;
1160     }
1161 }
1162
1163 /*
1164  * This function toggles the layout of a given container. toggle_mode can be
1165  * either 'default' (toggle only between stacked/tabbed/last_split_layout),
1166  * 'split' (toggle only between splitv/splith) or 'all' (toggle between all
1167  * layouts).
1168  *
1169  */
1170 void con_toggle_layout(Con *con, const char *toggle_mode) {
1171     Con *parent = con;
1172     /* Users can focus workspaces, but not any higher in the hierarchy.
1173      * Focus on the workspace is a special case, since in every other case, the
1174      * user means "change the layout of the parent split container". */
1175     if (con->type != CT_WORKSPACE)
1176         parent = con->parent;
1177     DLOG("con_toggle_layout(%p, %s), parent = %p\n", con, toggle_mode, parent);
1178
1179     if (strcmp(toggle_mode, "split") == 0) {
1180         /* Toggle between splits. When the current layout is not a split
1181          * layout, we just switch back to last_split_layout. Otherwise, we
1182          * change to the opposite split layout. */
1183         if (parent->layout != L_SPLITH && parent->layout != L_SPLITV)
1184             con_set_layout(con, parent->last_split_layout);
1185         else {
1186             if (parent->layout == L_SPLITH)
1187                 con_set_layout(con, L_SPLITV);
1188             else con_set_layout(con, L_SPLITH);
1189         }
1190     } else {
1191         if (parent->layout == L_STACKED)
1192             con_set_layout(con, L_TABBED);
1193         else if (parent->layout == L_TABBED) {
1194             if (strcmp(toggle_mode, "all") == 0)
1195                 con_set_layout(con, L_SPLITH);
1196             else con_set_layout(con, parent->last_split_layout);
1197         } else if (parent->layout == L_SPLITH || parent->layout == L_SPLITV) {
1198             if (strcmp(toggle_mode, "all") == 0) {
1199                 /* When toggling through all modes, we toggle between
1200                  * splith/splitv, whereas normally we just directly jump to
1201                  * stacked. */
1202                 if (parent->layout == L_SPLITH)
1203                     con_set_layout(con, L_SPLITV);
1204                 else con_set_layout(con, L_STACKED);
1205             } else {
1206                 con_set_layout(con, L_STACKED);
1207             }
1208         }
1209     }
1210 }
1211
1212 /*
1213  * Callback which will be called when removing a child from the given con.
1214  * Kills the container if it is empty and replaces it with the child if there
1215  * is exactly one child.
1216  *
1217  */
1218 static void con_on_remove_child(Con *con) {
1219     DLOG("on_remove_child\n");
1220
1221     /* Every container 'above' (in the hierarchy) the workspace content should
1222      * not be closed when the last child was removed */
1223     if (con->type == CT_OUTPUT ||
1224         con->type == CT_ROOT ||
1225         con->type == CT_DOCKAREA) {
1226         DLOG("not handling, type = %d\n", con->type);
1227         return;
1228     }
1229
1230     /* For workspaces, close them only if they're not visible anymore */
1231     if (con->type == CT_WORKSPACE) {
1232         if (TAILQ_EMPTY(&(con->focus_head)) && !workspace_is_visible(con)) {
1233             LOG("Closing old workspace (%p / %s), it is empty\n", con, con->name);
1234             tree_close(con, DONT_KILL_WINDOW, false, false);
1235             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"empty\"}");
1236         }
1237         return;
1238     }
1239
1240     /* TODO: check if this container would swallow any other client and
1241      * don’t close it automatically. */
1242     int children = con_num_children(con);
1243     if (children == 0) {
1244         DLOG("Container empty, closing\n");
1245         tree_close(con, DONT_KILL_WINDOW, false, false);
1246         return;
1247     }
1248 }
1249
1250 /*
1251  * Determines the minimum size of the given con by looking at its children (for
1252  * split/stacked/tabbed cons). Will be called when resizing floating cons
1253  *
1254  */
1255 Rect con_minimum_size(Con *con) {
1256     DLOG("Determining minimum size for con %p\n", con);
1257
1258     if (con_is_leaf(con)) {
1259         DLOG("leaf node, returning 75x50\n");
1260         return (Rect){ 0, 0, 75, 50 };
1261     }
1262
1263     if (con->type == CT_FLOATING_CON) {
1264         DLOG("floating con\n");
1265         Con *child = TAILQ_FIRST(&(con->nodes_head));
1266         return con_minimum_size(child);
1267     }
1268
1269     if (con->layout == L_STACKED || con->layout == L_TABBED) {
1270         uint32_t max_width = 0, max_height = 0, deco_height = 0;
1271         Con *child;
1272         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
1273             Rect min = con_minimum_size(child);
1274             deco_height += child->deco_rect.height;
1275             max_width = max(max_width, min.width);
1276             max_height = max(max_height, min.height);
1277         }
1278         DLOG("stacked/tabbed now, returning %d x %d + deco_rect = %d\n",
1279              max_width, max_height, deco_height);
1280         return (Rect){ 0, 0, max_width, max_height + deco_height };
1281     }
1282
1283     /* For horizontal/vertical split containers we sum up the width (h-split)
1284      * or height (v-split) and use the maximum of the height (h-split) or width
1285      * (v-split) as minimum size. */
1286     if (con->split) {
1287         uint32_t width = 0, height = 0;
1288         Con *child;
1289         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
1290             Rect min = con_minimum_size(child);
1291             if (con->layout == L_SPLITH) {
1292                 width += min.width;
1293                 height = max(height, min.height);
1294             } else {
1295                 height += min.height;
1296                 width = max(width, min.width);
1297             }
1298         }
1299         DLOG("split container, returning width = %d x height = %d\n", width, height);
1300         return (Rect){ 0, 0, width, height };
1301     }
1302
1303     ELOG("Unhandled case, type = %d, layout = %d, split = %d\n",
1304          con->type, con->layout, con->split);
1305     assert(false);
1306 }
1307
1308 /*
1309  * Returns true if changing the focus to con would be allowed considering
1310  * the fullscreen focus constraints. Specifically, if a fullscreen container or
1311  * any of its descendants is focused, this function returns true if and only if
1312  * focusing con would mean that focus would still be visible on screen, i.e.,
1313  * the newly focused container would not be obscured by a fullscreen container.
1314  *
1315  * In the simplest case, if a fullscreen container or any of its descendants is
1316  * fullscreen, this functions returns true if con is the fullscreen container
1317  * itself or any of its descendants, as this means focus wouldn't escape the
1318  * boundaries of the fullscreen container.
1319  *
1320  * In case the fullscreen container is of type CF_OUTPUT, this function returns
1321  * true if con is on a different workspace, as focus wouldn't be obscured by
1322  * the fullscreen container that is constrained to a different workspace.
1323  *
1324  * Note that this same logic can be applied to moving containers. If a
1325  * container can be focused under the fullscreen focus constraints, it can also
1326  * become a parent or sibling to the currently focused container.
1327  *
1328  */
1329 bool con_fullscreen_permits_focusing(Con *con) {
1330     /* No focus, no problem. */
1331     if (!focused)
1332         return true;
1333
1334     /* Find the first fullscreen ascendent. */
1335     Con *fs = focused;
1336     while (fs && fs->fullscreen_mode == CF_NONE)
1337         fs = fs->parent;
1338
1339     /* fs must be non-NULL since the workspace con doesn’t have CF_NONE and
1340      * there always has to be a workspace con in the hierarchy. */
1341     assert(fs != NULL);
1342     /* The most common case is we hit the workspace level. In this
1343      * situation, changing focus is also harmless. */
1344     assert(fs->fullscreen_mode != CF_NONE);
1345     if (fs->type == CT_WORKSPACE)
1346         return true;
1347
1348     /* Allow it if the container itself is the fullscreen container. */
1349     if (con == fs)
1350         return true;
1351
1352     /* If fullscreen is per-output, the focus being in a different workspace is
1353      * sufficient to guarantee that change won't leave fullscreen in bad shape. */
1354     if (fs->fullscreen_mode == CF_OUTPUT &&
1355         con_get_workspace(con) != con_get_workspace(fs)) {
1356             return true;
1357     }
1358
1359     /* Allow it only if the container to be focused is contained within the
1360      * current fullscreen container. */
1361     do {
1362         if (con->parent == fs)
1363             return true;
1364         con = con->parent;
1365     } while (con);
1366
1367     /* Focusing con would hide it behind a fullscreen window, disallow it. */
1368     return false;
1369 }