/* 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 "libpikabase/pikabase.h"
#include "libpikawidgets/pikawidgets.h"

#include "actions-types.h"

#include "core/pika.h"
#include "core/pika-edit.h"
#include "core/pikabuffer.h"
#include "core/pikacontainer.h"
#include "core/pikadrawable.h"
#include "core/pikadrawable-edit.h"
#include "core/pikafilloptions.h"
#include "core/pikalayer.h"
#include "core/pikalayer-new.h"
#include "core/pikalayermask.h"
#include "core/pikaimage.h"
#include "core/pikaimage-undo.h"

#include "vectors/pikavectors-import.h"

#include "widgets/pikaclipboard.h"
#include "widgets/pikahelp-ids.h"
#include "widgets/pikadialogfactory.h"
#include "widgets/pikamessagebox.h"
#include "widgets/pikamessagedialog.h"
#include "widgets/pikawidgets-utils.h"
#include "widgets/pikawindowstrategy.h"

#include "display/pikadisplay.h"
#include "display/pikadisplayshell.h"
#include "display/pikadisplayshell-transform.h"

#include "tools/pikatools-utils.h"
#include "tools/tool_manager.h"

#include "actions.h"
#include "edit-commands.h"

#include "pika-intl.h"


/*  local function prototypes  */

static gboolean   check_drawable_alpha               (PikaDrawable  *drawable,
                                                      gpointer       data);
static void       edit_paste                         (PikaDisplay   *display,
                                                      PikaPasteType  paste_type,
                                                      gboolean       merged,
                                                      gboolean       try_svg);
static void       cut_named_buffer_callback          (GtkWidget     *widget,
                                                      const gchar   *name,
                                                      gpointer       data);
static void       copy_named_buffer_callback         (GtkWidget     *widget,
                                                      const gchar   *name,
                                                      gpointer       data);
static void       copy_named_visible_buffer_callback (GtkWidget     *widget,
                                                      const gchar   *name,
                                                      gpointer       data);


/*  public functions  */

void
edit_undo_cmd_callback (PikaAction *action,
                        GVariant   *value,
                        gpointer    data)
{
  PikaImage   *image;
  PikaDisplay *display;
  return_if_no_image (image, data);
  return_if_no_display (display, data);

  if (tool_manager_undo_active (image->pika, display) ||
      pika_image_undo (image))
    {
      pika_image_flush (image);
    }
}

void
edit_redo_cmd_callback (PikaAction *action,
                        GVariant   *value,
                        gpointer    data)
{
  PikaImage   *image;
  PikaDisplay *display;
  return_if_no_image (image, data);
  return_if_no_display (display, data);

  if (tool_manager_redo_active (image->pika, display) ||
      pika_image_redo (image))
    {
      pika_image_flush (image);
    }
}

void
edit_strong_undo_cmd_callback (PikaAction *action,
                               GVariant   *value,
                               gpointer    data)
{
  PikaImage *image;
  return_if_no_image (image, data);

  if (pika_image_strong_undo (image))
    pika_image_flush (image);
}

void
edit_strong_redo_cmd_callback (PikaAction *action,
                               GVariant   *value,
                               gpointer    data)
{
  PikaImage *image;
  return_if_no_image (image, data);

  if (pika_image_strong_redo (image))
    pika_image_flush (image);
}

void
edit_undo_clear_cmd_callback (PikaAction *action,
                              GVariant   *value,
                              gpointer    data)
{
  PikaImage     *image;
  PikaUndoStack *undo_stack;
  PikaUndoStack *redo_stack;
  GtkWidget     *widget;
  GtkWidget     *dialog;
  gchar         *size;
  gint64         memsize;
  gint64         guisize;
  return_if_no_image (image, data);
  return_if_no_widget (widget, data);

  dialog = pika_message_dialog_new (_("Clear Undo History"),
                                    PIKA_ICON_DIALOG_WARNING,
                                    widget,
                                    GTK_DIALOG_MODAL |
                                    GTK_DIALOG_DESTROY_WITH_PARENT,
                                    pika_standard_help_func,
                                    PIKA_HELP_EDIT_UNDO_CLEAR,

                                    _("_Cancel"), GTK_RESPONSE_CANCEL,
                                    _("Cl_ear"),  GTK_RESPONSE_OK,

                                    NULL);

  pika_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
                                           GTK_RESPONSE_OK,
                                           GTK_RESPONSE_CANCEL,
                                           -1);

  g_signal_connect_object (gtk_widget_get_toplevel (widget), "unmap",
                           G_CALLBACK (gtk_widget_destroy),
                           dialog, G_CONNECT_SWAPPED);

  g_signal_connect_object (image, "disconnect",
                           G_CALLBACK (gtk_widget_destroy),
                           dialog, G_CONNECT_SWAPPED);

  pika_message_box_set_primary_text (PIKA_MESSAGE_DIALOG (dialog)->box,
                                     _("Really clear image's undo history?"));

  undo_stack = pika_image_get_undo_stack (image);
  redo_stack = pika_image_get_redo_stack (image);

  memsize =  pika_object_get_memsize (PIKA_OBJECT (undo_stack), &guisize);
  memsize += guisize;
  memsize += pika_object_get_memsize (PIKA_OBJECT (redo_stack), &guisize);
  memsize += guisize;

  size = g_format_size (memsize);

  pika_message_box_set_text (PIKA_MESSAGE_DIALOG (dialog)->box,
                             _("Clearing the undo history of this "
                               "image will gain %s of memory."), size);
  g_free (size);

  if (pika_dialog_run (PIKA_DIALOG (dialog)) == GTK_RESPONSE_OK)
    {
      pika_image_undo_disable (image);
      pika_image_undo_enable (image);
      pika_image_flush (image);
    }

  gtk_widget_destroy (dialog);
}

