// -*- c++ -*-
/* $Id: clipboard.ccg,v 1.11 2006/06/13 17:16:26 murrayc Exp $ */

/* 
 *
 * Copyright 2002 The gtkmm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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 Library General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <gtkmm/textbuffer.h>
#include <gtkmm/selectiondata_private.h>
#include <glibmm/utility.h> //For ScopedPtr<>.
#include <gtk/gtkclipboard.h>

namespace
{

// SignalProxy_GetClear:
// This Signal Proxy allows the C++ coder to specify a sigc::slot instead of a static function.
class SignalProxy_GetClear
{
public:
  SignalProxy_GetClear(const Gtk::Clipboard::SlotGet& slot_get,
                       const Gtk::Clipboard::SlotClear& slot_clear);

  static void gtk_callback_get(GtkClipboard* clipboard, GtkSelectionData* selection_data,
                               unsigned int info, void* data);
  static void gtk_callback_clear(GtkClipboard* clipboard, void* data);

  Gtk::Clipboard::SlotGet   slot_get_;
  Gtk::Clipboard::SlotClear slot_clear_;
};

SignalProxy_GetClear::SignalProxy_GetClear(const Gtk::Clipboard::SlotGet& slot_get,
                                           const Gtk::Clipboard::SlotClear& slot_clear)
:
  slot_get_   (slot_get),
  slot_clear_ (slot_clear)
{}

static void SignalProxy_GetClear_gtk_callback_get(GtkClipboard*, GtkSelectionData* selection_data,
                                            unsigned int info, void* data)
{
  SignalProxy_GetClear *const self = static_cast<SignalProxy_GetClear*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    Gtk::SelectionData_WithoutOwnership cppSelectionData(selection_data);
    (self->slot_get_)(cppSelectionData, info);
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED
}

static void SignalProxy_GetClear_gtk_callback_clear(GtkClipboard*, void* data)
{
  SignalProxy_GetClear *const self = static_cast<SignalProxy_GetClear*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    (self->slot_clear_)();
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED

  delete self; // After this callback has been called, none of the 2 callbacks will be called again.

  //This might leak the last SignalProxy_GetClear(), but only the last one,
  //because clear() is called when set() is called again.
}

} //anonymous namespace


static void SignalProxy_Received_gtk_callback(GtkClipboard*, GtkSelectionData* selection_data, void* data)
{
  Gtk::Clipboard::SlotReceived* the_slot = static_cast<Gtk::Clipboard::SlotReceived*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    Gtk::SelectionData cppSelectionData(selection_data, true /*take_copy=true*/);
    (*the_slot)(cppSelectionData);
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED

  delete the_slot;
}

//This is not public API:
typedef std::list<Glib::ustring> listStrings;
static listStrings util_convert_atoms_to_strings(GdkAtom* targets, int n_targets)
{
  listStrings listTargets;

  //Add the targets to the C++ container:
  for(int i = 0; i < n_targets; i++)
  {
    //Convert the atom to a string:
    char* atom_name = gdk_atom_name(targets[i]);
    if(atom_name)
    {
      listTargets.push_back( Glib::ustring(atom_name) );
      g_free(atom_name);
    }
  }

  return listTargets;
}

static void SignalProxy_TargetsReceived_gtk_callback(GtkClipboard*, GdkAtom* atoms, gint n_atoms, gpointer data)
{
  Gtk::Clipboard::SlotTargetsReceived* the_slot = static_cast<Gtk::Clipboard::SlotTargetsReceived*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    listStrings listTargets = util_convert_atoms_to_strings(atoms, n_atoms);
    (*the_slot)(listTargets);
    //I guess that GTK+ does a g_free of the GdkAtoms* array itself, so we do not need to. murrayc.
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED

  delete the_slot; // the callback is only used once
}


static void SignalProxy_TextReceived_gtk_callback(GtkClipboard*, const char* text, void* data)
{
  Gtk::Clipboard::SlotTextReceived* the_slot = static_cast<Gtk::Clipboard::SlotTextReceived*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    (*the_slot)((text) ? Glib::ustring(text) : Glib::ustring());
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED

  delete the_slot; // the callback is only used once
}

static void SignalProxy_RichTextReceived_gtk_callback(GtkClipboard*, GdkAtom format, const guint8* text, gsize             length, void* data)
{
  Gtk::Clipboard::SlotRichTextReceived* the_slot = static_cast<Gtk::Clipboard::SlotRichTextReceived*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    gchar* format_atom_name = gdk_atom_name(format);
    (*the_slot)( (format_atom_name ? Glib::ustring(format_atom_name) : Glib::ustring()), (text ? std::string((char*)text, length) : std::string()) );
    g_free(format_atom_name);
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED

  delete the_slot; // the callback is only used once
}

