#include <gtk/gtk.h>

static void owner_change_cb(GtkClipboard *clipboard,
                            GdkEvent     *event,
                            gpointer      user_data)
{
    g_message("owner change, gtk owner at %p", gtk_clipboard_get_owner(clipboard));
}

static void clipboard_get_cb(GtkClipboard     *clipboard,
                             GtkSelectionData *selection_data,
                             guint             info,
                             gpointer          user_data)
{
    if (!gtk_selection_data_set_text(selection_data, "Just a test string", -1))
        g_warning("setting clipboard selection failed");
}

static void clipboard_clear_cb(GtkClipboard *clipboard,
                               gpointer      user_data)
{
    g_message("clipboard clear");
}

static void button_click_cb(GtkButton *button,
                            gpointer   user_data)
{
    GtkClipboard *clipboard;
    GtkTargetList *list;
    GtkTargetEntry *targets;
    gint n_targets;

    clipboard = gtk_clipboard_get_for_display(gtk_widget_get_display(GTK_WIDGET(button)),
                                              GDK_SELECTION_CLIPBOARD);

    list = gtk_target_list_new(NULL, 0);
    gtk_target_list_add_text_targets(list, 0);
    targets = gtk_target_table_new_from_list(list, &n_targets);

    if (!gtk_clipboard_set_with_owner(clipboard,
                                      targets, n_targets,
                                      clipboard_get_cb, clipboard_clear_cb,
                                      user_data))
        g_warning("setting clipboard failed");

    gtk_target_table_free(targets, n_targets);
    gtk_target_list_unref(list);
}

int main(int argc, char **argv)
{
    GtkWidget *window, *button;
    GtkClipboard *clipboard;
    GObject *clip_owner;

    gtk_init();

    clip_owner = g_object_new(G_TYPE_OBJECT, NULL);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(window, "destroy", gtk_main_quit, NULL);

    clipboard = gtk_clipboard_get_for_display(gtk_widget_get_display(window),
                                              GDK_SELECTION_CLIPBOARD);
    g_signal_connect(G_OBJECT(clipboard), "owner-change",
                     G_CALLBACK(owner_change_cb), NULL);

    button = gtk_button_new_with_label("Set clipboard");
    g_object_set(button, "margin", 20, NULL);
    g_signal_connect(button, "clicked", G_CALLBACK(button_click_cb), clip_owner);
    gtk_container_add(GTK_CONTAINER(window), button);

    gtk_widget_show(window);
    gtk_widget_show(button);

    gtk_main();

    g_object_unref(clip_owner);

    return 0;
}
