/*===============================
|	PictureHandler.c
|
|	Blugs 1.1 handler for pictures - very simple
|	I was just playing around to see what might work.
|
|	Brian Hall 2002
|	www.blugs.com
|	This code is in the public domain.
|
|===============================*/
#include "Blugs.h"
#include "PictureHandler.h"
#include "BlugsAppearanceExtras.h"
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#elif TARGET_RT_MAC_MACHO
#include <Carbon/Carbon.h>
#else
#include <fp.h>
#endif

static void local_PictureDraw( BLHandlerParamPtr inParam, PicHandle inPicture );


pascal UInt32 PictureHandler( BLMessage message, BLHandlerParamPtr param )
{
	UInt32	reply = 0;
	
	switch (message)
	{
		//case blHandlerInitMsg:
		//reply = blWantsHilite;
		//break;
		
		case blCellDrawMsg:
		if (param->ioStorage) local_PictureDraw( param, (PicHandle)param->ioStorage );
		break;
		
		case blCellSetDataMsg:
		if (param->ioDataFlavor == kScrapFlavorTypePicture)
			param->ioStorage = *(Handle*)(param->ioDataBuffer);
		break;
	}
	return reply;
}

//===============================
static void local_PictureDraw( BLHandlerParamPtr inParam, PicHandle inPicture )
{
	Rect		cellRect, pictureRect;
	SInt16		pictureWidth, pictureHeight;
	double_t	wShrinkage = 1.0, hShrinkage = 1.0, oldRatio, newRatio;
	
	cellRect = inParam->inRect;
	pictureWidth = (*inPicture)->picFrame.right - (*inPicture)->picFrame.left;
	pictureHeight = (*inPicture)->picFrame.bottom - (*inPicture)->picFrame.top;
	oldRatio = (double_t)pictureWidth / (double_t)pictureHeight;
	if (pictureWidth > cellRect.right - cellRect.left)
	{
		wShrinkage = (double_t)(cellRect.right - cellRect.left) / (double_t)pictureWidth;
		pictureWidth = cellRect.right - cellRect.left;
	}
	if (pictureHeight > cellRect.bottom - cellRect.top)
	{
		hShrinkage = (double_t)(cellRect.bottom - cellRect.top) / (double_t)pictureHeight;
		pictureHeight = cellRect.bottom - cellRect.top;
	}
	if (wShrinkage < hShrinkage)
		pictureHeight = round( (double_t)((*inPicture)->picFrame.bottom -
										(*inPicture)->picFrame.top) * wShrinkage );
	else pictureWidth = round( (double_t)((*inPicture)->picFrame.right -
										(*inPicture)->picFrame.left) * hShrinkage );
	newRatio = (double_t)pictureWidth / (double_t)pictureHeight;
	pictureRect.left = cellRect.left;
	pictureRect.right = pictureRect.left + pictureWidth;
	pictureRect.top = cellRect.top + ((cellRect.bottom - cellRect.top - pictureHeight) >> 1);
	pictureRect.bottom = pictureRect.top + pictureHeight;
	BLAlignRectInRect( blAlignCenter, false, &pictureRect, &cellRect );
	//if (!BLIsActive( param->inList)) transform = kTransformDisabled;
	//if (param->inIsSelected) transform |= kTransformSelected;
	DrawPicture( inPicture, &pictureRect );
}


