#include <gtk/gtk.h>

static gboolean do_pointer_grab(GtkEventBox *eventbox)
{
        GdkWindow *window = GDK_WINDOW(gtk_widget_get_window(GTK_WIDGET(eventbox)));
        GdkGrabStatus status;

        gtk_widget_grab_focus(GTK_WIDGET(eventbox));

        if (!gtk_widget_get_realized(GTK_WIDGET(eventbox)))
                return FALSE;

        g_warning("grabbing GdkWindow 0x%p", window);
        status = gdk_pointer_grab(window, FALSE,
                                  GDK_POINTER_MOTION_MASK |
                                  GDK_BUTTON_PRESS_MASK |
                                  GDK_BUTTON_RELEASE_MASK |
                                  GDK_BUTTON_MOTION_MASK |
                                  GDK_SCROLL_MASK,
                                  NULL,
                                  NULL,
                                  GDK_CURRENT_TIME);

        g_warn_if_fail(status == GDK_GRAB_SUCCESS);

        return FALSE;
}


static gboolean grab_broken(GtkEventBox *self, GdkEventGrabBroken *event,
                            gpointer user_data G_GNUC_UNUSED)
{
        GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(self));

        g_warning("grab broken by new grab window 0x%p", event->grab_window);
        if (window == event->grab_window) {
                g_warning("grab broken by window we called gdk_pointer_grab() on!");
        }

        return FALSE;
}

static gboolean button_event(GtkWidget *widget, GdkEventButton *button)
{
        do_pointer_grab(GTK_EVENT_BOX(widget));

        return TRUE;
}


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

        gtk_init(&argc, &argv);
        label = gtk_label_new("Click Me!");

        eventbox = gtk_event_box_new();

        gtk_widget_add_events(eventbox, GDK_BUTTON_PRESS_MASK);

        /* Commenting this make the spurious grab-broken go away */
        gtk_event_box_set_above_child(GTK_EVENT_BOX(eventbox), TRUE);

        g_signal_connect(eventbox, "grab-broken-event", G_CALLBACK(grab_broken), NULL);

        g_signal_connect(eventbox, "button-press-event", G_CALLBACK(button_event), NULL);

        gtk_container_add(GTK_CONTAINER(eventbox), label);

        window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        gtk_window_set_default_size(GTK_WINDOW(window), 200, 100);
        gtk_container_add(GTK_CONTAINER(window), eventbox);

        g_timeout_add_seconds(20, (GSourceFunc)gtk_main_quit, NULL);

        gtk_widget_show_all(window);

        gtk_main();

        return 0;
}
