/* PIKA - Photo and Image Kooker Application
 * a rebranding of The GNU Image Manipulation Program (created with heckimp)
 * A derived work which may be trivial. However, any changes may be (C)2023 by Aldercone Studio
 *
 * Original copyright, applying to most contents (license remains unchanged): 
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * 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 3 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <string.h>

#include <gegl.h>
#include <gtk/gtk.h>

#include "libpikamath/pikamath.h"

#include "widgets-types.h"

#include "core/pika.h"
#include "core/pikabuffer.h"
#include "core/pikacurve.h"
#include "core/pikaimage.h"
#include "core/pikapickable.h"

#include "pikaclipboard.h"
#include "pikapixbuf.h"
#include "pikaselectiondata.h"

#include "pika-intl.h"


#define PIKA_CLIPBOARD_KEY "pika-clipboard"


typedef struct _PikaClipboard PikaClipboard;

struct _PikaClipboard
{
  GSList         *pixbuf_formats;

  GtkTargetEntry *image_target_entries;
  gint            n_image_target_entries;

  GtkTargetEntry *buffer_target_entries;
  gint            n_buffer_target_entries;

  GtkTargetEntry *svg_target_entries;
  gint            n_svg_target_entries;

  GtkTargetEntry *curve_target_entries;
  gint            n_curve_target_entries;

  PikaImage      *image;
  PikaBuffer     *buffer;
  gchar          *svg;
  PikaCurve      *curve;
};


static PikaClipboard * pika_clipboard_get        (Pika             *pika);

static PikaClipboard * pika_clipboard_new        (gboolean          verbose);
static void            pika_clipboard_free       (PikaClipboard    *pika_clip);

static void      pika_clipboard_clear            (PikaClipboard    *pika_clip);

static GdkAtom * pika_clipboard_wait_for_targets (Pika             *pika,
                                                  gint             *n_targets);
static GdkAtom   pika_clipboard_wait_for_image   (Pika             *pika);
static GdkAtom   pika_clipboard_wait_for_buffer  (Pika             *pika);
static GdkAtom   pika_clipboard_wait_for_svg     (Pika             *pika);
static GdkAtom   pika_clipboard_wait_for_curve   (Pika             *pika);

static void      pika_clipboard_send_image       (GtkClipboard     *clipboard,
                                                  GtkSelectionData *data,
                                                  guint             info,
                                                  Pika             *pika);
static void      pika_clipboard_send_buffer      (GtkClipboard     *clipboard,
                                                  GtkSelectionData *data,
                                                  guint             info,
                                                  Pika             *pika);
static void      pika_clipboard_send_svg         (GtkClipboard     *clipboard,
                                                  GtkSelectionData *data,
                                                  guint             info,
                                                  Pika             *pika);
static void      pika_clipboard_send_curve       (GtkClipboard     *clipboard,
                                                  GtkSelectionData *data,
                                                  guint             info,
                                                  Pika             *pika);


/*  public functions  */

void
pika_clipboard_init (Pika *pika)
{
  PikaClipboard *pika_clip;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  pika_clip = pika_clipboard_get (pika);

  g_return_if_fail (pika_clip == NULL);

  pika_clip = pika_clipboard_new (pika->be_verbose);

  g_object_set_data_full (G_OBJECT (pika), PIKA_CLIPBOARD_KEY,
                          pika_clip, (GDestroyNotify) pika_clipboard_free);
}

void
pika_clipboard_exit (Pika *pika)
{
  GtkClipboard *clipboard;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) == G_OBJECT (pika))
    {
      gtk_clipboard_store (clipboard);
    }

  if (clipboard)
    /* If we don't clear the clipboard, it keeps a reference on the object
     * owner (i.e. Pika object probably) which fails to finalize.
     */
    gtk_clipboard_clear (clipboard);

  g_object_set_data (G_OBJECT (pika), PIKA_CLIPBOARD_KEY, NULL);
}

/**
 * pika_clipboard_has_image:
 * @pika: pointer to #Pika
 *
 * Tests if there's an image in the clipboard. If the global image cut
 * buffer of @pika is empty, this function returns %NULL.
 *
 * Returns: %TRUE if there's an image in the clipboard, %FALSE otherwise
 **/
