/* 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 <stdlib.h>
#include <string.h>

#include <cairo.h>
#include <gegl.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#include "libpikabase/pikabase.h"
#include "libpikacolor/pikacolor.h"
#include "libpikaconfig/pikaconfig.h"
#include "libpikamath/pikamath.h"

#include "core-types.h"

#include "operations/layer-modes/pika-layer-modes.h"

#include "gegl/pika-babl.h"
#include "gegl/pika-gegl-apply-operation.h"
#include "gegl/pika-gegl-loops.h"
#include "gegl/pika-gegl-nodes.h"

#include "pikaboundary.h"
#include "pikachannel-select.h"
#include "pikacontext.h"
#include "pikacontainer.h"
#include "pikadrawable-floating-selection.h"
#include "pikaerror.h"
#include "pikagrouplayer.h"
#include "pikaimage-undo-push.h"
#include "pikaimage-undo.h"
#include "pikaimage.h"
#include "pikaimage-color-profile.h"
#include "pikalayer-floating-selection.h"
#include "pikalayer.h"
#include "pikalayermask.h"
#include "pikaobjectqueue.h"
#include "pikapickable.h"
#include "pikaprogress.h"

#include "pika-intl.h"


enum
{
  OPACITY_CHANGED,
  MODE_CHANGED,
  BLEND_SPACE_CHANGED,
  COMPOSITE_SPACE_CHANGED,
  COMPOSITE_MODE_CHANGED,
  EFFECTIVE_MODE_CHANGED,
  EXCLUDES_BACKDROP_CHANGED,
  LOCK_ALPHA_CHANGED,
  MASK_CHANGED,
  APPLY_MASK_CHANGED,
  EDIT_MASK_CHANGED,
  SHOW_MASK_CHANGED,
  LAST_SIGNAL
};

enum
{
  PROP_0,
  PROP_OPACITY,
  PROP_MODE,
  PROP_BLEND_SPACE,
  PROP_COMPOSITE_SPACE,
  PROP_COMPOSITE_MODE,
  PROP_EXCLUDES_BACKDROP,
  PROP_LOCK_ALPHA,
  PROP_MASK,
  PROP_FLOATING_SELECTION
};


static void       pika_color_managed_iface_init (PikaColorManagedInterface *iface);
static void       pika_pickable_iface_init      (PikaPickableInterface     *iface);

static void       pika_layer_set_property       (GObject            *object,
                                                 guint               property_id,
                                                 const GValue       *value,
                                                 GParamSpec         *pspec);
static void       pika_layer_get_property       (GObject            *object,
                                                 guint               property_id,
                                                 GValue             *value,
                                                 GParamSpec         *pspec);
static void       pika_layer_dispose            (GObject            *object);
static void       pika_layer_finalize           (GObject            *object);
static void       pika_layer_notify             (GObject            *object,
                                                 GParamSpec         *pspec);

static void       pika_layer_name_changed       (PikaObject         *object);
static gint64     pika_layer_get_memsize        (PikaObject         *object,
                                                 gint64             *gui_size);

static void       pika_layer_invalidate_preview (PikaViewable       *viewable);
static gchar    * pika_layer_get_description    (PikaViewable       *viewable,
                                                 gchar             **tooltip);

static GeglNode * pika_layer_get_node           (PikaFilter         *filter);

static void       pika_layer_removed            (PikaItem           *item);
static void       pika_layer_unset_removed      (PikaItem           *item);
static gboolean   pika_layer_is_attached        (PikaItem           *item);
static PikaItemTree * pika_layer_get_tree       (PikaItem           *item);
static PikaItem * pika_layer_duplicate          (PikaItem           *item,
                                                 GType               new_type);
static void       pika_layer_convert            (PikaItem           *item,
                                                 PikaImage          *dest_image,
                                                 GType               old_type);
static gboolean   pika_layer_rename             (PikaItem           *item,
                                                 const gchar        *new_name,
                                                 const gchar        *undo_desc,
                                                 GError            **error);
static void       pika_layer_start_move         (PikaItem           *item,
                                                 gboolean            push_undo);
static void       pika_layer_end_move           (PikaItem           *item,
                                                 gboolean            push_undo);
static void       pika_layer_translate          (PikaItem           *item,
                                                 gdouble             offset_x,
                                                 gdouble             offset_y,
                                                 gboolean            push_undo);
static void       pika_layer_scale              (PikaItem           *item,
                                                 gint                new_width,
                                                 gint                new_height,
                                                 gint                new_offset_x,
                                                 gint                new_offset_y,
                                                 PikaInterpolationType  interp_type,
                                                 PikaProgress       *progress);
static void       pika_layer_resize             (PikaItem           *item,
                                                 PikaContext        *context,
                                                 PikaFillType        fill_type,
                                                 gint                new_width,
                                                 gint                new_height,
                                                 gint                offset_x,
                                                 gint                offset_y);
static void       pika_layer_flip               (PikaItem           *item,
                                                 PikaContext        *context,
                                                 PikaOrientationType flip_type,
                                                 gdouble             axis,
                                                 gboolean            clip_result);
static void       pika_layer_rotate             (PikaItem           *item,
                                                 PikaContext        *context,
                                                 PikaRotationType    rotate_type,
                                                 gdouble             center_x,
                                                 gdouble             center_y,
                                                 gboolean            clip_result);
static void       pika_layer_transform          (PikaItem           *item,
                                                 PikaContext        *context,
                                                 const PikaMatrix3  *matrix,
                                                 PikaTransformDirection direction,
                                                 PikaInterpolationType  interpolation_type,
                                                 PikaTransformResize clip_result,
                                                 PikaProgress       *progress);
static void       pika_layer_to_selection       (PikaItem           *item,
                                                 PikaChannelOps      op,
                                                 gboolean            antialias,
                                                 gboolean            feather,
                                                 gdouble             feather_radius_x,
                                                 gdouble             feather_radius_y);

static void       pika_layer_alpha_changed      (PikaDrawable       *drawable);
static gint64     pika_layer_estimate_memsize   (PikaDrawable       *drawable,
                                                 PikaComponentType   component_type,
                                                 gint                width,
                                                 gint                height);
static gboolean   pika_layer_supports_alpha     (PikaDrawable       *drawable);
static void       pika_layer_convert_type       (PikaDrawable       *drawable,
                                                 PikaImage          *dest_image,
                                                 const Babl         *new_format,
                                                 PikaColorProfile   *src_profile,
                                                 PikaColorProfile   *dest_profile,
                                                 GeglDitherMethod    layer_dither_type,
                                                 GeglDitherMethod    mask_dither_type,
                                                 gboolean            push_undo,
                                                 PikaProgress       *progress);
static void    pika_layer_invalidate_boundary   (PikaDrawable       *drawable);
static void    pika_layer_get_active_components (PikaDrawable       *drawable,
                                                 gboolean           *active);
static PikaComponentMask
               pika_layer_get_active_mask       (PikaDrawable       *drawable);
static void    pika_layer_set_buffer            (PikaDrawable       *drawable,
                                                 gboolean            push_undo,
                                                 const gchar        *undo_desc,
                                                 GeglBuffer         *buffer,
                                                 const GeglRectangle *bounds);
static GeglRectangle
               pika_layer_get_bounding_box      (PikaDrawable       *drawable);

static PikaColorProfile *
               pika_layer_get_color_profile     (PikaColorManaged   *managed);

static gdouble pika_layer_get_opacity_at        (PikaPickable       *pickable,
                                                 gint                x,
                                                 gint                y);
static void    pika_layer_pixel_to_rgb          (PikaPickable       *pickable,
                                                 const Babl         *format,
                                                 gpointer            pixel,
                                                 PikaRGB            *color);
static void    pika_layer_rgb_to_pixel          (PikaPickable       *pickable,
                                                 const PikaRGB      *color,
                                                 const Babl         *format,
                                                 gpointer            pixel);

static gboolean pika_layer_real_is_alpha_locked (PikaLayer          *layer,
                                                 PikaLayer         **locked_layer);
static void       pika_layer_real_translate     (PikaLayer          *layer,
                                                 gint                offset_x,
                                                 gint                offset_y);
static void       pika_layer_real_scale         (PikaLayer          *layer,
                                                 gint                new_width,
                                                 gint                new_height,
                                                 gint                new_offset_x,
                                                 gint                new_offset_y,
                                                 PikaInterpolationType  interp_type,
                                                 PikaProgress       *progress);
static void       pika_layer_real_resize        (PikaLayer          *layer,
                                                 PikaContext        *context,
                                                 PikaFillType        fill_type,
                                                 gint                new_width,
                                                 gint                new_height,
                                                 gint                offset_x,
                                                 gint                offset_y);
static void       pika_layer_real_flip          (PikaLayer          *layer,
                                                 PikaContext        *context,
                                                 PikaOrientationType flip_type,
                                                 gdouble             axis,
                                                 gboolean            clip_result);
static void       pika_layer_real_rotate        (PikaLayer          *layer,
                                                 PikaContext        *context,
                                                 PikaRotationType    rotate_type,
                                                 gdouble             center_x,
                                                 gdouble             center_y,
                                                 gboolean            clip_result);
static void       pika_layer_real_transform     (PikaLayer          *layer,
                                                 PikaContext        *context,
                                                 const PikaMatrix3  *matrix,
                                                 PikaTransformDirection direction,
                                                 PikaInterpolationType  interpolation_type,
                                                 PikaTransformResize clip_result,
                                                 PikaProgress       *progress);
static void       pika_layer_real_convert_type  (PikaLayer          *layer,
                                                 PikaImage          *dest_image,
                                                 const Babl         *new_format,
                                                 PikaColorProfile   *src_profile,
                                                 PikaColorProfile   *dest_profile,
                                                 GeglDitherMethod    layer_dither_type,
                                                 GeglDitherMethod    mask_dither_type,
                                                 gboolean            push_undo,
                                                 PikaProgress       *progress);
static GeglRectangle
               pika_layer_real_get_bounding_box (PikaLayer          *layer);
static void  pika_layer_real_get_effective_mode (PikaLayer          *layer,
                                                 PikaLayerMode          *mode,
                                                 PikaLayerColorSpace    *blend_space,
                                                 PikaLayerColorSpace    *composite_space,
                                                 PikaLayerCompositeMode *composite_mode);
static gboolean
          pika_layer_real_get_excludes_backdrop (PikaLayer          *layer);

static void       pika_layer_layer_mask_update  (PikaDrawable       *layer_mask,
                                                 gint                x,
                                                 gint                y,
                                                 gint                width,
                                                 gint                height,
                                                 PikaLayer          *layer);


G_DEFINE_TYPE_WITH_CODE (PikaLayer, pika_layer, PIKA_TYPE_DRAWABLE,
                         G_IMPLEMENT_INTERFACE (PIKA_TYPE_COLOR_MANAGED,
                                                pika_color_managed_iface_init)
                         G_IMPLEMENT_INTERFACE (PIKA_TYPE_PICKABLE,
                                                pika_pickable_iface_init))

#define parent_class pika_layer_parent_class

static guint layer_signals[LAST_SIGNAL] = { 0 };


static void
pika_layer_class_init (PikaLayerClass *klass)
{
  GObjectClass      *object_class      = G_OBJECT_CLASS (klass);
  PikaObjectClass   *pika_object_class = PIKA_OBJECT_CLASS (klass);
  PikaViewableClass *viewable_class    = PIKA_VIEWABLE_CLASS (klass);
  PikaFilterClass   *filter_class      = PIKA_FILTER_CLASS (klass);
  PikaItemClass     *item_class        = PIKA_ITEM_CLASS (klass);
  PikaDrawableClass *drawable_class    = PIKA_DRAWABLE_CLASS (klass);

  layer_signals[OPACITY_CHANGED] =
    g_signal_new ("opacity-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, opacity_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[MODE_CHANGED] =
    g_signal_new ("mode-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, mode_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[BLEND_SPACE_CHANGED] =
    g_signal_new ("blend-space-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, blend_space_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[COMPOSITE_SPACE_CHANGED] =
    g_signal_new ("composite-space-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, composite_space_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[COMPOSITE_MODE_CHANGED] =
    g_signal_new ("composite-mode-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, composite_mode_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[EFFECTIVE_MODE_CHANGED] =
    g_signal_new ("effective-mode-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, effective_mode_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[EXCLUDES_BACKDROP_CHANGED] =
    g_signal_new ("excludes-backdrop-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, excludes_backdrop_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[LOCK_ALPHA_CHANGED] =
    g_signal_new ("lock-alpha-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, lock_alpha_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[MASK_CHANGED] =
    g_signal_new ("mask-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, mask_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[APPLY_MASK_CHANGED] =
    g_signal_new ("apply-mask-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, apply_mask_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[EDIT_MASK_CHANGED] =
    g_signal_new ("edit-mask-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, edit_mask_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  layer_signals[SHOW_MASK_CHANGED] =
    g_signal_new ("show-mask-changed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaLayerClass, show_mask_changed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  object_class->set_property          = pika_layer_set_property;
  object_class->get_property          = pika_layer_get_property;
  object_class->dispose               = pika_layer_dispose;
  object_class->finalize              = pika_layer_finalize;
  object_class->notify                = pika_layer_notify;

  pika_object_class->name_changed     = pika_layer_name_changed;
  pika_object_class->get_memsize      = pika_layer_get_memsize;

  viewable_class->default_icon_name   = "pika-layer";
  viewable_class->invalidate_preview  = pika_layer_invalidate_preview;
  viewable_class->get_description     = pika_layer_get_description;

  filter_class->get_node              = pika_layer_get_node;

  item_class->removed                 = pika_layer_removed;
  item_class->unset_removed           = pika_layer_unset_removed;
  item_class->is_attached             = pika_layer_is_attached;
  item_class->get_tree                = pika_layer_get_tree;
  item_class->duplicate               = pika_layer_duplicate;
  item_class->convert                 = pika_layer_convert;
  item_class->rename                  = pika_layer_rename;
  item_class->start_move              = pika_layer_start_move;
  item_class->end_move                = pika_layer_end_move;
  item_class->translate               = pika_layer_translate;
  item_class->scale                   = pika_layer_scale;
  item_class->resize                  = pika_layer_resize;
  item_class->flip                    = pika_layer_flip;
  item_class->rotate                  = pika_layer_rotate;
  item_class->transform               = pika_layer_transform;
  item_class->to_selection            = pika_layer_to_selection;
  item_class->default_name            = _("Layer");
  item_class->rename_desc             = C_("undo-type", "Rename Layer");
  item_class->translate_desc          = C_("undo-type", "Move Layer");
  item_class->scale_desc              = C_("undo-type", "Scale Layer");
  item_class->resize_desc             = C_("undo-type", "Resize Layer");
  item_class->flip_desc               = C_("undo-type", "Flip Layer");
  item_class->rotate_desc             = C_("undo-type", "Rotate Layer");
  item_class->transform_desc          = C_("undo-type", "Transform Layer");
  item_class->to_selection_desc       = C_("undo-type", "Alpha to Selection");
  item_class->reorder_desc            = C_("undo-type", "Reorder Layer");
  item_class->raise_desc              = C_("undo-type", "Raise Layer");
  item_class->raise_to_top_desc       = C_("undo-type", "Raise Layer to Top");
  item_class->lower_desc              = C_("undo-type", "Lower Layer");
  item_class->lower_to_bottom_desc    = C_("undo-type", "Lower Layer to Bottom");
  item_class->raise_failed            = _("Layer cannot be raised higher.");
  item_class->lower_failed            = _("Layer cannot be lowered more.");

  drawable_class->alpha_changed         = pika_layer_alpha_changed;
  drawable_class->estimate_memsize      = pika_layer_estimate_memsize;
  drawable_class->supports_alpha        = pika_layer_supports_alpha;
  drawable_class->convert_type          = pika_layer_convert_type;
  drawable_class->invalidate_boundary   = pika_layer_invalidate_boundary;
  drawable_class->get_active_components = pika_layer_get_active_components;
  drawable_class->get_active_mask       = pika_layer_get_active_mask;
  drawable_class->set_buffer            = pika_layer_set_buffer;
  drawable_class->get_bounding_box      = pika_layer_get_bounding_box;

  klass->opacity_changed              = NULL;
  klass->mode_changed                 = NULL;
  klass->blend_space_changed          = NULL;
  klass->composite_space_changed      = NULL;
  klass->composite_mode_changed       = NULL;
  klass->excludes_backdrop_changed    = NULL;
  klass->lock_alpha_changed           = NULL;
  klass->mask_changed                 = NULL;
  klass->apply_mask_changed           = NULL;
  klass->edit_mask_changed            = NULL;
  klass->show_mask_changed            = NULL;
  klass->is_alpha_locked              = pika_layer_real_is_alpha_locked;
  klass->translate                    = pika_layer_real_translate;
  klass->scale                        = pika_layer_real_scale;
  klass->resize                       = pika_layer_real_resize;
  klass->flip                         = pika_layer_real_flip;
  klass->rotate                       = pika_layer_real_rotate;
  klass->transform                    = pika_layer_real_transform;
  klass->convert_type                 = pika_layer_real_convert_type;
  klass->get_bounding_box             = pika_layer_real_get_bounding_box;
  klass->get_effective_mode           = pika_layer_real_get_effective_mode;
  klass->get_excludes_backdrop        = pika_layer_real_get_excludes_backdrop;

  g_object_class_install_property (object_class, PROP_OPACITY,
                                   g_param_spec_double ("opacity", NULL, NULL,
                                                        PIKA_OPACITY_TRANSPARENT,
                                                        PIKA_OPACITY_OPAQUE,
                                                        PIKA_OPACITY_OPAQUE,
                                                        PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_MODE,
                                   g_param_spec_enum ("mode", NULL, NULL,
                                                      PIKA_TYPE_LAYER_MODE,
                                                      PIKA_LAYER_MODE_NORMAL,
                                                      PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_BLEND_SPACE,
                                   g_param_spec_enum ("blend-space",
                                                      NULL, NULL,
                                                      PIKA_TYPE_LAYER_COLOR_SPACE,
                                                      PIKA_LAYER_COLOR_SPACE_AUTO,
                                                      PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_COMPOSITE_SPACE,
                                   g_param_spec_enum ("composite-space",
                                                      NULL, NULL,
                                                      PIKA_TYPE_LAYER_COLOR_SPACE,
                                                      PIKA_LAYER_COLOR_SPACE_AUTO,
                                                      PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_COMPOSITE_MODE,
                                   g_param_spec_enum ("composite-mode",
                                                      NULL, NULL,
                                                      PIKA_TYPE_LAYER_COMPOSITE_MODE,
                                                      PIKA_LAYER_COMPOSITE_AUTO,
                                                      PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_EXCLUDES_BACKDROP,
                                   g_param_spec_boolean ("excludes-backdrop",
                                                         NULL, NULL,
                                                         FALSE,
                                                         PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_LOCK_ALPHA,
                                   g_param_spec_boolean ("lock-alpha",
                                                         NULL, NULL,
                                                         FALSE,
                                                         PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_MASK,
                                   g_param_spec_object ("mask",
                                                        NULL, NULL,
                                                        PIKA_TYPE_LAYER_MASK,
                                                        PIKA_PARAM_READABLE));

  g_object_class_install_property (object_class, PROP_FLOATING_SELECTION,
                                   g_param_spec_boolean ("floating-selection",
                                                         NULL, NULL,
                                                         FALSE,
                                                         PIKA_PARAM_READABLE));
}

static void
pika_layer_init (PikaLayer *layer)
{
  layer->opacity                   = PIKA_OPACITY_OPAQUE;
  layer->mode                      = PIKA_LAYER_MODE_NORMAL;
  layer->blend_space               = PIKA_LAYER_COLOR_SPACE_AUTO;
  layer->composite_space           = PIKA_LAYER_COLOR_SPACE_AUTO;
  layer->composite_mode            = PIKA_LAYER_COMPOSITE_AUTO;
  layer->effective_mode            = layer->mode;
  layer->effective_blend_space     = pika_layer_get_real_blend_space (layer);
  layer->effective_composite_space = pika_layer_get_real_composite_space (layer);
  layer->effective_composite_mode  = pika_layer_get_real_composite_mode (layer);
  layer->excludes_backdrop         = FALSE;
  layer->lock_alpha                = FALSE;

  layer->mask       = NULL;
  layer->apply_mask = TRUE;
  layer->edit_mask  = TRUE;
  layer->show_mask  = FALSE;

  /*  floating selection  */
  layer->fs.drawable       = NULL;
  layer->fs.boundary_known = FALSE;
  layer->fs.segs           = NULL;
  layer->fs.num_segs       = 0;
}

