/*
  Compile with:
  gcc -o test test.c $(pkg-config --cflags --libs gtk+-2.0)
*/

#include <gtk/gtk.h>

#define NUM_WINDOWS 3

GtkWidget *win[NUM_WINDOWS];
GtkWidget *dialog[NUM_WINDOWS];
GtkWidget *button[NUM_WINDOWS];
GtkWindow *gdkwin[NUM_WINDOWS];

static int remaining_windows = NUM_WINDOWS;

static void
window_destroyed_cb (GtkWidget *win, gpointer data)
{
    int i = GPOINTER_TO_INT (data);
    g_debug ("Window %d destroyed", i);
    remaining_windows--;
    if (!remaining_windows)
        gtk_main_quit ();
}

static void
button_clicked_cb (GtkButton *button, gpointer data)
{
    int i = GPOINTER_TO_INT (data);
    g_debug ("Window %d button clicked", i);
    gtk_widget_show_all (dialog[i]);
    gtk_dialog_run (GTK_DIALOG (dialog[i]));
    gtk_widget_hide (dialog[i]);
}

int
main (int argc, char **argv)
{
    int i;

    gtk_init (&argc, &argv);

    for (i = 0; i < NUM_WINDOWS; i++) {
        GtkWindowGroup *group;
        gchar *text;

        text = g_strdup_printf ("This is window %d", i);
        win[i] = gtk_window_new (GTK_WINDOW_TOPLEVEL);
        gtk_window_set_title (GTK_WINDOW (win[i]), text);
        g_free (text);

        text = g_strdup_printf ("Click me %d", i);
        button[i] = gtk_button_new_with_label (text);
        g_free (text);

        group = gtk_window_group_new ();
        gtk_window_group_add_window (group, GTK_WINDOW (win[i]));

        text = g_strdup_printf ("This is dialog %d", i);
        dialog[i] = gtk_dialog_new_with_buttons (
            text, GTK_WINDOW (win[i]),
            GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_STOCK_CLOSE, GTK_RESPONSE_ACCEPT,
            NULL);
        g_free (text);

        gtk_container_add (GTK_CONTAINER (win[i]), button[i]);

        g_signal_connect (button[i], "clicked", G_CALLBACK (button_clicked_cb), GINT_TO_POINTER (i));
        g_signal_connect (win[i], "destroy", G_CALLBACK (window_destroyed_cb), GINT_TO_POINTER (i));

        gtk_widget_show_all (win[i]);
    }

    gtk_main ();

    return 0;
}
