#!/usr/bin/env python

#   rotcrop - crop rotated images to a rectangle
#   Copyright (C) 2006 Gopal V <gopalv82 -at- yahoo.com>
#
#    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.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import math
from gimpfu import *
import sys, os, math

# So this year it's going to be RGB and next year I'll plant CMYK
def rotate_crop(image, drawable, angle):
	radians = math.radians(angle)
	pdb.gimp_selection_clear(image)
	x = pdb.gimp_drawable_width(drawable)
	y = pdb.gimp_drawable_height(drawable)
	r = math.sqrt(x*x + y*y)/2
	
	# as calculated for top left corner
	theta = math.radians(45)
	phi = math.radians(45 + angle)
	dx = r * math.cos(phi) - r * math.cos(theta)
	# -1 * because as the angle comes down, our y decreases
	dy = -1 * (r * math.sin(phi) - r * math.cos(theta))

	# top left corner
	x1 = 0 - dx
	y1 = 0 - dy 
	# top right corner
	x2 = x - dx
	y2 = 0 + dy
	# bottom right corner
	x3 = x + dx
	y3 = y - dx
	# bottom left corner
	x4 = 0 + dx 
	y4 = y + dy
	
	# rectangle by top left and bot right corners
	topx = max(x1,x4)
	topy = max(y1,y2)
	botx = min(x2,x3)
	boty = min(y3,y4)

	newdrawable = pdb.gimp_rotate(drawable,0, radians) 
	pdb.gimp_image_crop(
			image,
			math.floor(botx - topx),
			math.floor(boty - topy),
			math.ceil(topx),
			math.ceil(topy)
			)
	pdb.gimp_image_flatten(image)

register(
    "python_fu_rotcrop",
    "Script to rotate and crop it back into a square",
    "Script to rotate and crop it back into a square image",
    "Gopal V",
    "Gopal V",
    "2006",
    "<Image>/Python-Fu/Generic/Rotate-Crop...",
    "RGB*",
    [
		(PF_FLOAT, "angle", "Angle", 0.00, (-360,360, 1)),
    ],
    [],
    rotate_crop)

main()