void
edit_cut_cmd_callback (PikaAction *action,
                       GVariant   *value,
                       gpointer    data)
{
  PikaImage    *image;
  GList        *drawables;
  GList        *iter;
  PikaObject   *cut;
  GError       *error = NULL;
  return_if_no_drawables (image, drawables, data);

  for (iter = drawables; iter; iter = iter->next)
    if (! check_drawable_alpha (iter->data, data))
      {
        g_list_free (drawables);
        return;
      }

  cut = pika_edit_cut (image, drawables, action_data_get_context (data), &error);

  if (cut)
    {
      PikaDisplay *display = action_data_get_display (data);

      if (display)
        {
          gchar *msg;

          if (PIKA_IS_IMAGE (cut))
            msg = g_strdup_printf (ngettext ("Cut layer to the clipboard.",
                                             "Cut %d layers to the clipboard.",
                                             g_list_length (drawables)),
                                   g_list_length (drawables));
          else
            msg = g_strdup (_("Cut pixels to the clipboard."));

          pika_message_literal (image->pika,
                                G_OBJECT (display), PIKA_MESSAGE_INFO,
                                msg);
          g_free (msg);
        }

      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika,
                            G_OBJECT (action_data_get_display (data)),
                            PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }
  g_list_free (drawables);
}

void
edit_copy_cmd_callback (PikaAction *action,
                        GVariant   *value,
                        gpointer    data)
{
  PikaImage    *image;
  GList        *drawables;
  PikaObject   *copy;
  GError       *error = NULL;
  return_if_no_drawables (image, drawables, data);

  copy = pika_edit_copy (image, drawables, action_data_get_context (data),
                         &error);

  if (copy)
    {
      PikaDisplay *display = action_data_get_display (data);

      if (display)
        pika_message_literal (image->pika,
                              G_OBJECT (display), PIKA_MESSAGE_INFO,
                              PIKA_IS_IMAGE (copy) ?
                              _("Copied layer to the clipboard.") :
                              _("Copied pixels to the clipboard."));

      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika,
                            G_OBJECT (action_data_get_display (data)),
                            PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }

  g_list_free (drawables);
}

void
edit_copy_visible_cmd_callback (PikaAction *action,
                                GVariant   *value,
                                gpointer    data)
{
  PikaImage *image;
  GError    *error = NULL;
  return_if_no_image (image, data);

  if (pika_edit_copy_visible (image, action_data_get_context (data), &error))
    {
      PikaDisplay *display = action_data_get_display (data);

      if (display)
        pika_message_literal (image->pika,
                              G_OBJECT (display), PIKA_MESSAGE_INFO,
                              _("Copied pixels to the clipboard."));

      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika,
                            G_OBJECT (action_data_get_display (data)),
                            PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }
}

