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

; Scales the layer to match the selection size while maintaining
; original aspect ration. If no selection is present, scales 
; layer to image size. Note: if the layer is floated (for example,
; after an Edit->Paste has been performed) there is no selection
; present even though there are marching ants around the originally
; selected region -- if this script is run without first making
; a new selection then the floating selection will be scaled to
; the image size. 

(define (script-fu-sg-layer-fit-in-selection image drawable)
  (let* (
      (layer (car (gimp-image-get-active-layer image)))
      (bounds (cdr (gimp-selection-bounds image)))
      (x (car bounds))
      (y (cadr bounds))
      (width (- (caddr bounds) x))
      (height (- (cadddr bounds) y))
      (layer-width (car (gimp-drawable-width layer)))
      (layer-height (car (gimp-drawable-height layer)))
      (aspect (/ layer-height layer-width))
      )
    (gimp-image-undo-group-start image)
    (gimp-layer-add-alpha layer)
    (if (< (/ width layer-width) (/ height layer-height))
      (begin
        (gimp-layer-scale-full layer 
                               width
                               (* width aspect)
                               TRUE 
                               INTERPOLATION-LANCZOS)
        (gimp-layer-set-offsets layer x (+ y (/ (- height (* width aspect)) 2) ))
        )                          
      (begin 
        (gimp-layer-scale-full layer 
                               (/ height aspect)
                               height
                               TRUE 
                               INTERPOLATION-LANCZOS)
        (gimp-layer-set-offsets layer (+ x (/ (- width (/ height aspect)) 2)) y)
        )
      )
    (gimp-image-undo-group-end image)
    (gimp-displays-flush)
    )
  )

(script-fu-register "script-fu-sg-layer-fit-in-selection"
 "Fit within Selection"
 "Scale the active layer so it fits in the selected region"
 "Saul Goode"
 "Saul Goode"
 "10/25/2010"
 "RGB*,GRAY*"
 SF-IMAGE    "Image"    0
 SF-DRAWABLE "Drawable" 0
 )

(script-fu-menu-register "script-fu-sg-layer-fit-in-selection"
 "<Image>/Layer/Resize"
 )
 