gboolean
pika_clipboard_has_image (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      if (pika_clipboard_wait_for_image (pika) != GDK_NONE)
        {
          return TRUE;
        }

      return FALSE;
    }

  pika_clip = pika_clipboard_get (pika);

  return (pika_clip->image != NULL);
}

/**
 * pika_clipboard_has_buffer:
 * @pika: pointer to #Pika
 *
 * Tests if there's image data in the clipboard. If the global cut
 * buffer of @pika is empty, this function checks if there's image
 * data in %GDK_SELECTION_CLIPBOARD. This is done in a main-loop
 * similar to gtk_clipboard_wait_is_text_available(). The same caveats
 * apply here.
 *
 * Returns: %TRUE if there's image data in the clipboard, %FALSE otherwise
 **/
gboolean
pika_clipboard_has_buffer (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      if (pika_clipboard_wait_for_buffer (pika) != GDK_NONE)
        {
          return TRUE;
        }

      return FALSE;
    }

  pika_clip = pika_clipboard_get (pika);

  return (pika_clip->buffer != NULL);
}

/**
 * pika_clipboard_has_svg:
 * @pika: pointer to #Pika
 *
 * Tests if there's SVG data in %GDK_SELECTION_CLIPBOARD.
 * This is done in a main-loop similar to
 * gtk_clipboard_wait_is_text_available(). The same caveats apply here.
 *
 * Returns: %TRUE if there's SVG data in the clipboard, %FALSE otherwise
 **/
gboolean
pika_clipboard_has_svg (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      if (pika_clipboard_wait_for_svg (pika) != GDK_NONE)
        {
          return TRUE;
        }

      return FALSE;
    }

  pika_clip = pika_clipboard_get (pika);

  return (pika_clip->svg != NULL);
}

/**
 * pika_clipboard_has_curve:
 * @pika: pointer to #Pika
 *
 * Tests if there's curve data in %GDK_SELECTION_CLIPBOARD.
 * This is done in a main-loop similar to
 * gtk_clipboard_wait_is_text_available(). The same caveats apply here.
 *
 * Returns: %TRUE if there's curve data in the clipboard, %FALSE otherwise
 **/
gboolean
pika_clipboard_has_curve (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      if (pika_clipboard_wait_for_curve (pika) != GDK_NONE)
        {
          return TRUE;
        }

      return FALSE;
    }

  pika_clip = pika_clipboard_get (pika);

  return (pika_clip->curve != NULL);
}

/**
 * pika_clipboard_get_object:
 * @pika: pointer to #Pika
 *
 * Retrieves either an image or a buffer from the global image cut
 * buffer of @pika.
 *
 * The returned #PikaObject needs to be unref'ed when it's no longer
 * needed.
 *
 * Returns: (nullable): a reference to a #PikaObject or %NULL if there's no
 *               image or buffer in the clipboard
 **/
PikaObject *
pika_clipboard_get_object (Pika *pika)
{
  PikaObject *object;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  object = PIKA_OBJECT (pika_clipboard_get_image (pika));

  if (! object)
    object = PIKA_OBJECT (pika_clipboard_get_buffer (pika));

  return object;
}

/**
 * pika_clipboard_get_image:
 * @pika: pointer to #Pika
 *
 * Retrieves an image from the global image cut buffer of @pika.
 *
 * The returned #PikaImage needs to be unref'ed when it's no longer
 * needed.
 *
 * Returns: (nullable): a reference to a #PikaImage or %NULL if there's no
 *               image in the clipboard
 **/
PikaImage *
pika_clipboard_get_image (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;
  PikaImage     *image = NULL;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), NULL);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      GdkAtom atom = pika_clipboard_wait_for_image (pika);

      if (atom != GDK_NONE)
        {
          GtkSelectionData *data;

          pika_set_busy (pika);

          data = gtk_clipboard_wait_for_contents (clipboard, atom);

          if (data)
            {
              image = pika_selection_data_get_xcf (data, pika);

              gtk_selection_data_free (data);
            }

          pika_unset_busy (pika);
        }

      return image;
    }

  pika_clip = pika_clipboard_get (pika);

  if (! image && pika_clip->image)
    image = g_object_ref (pika_clip->image);

  return image;
}