void
edit_paste_cmd_callback (PikaAction *action,
                         GVariant   *value,
                         gpointer    data)
{
  PikaImage     *image;
  PikaDisplay   *display    = action_data_get_display (data);
  PikaPasteType  paste_type = (PikaPasteType) g_variant_get_int32 (value);
  PikaPasteType  converted_type;
  GList         *drawables;
  gboolean       merged     = FALSE;

  if (paste_type == PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING)
    {
      if (! display || ! pika_display_get_image (display))
        {
          edit_paste_as_new_image_cmd_callback (action, value, data);
          return;
        }
    }

  return_if_no_image (image, data);

  if (! display)
    return;

  switch (paste_type)
    {
    case PIKA_PASTE_TYPE_FLOATING:
    case PIKA_PASTE_TYPE_FLOATING_IN_PLACE:
    case PIKA_PASTE_TYPE_FLOATING_INTO:
    case PIKA_PASTE_TYPE_FLOATING_INTO_IN_PLACE:
      edit_paste (display, paste_type, merged, TRUE);
      break;

    case PIKA_PASTE_TYPE_NEW_LAYER:
    case PIKA_PASTE_TYPE_NEW_LAYER_IN_PLACE:
      edit_paste (display, paste_type, merged, FALSE);
      break;

    case PIKA_PASTE_TYPE_NEW_MERGED_LAYER_OR_FLOATING:
    case PIKA_PASTE_TYPE_NEW_MERGED_LAYER_OR_FLOATING_IN_PLACE:
      merged = TRUE;
    case PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING:
    case PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING_IN_PLACE:
      drawables = pika_image_get_selected_drawables (image);

      if (drawables &&
         (g_list_length (drawables) == 1) &&
          PIKA_IS_LAYER_MASK (drawables->data))
        {
          converted_type = (paste_type == PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING ||
                            paste_type == PIKA_PASTE_TYPE_NEW_MERGED_LAYER_OR_FLOATING) ?
                            PIKA_PASTE_TYPE_FLOATING :
                            PIKA_PASTE_TYPE_FLOATING_IN_PLACE;

          edit_paste (display, converted_type, merged, TRUE);
        }
      else
        {
          converted_type = (paste_type == PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING ||
                            paste_type == PIKA_PASTE_TYPE_NEW_MERGED_LAYER_OR_FLOATING) ?
                            PIKA_PASTE_TYPE_NEW_LAYER :
                            PIKA_PASTE_TYPE_NEW_LAYER_IN_PLACE;

          edit_paste (display, converted_type, merged, FALSE);
        }
      g_list_free (drawables);

      break;
    }
}

void
edit_paste_as_new_image_cmd_callback (PikaAction *action,
                                      GVariant   *value,
                                      gpointer    data)
{
  Pika       *pika;
  GtkWidget  *widget;
  PikaObject *paste;
  PikaImage  *image = NULL;
  return_if_no_pika (pika, data);
  return_if_no_widget (widget, data);

  paste = pika_clipboard_get_object (pika);

  if (paste)
    {
      image = pika_edit_paste_as_new_image (pika, paste,
                                            action_data_get_context (data));
      g_object_unref (paste);
    }

  if (image)
    {
      pika_create_display (pika, image, PIKA_UNIT_PIXEL, 1.0,
                           G_OBJECT (pika_widget_get_monitor (widget)));
      g_object_unref (image);
    }
  else
    {
      pika_message_literal (pika, NULL, PIKA_MESSAGE_WARNING,
                            _("There is no image data in the clipboard "
                              "to paste."));
    }
}

void
edit_named_cut_cmd_callback (PikaAction *action,
                             GVariant   *value,
                             gpointer    data)
{
  PikaImage *image;
  GtkWidget *widget;
  GtkWidget *dialog;
  return_if_no_image (image, data);
  return_if_no_widget (widget, data);

  dialog = pika_query_string_box (_("Cut Named"), widget,
                                  pika_standard_help_func,
                                  PIKA_HELP_BUFFER_CUT,
                                  _("Enter a name for this buffer"),
                                  NULL,
                                  G_OBJECT (image), "disconnect",
                                  cut_named_buffer_callback,
                                  image, NULL);
  gtk_widget_show (dialog);
}

void
edit_named_copy_cmd_callback (PikaAction *action,
                              GVariant   *value,
                              gpointer    data)
{
  PikaImage *image;
  GtkWidget *widget;
  GtkWidget *dialog;
  return_if_no_image (image, data);
  return_if_no_widget (widget, data);

  dialog = pika_query_string_box (_("Copy Named"), widget,
                                  pika_standard_help_func,
                                  PIKA_HELP_BUFFER_COPY,
                                  _("Enter a name for this buffer"),
                                  NULL,
                                  G_OBJECT (image), "disconnect",
                                  copy_named_buffer_callback,
                                  image, NULL);
  gtk_widget_show (dialog);
}

void
edit_named_copy_visible_cmd_callback (PikaAction *action,
                                      GVariant   *value,
                                      gpointer    data)
{
  PikaImage *image;
  GtkWidget *widget;
  GtkWidget *dialog;
  return_if_no_image (image, data);
  return_if_no_widget (widget, data);

  dialog = pika_query_string_box (_("Copy Visible Named"), widget,
                                  pika_standard_help_func,
                                  PIKA_HELP_BUFFER_COPY,
                                  _("Enter a name for this buffer"),
                                  NULL,
                                  G_OBJECT (image), "disconnect",
                                  copy_named_visible_buffer_callback,
                                  image, NULL);
  gtk_widget_show (dialog);
}