static void
pika_color_managed_iface_init (PikaColorManagedInterface *iface)
{
  iface->get_color_profile = pika_layer_get_color_profile;
}

static void
pika_pickable_iface_init (PikaPickableInterface *iface)
{
  iface->get_opacity_at = pika_layer_get_opacity_at;
  iface->pixel_to_rgb   = pika_layer_pixel_to_rgb;
  iface->rgb_to_pixel   = pika_layer_rgb_to_pixel;
}

static void
pika_layer_set_property (GObject      *object,
                         guint         property_id,
                         const GValue *value,
                         GParamSpec   *pspec)
{
  switch (property_id)
    {
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
    }
}

static void
pika_layer_get_property (GObject    *object,
                         guint       property_id,
                         GValue     *value,
                         GParamSpec *pspec)
{
  PikaLayer *layer = PIKA_LAYER (object);

  switch (property_id)
    {
    case PROP_OPACITY:
      g_value_set_double (value, pika_layer_get_opacity (layer));
      break;
    case PROP_MODE:
      g_value_set_enum (value, pika_layer_get_mode (layer));
      break;
    case PROP_BLEND_SPACE:
      g_value_set_enum (value, pika_layer_get_blend_space (layer));
      break;
    case PROP_COMPOSITE_SPACE:
      g_value_set_enum (value, pika_layer_get_composite_space (layer));
      break;
    case PROP_COMPOSITE_MODE:
      g_value_set_enum (value, pika_layer_get_composite_mode (layer));
      break;
    case PROP_EXCLUDES_BACKDROP:
      g_value_set_boolean (value, pika_layer_get_excludes_backdrop (layer));
      break;
    case PROP_LOCK_ALPHA:
      g_value_set_boolean (value, pika_layer_get_lock_alpha (layer));
      break;
    case PROP_MASK:
      g_value_set_object (value, pika_layer_get_mask (layer));
      break;
    case PROP_FLOATING_SELECTION:
      g_value_set_boolean (value, pika_layer_is_floating_sel (layer));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
    }
}

static void
pika_layer_dispose (GObject *object)
{
  PikaLayer *layer = PIKA_LAYER (object);

  if (layer->mask)
    g_signal_handlers_disconnect_by_func (layer->mask,
                                          pika_layer_layer_mask_update,
                                          layer);

  if (pika_layer_is_floating_sel (layer))
    {
      PikaDrawable *fs_drawable = pika_layer_get_floating_sel_drawable (layer);

      /* only detach if this is actually the drawable's fs because the
       * layer might be on the undo stack and not attached to anything
       */
      if (pika_drawable_get_floating_sel (fs_drawable) == layer)
        pika_drawable_detach_floating_sel (fs_drawable);

      pika_layer_set_floating_sel_drawable (layer, NULL);
    }

  G_OBJECT_CLASS (parent_class)->dispose (object);
}