/**
 * pika_clipboard_get_buffer:
 * @pika: pointer to #Pika
 *
 * Retrieves either image data from %GDK_SELECTION_CLIPBOARD or from
 * the global cut buffer of @pika.
 *
 * The returned #PikaBuffer needs to be unref'ed when it's no longer
 * needed.
 *
 * Returns: (nullable): a reference to a #PikaBuffer or %NULL if there's no
 *               image data
 **/
PikaBuffer *
pika_clipboard_get_buffer (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;
  PikaBuffer    *buffer = NULL;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), NULL);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      GdkAtom atom = pika_clipboard_wait_for_buffer (pika);

      if (atom != GDK_NONE)
        {
          GtkSelectionData *data;

          pika_set_busy (pika);

          data = gtk_clipboard_wait_for_contents (clipboard, atom);

          if (data)
            {
              GdkPixbuf *pixbuf = gtk_selection_data_get_pixbuf (data);

              gtk_selection_data_free (data);

              if (pixbuf)
                {
                  buffer = pika_buffer_new_from_pixbuf (pixbuf, _("Clipboard"),
                                                        0, 0);
                  g_object_unref (pixbuf);
                }
            }

          pika_unset_busy (pika);
        }

      return buffer;
    }

  pika_clip = pika_clipboard_get (pika);

  if (! buffer && pika_clip->buffer)
    buffer = g_object_ref (pika_clip->buffer);

  return buffer;
}

/**
 * pika_clipboard_get_svg:
 * @pika: pointer to #Pika
 * @svg_length: returns the size of the SVG stream in bytes
 *
 * Retrieves SVG data from %GDK_SELECTION_CLIPBOARD or from the global
 * SVG buffer of @pika.
 *
 * The returned data needs to be freed when it's no longer needed.
 *
 * Returns: (nullable): a reference to a #PikaBuffer or %NULL if there's no
 *               image data
 **/
gchar *
pika_clipboard_get_svg (Pika  *pika,
                        gsize *svg_length)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;
  gchar         *svg = NULL;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), NULL);
  g_return_val_if_fail (svg_length != NULL, NULL);

  *svg_length = 0;

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      GdkAtom atom = pika_clipboard_wait_for_svg (pika);

      if (atom != GDK_NONE)
        {
          GtkSelectionData *data;

          pika_set_busy (pika);

          data = gtk_clipboard_wait_for_contents (clipboard, atom);

          if (data)
            {
              const guchar *stream;

              stream = pika_selection_data_get_stream (data, svg_length);

              if (stream)
                svg = g_memdup2 (stream, *svg_length);

              gtk_selection_data_free (data);
            }

          pika_unset_busy (pika);
        }

      return svg;
    }

  pika_clip = pika_clipboard_get (pika);

  if (! svg && pika_clip->svg)
    {
      svg = g_strdup (pika_clip->svg);
      *svg_length = strlen (svg);
    }

  return svg;
}

/**
 * pika_clipboard_get_curve:
 * @pika: pointer to #Pika
 *
 * Retrieves curve data from %GDK_SELECTION_CLIPBOARD or from the global
 * curve buffer of @pika.
 *
 * The returned curve needs to be unref'ed when it's no longer needed.
 *
 * Returns: (nullable): a reference to a #PikaCurve or %NULL if there's no
 *               curve data
 **/
PikaCurve *
pika_clipboard_get_curve (Pika *pika)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;
  PikaCurve     *curve = NULL;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), NULL);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard &&
      gtk_clipboard_get_owner (clipboard) != G_OBJECT (pika))
    {
      GdkAtom atom = pika_clipboard_wait_for_curve (pika);

      if (atom != GDK_NONE)
        {
          GtkSelectionData *data;

          pika_set_busy (pika);

          data = gtk_clipboard_wait_for_contents (clipboard, atom);

          if (data)
            {
              curve = pika_selection_data_get_curve (data);

              gtk_selection_data_free (data);
            }

          pika_unset_busy (pika);
        }

      return curve;
    }

  pika_clip = pika_clipboard_get (pika);

  if (! curve && pika_clip->curve)
    curve = g_object_ref (pika_clip->curve);

  return curve;
}

