+ /* We compare the focus order of the children of the lowest common ancestor. If con or
+ * its ancestor is before target's ancestor then con should be placed before the target
+ * in the focus stack. */
+ Con *lca = lowest_common_ancestor(con, parent);
+ if (lca == con) {
+ ELOG("Container is being inserted into one of its descendants.\n");
+ return;
+ }
+
+ Con *con_ancestor = child_containing_con_recursively(lca, con);
+ Con *target_ancestor = child_containing_con_recursively(lca, target);
+ bool moves_focus_from_ancestor = is_focused_descendant(con, con_ancestor);
+ bool focus_before;
+
+ /* Determine if con is going to be placed before or after target in the parent's focus stack. */
+ if (con_ancestor == target_ancestor) {
+ /* Happens when the target is con's old parent. Eg with layout V [ A H [ B C ] ],
+ * if we move C up. Target will be H. */
+ focus_before = moves_focus_from_ancestor;
+ } else {
+ /* Look at the focus stack order of the children of the lowest common ancestor. */
+ Con *current;
+ TAILQ_FOREACH(current, &(lca->focus_head), focused) {
+ if (current == con_ancestor || current == target_ancestor) {
+ break;
+ }
+ }
+ focus_before = (current == con_ancestor);
+ }
+
+ /* If con is the focused container in our old ancestor we place the new ancestor
+ * before the old ancestor in the focus stack. Example:
+ * Consider the layout [ H [ V1 [ A* B ] V2 [ C ] ] ] where A is focused. We move to
+ * a second workspace and from there we move A to the right and switch back to the
+ * original workspace. Without the change focus would move to B instead of staying
+ * with A. */
+ if (moves_focus_from_ancestor && focus_before) {
+ Con *place = TAILQ_PREV(con_ancestor, focus_head, focused);
+ TAILQ_REMOVE(&(lca->focus_head), target_ancestor, focused);
+ if (place) {
+ TAILQ_INSERT_AFTER(&(lca->focus_head), place, target_ancestor, focused);
+ } else {
+ TAILQ_INSERT_HEAD(&(lca->focus_head), target_ancestor, focused);
+ }
+ }
+