static void
pika_layer_finalize (GObject *object)
{
  PikaLayer *layer = PIKA_LAYER (object);

  g_clear_object (&layer->mask);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
pika_layer_update_mode_node (PikaLayer *layer)
{
  GeglNode               *mode_node;
  PikaLayerMode           visible_mode;
  PikaLayerColorSpace     visible_blend_space;
  PikaLayerColorSpace     visible_composite_space;
  PikaLayerCompositeMode  visible_composite_mode;

  mode_node = pika_drawable_get_mode_node (PIKA_DRAWABLE (layer));

  if (layer->mask && layer->show_mask)
    {
      visible_mode            = PIKA_LAYER_MODE_NORMAL;
      visible_blend_space     = PIKA_LAYER_COLOR_SPACE_AUTO;
      visible_composite_space = PIKA_LAYER_COLOR_SPACE_AUTO;
      visible_composite_mode  = PIKA_LAYER_COMPOSITE_AUTO;

      /* This makes sure that masks of LEGACY-mode layers are
       * composited in PERCEPTUAL space, and non-LEGACY layers in
       * LINEAR space, or whatever composite space was chosen in the
       * layer attributes dialog
       */
      visible_composite_space = pika_layer_get_real_composite_space (layer);
    }
  else
    {
      visible_mode            = layer->effective_mode;
      visible_blend_space     = layer->effective_blend_space;
      visible_composite_space = layer->effective_composite_space;
      visible_composite_mode  = layer->effective_composite_mode;
    }

  pika_gegl_mode_node_set_mode (mode_node,
                                visible_mode,
                                visible_blend_space,
                                visible_composite_space,
                                visible_composite_mode);
  pika_gegl_mode_node_set_opacity (mode_node, layer->opacity);
}

static void
pika_layer_notify (GObject    *object,
                   GParamSpec *pspec)
{
  if (! strcmp (pspec->name, "is-last-node") &&
      pika_filter_peek_node (PIKA_FILTER (object)))
    {
      pika_layer_update_mode_node (PIKA_LAYER (object));

      pika_drawable_update (PIKA_DRAWABLE (object), 0, 0, -1, -1);
    }
}

static void
pika_layer_name_changed (PikaObject *object)
{
  PikaLayer *layer = PIKA_LAYER (object);

  if (PIKA_OBJECT_CLASS (parent_class)->name_changed)
    PIKA_OBJECT_CLASS (parent_class)->name_changed (object);

  if (layer->mask)
    {
      gchar *mask_name = g_strdup_printf (_("%s mask"),
                                          pika_object_get_name (object));

      pika_object_take_name (PIKA_OBJECT (layer->mask), mask_name);
    }
}

static gint64
pika_layer_get_memsize (PikaObject *object,
                        gint64     *gui_size)
{
  PikaLayer *layer   = PIKA_LAYER (object);
  gint64     memsize = 0;

  memsize += pika_object_get_memsize (PIKA_OBJECT (layer->mask), gui_size);

  *gui_size += layer->fs.num_segs * sizeof (PikaBoundSeg);

  return memsize + PIKA_OBJECT_CLASS (parent_class)->get_memsize (object,
                                                                  gui_size);
}

static void
pika_layer_invalidate_preview (PikaViewable *viewable)
{
  PikaLayer *layer = PIKA_LAYER (viewable);

  PIKA_VIEWABLE_CLASS (parent_class)->invalidate_preview (viewable);

  if (pika_layer_is_floating_sel (layer))
    floating_sel_invalidate (layer);
}

static gchar *
pika_layer_get_description (PikaViewable  *viewable,
                            gchar        **tooltip)
{
  if (pika_layer_is_floating_sel (PIKA_LAYER (viewable)))
    {
      PikaDrawable *drawable;
      const gchar  *header = _("Floating Selection");

      drawable = pika_layer_get_floating_sel_drawable (PIKA_LAYER (viewable));
      if (PIKA_IS_LAYER_MASK (drawable))
        header = _("Floating Mask");
      else if (PIKA_IS_LAYER (drawable))
        header = _("Floating Layer");
      /* TRANSLATORS: the first %s will be the type of floating item, i.e.
       * either a "Floating Layer" or "Floating Mask" usually. The second will
       * be a layer name.
       */
      return g_strdup_printf (_("%s\n(%s)"),
                              header, pika_object_get_name (viewable));
    }

  return PIKA_VIEWABLE_CLASS (parent_class)->get_description (viewable,
                                                              tooltip);
}

static GeglNode *
pika_layer_get_node (PikaFilter *filter)
{
  PikaDrawable *drawable = PIKA_DRAWABLE (filter);
  PikaLayer    *layer    = PIKA_LAYER (filter);
  GeglNode     *node;
  GeglNode     *input;
  GeglNode     *source;
  GeglNode     *mode_node;
  gboolean      source_node_hijacked = FALSE;

  node = PIKA_FILTER_CLASS (parent_class)->get_node (filter);

  input = gegl_node_get_input_proxy (node, "input");

  source = pika_drawable_get_source_node (drawable);

  /* if the source node already has a parent, we are a floating
   * selection and the source node has been hijacked by the fs'
   * drawable
   */
  if (gegl_node_get_parent (source))
    source_node_hijacked = TRUE;

  if (! source_node_hijacked)
    gegl_node_add_child (node, source);

  gegl_node_connect (input, "output", source, "input");

  g_warn_if_fail (layer->layer_offset_node == NULL);
  g_warn_if_fail (layer->mask_offset_node == NULL);

  /* the mode node connects it all, and has aux and aux2 inputs for
   * the layer and its mask
   */
  mode_node = pika_drawable_get_mode_node (drawable);
  pika_layer_update_mode_node (layer);

  /* the layer's offset node */
  layer->layer_offset_node = gegl_node_new_child (node,
                                                  "operation", "gegl:translate",
                                                  NULL);
  pika_item_add_offset_node (PIKA_ITEM (layer), layer->layer_offset_node);

  /* the layer mask's offset node */
  layer->mask_offset_node = gegl_node_new_child (node,
                                                 "operation", "gegl:translate",
                                                  NULL);
  pika_item_add_offset_node (PIKA_ITEM (layer), layer->mask_offset_node);

  if (! source_node_hijacked)
    {
      gegl_node_connect (source,                   "output",
                         layer->layer_offset_node, "input");
    }

  if (! (layer->mask && pika_layer_get_show_mask (layer)))
    {
      gegl_node_connect (layer->layer_offset_node, "output",
                         mode_node,                "aux");
    }

  if (layer->mask)
    {
      GeglNode *mask;

      mask = pika_drawable_get_source_node (PIKA_DRAWABLE (layer->mask));

      gegl_node_connect (mask,                    "output",
                         layer->mask_offset_node, "input");

      if (pika_layer_get_show_mask (layer))
        {
          gegl_node_connect (layer->mask_offset_node, "output",
                             mode_node,               "aux");
        }
      else if (pika_layer_get_apply_mask (layer))
        {
          gegl_node_connect (layer->mask_offset_node, "output",
                             mode_node,               "aux2");
        }
    }

  return node;
}

static void
pika_layer_removed (PikaItem *item)
{
  PikaLayer *layer = PIKA_LAYER (item);

  if (layer->mask)
    pika_item_removed (PIKA_ITEM (layer->mask));

  if (PIKA_ITEM_CLASS (parent_class)->removed)
    PIKA_ITEM_CLASS (parent_class)->removed (item);
}

static void
pika_layer_unset_removed (PikaItem *item)
{
  PikaLayer *layer = PIKA_LAYER (item);

  if (layer->mask)
    pika_item_unset_removed (PIKA_ITEM (layer->mask));

  if (PIKA_ITEM_CLASS (parent_class)->unset_removed)
    PIKA_ITEM_CLASS (parent_class)->unset_removed (item);
}

static gboolean
pika_layer_is_attached (PikaItem *item)
{
  PikaImage *image = pika_item_get_image (item);

  return (PIKA_IS_IMAGE (image) &&
          pika_container_have (pika_image_get_layers (image),
                               PIKA_OBJECT (item)));
}

static PikaItemTree *
pika_layer_get_tree (PikaItem *item)
{
  if (pika_item_is_attached (item))
    {
      PikaImage *image = pika_item_get_image (item);

      return pika_image_get_layer_tree (image);
    }

  return NULL;
}

static PikaItem *
pika_layer_duplicate (PikaItem *item,
                      GType     new_type)
{
  PikaItem *new_item;

  g_return_val_if_fail (g_type_is_a (new_type, PIKA_TYPE_DRAWABLE), NULL);

  new_item = PIKA_ITEM_CLASS (parent_class)->duplicate (item, new_type);

  if (PIKA_IS_LAYER (new_item))
    {
      PikaLayer *layer     = PIKA_LAYER (item);
      PikaLayer *new_layer = PIKA_LAYER (new_item);

      pika_layer_set_mode            (new_layer,
                                      pika_layer_get_mode (layer), FALSE);
      pika_layer_set_blend_space     (new_layer,
                                      pika_layer_get_blend_space (layer), FALSE);
      pika_layer_set_composite_space (new_layer,
                                      pika_layer_get_composite_space (layer), FALSE);
      pika_layer_set_composite_mode  (new_layer,
                                      pika_layer_get_composite_mode (layer), FALSE);
      pika_layer_set_opacity         (new_layer,
                                      pika_layer_get_opacity (layer), FALSE);

      if (pika_layer_can_lock_alpha (new_layer))
        pika_layer_set_lock_alpha (new_layer,
                                   pika_layer_get_lock_alpha (layer), FALSE);

      /*  duplicate the layer mask if necessary  */
      if (layer->mask)
        {
          PikaItem *mask;

          mask = pika_item_duplicate (PIKA_ITEM (layer->mask),
                                      G_TYPE_FROM_INSTANCE (layer->mask));
          pika_layer_add_mask (new_layer, PIKA_LAYER_MASK (mask), FALSE, NULL);

          new_layer->apply_mask = layer->apply_mask;
          new_layer->edit_mask  = layer->edit_mask;
          new_layer->show_mask  = layer->show_mask;
        }
    }

  return new_item;
}

static void
pika_layer_convert (PikaItem  *item,
                    PikaImage *dest_image,
                    GType      old_type)
{
  PikaLayer         *layer    = PIKA_LAYER (item);
  PikaDrawable      *drawable = PIKA_DRAWABLE (item);
  PikaImageBaseType  old_base_type;
  PikaImageBaseType  new_base_type;
  PikaPrecision      old_precision;
  PikaPrecision      new_precision;
  PikaColorProfile  *src_profile  = NULL;
  PikaColorProfile  *dest_profile = NULL;

  old_base_type = pika_drawable_get_base_type (drawable);
  new_base_type = pika_image_get_base_type (dest_image);

  old_precision = pika_drawable_get_precision (drawable);
  new_precision = pika_image_get_precision (dest_image);

  if (g_type_is_a (old_type, PIKA_TYPE_LAYER))
    {
      src_profile =
        pika_color_managed_get_color_profile (PIKA_COLOR_MANAGED (item));

      dest_profile =
        pika_color_managed_get_color_profile (PIKA_COLOR_MANAGED (dest_image));

      if (pika_color_profile_is_equal (dest_profile, src_profile))
        {
          src_profile  = NULL;
          dest_profile = NULL;
        }
    }

  if (old_base_type != new_base_type ||
      old_precision != new_precision ||
      dest_profile)
    {
      pika_drawable_convert_type (drawable, dest_image,
                                  new_base_type,
                                  new_precision,
                                  pika_drawable_has_alpha (drawable),
                                  src_profile,
                                  dest_profile,
                                  GEGL_DITHER_NONE, GEGL_DITHER_NONE,
                                  FALSE, NULL);
    }

  if (layer->mask)
    pika_item_set_image (PIKA_ITEM (layer->mask), dest_image);

  PIKA_ITEM_CLASS (parent_class)->convert (item, dest_image, old_type);
}

static gboolean
pika_layer_rename (PikaItem     *item,
                   const gchar  *new_name,
                   const gchar  *undo_desc,
                   GError      **error)
{
  PikaLayer *layer = PIKA_LAYER (item);
  PikaImage *image = pika_item_get_image (item);
  gboolean   attached;
  gboolean   floating_sel;

  attached     = pika_item_is_attached (item);
  floating_sel = pika_layer_is_floating_sel (layer);

  if (floating_sel)
    {
      if (PIKA_IS_CHANNEL (pika_layer_get_floating_sel_drawable (layer)))
        {
          g_set_error_literal (error, PIKA_ERROR, PIKA_FAILED,
                               _("Cannot create a new layer from the floating "
                                 "selection because it belongs to a layer mask "
                                 "or channel."));
          return FALSE;
        }

      if (attached)
        {
          pika_image_undo_group_start (image,
                                       PIKA_UNDO_GROUP_ITEM_PROPERTIES,
                                       undo_desc);

          floating_sel_to_layer (layer, NULL);
        }
    }

  PIKA_ITEM_CLASS (parent_class)->rename (item, new_name, undo_desc, error);

  if (attached && floating_sel)
    pika_image_undo_group_end (image);

  return TRUE;
}

static void
pika_layer_start_move (PikaItem *item,
                       gboolean  push_undo)
{
  PikaLayer *layer     = PIKA_LAYER (item);
  PikaLayer *ancestor  = layer;
  GSList    *ancestors = NULL;

  /* suspend mask cropping for all of the layer's ancestors */
  while ((ancestor = pika_layer_get_parent (ancestor)))
    {
      pika_group_layer_suspend_mask (PIKA_GROUP_LAYER (ancestor), push_undo);

      ancestors = g_slist_prepend (ancestors, g_object_ref (ancestor));
    }

  /* we keep the ancestor list around, so that we can resume mask cropping for
   * the same set of groups in pika_layer_end_move().  note that
   * pika_image_remove_layer() calls start_move() before removing the layer,
   * while it's still part of the layer tree, and end_move() afterwards, when
   * it's no longer part of the layer tree, and hence we can't use get_parent()
   * in end_move() to get the same set of ancestors.
   */
  layer->move_stack = g_slist_prepend (layer->move_stack, ancestors);

  if (PIKA_ITEM_CLASS (parent_class)->start_move)
    PIKA_ITEM_CLASS (parent_class)->start_move (item, push_undo);
}

static void
pika_layer_end_move (PikaItem *item,
                     gboolean  push_undo)
{
  PikaLayer *layer = PIKA_LAYER (item);
  GSList    *ancestors;
  GSList    *iter;

  g_return_if_fail (layer->move_stack != NULL);

  if (PIKA_ITEM_CLASS (parent_class)->end_move)
    PIKA_ITEM_CLASS (parent_class)->end_move (item, push_undo);

  ancestors = layer->move_stack->data;

  layer->move_stack = g_slist_remove (layer->move_stack, ancestors);

  /* resume mask cropping for all of the layer's ancestors */
  for (iter = ancestors; iter; iter = g_slist_next (iter))
    {
      PikaGroupLayer *ancestor = iter->data;

      pika_group_layer_resume_mask (ancestor, push_undo);

      g_object_unref (ancestor);
    }

  g_slist_free (ancestors);
}

static void
pika_layer_translate (PikaItem *item,
                      gdouble   offset_x,
                      gdouble   offset_y,
                      gboolean  push_undo)
{
  PikaLayer *layer = PIKA_LAYER (item);

  if (push_undo)
    pika_image_undo_push_item_displace (pika_item_get_image (item), NULL, item);

  PIKA_LAYER_GET_CLASS (layer)->translate (layer,
                                           SIGNED_ROUND (offset_x),
                                           SIGNED_ROUND (offset_y));

  if (layer->mask)
    {
      gint off_x, off_y;

      pika_item_get_offset (item, &off_x, &off_y);
      pika_item_set_offset (PIKA_ITEM (layer->mask), off_x, off_y);

      pika_viewable_invalidate_preview (PIKA_VIEWABLE (layer->mask));
    }
}

static void
pika_layer_scale (PikaItem              *item,
                  gint                   new_width,
                  gint                   new_height,
                  gint                   new_offset_x,
                  gint                   new_offset_y,
                  PikaInterpolationType  interpolation_type,
                  PikaProgress          *progress)
{
  PikaLayer       *layer = PIKA_LAYER (item);
  PikaObjectQueue *queue = NULL;

  if (progress && layer->mask)
    {
      PikaLayerMask *mask;

      queue    = pika_object_queue_new (progress);
      progress = PIKA_PROGRESS (queue);

      /* temporarily set layer->mask to NULL, so that its size won't be counted
       * when pushing the layer to the queue.
       */
      mask        = layer->mask;
      layer->mask = NULL;

      pika_object_queue_push (queue, layer);
      pika_object_queue_push (queue, mask);

      layer->mask = mask;
    }

  if (queue)
    pika_object_queue_pop (queue);

  PIKA_LAYER_GET_CLASS (layer)->scale (layer, new_width, new_height,
                                       new_offset_x, new_offset_y,
                                       interpolation_type, progress);

  if (layer->mask)
    {
      if (queue)
        pika_object_queue_pop (queue);

      pika_item_scale (PIKA_ITEM (layer->mask),
                       new_width, new_height,
                       new_offset_x, new_offset_y,
                       interpolation_type, progress);
    }

  g_clear_object (&queue);
}

static void
pika_layer_resize (PikaItem     *item,
                   PikaContext  *context,
                   PikaFillType  fill_type,
                   gint          new_width,
                   gint          new_height,
                   gint          offset_x,
                   gint          offset_y)
{
  PikaLayer *layer  = PIKA_LAYER (item);

  PIKA_LAYER_GET_CLASS (layer)->resize (layer, context, fill_type,
                                        new_width, new_height,
                                        offset_x, offset_y);

  if (layer->mask)
    pika_item_resize (PIKA_ITEM (layer->mask), context, PIKA_FILL_TRANSPARENT,
                      new_width, new_height, offset_x, offset_y);
}

static void
pika_layer_flip (PikaItem            *item,
                 PikaContext         *context,
                 PikaOrientationType  flip_type,
                 gdouble              axis,
                 gboolean             clip_result)
{
  PikaLayer *layer = PIKA_LAYER (item);

  PIKA_LAYER_GET_CLASS (layer)->flip (layer, context, flip_type, axis,
                                      clip_result);

  if (layer->mask)
    pika_item_flip (PIKA_ITEM (layer->mask), context,
                    flip_type, axis, clip_result);
}

static void
pika_layer_rotate (PikaItem         *item,
                   PikaContext      *context,
                   PikaRotationType  rotate_type,
                   gdouble           center_x,
                   gdouble           center_y,
                   gboolean          clip_result)
{
  PikaLayer *layer = PIKA_LAYER (item);

  PIKA_LAYER_GET_CLASS (layer)->rotate (layer, context,
                                        rotate_type, center_x, center_y,
                                        clip_result);

  if (layer->mask)
    pika_item_rotate (PIKA_ITEM (layer->mask), context,
                      rotate_type, center_x, center_y, clip_result);
}

static void
pika_layer_transform (PikaItem               *item,
                      PikaContext            *context,
                      const PikaMatrix3      *matrix,
                      PikaTransformDirection  direction,
                      PikaInterpolationType   interpolation_type,
                      PikaTransformResize     clip_result,
                      PikaProgress           *progress)
{
  PikaLayer       *layer = PIKA_LAYER (item);
  PikaObjectQueue *queue = NULL;

  if (progress && layer->mask)
    {
      PikaLayerMask *mask;

      queue    = pika_object_queue_new (progress);
      progress = PIKA_PROGRESS (queue);

      /* temporarily set layer->mask to NULL, so that its size won't be counted
       * when pushing the layer to the queue.
       */
      mask        = layer->mask;
      layer->mask = NULL;

      pika_object_queue_push (queue, layer);
      pika_object_queue_push (queue, mask);

      layer->mask = mask;
    }

  if (queue)
    pika_object_queue_pop (queue);

  PIKA_LAYER_GET_CLASS (layer)->transform (layer, context, matrix, direction,
                                           interpolation_type,
                                           clip_result,
                                           progress);

  if (layer->mask)
    {
      if (queue)
        pika_object_queue_pop (queue);

      pika_item_transform (PIKA_ITEM (layer->mask), context,
                           matrix, direction,
                           interpolation_type,
                           clip_result, progress);
    }

  g_clear_object (&queue);
}

static void
pika_layer_to_selection (PikaItem       *item,
                         PikaChannelOps  op,
                         gboolean        antialias,
                         gboolean        feather,
                         gdouble         feather_radius_x,
                         gdouble         feather_radius_y)
{
  PikaLayer *layer = PIKA_LAYER (item);
  PikaImage *image = pika_item_get_image (item);

  pika_channel_select_alpha (pika_image_get_mask (image),
                             PIKA_DRAWABLE (layer),
                             op,
                             feather, feather_radius_x, feather_radius_y);
}

static void
pika_layer_alpha_changed (PikaDrawable *drawable)
{
  if (PIKA_DRAWABLE_CLASS (parent_class)->alpha_changed)
    PIKA_DRAWABLE_CLASS (parent_class)->alpha_changed (drawable);

  /* When we add/remove alpha, whatever cached color transforms in
   * view renderers need to be recreated because they cache the wrong
   * lcms formats. See bug 478528.
   */
  pika_color_managed_profile_changed (PIKA_COLOR_MANAGED (drawable));
}

static gint64
pika_layer_estimate_memsize (PikaDrawable      *drawable,
                             PikaComponentType  component_type,
                             gint               width,
                             gint               height)
{
  PikaLayer *layer   = PIKA_LAYER (drawable);
  gint64     memsize = 0;

  if (layer->mask)
    memsize += pika_drawable_estimate_memsize (PIKA_DRAWABLE (layer->mask),
                                               component_type,
                                               width, height);

  return memsize +
         PIKA_DRAWABLE_CLASS (parent_class)->estimate_memsize (drawable,
                                                               component_type,
                                                               width, height);
}

static gboolean
pika_layer_supports_alpha (PikaDrawable *drawable)
{
  return TRUE;
}

static void
pika_layer_convert_type (PikaDrawable     *drawable,
                         PikaImage        *dest_image,
                         const Babl       *new_format,
                         PikaColorProfile *src_profile,
                         PikaColorProfile *dest_profile,
                         GeglDitherMethod  layer_dither_type,
                         GeglDitherMethod  mask_dither_type,
                         gboolean          push_undo,
                         PikaProgress     *progress)
{
  PikaLayer       *layer = PIKA_LAYER (drawable);
  PikaObjectQueue *queue = NULL;
  const Babl      *dest_space;
  const Babl      *space_format;
  gboolean         convert_mask;

  convert_mask = layer->mask &&
                 pika_babl_format_get_precision (new_format) !=
                 pika_drawable_get_precision (PIKA_DRAWABLE (layer->mask));

  if (progress && convert_mask)
    {
      PikaLayerMask *mask;

      queue    = pika_object_queue_new (progress);
      progress = PIKA_PROGRESS (queue);

      /* temporarily set layer->mask to NULL, so that its size won't be counted
       * when pushing the layer to the queue.
       */
      mask        = layer->mask;
      layer->mask = NULL;

      pika_object_queue_push (queue, layer);
      pika_object_queue_push (queue, mask);

      layer->mask = mask;
    }

  if (queue)
    pika_object_queue_pop (queue);

  /*  when called with a dest_profile, always use the space from that
   *  profile, we can't use pika_image_get_layer_space() during an
   *  image type or precision conversion
   */
  if (dest_profile)
    {
      dest_space =
        pika_color_profile_get_space (dest_profile,
                                      PIKA_COLOR_RENDERING_INTENT_RELATIVE_COLORIMETRIC,
                                      NULL);
    }
  else
    {
      dest_space = pika_image_get_layer_space (dest_image);
    }

  space_format = babl_format_with_space ((const gchar *) new_format,
                                         dest_space);

  PIKA_LAYER_GET_CLASS (layer)->convert_type (layer, dest_image, space_format,
                                              src_profile, dest_profile,
                                              layer_dither_type,
                                              mask_dither_type, push_undo,
                                              progress);

  if (convert_mask)
    {
      if (queue)
        pika_object_queue_pop (queue);

      pika_drawable_convert_type (PIKA_DRAWABLE (layer->mask), dest_image,
                                  PIKA_GRAY,
                                  pika_babl_format_get_precision (new_format),
                                  pika_drawable_has_alpha (PIKA_DRAWABLE (layer->mask)),
                                  NULL, NULL,
                                  layer_dither_type, mask_dither_type,
                                  push_undo, progress);
    }

  g_clear_object (&queue);
}

static void
pika_layer_invalidate_boundary (PikaDrawable *drawable)
{
  PikaLayer *layer = PIKA_LAYER (drawable);

  if (pika_item_is_attached (PIKA_ITEM (drawable)) &&
      pika_item_is_visible (PIKA_ITEM (drawable)))
    {
      PikaImage   *image = pika_item_get_image (PIKA_ITEM (drawable));
      PikaChannel *mask  = pika_image_get_mask (image);

      /*  Turn the current selection off  */
      pika_image_selection_invalidate (image);

      /*  Only bother with the bounds if there is a selection  */
      if (! pika_channel_is_empty (mask))
        {
          mask->bounds_known   = FALSE;
          mask->boundary_known = FALSE;
        }
    }

  if (pika_layer_is_floating_sel (layer))
    floating_sel_invalidate (layer);
}

static void
pika_layer_get_active_components (PikaDrawable *drawable,
                                  gboolean     *active)
{
  PikaLayer  *layer  = PIKA_LAYER (drawable);
  PikaImage  *image  = pika_item_get_image (PIKA_ITEM (drawable));
  const Babl *format = pika_drawable_get_format (drawable);

  /*  first copy the image active channels  */
  pika_image_get_active_array (image, active);

  if (pika_drawable_has_alpha (drawable) &&
      pika_layer_is_alpha_locked (layer, NULL))
    active[babl_format_get_n_components (format) - 1] = FALSE;
}

static PikaComponentMask
pika_layer_get_active_mask (PikaDrawable *drawable)
{
  PikaLayer         *layer = PIKA_LAYER (drawable);
  PikaImage         *image = pika_item_get_image (PIKA_ITEM (drawable));
  PikaComponentMask  mask  = pika_image_get_active_mask (image);

  if (pika_drawable_has_alpha (drawable) &&
      pika_layer_is_alpha_locked (layer, NULL))
    mask &= ~PIKA_COMPONENT_MASK_ALPHA;

  return mask;
}

static void
pika_layer_set_buffer (PikaDrawable        *drawable,
                       gboolean             push_undo,
                       const gchar         *undo_desc,
                       GeglBuffer          *buffer,
                       const GeglRectangle *bounds)
{
  GeglBuffer *old_buffer = pika_drawable_get_buffer (drawable);
  gint        old_trc    = -1;

  if (old_buffer)
    old_trc = pika_drawable_get_trc (drawable);

  PIKA_DRAWABLE_CLASS (parent_class)->set_buffer (drawable,
                                                  push_undo, undo_desc,
                                                  buffer, bounds);

  if (pika_filter_peek_node (PIKA_FILTER (drawable)))
    {
      if (pika_drawable_get_trc (drawable) != old_trc)
        pika_layer_update_mode_node (PIKA_LAYER (drawable));
    }
}

static GeglRectangle
pika_layer_get_bounding_box (PikaDrawable *drawable)
{
  PikaLayer     *layer = PIKA_LAYER (drawable);
  PikaLayerMask *mask  = pika_layer_get_mask (layer);
  GeglRectangle  bounding_box;

  if (mask && pika_layer_get_show_mask (layer))
    {
      bounding_box = pika_drawable_get_bounding_box (PIKA_DRAWABLE (mask));
    }
  else
    {
      bounding_box = PIKA_LAYER_GET_CLASS (layer)->get_bounding_box (layer);

      if (mask && pika_layer_get_apply_mask (layer))
        {
          GeglRectangle mask_bounding_box;

          mask_bounding_box = pika_drawable_get_bounding_box (
            PIKA_DRAWABLE (mask));

          gegl_rectangle_intersect (&bounding_box,
                                    &bounding_box, &mask_bounding_box);
        }
    }

  return bounding_box;
}

static PikaColorProfile *
pika_layer_get_color_profile (PikaColorManaged *managed)
{
  PikaImage *image = pika_item_get_image (PIKA_ITEM (managed));

  return pika_color_managed_get_color_profile (PIKA_COLOR_MANAGED (image));
}

static gdouble
pika_layer_get_opacity_at (PikaPickable *pickable,
                           gint          x,
                           gint          y)
{
  PikaLayer *layer = PIKA_LAYER (pickable);
  gdouble    value = PIKA_OPACITY_TRANSPARENT;

  if (x >= 0 && x < pika_item_get_width  (PIKA_ITEM (layer)) &&
      y >= 0 && y < pika_item_get_height (PIKA_ITEM (layer)) &&
      pika_item_is_visible (PIKA_ITEM (layer)))
    {
      if (! pika_drawable_has_alpha (PIKA_DRAWABLE (layer)))
        {
          value = PIKA_OPACITY_OPAQUE;
        }
      else
        {
          gegl_buffer_sample (pika_drawable_get_buffer (PIKA_DRAWABLE (layer)),
                              x, y, NULL, &value, babl_format ("A double"),
                              GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
        }

      if (pika_layer_get_mask (layer) &&
          pika_layer_get_apply_mask (layer))
        {
          gdouble mask_value;

          mask_value = pika_pickable_get_opacity_at (PIKA_PICKABLE (layer->mask),
                                                     x, y);

          value *= mask_value;
        }
    }

  return value;
}

static void
pika_layer_pixel_to_rgb (PikaPickable *pickable,
                         const Babl   *format,
                         gpointer      pixel,
                         PikaRGB      *color)
{
  PikaImage *image = pika_item_get_image (PIKA_ITEM (pickable));

  pika_pickable_pixel_to_rgb (PIKA_PICKABLE (image), format, pixel, color);
}

static void
pika_layer_rgb_to_pixel (PikaPickable  *pickable,
                         const PikaRGB *color,
                         const Babl    *format,
                         gpointer       pixel)
{
  PikaImage *image = pika_item_get_image (PIKA_ITEM (pickable));

  pika_pickable_rgb_to_pixel (PIKA_PICKABLE (image), color, format, pixel);
}

static gboolean
pika_layer_real_is_alpha_locked (PikaLayer  *layer,
                                 PikaLayer **locked_layer)
{
  PikaItem *parent = pika_item_get_parent (PIKA_ITEM (layer));

  if (layer->lock_alpha)
    {
      if (locked_layer)
        *locked_layer = layer;
    }
  else if (parent &&
           pika_layer_is_alpha_locked (PIKA_LAYER (parent), locked_layer))
    {
      return TRUE;
    }

  return layer->lock_alpha;
}

static void
pika_layer_real_translate (PikaLayer *layer,
                           gint       offset_x,
                           gint       offset_y)
{
  /*  update the old region  */
  pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);

  /*  invalidate the selection boundary because of a layer modification  */
  pika_drawable_invalidate_boundary (PIKA_DRAWABLE (layer));

  PIKA_ITEM_CLASS (parent_class)->translate (PIKA_ITEM (layer),
                                             offset_x, offset_y,
                                             FALSE);

  /*  update the new region  */
  pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);
}