/**
 * pika_clipboard_set_image:
 * @pika:  pointer to #Pika
 * @image: (nullable): a #PikaImage, or %NULL.
 *
 * Offers the image in %GDK_SELECTION_CLIPBOARD.
 **/
void
pika_clipboard_set_image (Pika      *pika,
                          PikaImage *image)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (image == NULL || PIKA_IS_IMAGE (image));

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);
  if (! clipboard)
    return;

  pika_clip = pika_clipboard_get (pika);

  pika_clipboard_clear (pika_clip);

  if (image)
    {
      pika_clip->image = g_object_ref (image);

      gtk_clipboard_set_with_owner (clipboard,
                                    pika_clip->image_target_entries,
                                    pika_clip->n_image_target_entries,
                                    (GtkClipboardGetFunc) pika_clipboard_send_image,
                                    (GtkClipboardClearFunc) NULL,
                                    G_OBJECT (pika));

      /*  mark the first two entries (image/x-xcf and image/png) as
       *  suitable for storing
       */
      gtk_clipboard_set_can_store (clipboard,
                                   pika_clip->image_target_entries,
                                   MIN (2, pika_clip->n_image_target_entries));
    }
  else if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (pika))
    {
      gtk_clipboard_clear (clipboard);
    }
}

/**
 * pika_clipboard_set_buffer:
 * @pika:   pointer to #Pika
 * @buffer: (nullable): a #PikaBuffer, or %NULL.
 *
 * Offers the buffer in %GDK_SELECTION_CLIPBOARD.
 **/
void
pika_clipboard_set_buffer (Pika       *pika,
                           PikaBuffer *buffer)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (buffer == NULL || PIKA_IS_BUFFER (buffer));

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);
  if (! clipboard)
    return;

  pika_clip = pika_clipboard_get (pika);

  pika_clipboard_clear (pika_clip);

  if (buffer)
    {
      pika_clip->buffer = g_object_ref (buffer);

      gtk_clipboard_set_with_owner (clipboard,
                                    pika_clip->buffer_target_entries,
                                    pika_clip->n_buffer_target_entries,
                                    (GtkClipboardGetFunc) pika_clipboard_send_buffer,
                                    (GtkClipboardClearFunc) NULL,
                                    G_OBJECT (pika));

      /*  mark the first entry (image/png) as suitable for storing  */
      if (pika_clip->n_buffer_target_entries > 0)
        gtk_clipboard_set_can_store (clipboard,
                                     pika_clip->buffer_target_entries, 1);
    }
  else if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (pika))
    {
      gtk_clipboard_clear (clipboard);
    }
}

/**
 * pika_clipboard_set_svg:
 * @pika: pointer to #Pika
 * @svg: (nullable): a string containing the SVG data, or %NULL
 *
 * Offers SVG data in %GDK_SELECTION_CLIPBOARD.
 **/
void
pika_clipboard_set_svg (Pika        *pika,
                        const gchar *svg)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);
  if (! clipboard)
    return;

  pika_clip = pika_clipboard_get (pika);

  pika_clipboard_clear (pika_clip);

  if (svg)
    {
      pika_clip->svg = g_strdup (svg);

      gtk_clipboard_set_with_owner (clipboard,
                                    pika_clip->svg_target_entries,
                                    pika_clip->n_svg_target_entries,
                                    (GtkClipboardGetFunc) pika_clipboard_send_svg,
                                    (GtkClipboardClearFunc) NULL,
                                    G_OBJECT (pika));

      /*  mark the first entry (image/svg) as suitable for storing  */
      gtk_clipboard_set_can_store (clipboard,
                                   pika_clip->svg_target_entries, 1);
    }
  else if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (pika))
    {
      gtk_clipboard_clear (clipboard);
    }
}

