#include <gtk/gtk.h>

enum {
  DESTROY_PARENT,
  DETACH_ATTACH
};

static void
dialog_response (GtkDialog *dialog, int response, gpointer user_data)
{
  GtkWidget **window = user_data;

  if (response == DESTROY_PARENT)
    {
      gtk_dialog_set_response_sensitive (dialog, DESTROY_PARENT, FALSE);
      gtk_dialog_set_response_sensitive (dialog, DETACH_ATTACH, FALSE);
      gtk_widget_destroy (*window);
      *window = NULL;
    }
  else if (response == DETACH_ATTACH)
    {
      GtkWidget *button = gtk_dialog_get_widget_for_response (dialog, response);

      if (gtk_window_get_transient_for (GTK_WINDOW (dialog)))
	{
	  gtk_dialog_set_response_sensitive (dialog, DESTROY_PARENT, FALSE);
	  gtk_window_set_transient_for (GTK_WINDOW (dialog), NULL);
	  gtk_button_set_label (GTK_BUTTON (button), "Reattach");
	}
      else
	{
	  if (*window)
	    gtk_dialog_set_response_sensitive (dialog, DESTROY_PARENT, TRUE);
	  gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (*window));
	  gtk_button_set_label (GTK_BUTTON (button), "Detach");
	}
    }
  else if (response == GTK_RESPONSE_CLOSE)
    gtk_main_quit ();
}

int
main (int argc, char **argv)
{
  GtkWidget *window, *dialog;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Parent");
  gtk_widget_show (window);

  dialog = gtk_dialog_new_with_buttons ("Child",
					GTK_WINDOW (window),
					GTK_DIALOG_MODAL,
					"Destroy Parent",
					DESTROY_PARENT,
					"Detach",
					DETACH_ATTACH,
					GTK_STOCK_CLOSE,
					GTK_RESPONSE_CLOSE,
					NULL);
  g_signal_connect (dialog, "response", G_CALLBACK (dialog_response), &window);
  gtk_widget_show (dialog);

  gtk_main ();

  return 0;
}