static void
pika_layer_real_scale (PikaLayer             *layer,
                       gint                   new_width,
                       gint                   new_height,
                       gint                   new_offset_x,
                       gint                   new_offset_y,
                       PikaInterpolationType  interpolation_type,
                       PikaProgress          *progress)
{
  PIKA_ITEM_CLASS (parent_class)->scale (PIKA_ITEM (layer),
                                         new_width, new_height,
                                         new_offset_x, new_offset_y,
                                         interpolation_type, progress);
}

static void
pika_layer_real_resize (PikaLayer    *layer,
                        PikaContext  *context,
                        PikaFillType  fill_type,
                        gint          new_width,
                        gint          new_height,
                        gint          offset_x,
                        gint          offset_y)
{
  if (fill_type == PIKA_FILL_TRANSPARENT &&
      ! pika_drawable_has_alpha (PIKA_DRAWABLE (layer)))
    {
      fill_type = PIKA_FILL_BACKGROUND;
    }

  PIKA_ITEM_CLASS (parent_class)->resize (PIKA_ITEM (layer),
                                          context, fill_type,
                                          new_width, new_height,
                                          offset_x, offset_y);
}

static void
pika_layer_real_flip (PikaLayer           *layer,
                      PikaContext         *context,
                      PikaOrientationType  flip_type,
                      gdouble              axis,
                      gboolean             clip_result)
{
  PIKA_ITEM_CLASS (parent_class)->flip (PIKA_ITEM (layer),
                                        context, flip_type, axis, clip_result);
}