/**
 * pika_clipboard_set_text:
 * @pika: pointer to #Pika
 * @text: a %NULL-terminated string in UTF-8 encoding
 *
 * Offers @text in %GDK_SELECTION_CLIPBOARD and %GDK_SELECTION_PRIMARY.
 **/
void
pika_clipboard_set_text (Pika        *pika,
                         const gchar *text)
{
  GtkClipboard *clipboard;

  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (text != NULL);

  pika_clipboard_clear (pika_clipboard_get (pika));

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);
  if (clipboard)
    gtk_clipboard_set_text (clipboard, text, -1);

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_PRIMARY);
  if (clipboard)
    gtk_clipboard_set_text (clipboard, text, -1);
}

/**
 * pika_clipboard_set_curve:
 * @pika: pointer to #Pika
 * @curve: (nullable): a #PikaCurve, or %NULL
 *
 * Offers curve data in %GDK_SELECTION_CLIPBOARD.
 **/
void
pika_clipboard_set_curve (Pika      *pika,
                          PikaCurve *curve)
{
  PikaClipboard *pika_clip;
  GtkClipboard  *clipboard;

  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (curve == NULL || PIKA_IS_CURVE (curve));

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);
  if (! clipboard)
    return;

  pika_clip = pika_clipboard_get (pika);

  pika_clipboard_clear (pika_clip);

  if (curve)
    {
      pika_clip->curve = g_object_ref (curve);

      gtk_clipboard_set_with_owner (clipboard,
                                    pika_clip->curve_target_entries,
                                    pika_clip->n_curve_target_entries,
                                    (GtkClipboardGetFunc) pika_clipboard_send_curve,
                                    (GtkClipboardClearFunc) NULL,
                                    G_OBJECT (pika));

      gtk_clipboard_set_can_store (clipboard,
                                   pika_clip->curve_target_entries, 1);
    }
  else if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (pika))
    {
      gtk_clipboard_clear (clipboard);
    }
}


/*  private functions  */

static PikaClipboard *
pika_clipboard_get (Pika *pika)
{
  return g_object_get_data (G_OBJECT (pika), PIKA_CLIPBOARD_KEY);
}

static PikaClipboard *
pika_clipboard_new (gboolean verbose)
{
  PikaClipboard *pika_clip = g_slice_new0 (PikaClipboard);
  GSList        *list;

  pika_clip->pixbuf_formats = pika_pixbuf_get_formats ();

  for (list = pika_clip->pixbuf_formats; list; list = g_slist_next (list))
    {
      GdkPixbufFormat *format = list->data;

      if (gdk_pixbuf_format_is_writable (format))
        {
          gchar **mime_types;
          gchar **type;

          mime_types = gdk_pixbuf_format_get_mime_types (format);

          for (type = mime_types; *type; type++)
            pika_clip->n_buffer_target_entries++;

          g_strfreev (mime_types);
        }
    }

  /*  the image_target_entries have the XCF target, and all pixbuf
   *  targets that are also in buffer_target_entries
   */
  pika_clip->n_image_target_entries = pika_clip->n_buffer_target_entries + 1;
  pika_clip->image_target_entries   = g_new0 (GtkTargetEntry,
                                              pika_clip->n_image_target_entries);

  pika_clip->image_target_entries[0].target = g_strdup ("image/x-xcf");
  pika_clip->image_target_entries[0].flags  = 0;
  pika_clip->image_target_entries[0].info   = 0;

  if (pika_clip->n_buffer_target_entries > 0)
    {
      gint i = 0;

      pika_clip->buffer_target_entries = g_new0 (GtkTargetEntry,
                                                 pika_clip->n_buffer_target_entries);

      for (list = pika_clip->pixbuf_formats; list; list = g_slist_next (list))
        {
          GdkPixbufFormat *format = list->data;

          if (gdk_pixbuf_format_is_writable (format))
            {
              gchar  *format_name;
              gchar **mime_types;
              gchar **type;

              format_name = gdk_pixbuf_format_get_name (format);
              mime_types  = gdk_pixbuf_format_get_mime_types (format);

              for (type = mime_types; *type; type++)
                {
                  const gchar *mime_type = *type;

                  if (verbose)
                    g_printerr ("clipboard: writable pixbuf format: %s\n",
                                mime_type);

                  pika_clip->image_target_entries[i + 1].target = g_strdup (mime_type);
                  pika_clip->image_target_entries[i + 1].flags  = 0;
                  pika_clip->image_target_entries[i + 1].info   = i + 1;

                  pika_clip->buffer_target_entries[i].target = g_strdup (mime_type);
                  pika_clip->buffer_target_entries[i].flags  = 0;
                  pika_clip->buffer_target_entries[i].info   = i;

                  i++;
                }

              g_strfreev (mime_types);
              g_free (format_name);
            }
        }
    }

  pika_clip->n_svg_target_entries = 2;
  pika_clip->svg_target_entries   = g_new0 (GtkTargetEntry, 2);

  pika_clip->svg_target_entries[0].target = g_strdup ("image/svg");
  pika_clip->svg_target_entries[0].flags  = 0;
  pika_clip->svg_target_entries[0].info   = 0;

  pika_clip->svg_target_entries[1].target = g_strdup ("image/svg+xml");
  pika_clip->svg_target_entries[1].flags  = 0;
  pika_clip->svg_target_entries[1].info   = 1;

  pika_clip->n_curve_target_entries = 1;
  pika_clip->curve_target_entries   = g_new0 (GtkTargetEntry, 1);

  pika_clip->curve_target_entries[0].target = g_strdup ("application/x-pika-curve");
  pika_clip->curve_target_entries[0].flags  = 0;
  pika_clip->curve_target_entries[0].info   = 0;

  return pika_clip;
}

