; 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.
; If no selection is present, scales layer to image size 
; Note: if the layer is floated 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 (sg-layer-scale-to-selection image drawable)
  (let* (
      (layer (car (gimp-image-get-active-layer image)))
      (bounds (gimp-selection-bounds image))
      (x 0)
      (y 0)
      (width (car (gimp-image-width image)))
      (height (car (gimp-image-height image)))
      )
    (when (= (car bounds) TRUE)
      (set! x (cadr bounds))
      (set! y (caddr bounds))
      (set! width (- (cadddr bounds) x))
      (set! height (- (car (cddddr bounds)) y)))
    (gimp-image-undo-group-start image)
    (gimp-layer-scale layer width height TRUE)
    (gimp-layer-set-offsets layer x y)
    (gimp-image-undo-group-end image)
    (gimp-displays-flush)
    )
  )

(script-fu-register "sg-layer-scale-to-selection"
 "Scale to Selection"
 "Scale the active layer and fit it in the selection (rectangular)"
 "Saul Goode"
 "Saul Goode"
 "1/3/2010"
 "*"
 SF-IMAGE    "Image"    0
 SF-DRAWABLE "Drawable" 0
 )
(script-fu-menu-register "sg-layer-scale-to-selection"
 "<Image>/Layer/Resize"
 )
 
