/*
 *  Copyright (C) 2004 Morten Fjord-Larsen
 *
 *  $Id: clipboard.c,v 1.1 2004/06/11 12:51:36 fjord Exp $
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gnome.h>
#include <string.h>


static void get_selection_cb (GtkClipboard *clipboard,
                              GtkSelectionData *selection_data,
			      guint info,
			      gpointer user_data)
{
    GSList *list = (GSList *)user_data;

    while (list != NULL && list->data == NULL) {
	list = g_slist_next(list);
    }
    
    if (list != NULL) {
	gchar *str = (gchar *)list->data;

	gtk_selection_data_set(selection_data, GDK_TARGET_STRING, 8,
		               str, strlen(str));

	if (list->next != NULL) {
	    list->data = NULL;
	    g_free(str);
	}
    }

    app_status_say(_("Username/password retrieved from clipboard by another application."));
}


static void clear_selection_cb(GtkClipboard *clipboard, 
			       gpointer user_data)
{
    GSList *list = (GSList *)user_data;
    GSList *it;

    for (it = list; it != NULL; it = g_slist_next(it)) {
	g_free(it->data);
	it->data = NULL;
    }

    g_slist_free(list);
}


static void clipboard_copy_to (GdkAtom atom, const char *const *str, int n)
{
    GtkClipboard *clipboard = gtk_clipboard_get(atom);
    GtkTargetEntry targets[] = {{ "STRING", 0, 0 }};
    GSList *list = NULL;
    int i;

    for (i = n-1; i >= 0; i--) {
	list = g_slist_prepend(list, g_strdup(str[i]));
    }

    g_assert(clipboard != NULL);
    gtk_clipboard_set_with_data(clipboard, targets, 1, 
	    			get_selection_cb,
				clear_selection_cb, 
				list);
}

void clipboard_copy_sequence (const gchar *const *str, int n)
{
    clipboard_copy_to(GDK_SELECTION_PRIMARY, str, n);
    clipboard_copy_to(GDK_SELECTION_CLIPBOARD, str, n);
}

void clipboard_copy (const char *str) 
{
    const char *seq[] = { str };
    clipboard_copy_sequence(seq, 1);
}


void clipboard_clear ()
{
    GtkClipboard *clipboard;
    clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
    g_assert(clipboard != NULL);
    gtk_clipboard_clear(clipboard);

    clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
    g_assert(clipboard != NULL);
    gtk_clipboard_clear(clipboard);
}