static void
pika_layer_real_rotate (PikaLayer        *layer,
                        PikaContext      *context,
                        PikaRotationType  rotate_type,
                        gdouble           center_x,
                        gdouble           center_y,
                        gboolean          clip_result)
{
  PIKA_ITEM_CLASS (parent_class)->rotate (PIKA_ITEM (layer),
                                          context, rotate_type,
                                          center_x, center_y,
                                          clip_result);
}

static void
pika_layer_real_transform (PikaLayer              *layer,
                           PikaContext            *context,
                           const PikaMatrix3      *matrix,
                           PikaTransformDirection  direction,
                           PikaInterpolationType   interpolation_type,
                           PikaTransformResize     clip_result,
                           PikaProgress           *progress)
{
  PIKA_ITEM_CLASS (parent_class)->transform (PIKA_ITEM (layer),
                                             context, matrix, direction,
                                             interpolation_type,
                                             clip_result,
                                             progress);
}

static void
pika_layer_real_convert_type (PikaLayer        *layer,
                              PikaImage        *dest_image,
                              const Babl       *new_format,
                              PikaColorProfile *src_profile,
                              PikaColorProfile *dest_profile,
                              GeglDitherMethod  layer_dither_type,
                              GeglDitherMethod  mask_dither_type,
                              gboolean          push_undo,
                              PikaProgress     *progress)
{
  PikaDrawable *drawable = PIKA_DRAWABLE (layer);
  GeglBuffer   *src_buffer;
  GeglBuffer   *dest_buffer;

  if (layer_dither_type == GEGL_DITHER_NONE)
    {
      src_buffer = g_object_ref (pika_drawable_get_buffer (drawable));
    }
  else
    {
      gint bits;

      src_buffer =
        gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                         pika_item_get_width  (PIKA_ITEM (layer)),
                                         pika_item_get_height (PIKA_ITEM (layer))),
                         pika_drawable_get_format (drawable));

      bits = (babl_format_get_bytes_per_pixel (new_format) * 8 /
              babl_format_get_n_components (new_format));

      pika_gegl_apply_dither (pika_drawable_get_buffer (drawable),
                              NULL, NULL,
                              src_buffer, 1 << bits, layer_dither_type);
    }

  dest_buffer =
    gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                     pika_item_get_width  (PIKA_ITEM (layer)),
                                     pika_item_get_height (PIKA_ITEM (layer))),
                     new_format);

  if (dest_profile)
    {
      if (! src_profile)
        src_profile =
          pika_color_managed_get_color_profile (PIKA_COLOR_MANAGED (layer));

      pika_gegl_convert_color_profile (src_buffer,  NULL, src_profile,
                                       dest_buffer, NULL, dest_profile,
                                       PIKA_COLOR_RENDERING_INTENT_PERCEPTUAL,
                                       TRUE, progress);
    }
  else
    {
      pika_gegl_buffer_copy (src_buffer, NULL, GEGL_ABYSS_NONE,
                             dest_buffer, NULL);
    }

  pika_drawable_set_buffer (drawable, push_undo, NULL, dest_buffer);

  g_object_unref (src_buffer);
  g_object_unref (dest_buffer);
}

