; 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 (sg-copy-mask-to-layers image drawable)
  (gimp-image-undo-group-start image)
  (let ((active-layer (car (gimp-image-get-active-layer image)))
        (orig-sel (car (gimp-selection-save image)))
        (layers 
          (let loop ((layers (vector->list (cadr (gimp-image-get-layers image))))
                     (visibles '()) )
            (if (null? layers)
              (reverse visibles)
              (loop (cdr layers)
                    (if (zero? (car (gimp-drawable-get-visible (car layers))))
                      visibles
                      (cons (car layers) visibles) ))))) )
    (let ((source-layer (car (gimp-layer-new-from-drawable active-layer image)))
          (source-mask 0) 
          (mask 0) )
      (gimp-image-add-layer image source-layer -1)
      (set! source-mask (car (gimp-layer-get-mask source-layer)))
      (when (= source-mask -1)
        (set! source-mask (car (gimp-layer-create-mask source-layer ADD-COPY-MASK)))
        (gimp-layer-add-mask source-layer source-mask))
      (gimp-selection-load source-mask)
      (let loop ((layers layers))
        (unless (null? layers)
          (when (= (car (gimp-layer-get-mask (car layers))) -1)
            (set! mask (car (gimp-layer-create-mask (car layers) ADD-SELECTION-MASK)))
            (gimp-layer-add-mask (car layers) mask) )
          (loop (cdr layers)) ))
      (gimp-image-remove-layer image source-layer) )
    (gimp-selection-load orig-sel)
    (gimp-image-remove-channel image orig-sel) )
  (gimp-image-undo-group-end image)
  (gimp-displays-flush) 
  )

(script-fu-register "sg-copy-mask-to-layers"
 "_Copy mask to layers"
 "Copy the mask from the current layer to all visible layers"
 "Saul Goode"
 "Saul Goode"
 "6/14/2006 (updated Sept 2012)"
 "*"
 SF-IMAGE    "Image"    0
 SF-DRAWABLE "Drawable" 0
 )
(script-fu-menu-register "sg-copy-mask-to-layers"
                         "<Image>/Layer/Mask")
(script-fu-menu-register "sg-copy-mask-to-layers"
                         "<Layers>")                        
