; This program is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation; either version 2 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; GNU General Public License for more details.


(define (script-fu-sg-add-group-mask image group)
  (gimp-image-undo-group-start image)
  (gimp-context-push)
  (if (zero? (car (gimp-item-is-group group)))
    (begin
      (gimp-message "Layer must be a group"))
    (let ((x-offset (car (gimp-drawable-offsets group)))
          (y-offset (cadr (gimp-drawable-offsets group))) 
          (group-mask (car (gimp-layer-new image 
                                     (car (gimp-drawable-width group))
                                     (car (gimp-drawable-height group))
                                     (car (gimp-drawable-type group))
                                     "Group Mask"
                                     100
                                     24 ; REPLACE-MODE
                                     ))))
      (gimp-context-set-default-colors) 
      (gimp-drawable-fill group-mask TRANSPARENT-FILL)
      (gimp-image-insert-layer image group-mask group 0)
      (gimp-layer-set-offsets group-mask x-offset y-offset)
      (gimp-edit-fill group-mask FOREGROUND-FILL)
      (gimp-selection-invert image)
      (let ((layer-mask (car (gimp-layer-create-mask group-mask ADD-SELECTION-MASK))))
        (gimp-layer-add-mask group-mask layer-mask))
      (gimp-selection-invert image)
      (gimp-image-set-active-layer image group)))
  (gimp-context-pop)
  (gimp-image-undo-group-end image)
  (gimp-displays-flush)
  )

(script-fu-register "script-fu-sg-add-group-mask"
  "Add Group Mask  (from selection)"
  "Insert a layer that behaves as a group mask"
  "Saul Goode"
  "saulgoode"
  "February 2015"
  "*"
  SF-IMAGE    "Image"    0
  SF-DRAWABLE "Drawable" 0
  )
(script-fu-menu-register "script-fu-sg-add-group-mask"
  "<Layers>"
  )
(script-fu-menu-register "script-fu-sg-add-group-mask"
  "<Image>/Layer/Mask"
  )