static GeglRectangle
pika_layer_real_get_bounding_box (PikaLayer *layer)
{
  return PIKA_DRAWABLE_CLASS (parent_class)->get_bounding_box (
    PIKA_DRAWABLE (layer));
}

static void
pika_layer_real_get_effective_mode (PikaLayer              *layer,
                                    PikaLayerMode          *mode,
                                    PikaLayerColorSpace    *blend_space,
                                    PikaLayerColorSpace    *composite_space,
                                    PikaLayerCompositeMode *composite_mode)
{
  *mode            = pika_layer_get_mode (layer);
  *blend_space     = pika_layer_get_real_blend_space (layer);
  *composite_space = pika_layer_get_real_composite_space (layer);
  *composite_mode  = pika_layer_get_real_composite_mode (layer);
}

static gboolean
pika_layer_real_get_excludes_backdrop (PikaLayer *layer)
{
  PikaLayerCompositeRegion included_region;

  included_region = pika_layer_mode_get_included_region (layer->mode,
                                                         layer->effective_composite_mode);

  return ! (included_region & PIKA_LAYER_COMPOSITE_REGION_DESTINATION);
}

static void
pika_layer_layer_mask_update (PikaDrawable *drawable,
                              gint          x,
                              gint          y,
                              gint          width,
                              gint          height,
                              PikaLayer    *layer)
{
  if (pika_layer_get_apply_mask (layer) ||
      pika_layer_get_show_mask (layer))
    {
      pika_drawable_update (PIKA_DRAWABLE (layer),
                            x, y, width, height);
    }
}


/*  public functions  */

void
pika_layer_fix_format_space (PikaLayer *layer,
                             gboolean   copy_buffer,
                             gboolean   push_undo)
{
  PikaDrawable *drawable;
  const Babl   *format;

  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (push_undo == FALSE || copy_buffer == TRUE);

  drawable = PIKA_DRAWABLE (layer);

  format = pika_image_get_layer_format (pika_item_get_image (PIKA_ITEM (layer)),
                                        pika_drawable_has_alpha (drawable));

  if (format != pika_drawable_get_format (drawable))
    {
      pika_drawable_set_format (drawable, format, copy_buffer, push_undo);
    }
}

PikaLayer *
pika_layer_get_parent (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), NULL);

  return PIKA_LAYER (pika_viewable_get_parent (PIKA_VIEWABLE (layer)));
}

PikaLayerMask *
pika_layer_get_mask (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), NULL);

  return layer->mask;
}

PikaLayerMask *
pika_layer_add_mask (PikaLayer      *layer,
                     PikaLayerMask  *mask,
                     gboolean        push_undo,
                     GError        **error)
{
  PikaImage *image;

  g_return_val_if_fail (PIKA_IS_LAYER (layer), NULL);
  g_return_val_if_fail (PIKA_IS_LAYER_MASK (mask), NULL);
  g_return_val_if_fail (pika_item_get_image (PIKA_ITEM (layer)) ==
                        pika_item_get_image (PIKA_ITEM (mask)), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  if (! pika_item_is_attached (PIKA_ITEM (layer)))
    push_undo = FALSE;

  image = pika_item_get_image (PIKA_ITEM (layer));

  if (layer->mask)
    {
      g_set_error_literal (error, PIKA_ERROR, PIKA_FAILED,
                           _("Unable to add a layer mask since "
                             "the layer already has one."));
      return NULL;
    }

  if ((pika_item_get_width (PIKA_ITEM (layer)) !=
       pika_item_get_width (PIKA_ITEM (mask))) ||
      (pika_item_get_height (PIKA_ITEM (layer)) !=
       pika_item_get_height (PIKA_ITEM (mask))))
    {
      g_set_error_literal (error, PIKA_ERROR, PIKA_FAILED,
                           _("Cannot add layer mask of different "
                             "dimensions than specified layer."));
      return NULL;
    }

  if (push_undo)
    pika_image_undo_push_layer_mask_add (image, C_("undo-type", "Add Layer Mask"),
                                         layer, mask);

  layer->mask = g_object_ref_sink (mask);
  layer->apply_mask = TRUE;
  layer->edit_mask  = TRUE;
  layer->show_mask  = FALSE;

  pika_layer_mask_set_layer (mask, layer);

  if (pika_filter_peek_node (PIKA_FILTER (layer)))
    {
      GeglNode *mode_node;
      GeglNode *mask;

      mode_node = pika_drawable_get_mode_node (PIKA_DRAWABLE (layer));

      mask = pika_drawable_get_source_node (PIKA_DRAWABLE (layer->mask));

      gegl_node_connect (mask,                    "output",
                         layer->mask_offset_node, "input");

      if (layer->show_mask)
        {
          gegl_node_connect (layer->mask_offset_node, "output",
                             mode_node,               "aux");
        }
      else
        {
          gegl_node_connect (layer->mask_offset_node, "output",
                             mode_node,               "aux2");
        }

      pika_layer_update_mode_node (layer);
    }

  pika_drawable_update_bounding_box (PIKA_DRAWABLE (layer));

  pika_layer_update_effective_mode (layer);
  pika_layer_update_excludes_backdrop (layer);

  if (pika_layer_get_apply_mask (layer) ||
      pika_layer_get_show_mask (layer))
    {
      pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);
    }

  g_signal_connect (mask, "update",
                    G_CALLBACK (pika_layer_layer_mask_update),
                    layer);

  g_signal_emit (layer, layer_signals[MASK_CHANGED], 0);

  g_object_notify (G_OBJECT (layer), "mask");

  /*  if the mask came from the undo stack, reset its "removed" state  */
  if (pika_item_is_removed (PIKA_ITEM (mask)))
    pika_item_unset_removed (PIKA_ITEM (mask));

  return layer->mask;
}

PikaLayerMask *
pika_layer_create_mask (PikaLayer       *layer,
                        PikaAddMaskType  add_mask_type,
                        PikaChannel     *channel)
{
  PikaDrawable  *drawable;
  PikaItem      *item;
  PikaLayerMask *mask;
  PikaImage     *image;
  gchar         *mask_name;
  PikaRGB        black = { 0.0, 0.0, 0.0, PIKA_OPACITY_OPAQUE };

  g_return_val_if_fail (PIKA_IS_LAYER (layer), NULL);
  g_return_val_if_fail (add_mask_type != PIKA_ADD_MASK_CHANNEL ||
                        PIKA_IS_CHANNEL (channel), NULL);

  drawable = PIKA_DRAWABLE (layer);
  item     = PIKA_ITEM (layer);
  image    = pika_item_get_image (item);

  mask_name = g_strdup_printf (_("%s mask"),
                               pika_object_get_name (layer));

  mask = pika_layer_mask_new (image,
                              pika_item_get_width  (item),
                              pika_item_get_height (item),
                              mask_name, &black);

  g_free (mask_name);

  switch (add_mask_type)
    {
    case PIKA_ADD_MASK_WHITE:
      pika_channel_all (PIKA_CHANNEL (mask), FALSE);
      break;

    case PIKA_ADD_MASK_BLACK:
      pika_channel_clear (PIKA_CHANNEL (mask), NULL, FALSE);
      break;

    case PIKA_ADD_MASK_ALPHA:
    case PIKA_ADD_MASK_ALPHA_TRANSFER:
      if (pika_drawable_has_alpha (drawable))
        {
          GeglBuffer *dest_buffer;
          const Babl *component_format;

          dest_buffer = pika_drawable_get_buffer (PIKA_DRAWABLE (mask));

          component_format =
            pika_image_get_component_format (image, PIKA_CHANNEL_ALPHA);

          gegl_buffer_set_format (dest_buffer, component_format);
          pika_gegl_buffer_copy (pika_drawable_get_buffer (drawable), NULL,
                                 GEGL_ABYSS_NONE,
                                 dest_buffer, NULL);
          gegl_buffer_set_format (dest_buffer, NULL);

          if (add_mask_type == PIKA_ADD_MASK_ALPHA_TRANSFER)
            {
              pika_drawable_push_undo (drawable,
                                       C_("undo-type", "Transfer Alpha to Mask"),
                                       NULL,
                                       0, 0,
                                       pika_item_get_width  (item),
                                       pika_item_get_height (item));

              pika_gegl_apply_set_alpha (pika_drawable_get_buffer (drawable),
                                         NULL, NULL,
                                         pika_drawable_get_buffer (drawable),
                                         1.0);
            }
        }
      break;

    case PIKA_ADD_MASK_SELECTION:
    case PIKA_ADD_MASK_CHANNEL:
      {
        gboolean channel_empty;
        gint     offset_x, offset_y;
        gint     copy_x, copy_y;
        gint     copy_width, copy_height;

        if (add_mask_type == PIKA_ADD_MASK_SELECTION)
          channel = PIKA_CHANNEL (pika_image_get_mask (image));

        channel_empty = pika_channel_is_empty (channel);

        pika_item_get_offset (item, &offset_x, &offset_y);

        pika_rectangle_intersect (0, 0,
                                  pika_image_get_width  (image),
                                  pika_image_get_height (image),
                                  offset_x, offset_y,
                                  pika_item_get_width  (item),
                                  pika_item_get_height (item),
                                  &copy_x, &copy_y,
                                  &copy_width, &copy_height);

        if (copy_width  < pika_item_get_width  (item) ||
            copy_height < pika_item_get_height (item) ||
            channel_empty)
          pika_channel_clear (PIKA_CHANNEL (mask), NULL, FALSE);

        if ((copy_width || copy_height) && ! channel_empty)
          {
            GeglBuffer *src;
            GeglBuffer *dest;
            const Babl *format;

            src  = pika_drawable_get_buffer (PIKA_DRAWABLE (channel));
            dest = pika_drawable_get_buffer (PIKA_DRAWABLE (mask));

            format = gegl_buffer_get_format (src);

            /* make sure no gamma conversion happens */
            gegl_buffer_set_format (dest, format);
            pika_gegl_buffer_copy (src,
                                   GEGL_RECTANGLE (copy_x, copy_y,
                                                   copy_width, copy_height),
                                   GEGL_ABYSS_NONE,
                                   dest,
                                   GEGL_RECTANGLE (copy_x - offset_x,
                                                   copy_y - offset_y,
                                                   0, 0));
            gegl_buffer_set_format (dest, NULL);

            PIKA_CHANNEL (mask)->bounds_known = FALSE;
          }
      }
      break;

    case PIKA_ADD_MASK_COPY:
      {
        GeglBuffer *src_buffer;
        GeglBuffer *dest_buffer;

        if (! pika_drawable_is_gray (drawable))
          {
            const Babl *copy_format =
              pika_image_get_format (image, PIKA_GRAY,
                                     pika_drawable_get_precision (drawable),
                                     pika_drawable_has_alpha (drawable),
                                     NULL);

            src_buffer =
              gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                               pika_item_get_width  (item),
                                               pika_item_get_height (item)),
                               copy_format);

            pika_gegl_buffer_copy (pika_drawable_get_buffer (drawable), NULL,
                                   GEGL_ABYSS_NONE,
                                   src_buffer, NULL);
          }
        else
          {
            src_buffer = pika_drawable_get_buffer (drawable);
            g_object_ref (src_buffer);
          }

        dest_buffer = pika_drawable_get_buffer (PIKA_DRAWABLE (mask));

        if (pika_drawable_has_alpha (drawable))
          {
            PikaRGB background;

            pika_rgba_set (&background, 0.0, 0.0, 0.0, 0.0);

            pika_gegl_apply_flatten (src_buffer, NULL, NULL,
                                     dest_buffer, &background, NULL,
                                     PIKA_LAYER_COLOR_SPACE_RGB_LINEAR);
          }
        else
          {
            pika_gegl_buffer_copy (src_buffer, NULL, GEGL_ABYSS_NONE,
                                   dest_buffer, NULL);
          }

        g_object_unref (src_buffer);
      }

      PIKA_CHANNEL (mask)->bounds_known = FALSE;
      break;
    }

  return mask;
}

