/* -*- Mode: C; c-file-style: "gnu"; tab-width: 8 -*- */
#include <gtk/gtk.h>

gchar *tabs1 [] = {
  "a",
  "b",
  "c",
  "d",
  NULL
};

gchar *tabs2 [] = {
  "1",
  "2",
  "3",
  "4",
  "5",
  NULL
};

gchar *tabs3 [] = {
  "foo",
  "bar",
  NULL
};

gchar *tabs4 [] = {
  "beer",
  "water",
  "lemonade",
  "coffee",
  "tea",
  NULL
};

static void
on_tab_detached (GtkWidget *widget, GtkWidget *child, gpointer user_data)
{
  GdkWindow *window;
  GdkDisplay *display;
  GtkWidget *label, *dest_widget;
  gint x, y;

  display = gdk_display_get_default ();
  window = gdk_display_get_window_at_pointer (display, &x, &y);

  if (!window)
    return;

  gdk_window_get_user_data (window, (gpointer*) &dest_widget);

  if (!dest_widget)
    return;

  if (!GTK_IS_NOTEBOOK (dest_widget))
    return;

  label = gtk_notebook_get_tab_label (GTK_NOTEBOOK (widget), child);
  g_object_ref (child);
  g_object_ref (label);

  gtk_container_remove (GTK_CONTAINER (widget), child);

  gtk_notebook_append_page (GTK_NOTEBOOK (dest_widget), child, label);
}

static GtkWidget*
create_notebook (gchar **labels)
{
  GtkWidget *notebook, *title, *label;

  notebook = gtk_notebook_new ();

  gtk_notebook_set_scrollable (GTK_NOTEBOOK (notebook), TRUE);
  gtk_container_set_border_width (GTK_CONTAINER (notebook), 6);

  while (*labels)
    {
      label = gtk_label_new (*labels);
      title = gtk_label_new (*labels);

      gtk_notebook_append_page (GTK_NOTEBOOK (notebook), label, title);
      gtk_notebook_set_tab_reorderable (GTK_NOTEBOOK (notebook), label, TRUE);
      gtk_notebook_set_tab_detachable (GTK_NOTEBOOK (notebook), label, TRUE);

      labels++;
    }

  g_signal_connect (G_OBJECT (notebook), "tab-detached",
		    G_CALLBACK (on_tab_detached), NULL);

  return notebook;
}

gint
main (gint argc, gchar *argv[])
{
  GtkWidget *window, *table;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  table = gtk_table_new (2, 2, TRUE);

  gtk_table_attach_defaults (GTK_TABLE (table), create_notebook (tabs1), 0, 1, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE (table), create_notebook (tabs2), 0, 1, 1, 2);
  gtk_table_attach_defaults (GTK_TABLE (table), create_notebook (tabs3), 1, 2, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE (table), create_notebook (tabs4), 1, 2, 1, 2);

  gtk_container_add (GTK_CONTAINER (window), table);
  gtk_window_set_default_size (GTK_WINDOW (window), 400, 400);
  gtk_widget_show_all (window);

  gtk_main ();

  return 0;
}
