#include <gtk/gtk.h>
#include <pthread.h>
#include <unistd.h>

#define MAX_LABELS 16

static GtkWidget* labels[MAX_LABELS];
static int f_exit = 0;

static void* leaker_proc(void* data)
{
    int i;

    while(!f_exit)
    {
        for(i = 0; i < MAX_LABELS && !f_exit; i += 4)
        {
            gdk_threads_enter();
            gtk_label_set_text(GTK_LABEL(labels[i + 0]), "FOOBAR1");
            gtk_label_set_text(GTK_LABEL(labels[i + 1]), "FOOBAR2");
            gtk_label_set_text(GTK_LABEL(labels[i + 2]), "FOOBAR3");
            gtk_label_set_text(GTK_LABEL(labels[i + 3]), "FOOBAR4");
            gdk_threads_leave();
        };
        usleep(10);
    };

    g_warning("%s: finished", __FUNCTION__);

    return NULL;
};

static GtkWidget* ui_create()
{
    int i;
    GtkWidget *wnd;
    GtkWidget* vbox = NULL;
    PangoFontDescription *desc;

    wnd = gtk_window_new (GTK_WINDOW_TOPLEVEL);

    vbox = gtk_vbox_new(FALSE, 0);
    gtk_widget_set_size_request(vbox, 250, -1);
    gtk_widget_show(vbox);
    gtk_container_add(GTK_CONTAINER(wnd), vbox);

    desc = pango_font_description_from_string("Monospace 14");

    for(i = 0; i < MAX_LABELS; i++)
    {
        labels[i] = gtk_label_new(" 12123 123123 123213 ");
        gtk_widget_show(labels[i]);
        if(i & 1)
            gtk_box_pack_start(GTK_BOX(vbox), labels[i], TRUE, TRUE, 0);
        else
            gtk_box_pack_start(GTK_BOX(vbox), labels[i], FALSE, FALSE, 0);
        if(i & 2)
            gtk_widget_modify_font(labels[i], desc);
    }

    pango_font_description_free(desc);

    return wnd;
}

static gboolean on_main_window_delete_event( GtkWidget *widget, GdkEvent *event, gpointer user_data )
{

    g_print ("delete event occurred [start]\n");
    gdk_threads_leave();
    f_exit = 1;
    gdk_threads_enter();
    g_print ("delete event occurred [finish]\n");

    return FALSE;
}

static void on_main_window_destroy( GtkWidget *widget, gpointer user_data )
{
    g_print ("destroy occurred\n");
    gtk_main_quit();
}

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

    g_thread_init(NULL);
    gdk_threads_init();
    gtk_set_locale();
    gtk_init(&argc, &argv);

    window = ui_create();

    gdk_threads_enter();

    gtk_widget_show(window);

    gtk_signal_connect(GTK_OBJECT(window ), "delete-event",
        GTK_SIGNAL_FUNC(on_main_window_delete_event), NULL);

    gtk_signal_connect(GTK_OBJECT(window ), "destroy",
        GTK_SIGNAL_FUNC(on_main_window_destroy), NULL);

    /* create library notification update thread */
    pthread_create(&th, NULL, leaker_proc, NULL);

    gtk_main();
    gdk_threads_leave();

    pthread_join(th, NULL);

    return 0;
}
