diff --git a/gtk/gtkapplication.c b/gtk/gtkapplication.c
index 701a0e8..d538ebc 100644
--- a/gtk/gtkapplication.c
+++ b/gtk/gtkapplication.c
@@ -67,6 +67,29 @@ struct _GtkApplicationPrivate
   GList *windows;
 };
 
+static gboolean
+gtk_application_focus_in_event_cb (GtkWindow      *window,
+                                   GdkEventFocus  *event,
+                                   GtkApplication *application)
+{
+  GtkApplicationPrivate *priv = application->priv;
+  GList *link;
+
+  /* Keep the window list sorted by most-recently-focused. */
+
+  link = g_list_find (priv->windows, window);
+  if (link == NULL)
+    return FALSE;
+
+  if (link != priv->windows)
+    {
+      priv->windows = g_list_remove_link (priv->windows, link);
+      priv->windows = g_list_concat (link, priv->windows);
+    }
+
+  return FALSE;
+}
+
 static void
 gtk_application_startup (GApplication *application)
 {
@@ -209,6 +232,10 @@ gtk_application_add_window (GtkApplication *application,
       priv->windows = g_list_prepend (priv->windows, window);
       gtk_window_set_application (window, application);
       g_application_hold (G_APPLICATION (application));
+
+      g_signal_connect (window, "focus-in-event",
+                        G_CALLBACK (gtk_application_focus_in_event_cb),
+                        application);
     }
 }
 
@@ -239,6 +266,11 @@ gtk_application_remove_window (GtkApplication *application,
   priv = application->priv;
   if (g_list_find (priv->windows, window))
     {
+      if (GTK_IS_WINDOW (window))
+        g_signal_handlers_disconnect_by_func (window,
+                                              gtk_application_focus_in_event_cb,
+                                              application);
+
       priv->windows = g_list_remove (priv->windows, window);
       g_application_release (G_APPLICATION (application));
       gtk_window_set_application (window, NULL);
@@ -251,6 +283,10 @@ gtk_application_remove_window (GtkApplication *application,
  *
  * Gets a list of the #GtkWindow<!-- -->s associated with @application.
  *
+ * The list is sorted by most recently focused window, such that the first
+ * element is the currently focused window.  (Useful for choosing a parent
+ * for a transient window.)
+ *
  * The list that is returned should not be modified in any way.
  *
  * Returns: (element-type GtkWindow) (transfer none): a #GList of #GtkWindow
