#lang racket
(require gigls/unsafe)

;;; Procedure:
;;;   image-selection-as-item
;;; Parameters:
;;;   image, an image
;;; Purpose:
;;;   Get an "item" that corresponds to the currently selected
;;;   area of the image.
;;; Produces:
;;;   item, an item id
;;; Preconditions:
;;;   Something is selected on image.
;;; Postcondition:
;;;   item can be used by the PDB procedures that expect an item.
;;; Ponderings:
;;;   Should probably be followed by a transformation (gimp-item-transform-___)
;;;   and then (gimp-image-flatten) and probably (context-update-displays!)
(define image-selection-as-item
  (lambda (image)
    (gimp-edit-copy-visible image)
    (car (gimp-edit-paste (image-get-layer image) 2))))

;(define kitten (image-show (image-load "/home/rebelsky/Desktop/kitten.jpg")))
;(image-select-ellipse! kitten REPLACE 100 100 200 100)
;(define item (image-selection-as-item kitten))
;(gimp-item-transform-rotate item (/ pi 4) 1 100 100)
;(gimp-image-flatten kitten)
;(context-update-displays!)
;
;(image-select-ellipse! kitten REPLACE 100 100 200 50)
;(define item (image-selection-as-item kitten))
;(gimp-item-transform-rotate item (- (/ pi 4)) 0 100 100)
;(gimp-image-flatten kitten)
;(context-update-displays!)

;;; Procedure:
;;;   bean!
;;; Parameters:
;;;   image, an image
;;;   x, a real number
;;;   y, a real number
;;;   width, a positive real number
;;;   height, a positive real number
;;;   angle, a real number
;;; Purpose:
;;;   Draw a "bean" (a rotated ellipse) centered at (x,y).
;;; Produces:
;;;   [Nothing; called for the side effect]
;;; Preconditions:
;;;   Some part of the resulting ellipse should be within the bounds
;;;     of the image.
;;;   (<= width (image-width image))
;;;   (<= height (image-height image))
;;; Postconditions:
;;;   The image now contains the described figure.
;;; Problems:
;;;   In order to see the result, you may need to call context-update-displays!
(define bean!
  (let ([d2r (/ pi 180)])
    (lambda (image x y width height angle)
      ; Select the right size ellipse, centered at (0,0).  We use (0,0) as
      ; top-left to selet the largest possible ellipse.
      (image-select-ellipse! image REPLACE 0 0 width height)
      ; Convert the selection to an item for gimp-item-transform-...
      (let ([item (image-selection-as-item image)])
        ; Rotate to the correct angle and shift to the correct position.
        ; We're using gimp-item-transform-2d, rather than gimp-item-rotate,
        ; because it gives us a bit more freedom (in particular, we can be sure
        ; to select within the image, more or less)
        (gimp-item-transform-2d item (/ width 2) (/ height 2) 1 1 (* angle d2r) x y)
        ; Fill with the foreground color
        (image-fill! image)
        ; And finish up!
        (gimp-image-flatten image)
        (void)))))