static void SignalProxy_ImageReceived_gtk_callback(GtkClipboard*, GdkPixbuf* image, void* data)
{
  Gtk::Clipboard::SlotImageReceived* the_slot = static_cast<Gtk::Clipboard::SlotImageReceived*>(data);

  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  try
  {
  #endif //GLIBMM_EXCEPTIONS_ENABLED
    (*the_slot)(Glib::wrap(image, true /* take_ref */));
  #ifdef GLIBMM_EXCEPTIONS_ENABLED
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
  #endif //GLIBMM_EXCEPTIONS_ENABLED

  delete the_slot; // the callback is only used once
}


namespace Gtk
{

bool Clipboard::set(const ArrayHandle_TargetEntry& targets,
                    const SlotGet& slot_get, const SlotClear& slot_clear)
{
  // Create a signal proxy. A pointer to this will be passed through the callback's data parameter.
  SignalProxy_GetClear *const pSignalProxy = new SignalProxy_GetClear(slot_get, slot_clear);

  return gtk_clipboard_set_with_data(
      gobj(), targets.data(), targets.size(),
      &SignalProxy_GetClear_gtk_callback_get,
      &SignalProxy_GetClear_gtk_callback_clear,
      pSignalProxy);
}

void Clipboard::set_text(const Glib::ustring& text)
{
  gtk_clipboard_set_text(gobj(), text.c_str(), text.bytes());
}


void Clipboard::request_contents(const Glib::ustring& target, const SlotReceived& slot)
{
  // Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  SlotReceived* slot_copy = new SlotReceived(slot);

  gtk_clipboard_request_contents(gobj(), gdk_atom_intern(target.c_str(), FALSE),
      &SignalProxy_Received_gtk_callback, slot_copy);
}

void Clipboard::request_text(const SlotTextReceived& slot)
{
  // Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  SlotTextReceived* slot_copy = new SlotTextReceived(slot);

  gtk_clipboard_request_text(gobj(),
      &SignalProxy_TextReceived_gtk_callback, slot_copy);
}

void Clipboard::request_rich_text(const Glib::RefPtr<TextBuffer>& buffer, const SlotRichTextReceived& slot)
{
  // Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  SlotRichTextReceived* slot_copy = new SlotRichTextReceived(slot);

  gtk_clipboard_request_rich_text(gobj(), buffer->gobj(), 
      &SignalProxy_RichTextReceived_gtk_callback, slot_copy);
}

void Clipboard::request_image(const SlotImageReceived& slot)
{
  // Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  SlotImageReceived* slot_copy = new SlotImageReceived(slot);

  gtk_clipboard_request_image(gobj(),
      &SignalProxy_ImageReceived_gtk_callback, slot_copy);
}

void Clipboard::request_targets(const SlotTargetsReceived& slot)
{
  // Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  SlotTargetsReceived* slot_copy = new SlotTargetsReceived(slot);

  gtk_clipboard_request_targets(gobj(), &SignalProxy_TargetsReceived_gtk_callback, slot_copy);
}

SelectionData Clipboard::wait_for_contents(const Glib::ustring& target) const
{
  //gtk_clipboard_wait_for_contents returns a newly-allocated GtkSelectionData, or NULL.
  GtkSelectionData* cData = gtk_clipboard_wait_for_contents( const_cast<GtkClipboard*>(gobj()), gdk_atom_intern(target.c_str(), FALSE) );
  return SelectionData(cData, false /* take_copy */);
}

Glib::StringArrayHandle Clipboard::wait_for_targets() const
{
  std::list<Glib::ustring> listTargets;

  //Get a newly-allocated array of atoms:
  GdkAtom* targets = 0;
  gint n_targets = 0;
  gboolean test = gtk_clipboard_wait_for_targets( const_cast<GtkClipboard*>(gobj()), &targets, &n_targets );
  if(!test)
    n_targets = 0; //otherwise it will be -1.

  //Add the targets to the C++ container:
  for(int i = 0; i < n_targets; i++)
  {
    //Convert the atom to a string:
    gchar* const atom_name = gdk_atom_name(targets[i]);

    Glib::ustring target;
    if(atom_name)
      target = Glib::ScopedPtr<char>(atom_name).get(); //This frees the gchar*.

    listTargets.push_back(target);
  }

  return listTargets;
}

void Clipboard::set_can_store(const ArrayHandle_TargetEntry& targets)
{
  gtk_clipboard_set_can_store( gobj(), targets.data(), targets.size() );
}

void Clipboard::set_can_store()
{
  gtk_clipboard_set_can_store( gobj(), 0, 0 /* See C docs */ );
}

std::string Clipboard::wait_for_rich_text(const Glib::RefPtr<TextBuffer>& buffer, std::string& format)
{
  std::string result;

  GdkAtom format_atom = 0;
  gsize length = 0;
  guint8* text = gtk_clipboard_wait_for_rich_text(const_cast<GtkClipboard*>(gobj()), buffer->gobj(), &format_atom, &length);
  if(text && length)
  {
    gchar* format_atom_name = gdk_atom_name(format_atom);
    if(format_atom_name)
      format = Glib::ScopedPtr<char>(format_atom_name).get(); //This frees the buffer.

    result = std::string((char*)text, length);
    g_free(text);
  }

  return result;
}

    
} //namespace Gtk