void
edit_named_paste_cmd_callback (PikaAction *action,
                               GVariant   *value,
                               gpointer    data)
{
  Pika      *pika;
  GtkWidget *widget;
  return_if_no_pika (pika, data);
  return_if_no_widget (widget, data);

  pika_window_strategy_show_dockable_dialog (PIKA_WINDOW_STRATEGY (pika_get_window_strategy (pika)),
                                             pika,
                                             pika_dialog_factory_get_singleton (),
                                             pika_widget_get_monitor (widget),
                                             "pika-buffer-list|pika-buffer-grid");
}

void
edit_clear_cmd_callback (PikaAction *action,
                         GVariant   *value,
                         gpointer    data)
{
  PikaImage *image;
  GList     *drawables;
  GList     *iter;

  return_if_no_drawables (image, drawables, data);

  for (iter = drawables; iter; iter = iter->next)
    /* Return if any has a locked alpha. */
    if (! check_drawable_alpha (iter->data, data))
      {
        g_list_free (drawables);
        return;
      }

  pika_image_undo_group_start (image, PIKA_UNDO_GROUP_PAINT,
                               _("Clear"));

  for (iter = drawables; iter; iter = iter->next)
    if (! pika_viewable_get_children (PIKA_VIEWABLE (iter->data)) &&
        ! pika_item_is_content_locked (PIKA_ITEM (iter->data), NULL))
      pika_drawable_edit_clear (iter->data, action_data_get_context (data));

  pika_image_undo_group_end (image);
  pika_image_flush (image);
  g_list_free (drawables);
}

void
edit_fill_cmd_callback (PikaAction *action,
                        GVariant   *value,
                        gpointer    data)
{
  PikaImage       *image;
  GList           *drawables;
  GList           *iter;
  PikaFillType     fill_type;
  PikaFillOptions *options;
  GError          *error = NULL;
  return_if_no_drawables (image, drawables, data);

  fill_type = (PikaFillType) g_variant_get_int32 (value);

  options = pika_fill_options_new (action_data_get_pika (data), NULL, FALSE);

  if (pika_fill_options_set_by_fill_type (options,
                                          action_data_get_context (data),
                                          fill_type, &error))
    {
      pika_image_undo_group_start (image, PIKA_UNDO_GROUP_PAINT,
                                   pika_fill_options_get_undo_desc (options));

      for (iter = drawables; iter; iter = iter->next)
        pika_drawable_edit_fill (iter->data, options, NULL);

      pika_image_undo_group_end (image);
      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika, NULL, PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }

  g_list_free (drawables);
  g_object_unref (options);
}


/*  private functions  */

static gboolean
check_drawable_alpha (PikaDrawable *drawable,
                      gpointer      data)
{
  PikaLayer *locked_layer = NULL;

  if (pika_drawable_has_alpha (drawable) &&
      PIKA_IS_LAYER (drawable)           &&
      pika_layer_is_alpha_locked (PIKA_LAYER (drawable), &locked_layer))
    {
      Pika        *pika    = action_data_get_pika    (data);
      PikaDisplay *display = action_data_get_display (data);

      if (pika && display)
        {
          pika_message_literal (
            pika, G_OBJECT (display), PIKA_MESSAGE_WARNING,
            _("A selected layer's alpha channel is locked."));

          pika_tools_blink_lock_box (pika, PIKA_ITEM (locked_layer));
        }

      return FALSE;
    }

  return TRUE;
}

