; 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.

;; Take a pattern file with multiple layers -- for example, one
;; created by the Photoshop Pattern Loader plug-in -- and save
;; each layer as a separate GIMP-usable pattern.
;;
;; Installed in "Filters->Animations->Save layers as patterns"

(define (script-fu-save-pat-layers image drawable)

  (gimp-progress-set-text "Saving layers as pattern files")
  (gimp-image-undo-group-start image)
  (gimp-selection-none image)
  (let* (
      (layers (gimp-image-get-layers image))
      (num-layers (car layers))
      (i 0)
      (layers (cadr layers))
      (path (string-append gimp-directory "/patterns/"))
      (extension ".pat")
      )
    (while (< i num-layers)
           (let* (
              (layer (aref layers i))
              (layer-name (car (gimp-layer-get-name layer)))
              (fullpath (string-append path layer-name extension))
              )
             (plug-in-autocrop-layer RUN-NONINTERACTIVE image layer)
               ;; Note -- this changes the original image,
               ;; leaving each layer autocropped

             (file-pat-save RUN-NONINTERACTIVE image layer fullpath fullpath
                            layer-name)
            )
           (set! i (+ i 1))
  ))

  (gimp-progress-set-text "Saved all layers")
  (gimp-image-undo-group-end image)
  (gimp-displays-flush)
)

(script-fu-register "script-fu-save-pat-layers"
 "<Image>/File/Save layers as patterns (*.pat)"
 "Save each layer to a separate file after autocropping *.pat in gimp-directory /patterns/"
 "Akkana Peck"
 "Akkana Peck"
 "6/3/2009"
 ""
 SF-IMAGE    "Image"    0
 SF-DRAWABLE "Drawable" 0
 )