void
pika_layer_apply_mask (PikaLayer         *layer,
                       PikaMaskApplyMode  mode,
                       gboolean           push_undo)
{
  PikaItem      *item;
  PikaImage     *image;
  PikaLayerMask *mask;
  gboolean       view_changed = FALSE;

  g_return_if_fail (PIKA_IS_LAYER (layer));

  mask = pika_layer_get_mask (layer);

  if (! mask)
    return;

  /*  APPLY can not be done to group layers  */
  g_return_if_fail (! pika_viewable_get_children (PIKA_VIEWABLE (layer)) ||
                    mode == PIKA_MASK_DISCARD);

  /*  APPLY can only be done to layers with an alpha channel  */
  g_return_if_fail (pika_drawable_has_alpha (PIKA_DRAWABLE (layer)) ||
                    mode == PIKA_MASK_DISCARD || push_undo == TRUE);

  item  = PIKA_ITEM (layer);
  image = pika_item_get_image (item);

  if (! image)
    return;

  if (push_undo)
    {
      pika_image_undo_group_start (image, PIKA_UNDO_GROUP_LAYER_APPLY_MASK,
                                   (mode == PIKA_MASK_APPLY) ?
                                   C_("undo-type", "Apply Layer Mask") :
                                   C_("undo-type", "Delete Layer Mask"));

      pika_image_undo_push_layer_mask_show (image, NULL, layer);
      pika_image_undo_push_layer_mask_apply (image, NULL, layer);
      pika_image_undo_push_layer_mask_remove (image, NULL, layer, mask);

      if (mode == PIKA_MASK_APPLY &&
          ! pika_drawable_has_alpha (PIKA_DRAWABLE (layer)))
        {
          pika_layer_add_alpha (layer);
        }
    }

  /*  check if applying the mask changes the projection  */
  if (pika_layer_get_show_mask (layer)                                   ||
      (mode == PIKA_MASK_APPLY   && ! pika_layer_get_apply_mask (layer)) ||
      (mode == PIKA_MASK_DISCARD &&   pika_layer_get_apply_mask (layer)))
    {
      view_changed = TRUE;
    }

  if (mode == PIKA_MASK_APPLY)
    {
      GeglBuffer *mask_buffer;
      GeglBuffer *dest_buffer;

      if (push_undo)
        pika_drawable_push_undo (PIKA_DRAWABLE (layer), NULL,
                                 NULL,
                                 0, 0,
                                 pika_item_get_width  (item),
                                 pika_item_get_height (item));

      /*  Combine the current layer's alpha channel and the mask  */
      mask_buffer = pika_drawable_get_buffer (PIKA_DRAWABLE (mask));
      dest_buffer = pika_drawable_get_buffer (PIKA_DRAWABLE (layer));

      pika_gegl_apply_opacity (pika_drawable_get_buffer (PIKA_DRAWABLE (layer)),
                               NULL, NULL, dest_buffer,
                               mask_buffer, 0, 0, 1.0);
    }

  g_signal_handlers_disconnect_by_func (mask,
                                        pika_layer_layer_mask_update,
                                        layer);

  pika_item_removed (PIKA_ITEM (mask));
  g_object_unref (mask);
  layer->mask = NULL;

  if (push_undo)
    pika_image_undo_group_end (image);

  if (pika_filter_peek_node (PIKA_FILTER (layer)))
    {
      GeglNode *mode_node;

      mode_node = pika_drawable_get_mode_node (PIKA_DRAWABLE (layer));

      if (layer->show_mask)
        {
          gegl_node_connect (layer->layer_offset_node, "output",
                             mode_node,                "aux");
        }
      else
        {
          gegl_node_disconnect (mode_node, "aux2");
        }

      pika_layer_update_mode_node (layer);
    }

  pika_drawable_update_bounding_box (PIKA_DRAWABLE (layer));

  pika_layer_update_effective_mode (layer);
  pika_layer_update_excludes_backdrop (layer);

  /*  If applying actually changed the view  */
  if (view_changed)
    {
      pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);
    }
  else
    {
      pika_viewable_invalidate_preview (PIKA_VIEWABLE (layer));
    }

  g_signal_emit (layer, layer_signals[MASK_CHANGED], 0);

  g_object_notify (G_OBJECT (layer), "mask");
}

void
pika_layer_set_apply_mask (PikaLayer *layer,
                           gboolean   apply,
                           gboolean   push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (layer->mask != NULL);

  if (layer->apply_mask != apply)
    {
      PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

      if (push_undo && pika_item_is_attached (PIKA_ITEM (layer)))
        pika_image_undo_push_layer_mask_apply (image,
                                               apply ?
                                               C_("undo-type", "Enable Layer Mask") :
                                               C_("undo-type", "Disable Layer Mask"),
                                               layer);

      layer->apply_mask = apply ? TRUE : FALSE;

      if (pika_filter_peek_node (PIKA_FILTER (layer)) &&
          ! pika_layer_get_show_mask (layer))
        {
          GeglNode *mode_node;

          mode_node = pika_drawable_get_mode_node (PIKA_DRAWABLE (layer));

          if (layer->apply_mask)
            {
              gegl_node_connect (layer->mask_offset_node, "output",
                                 mode_node,               "aux2");
            }
          else
            {
              gegl_node_disconnect (mode_node, "aux2");
            }
        }

      pika_drawable_update_bounding_box (PIKA_DRAWABLE (layer));

      pika_layer_update_effective_mode (layer);
      pika_layer_update_excludes_backdrop (layer);

      pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);

      g_signal_emit (layer, layer_signals[APPLY_MASK_CHANGED], 0);
    }
}

gboolean
pika_layer_get_apply_mask (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);
  g_return_val_if_fail (layer->mask, FALSE);

  return layer->apply_mask;
}

void
pika_layer_set_edit_mask (PikaLayer *layer,
                          gboolean   edit)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (layer->mask != NULL);

  if (layer->edit_mask != edit)
    {
      layer->edit_mask = edit ? TRUE : FALSE;

      g_signal_emit (layer, layer_signals[EDIT_MASK_CHANGED], 0);
    }
}

gboolean
pika_layer_get_edit_mask (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);
  g_return_val_if_fail (layer->mask, FALSE);

  return layer->edit_mask;
}

void
pika_layer_set_show_mask (PikaLayer *layer,
                          gboolean   show,
                          gboolean   push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (layer->mask != NULL);

  if (layer->show_mask != show)
    {
      PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

      if (push_undo)
        pika_image_undo_push_layer_mask_show (image,
                                              C_("undo-type", "Show Layer Mask"),
                                              layer);

      layer->show_mask = show ? TRUE : FALSE;

      if (pika_filter_peek_node (PIKA_FILTER (layer)))
        {
          GeglNode *mode_node;

          mode_node = pika_drawable_get_mode_node (PIKA_DRAWABLE (layer));

          if (layer->show_mask)
            {
              gegl_node_disconnect (mode_node, "aux2");

              gegl_node_connect (layer->mask_offset_node, "output",
                                 mode_node,               "aux");
            }
          else
            {
              gegl_node_connect (layer->layer_offset_node, "output",
                                 mode_node,                "aux");

              if (pika_layer_get_apply_mask (layer))
                {
                  gegl_node_connect (layer->mask_offset_node, "output",
                                     mode_node,               "aux2");
                }
            }

          pika_layer_update_mode_node (layer);
        }

      pika_drawable_update_bounding_box (PIKA_DRAWABLE (layer));

      pika_layer_update_effective_mode (layer);
      pika_layer_update_excludes_backdrop (layer);

      pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);

      g_signal_emit (layer, layer_signals[SHOW_MASK_CHANGED], 0);
    }
}

gboolean
pika_layer_get_show_mask (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);
  g_return_val_if_fail (layer->mask, FALSE);

  return layer->show_mask;
}

void
pika_layer_add_alpha (PikaLayer *layer)
{
  PikaItem     *item;
  PikaDrawable *drawable;
  GeglBuffer   *new_buffer;

  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (pika_drawable_has_alpha (PIKA_DRAWABLE (layer)))
    return;

  item     = PIKA_ITEM (layer);
  drawable = PIKA_DRAWABLE (layer);

  new_buffer = gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                                pika_item_get_width  (item),
                                                pika_item_get_height (item)),
                                pika_drawable_get_format_with_alpha (drawable));

  pika_gegl_buffer_copy (
    pika_drawable_get_buffer (drawable), NULL, GEGL_ABYSS_NONE,
    new_buffer, NULL);

  pika_drawable_set_buffer (PIKA_DRAWABLE (layer),
                            pika_item_is_attached (PIKA_ITEM (layer)),
                            C_("undo-type", "Add Alpha Channel"),
                            new_buffer);
  g_object_unref (new_buffer);
}

void
pika_layer_remove_alpha (PikaLayer   *layer,
                         PikaContext *context)
{
  GeglBuffer *new_buffer;
  PikaRGB     background;

  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (PIKA_IS_CONTEXT (context));

  if (! pika_drawable_has_alpha (PIKA_DRAWABLE (layer)))
    return;

  new_buffer =
    gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                     pika_item_get_width  (PIKA_ITEM (layer)),
                                     pika_item_get_height (PIKA_ITEM (layer))),
                     pika_drawable_get_format_without_alpha (PIKA_DRAWABLE (layer)));

  pika_context_get_background (context, &background);
  pika_pickable_srgb_to_image_color (PIKA_PICKABLE (layer),
                                     &background, &background);

  pika_gegl_apply_flatten (pika_drawable_get_buffer (PIKA_DRAWABLE (layer)),
                           NULL, NULL,
                           new_buffer, &background,
                           pika_drawable_get_space (PIKA_DRAWABLE (layer)),
                           pika_layer_get_real_composite_space (layer));

  pika_drawable_set_buffer (PIKA_DRAWABLE (layer),
                            pika_item_is_attached (PIKA_ITEM (layer)),
                            C_("undo-type", "Remove Alpha Channel"),
                            new_buffer);
  g_object_unref (new_buffer);
}

void
pika_layer_resize_to_image (PikaLayer    *layer,
                            PikaContext  *context,
                            PikaFillType  fill_type)
{
  PikaImage *image;
  gint       offset_x;
  gint       offset_y;

  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (pika_item_is_attached (PIKA_ITEM (layer)));
  g_return_if_fail (PIKA_IS_CONTEXT (context));

  image = pika_item_get_image (PIKA_ITEM (layer));

  pika_image_undo_group_start (image, PIKA_UNDO_GROUP_ITEM_RESIZE,
                               C_("undo-type", "Layer to Image Size"));

  pika_item_get_offset (PIKA_ITEM (layer), &offset_x, &offset_y);
  pika_item_resize (PIKA_ITEM (layer), context, fill_type,
                    pika_image_get_width  (image),
                    pika_image_get_height (image),
                    offset_x, offset_y);

  pika_image_undo_group_end (image);
}

/**********************/
/*  access functions  */
/**********************/