static void
pika_clipboard_free (PikaClipboard *pika_clip)
{
  gint i;

  pika_clipboard_clear (pika_clip);

  g_slist_free (pika_clip->pixbuf_formats);

  for (i = 0; i < pika_clip->n_image_target_entries; i++)
    g_free ((gchar *) pika_clip->image_target_entries[i].target);

  g_free (pika_clip->image_target_entries);

  for (i = 0; i < pika_clip->n_buffer_target_entries; i++)
    g_free ((gchar *) pika_clip->buffer_target_entries[i].target);

  g_free (pika_clip->buffer_target_entries);

  for (i = 0; i < pika_clip->n_svg_target_entries; i++)
    g_free ((gchar *) pika_clip->svg_target_entries[i].target);

  g_free (pika_clip->svg_target_entries);

  for (i = 0; i < pika_clip->n_curve_target_entries; i++)
    g_free ((gchar *) pika_clip->curve_target_entries[i].target);

  g_free (pika_clip->curve_target_entries);

  g_slice_free (PikaClipboard, pika_clip);
}

static void
pika_clipboard_clear (PikaClipboard *pika_clip)
{
  g_clear_object (&pika_clip->image);
  g_clear_object (&pika_clip->buffer);
  g_clear_pointer (&pika_clip->svg, g_free);
  g_clear_object (&pika_clip->curve);
}

static GdkAtom *
pika_clipboard_wait_for_targets (Pika *pika,
                                 gint *n_targets)
{
  GtkClipboard *clipboard;

  clipboard = gtk_clipboard_get_for_display (gdk_display_get_default (),
                                             GDK_SELECTION_CLIPBOARD);

  if (clipboard)
    {
      GtkSelectionData *data;
      GdkAtom           atom = gdk_atom_intern_static_string ("TARGETS");

      data = gtk_clipboard_wait_for_contents (clipboard, atom);

      if (data)
        {
          GdkAtom  *targets;
          gboolean  success;

          success = gtk_selection_data_get_targets (data, &targets, n_targets);

          gtk_selection_data_free (data);

          if (success)
            {
              if (pika->be_verbose)
                {
                  gint i;

                  for (i = 0; i < *n_targets; i++)
                    g_printerr ("clipboard: offered type: %s\n",
                                gdk_atom_name (targets[i]));

                  g_printerr ("\n");
                }

              return targets;
            }
        }
    }

  return NULL;
}

