/* Bug 710471 - Make gtk_scrolled_window_remove() smart */

/* Test cases:
 * even     Don't ref_sink and unref.
 * odd      ref_sink and unref.
 * 0 and 1  Don't remove and re-add.
 * 2 and 3  Remove with
 *          gtk_container_remove(GTK_CONTAINER(main_area), button_test)
 * 4 and 5  Remove with
 *          gtk_container_remove(GTK_CONTAINER(main_area), gtk_bin_get_child(GTK_BIN(main_area)))
 * 6 and 7  Imitate the gtkmm function Gtk::ScrolledWindow::remove_with_viewport().
 *
 * Cases 0, 1 and 7 work.
 * Case 5 does not work because the GtkButton is destroyed when its parent
 * (the GtkViewport) is destroyed.
 * Case 5 works if the patch in bug 710471 comment 1 is applied.
 */
#define TEST_CASE 5

#include <gtk/gtk.h>

int main(int argc, char* argv[])
{
  GtkWidget* main_win;
  GtkWidget* main_area;
  GtkWidget* button_test;

  gtk_init(&argc, &argv);

  /* Create the window. */
  main_win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(main_win), "gtktest");
  gtk_widget_set_size_request(main_win, 200, 80);

  /* Create the GtkScrolledWindow. */
  /* If I use a Gtk::Frame here instead, everything works. */
  main_area = gtk_scrolled_window_new(NULL, NULL);

  /* Add some button just to show everything works without the buggy code. */
  button_test = gtk_button_new_with_label("asdf");
#if TEST_CASE & 1
  g_object_ref_sink(button_test); /* assume ownership of the button */
#endif
  gtk_widget_set_size_request(button_test, 200, 100);

  /* Add the button to the ScrolledWindow; the ScrolledWindow to the main window. */
  gtk_container_add(GTK_CONTAINER(main_area), button_test);
  gtk_container_add(GTK_CONTAINER(main_win), main_area);

  /* Show all widgets on the main window. */
  gtk_widget_show_all(main_win);

  /* This should simply remove the button from the ScrolledWindow and re-add it. */
#if TEST_CASE == 2 || TEST_CASE == 3
  gtk_container_remove(GTK_CONTAINER(main_area), button_test);
  gtk_container_add(GTK_CONTAINER(main_area), button_test);
#elif TEST_CASE == 4 || TEST_CASE == 5
  gtk_container_remove(GTK_CONTAINER(main_area), gtk_bin_get_child(GTK_BIN(main_area)));
  gtk_container_add(GTK_CONTAINER(main_area), button_test);
#elif TEST_CASE == 6 || TEST_CASE == 7
  /* Imitate Gtk::ScrolledWindow::remove_with_viewport(). */
  gtk_container_remove(GTK_CONTAINER(gtk_bin_get_child(GTK_BIN(main_area))), button_test);
  gtk_container_remove(GTK_CONTAINER(main_area), gtk_bin_get_child(GTK_BIN(main_area)));
  gtk_container_add(GTK_CONTAINER(main_area), button_test);
#endif

  g_signal_connect(main_win, "destroy", G_CALLBACK (gtk_main_quit), NULL);
  gtk_main();
#if TEST_CASE & 1
  g_object_unref(button_test);
#endif
  return 0;
}