PikaDrawable *
pika_layer_get_floating_sel_drawable (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), NULL);

  return layer->fs.drawable;
}

void
pika_layer_set_floating_sel_drawable (PikaLayer    *layer,
                                      PikaDrawable *drawable)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (drawable == NULL || PIKA_IS_DRAWABLE (drawable));

  if (g_set_object (&layer->fs.drawable, drawable))
    {
      if (layer->fs.segs)
        {
          g_clear_pointer (&layer->fs.segs, g_free);
          layer->fs.num_segs = 0;
        }

      g_object_notify (G_OBJECT (layer), "floating-selection");
    }
}

gboolean
pika_layer_is_floating_sel (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);

  return (pika_layer_get_floating_sel_drawable (layer) != NULL);
}

void
pika_layer_set_opacity (PikaLayer *layer,
                        gdouble    opacity,
                        gboolean   push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));

  opacity = CLAMP (opacity, PIKA_OPACITY_TRANSPARENT, PIKA_OPACITY_OPAQUE);

  if (layer->opacity != opacity)
    {
      if (push_undo && pika_item_is_attached (PIKA_ITEM (layer)))
        {
          PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

          pika_image_undo_push_layer_opacity (image, NULL, layer);
        }

      layer->opacity = opacity;

      g_signal_emit (layer, layer_signals[OPACITY_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "opacity");

      if (pika_filter_peek_node (PIKA_FILTER (layer)))
        pika_layer_update_mode_node (layer);

      pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);
    }
}

gdouble
pika_layer_get_opacity (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_OPACITY_OPAQUE);

  return layer->opacity;
}

void
pika_layer_set_mode (PikaLayer     *layer,
                     PikaLayerMode  mode,
                     gboolean       push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (pika_viewable_get_children (PIKA_VIEWABLE (layer)) == NULL)
    {
      g_return_if_fail (pika_layer_mode_get_context (mode) &
                        PIKA_LAYER_MODE_CONTEXT_LAYER);
    }
  else
    {
      g_return_if_fail (pika_layer_mode_get_context (mode) &
                        PIKA_LAYER_MODE_CONTEXT_GROUP);
    }

  if (layer->mode != mode)
    {
      if (pika_item_is_attached (PIKA_ITEM (layer)))
        {
          PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

          pika_image_unset_default_new_layer_mode (image);

          if (push_undo)
            pika_image_undo_push_layer_mode (image, NULL, layer);
        }

      g_object_freeze_notify (G_OBJECT (layer));

      layer->mode = mode;

      g_signal_emit (layer, layer_signals[MODE_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "mode");

      /*  when changing modes, we always switch to AUTO blend and
       *  composite in order to avoid confusion
       */
      if (layer->blend_space != PIKA_LAYER_COLOR_SPACE_AUTO)
        {
          layer->blend_space = PIKA_LAYER_COLOR_SPACE_AUTO;

          g_signal_emit (layer, layer_signals[BLEND_SPACE_CHANGED], 0);
          g_object_notify (G_OBJECT (layer), "blend-space");
        }

      if (layer->composite_space != PIKA_LAYER_COLOR_SPACE_AUTO)
        {
          layer->composite_space = PIKA_LAYER_COLOR_SPACE_AUTO;

          g_signal_emit (layer, layer_signals[COMPOSITE_SPACE_CHANGED], 0);
          g_object_notify (G_OBJECT (layer), "composite-space");
        }

      if (layer->composite_mode != PIKA_LAYER_COMPOSITE_AUTO)
        {
          layer->composite_mode = PIKA_LAYER_COMPOSITE_AUTO;

          g_signal_emit (layer, layer_signals[COMPOSITE_MODE_CHANGED], 0);
          g_object_notify (G_OBJECT (layer), "composite-mode");
        }

      g_object_thaw_notify (G_OBJECT (layer));

      pika_layer_update_effective_mode (layer);
      pika_layer_update_excludes_backdrop (layer);
    }
}

PikaLayerMode
pika_layer_get_mode (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_MODE_NORMAL);

  return layer->mode;
}

void
pika_layer_set_blend_space (PikaLayer           *layer,
                            PikaLayerColorSpace  blend_space,
                            gboolean             push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (! pika_layer_mode_is_blend_space_mutable (layer->mode))
    return;

  if (layer->blend_space != blend_space)
    {
      if (push_undo && pika_item_is_attached (PIKA_ITEM (layer)))
        {
          PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

          pika_image_undo_push_layer_mode (image, _("Set layer's blend space"), layer);
        }

      layer->blend_space = blend_space;

      g_signal_emit (layer, layer_signals[BLEND_SPACE_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "blend-space");

      pika_layer_update_effective_mode (layer);
    }
}

PikaLayerColorSpace
pika_layer_get_blend_space (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_COLOR_SPACE_AUTO);

  return layer->blend_space;
}

PikaLayerColorSpace
pika_layer_get_real_blend_space (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_COLOR_SPACE_RGB_LINEAR);

  if (layer->blend_space == PIKA_LAYER_COLOR_SPACE_AUTO)
    return pika_layer_mode_get_blend_space (layer->mode);
  else
    return layer->blend_space;
}

void
pika_layer_set_composite_space (PikaLayer           *layer,
                                PikaLayerColorSpace  composite_space,
                                gboolean             push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (! pika_layer_mode_is_composite_space_mutable (layer->mode))
    return;

  if (layer->composite_space != composite_space)
    {
      if (push_undo && pika_item_is_attached (PIKA_ITEM (layer)))
        {
          PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

          pika_image_undo_push_layer_mode (image, _("Set layer's composite space"), layer);
        }

      layer->composite_space = composite_space;

      g_signal_emit (layer, layer_signals[COMPOSITE_SPACE_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "composite-space");

      pika_layer_update_effective_mode (layer);
    }
}

PikaLayerColorSpace
pika_layer_get_composite_space (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_COLOR_SPACE_AUTO);

  return layer->composite_space;
}

PikaLayerColorSpace
pika_layer_get_real_composite_space (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_COLOR_SPACE_RGB_LINEAR);

  if (layer->composite_space == PIKA_LAYER_COLOR_SPACE_AUTO)
    return pika_layer_mode_get_composite_space (layer->mode);
  else
    return layer->composite_space;
}

void
pika_layer_set_composite_mode (PikaLayer              *layer,
                               PikaLayerCompositeMode  composite_mode,
                               gboolean                push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (! pika_layer_mode_is_composite_mode_mutable (layer->mode))
    return;

  if (layer->composite_mode != composite_mode)
    {
      if (push_undo && pika_item_is_attached (PIKA_ITEM (layer)))
        {
          PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

          pika_image_undo_push_layer_mode (image, _("Set layer's composite mode"), layer);
        }

      layer->composite_mode = composite_mode;

      g_signal_emit (layer, layer_signals[COMPOSITE_MODE_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "composite-mode");

      pika_layer_update_effective_mode (layer);
      pika_layer_update_excludes_backdrop (layer);
    }
}

PikaLayerCompositeMode
pika_layer_get_composite_mode (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_COMPOSITE_AUTO);

  return layer->composite_mode;
}

PikaLayerCompositeMode
pika_layer_get_real_composite_mode (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), PIKA_LAYER_COMPOSITE_UNION);

  if (layer->composite_mode == PIKA_LAYER_COMPOSITE_AUTO)
    return pika_layer_mode_get_composite_mode (layer->mode);
  else
    return layer->composite_mode;
}

void
pika_layer_get_effective_mode (PikaLayer              *layer,
                               PikaLayerMode          *mode,
                               PikaLayerColorSpace    *blend_space,
                               PikaLayerColorSpace    *composite_space,
                               PikaLayerCompositeMode *composite_mode)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (mode)            *mode            = layer->effective_mode;
  if (blend_space)     *blend_space     = layer->effective_blend_space;
  if (composite_space) *composite_space = layer->effective_composite_space;
  if (composite_mode)  *composite_mode  = layer->effective_composite_mode;
}

gboolean
pika_layer_get_excludes_backdrop (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);

  return layer->excludes_backdrop;
}

void
pika_layer_set_lock_alpha (PikaLayer *layer,
                           gboolean   lock_alpha,
                           gboolean   push_undo)
{
  g_return_if_fail (PIKA_IS_LAYER (layer));
  g_return_if_fail (pika_layer_can_lock_alpha (layer));

  lock_alpha = lock_alpha ? TRUE : FALSE;

  if (layer->lock_alpha != lock_alpha)
    {
      if (push_undo && pika_item_is_attached (PIKA_ITEM (layer)))
        {
          PikaImage *image = pika_item_get_image (PIKA_ITEM (layer));

          pika_image_undo_push_layer_lock_alpha (image, NULL, layer);
        }

      layer->lock_alpha = lock_alpha;

      g_signal_emit (layer, layer_signals[LOCK_ALPHA_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "lock-alpha");
    }
}

gboolean
pika_layer_get_lock_alpha (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);

  return layer->lock_alpha;
}

gboolean
pika_layer_can_lock_alpha (PikaLayer *layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);

  return TRUE;
}

gboolean
pika_layer_is_alpha_locked (PikaLayer  *layer,
                            PikaLayer **locked_layer)
{
  g_return_val_if_fail (PIKA_IS_LAYER (layer), FALSE);

  return PIKA_LAYER_GET_CLASS (layer)->is_alpha_locked (layer, locked_layer);
}

/*  protected functions  */

void
pika_layer_update_effective_mode (PikaLayer *layer)
{
  PikaLayerMode          mode;
  PikaLayerColorSpace    blend_space;
  PikaLayerColorSpace    composite_space;
  PikaLayerCompositeMode composite_mode;

  g_return_if_fail (PIKA_IS_LAYER (layer));

  if (layer->mask && layer->show_mask)
    {
      mode            = PIKA_LAYER_MODE_NORMAL;
      blend_space     = PIKA_LAYER_COLOR_SPACE_AUTO;
      composite_space = PIKA_LAYER_COLOR_SPACE_AUTO;
      composite_mode  = PIKA_LAYER_COMPOSITE_AUTO;

      /* This makes sure that masks of LEGACY-mode layers are
       * composited in PERCEPTUAL space, and non-LEGACY layers in
       * LINEAR space, or whatever composite space was chosen in the
       * layer attributes dialog
       */
      composite_space = pika_layer_get_real_composite_space (layer);
    }
  else
    {
      PIKA_LAYER_GET_CLASS (layer)->get_effective_mode (layer,
                                                        &mode,
                                                        &blend_space,
                                                        &composite_space,
                                                        &composite_mode);
    }

  if (mode            != layer->effective_mode            ||
      blend_space     != layer->effective_blend_space     ||
      composite_space != layer->effective_composite_space ||
      composite_mode  != layer->effective_composite_mode)
    {
      layer->effective_mode            = mode;
      layer->effective_blend_space     = blend_space;
      layer->effective_composite_space = composite_space;
      layer->effective_composite_mode  = composite_mode;

      g_signal_emit (layer, layer_signals[EFFECTIVE_MODE_CHANGED], 0);

      if (pika_filter_peek_node (PIKA_FILTER (layer)))
        pika_layer_update_mode_node (layer);

      pika_drawable_update (PIKA_DRAWABLE (layer), 0, 0, -1, -1);
    }
}

void
pika_layer_update_excludes_backdrop (PikaLayer *layer)
{
  gboolean excludes_backdrop;

  g_return_if_fail (PIKA_IS_LAYER (layer));

  excludes_backdrop =
    PIKA_LAYER_GET_CLASS (layer)->get_excludes_backdrop (layer);

  if (excludes_backdrop != layer->excludes_backdrop)
    {
      layer->excludes_backdrop = excludes_backdrop;

      g_signal_emit (layer, layer_signals[EXCLUDES_BACKDROP_CHANGED], 0);
      g_object_notify (G_OBJECT (layer), "excludes-backdrop");
    }
}
