desktop-shell: Embed keyboard focus handle code when activating

We shouldn't be constrained by having a keyboard plugged-in, so avoid
activating/de-activating the window/surface in the keyboard focus
handler and embed it straight into the window activation part.

Signed-off-by: Marius Vlad <marius.vlad@collabora.com>
diff --git a/desktop-shell/shell.c b/desktop-shell/shell.c
index 13b7d47..89fc2a7 100644
--- a/desktop-shell/shell.c
+++ b/desktop-shell/shell.c
@@ -1889,22 +1889,7 @@
 static void
 handle_keyboard_focus(struct wl_listener *listener, void *data)
 {
-	struct weston_keyboard *keyboard = data;
-	struct shell_seat *seat = get_shell_seat(keyboard->seat);
-
-	if (seat->focused_surface) {
-		struct shell_surface *shsurf = get_shell_surface(seat->focused_surface);
-		if (shsurf)
-			shell_surface_deactivate(shsurf);
-	}
-
-	seat->focused_surface = weston_surface_get_main_surface(keyboard->focus);
-
-	if (seat->focused_surface) {
-		struct shell_surface *shsurf = get_shell_surface(seat->focused_surface);
-		if (shsurf)
-			shell_surface_activate(shsurf);
-	}
+	/* FIXME: To be removed later. */
 }
 
 /* The surface will be inserted into the list immediately after the link
@@ -2461,6 +2446,7 @@
 	struct shell_surface *shsurf_child, *tmp;
 	struct weston_surface *surface =
 		weston_desktop_surface_get_surface(desktop_surface);
+	struct weston_seat *seat;
 
 	if (!shsurf)
 		return;
@@ -2471,6 +2457,18 @@
 	}
 	wl_list_remove(&shsurf->children_link);
 
+	wl_list_for_each(seat, &shsurf->shell->compositor->seat_list, link) {
+		struct shell_seat *shseat = get_shell_seat(seat);
+		/* activate() controls the focused surface activation and
+		 * removal of a surface requires invalidating the
+		 * focused_surface to avoid activate() use a stale (and just
+		 * removed) surface when attempting to de-activate it. It will
+		 * also update the focused_surface once it has a chance to run.
+		 */
+		if (surface == shseat->focused_surface)
+			shseat->focused_surface = NULL;
+	}
+
 	wl_signal_emit(&shsurf->destroy_signal, shsurf);
 
 	if (shsurf->fullscreen.black_view)
@@ -3867,6 +3865,7 @@
 	struct workspace *ws;
 	struct weston_surface *old_es;
 	struct shell_surface *shsurf, *shsurf_child;
+	struct shell_seat *shseat = get_shell_seat(seat);
 
 	main_surface = weston_surface_get_main_surface(es);
 	shsurf = get_shell_surface(main_surface);
@@ -3886,6 +3885,16 @@
 
 	weston_view_activate(view, seat, flags);
 
+	if (shseat->focused_surface) {
+		struct shell_surface *current_focus =
+			get_shell_surface(shseat->focused_surface);
+		assert(current_focus);
+		shell_surface_deactivate(current_focus);
+	}
+
+	shseat->focused_surface = main_surface;
+	shell_surface_activate(shsurf);
+
 	state = ensure_focus_state(shell, seat);
 	if (state == NULL)
 		return;