static GdkAtom
pika_clipboard_wait_for_image (Pika *pika)
{
  GdkAtom *targets;
  gint     n_targets;
  GdkAtom  result = GDK_NONE;

  targets = pika_clipboard_wait_for_targets (pika, &n_targets);

  if (targets)
    {
      GdkAtom image_atom = gdk_atom_intern_static_string ("image/x-xcf");
      gint    i;

      for (i = 0; i < n_targets; i++)
        {
          if (targets[i] == image_atom)
            {
              result = image_atom;
              break;
            }
        }

      g_free (targets);
    }

  return result;
}

static GdkAtom
pika_clipboard_wait_for_buffer (Pika *pika)
{
  PikaClipboard *pika_clip = pika_clipboard_get (pika);
  GdkAtom       *targets;
  gint           n_targets;
  GdkAtom        result    = GDK_NONE;

  targets = pika_clipboard_wait_for_targets (pika, &n_targets);

  if (targets)
    {
      GSList *list;

      for (list = pika_clip->pixbuf_formats; list; list = g_slist_next (list))
        {
          GdkPixbufFormat  *format = list->data;
          gchar           **mime_types;
          gchar           **type;

          if (pika->be_verbose)
            g_printerr ("clipboard: checking pixbuf format '%s'\n",
                        gdk_pixbuf_format_get_name (format));

          mime_types = gdk_pixbuf_format_get_mime_types (format);

          for (type = mime_types; *type; type++)
            {
              gchar   *mime_type = *type;
              GdkAtom  atom      = gdk_atom_intern (mime_type, FALSE);
              gint     i;

              if (pika->be_verbose)
                g_printerr ("  - checking mime type '%s'\n", mime_type);

              for (i = 0; i < n_targets; i++)
                {
                  if (targets[i] == atom)
                    {
                      result = atom;
                      break;
                    }
                }

              if (result != GDK_NONE)
                break;
            }

          g_strfreev (mime_types);

          if (result != GDK_NONE)
            break;
        }

      g_free (targets);
    }

  return result;
}

static GdkAtom
pika_clipboard_wait_for_svg (Pika *pika)
{
  GdkAtom *targets;
  gint     n_targets;
  GdkAtom  result = GDK_NONE;

  targets = pika_clipboard_wait_for_targets (pika, &n_targets);

  if (targets)
    {
      GdkAtom svg_atom     = gdk_atom_intern_static_string ("image/svg");
      GdkAtom svg_xml_atom = gdk_atom_intern_static_string ("image/svg+xml");
      gint    i;

      for (i = 0; i < n_targets; i++)
        {
          if (targets[i] == svg_atom)
            {
              result = svg_atom;
              break;
            }
          else if (targets[i] == svg_xml_atom)
            {
              result = svg_xml_atom;
              break;
            }
        }

      g_free (targets);
    }

  return result;
}

static GdkAtom
pika_clipboard_wait_for_curve (Pika *pika)
{
  GdkAtom *targets;
  gint     n_targets;
  GdkAtom  result = GDK_NONE;

  targets = pika_clipboard_wait_for_targets (pika, &n_targets);

  if (targets)
    {
      GdkAtom curve_atom = gdk_atom_intern_static_string ("application/x-pika-curve");
      gint    i;

      for (i = 0; i < n_targets; i++)
        {
          if (targets[i] == curve_atom)
            {
              result = curve_atom;
              break;
            }
        }

      g_free (targets);
    }

  return result;
}