static void
edit_paste (PikaDisplay   *display,
            PikaPasteType  paste_type,
            gboolean       merged,
            gboolean       try_svg)
{
  PikaImage  *image = pika_display_get_image (display);
  PikaObject *paste;

  g_return_if_fail (paste_type != PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING          &&
                    paste_type != PIKA_PASTE_TYPE_NEW_LAYER_OR_FLOATING_IN_PLACE &&
                    paste_type != PIKA_PASTE_TYPE_NEW_MERGED_LAYER_OR_FLOATING   &&
                    paste_type != PIKA_PASTE_TYPE_NEW_MERGED_LAYER_OR_FLOATING_IN_PLACE);

  if (try_svg)
    {
      gchar *svg;
      gsize  svg_size;

      svg = pika_clipboard_get_svg (display->pika, &svg_size);

      if (svg)
        {
          if (pika_vectors_import_buffer (image, svg, svg_size,
                                          TRUE, FALSE,
                                          PIKA_IMAGE_ACTIVE_PARENT, -1,
                                          NULL, NULL))
            {
              pika_image_flush (image);
            }

          g_free (svg);

          return;
        }
    }

  paste = pika_clipboard_get_object (display->pika);

  if (paste)
    {
      PikaDisplayShell *shell     = pika_display_get_shell (display);
      GList            *drawables = pika_image_get_selected_drawables (image);
      GList            *pasted_layers;
      gint              x, y;
      gint              width, height;

      if (g_list_length (drawables) != 1 ||
          (paste_type != PIKA_PASTE_TYPE_NEW_LAYER &&
           paste_type != PIKA_PASTE_TYPE_NEW_LAYER_IN_PLACE))
        {
          if (g_list_length (drawables) != 1)
            {
              pika_message_literal (display->pika, G_OBJECT (display),
                                    PIKA_MESSAGE_INFO,
                                    _("Pasted as new layer because the "
                                      "target is not a single layer or layer mask."));
            }
          else if (pika_viewable_get_children (PIKA_VIEWABLE (drawables->data)))
            {
              pika_message_literal (display->pika, G_OBJECT (display),
                                    PIKA_MESSAGE_INFO,
                                    _("Pasted as new layer because the "
                                      "target is a layer group."));
            }
          else if (pika_item_is_content_locked (PIKA_ITEM (drawables->data), NULL))
            {
              pika_message_literal (display->pika, G_OBJECT (display),
                                    PIKA_MESSAGE_INFO,
                                    _("Pasted as new layer because the "
                                      "target's pixels are locked."));
            }

          /* the actual paste-type conversion happens in pika_edit_paste() */
        }

      pika_display_shell_untransform_viewport (
        shell,
        ! pika_display_shell_get_infinite_canvas (shell),
        &x, &y, &width, &height);

      if ((pasted_layers = pika_edit_paste (image, drawables, paste, paste_type,
                                            pika_get_user_context (display->pika),
                                            merged, x, y, width, height)))
        {
          pika_image_set_selected_layers (image, pasted_layers);
          g_list_free (pasted_layers);
          pika_image_flush (image);
        }

      g_list_free (drawables);
      g_object_unref (paste);
    }
  else
    {
      pika_message_literal (display->pika, G_OBJECT (display),
                            PIKA_MESSAGE_WARNING,
                            _("There is no image data in the clipboard "
                              "to paste."));
    }
}

static void
cut_named_buffer_callback (GtkWidget   *widget,
                           const gchar *name,
                           gpointer     data)
{
  PikaImage *image     = PIKA_IMAGE (data);
  GList     *drawables = pika_image_get_selected_drawables (image);
  GError    *error     = NULL;

  if (! drawables)
    {
      pika_message_literal (image->pika, NULL, PIKA_MESSAGE_WARNING,
                            _("There are no selected layers or channels to cut from."));
      return;
    }

  if (! (name && strlen (name)))
    name = _("(Unnamed Buffer)");

  if (pika_edit_named_cut (image, name, drawables,
                           pika_get_user_context (image->pika), &error))
    {
      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika, NULL, PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }
  g_list_free (drawables);
}

static void
copy_named_buffer_callback (GtkWidget   *widget,
                            const gchar *name,
                            gpointer     data)
{
  PikaImage *image     = PIKA_IMAGE (data);
  GList     *drawables = pika_image_get_selected_drawables (image);
  GError    *error     = NULL;

  if (! drawables)
    {
      pika_message_literal (image->pika, NULL, PIKA_MESSAGE_WARNING,
                            _("There are no selected layers or channels to copy from."));
      return;
    }

  if (! (name && strlen (name)))
    name = _("(Unnamed Buffer)");

  if (pika_edit_named_copy (image, name, drawables,
                            pika_get_user_context (image->pika), &error))
    {
      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika, NULL, PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }
  g_list_free (drawables);
}

static void
copy_named_visible_buffer_callback (GtkWidget   *widget,
                                    const gchar *name,
                                    gpointer     data)
{
  PikaImage *image = PIKA_IMAGE (data);
  GError    *error = NULL;

  if (! (name && strlen (name)))
    name = _("(Unnamed Buffer)");

  if (pika_edit_named_copy_visible (image, name,
                                    pika_get_user_context (image->pika),
                                    &error))
    {
      pika_image_flush (image);
    }
  else
    {
      pika_message_literal (image->pika, NULL, PIKA_MESSAGE_WARNING,
                            error->message);
      g_clear_error (&error);
    }
}