static void
pika_clipboard_send_image (GtkClipboard     *clipboard,
                           GtkSelectionData *data,
                           guint             info,
                           Pika             *pika)
{
  PikaClipboard *pika_clip = pika_clipboard_get (pika);

  pika_set_busy (pika);

  if (info == 0)
    {
      if (pika->be_verbose)
        g_printerr ("clipboard: sending image data as '%s'\n",
                    pika_clip->image_target_entries[info].target);

      pika_selection_data_set_xcf (data, pika_clip->image);
    }
  else
    {
      GdkPixbuf *pixbuf;

      pika_pickable_flush (PIKA_PICKABLE (pika_clip->image));

      pixbuf = pika_viewable_get_pixbuf (PIKA_VIEWABLE (pika_clip->image),
                                         pika_get_user_context (pika),
                                         pika_image_get_width (pika_clip->image),
                                         pika_image_get_height (pika_clip->image));

      if (pixbuf)
        {
          gdouble res_x;
          gdouble res_y;
          gchar   str[16];

          pika_image_get_resolution (pika_clip->image, &res_x, &res_y);

          g_snprintf (str, sizeof (str), "%d", ROUND (res_x));
          gdk_pixbuf_set_option (pixbuf, "x-dpi", str);

          g_snprintf (str, sizeof (str), "%d", ROUND (res_y));
          gdk_pixbuf_set_option (pixbuf, "y-dpi", str);

          if (pika->be_verbose)
            g_printerr ("clipboard: sending image data as '%s'\n",
                        pika_clip->image_target_entries[info].target);

          gtk_selection_data_set_pixbuf (data, pixbuf);
        }
      else
        {
          g_warning ("%s: pika_viewable_get_pixbuf() failed", G_STRFUNC);
        }
    }

  pika_unset_busy (pika);
}

static void
pika_clipboard_send_buffer (GtkClipboard     *clipboard,
                            GtkSelectionData *data,
                            guint             info,
                            Pika             *pika)
{
  PikaClipboard *pika_clip = pika_clipboard_get (pika);
  GdkPixbuf     *pixbuf;

  pika_set_busy (pika);

  pixbuf = pika_viewable_get_pixbuf (PIKA_VIEWABLE (pika_clip->buffer),
                                     pika_get_user_context (pika),
                                     pika_buffer_get_width (pika_clip->buffer),
                                     pika_buffer_get_height (pika_clip->buffer));

  if (pixbuf)
    {
      gdouble res_x;
      gdouble res_y;
      gchar   str[16];

      pika_buffer_get_resolution (pika_clip->buffer, &res_x, &res_y);

      g_snprintf (str, sizeof (str), "%d", ROUND (res_x));
      gdk_pixbuf_set_option (pixbuf, "x-dpi", str);

      g_snprintf (str, sizeof (str), "%d", ROUND (res_y));
      gdk_pixbuf_set_option (pixbuf, "y-dpi", str);

      if (pika->be_verbose)
        g_printerr ("clipboard: sending pixbuf data as '%s'\n",
                    pika_clip->buffer_target_entries[info].target);

      gtk_selection_data_set_pixbuf (data, pixbuf);
    }
  else
    {
      g_warning ("%s: pika_viewable_get_pixbuf() failed", G_STRFUNC);
    }

  pika_unset_busy (pika);
}

static void
pika_clipboard_send_svg (GtkClipboard     *clipboard,
                         GtkSelectionData *data,
                         guint             info,
                         Pika             *pika)
{
  PikaClipboard *pika_clip = pika_clipboard_get (pika);

  pika_set_busy (pika);

  if (pika_clip->svg)
    {
      if (pika->be_verbose)
        g_printerr ("clipboard: sending SVG data as '%s'\n",
                    pika_clip->svg_target_entries[info].target);

      pika_selection_data_set_stream (data,
                                      (const guchar *) pika_clip->svg,
                                      strlen (pika_clip->svg));
    }

  pika_unset_busy (pika);
}

static void
pika_clipboard_send_curve (GtkClipboard     *clipboard,
                           GtkSelectionData *data,
                           guint             info,
                           Pika             *pika)
{
  PikaClipboard *pika_clip = pika_clipboard_get (pika);

  pika_set_busy (pika);

  if (pika_clip->curve)
    {
      if (pika->be_verbose)
        g_printerr ("clipboard: sending curve data as '%s'\n",
                    pika_clip->curve_target_entries[info].target);

      pika_selection_data_set_curve (data, pika_clip->curve);
    }

  pika_unset_busy (pika);
}
