
/*
	NSMovieView subclass to force movie to maintain proper aspect ratio
	Original Source: <http://cocoa.karelia.com/AppKit_Classes/NSMovieView_subclas.m>
	(See copyright notice at <http://cocoa.karelia.com>)
*/

// In your NSMovieView subclass, override movieRect something like this, to force movie to be centered, with the proper aspect ratio, within the movie view.

- (NSRect) movieRect
{
	NSRect viewRect = [super movieRect];

	Movie qtMovie = [[self movie] QTMovie];
	Rect movieRect = { 0,0,0,0 };
	GetMovieNaturalBoundsRect (qtMovie, &movieRect);

	float movieWidth = movieRect.right - movieRect.left;
	float movieHeight = movieRect.bottom - movieRect.top;

	if (movieWidth <= viewRect.size.width && movieHeight <= viewRect.size.height)
	{
		// Movie is smaller or equal to view size; just center the movie.
		viewRect.origin.y += (int) ((viewRect.size.height - movieHeight) / 2.0);
		viewRect.size.height = movieHeight;

		viewRect.origin.x += (int) ((viewRect.size.width - movieWidth) / 2.0);
		viewRect.size.width = movieWidth;

	}
	else	// need to scale down movie, centering horizontally/vertically.
	{
		float movieRatio = movieWidth / movieHeight;
		float viewRatio = viewRect.size.width / viewRect.size.height;

		if ( movieRatio > viewRatio  )
		{
			// movie is wider than will fit, rescale.
			// Leave the view's width full size
			// Shorten the view's height, though.
			float newHeight = viewRect.size.width / movieRatio;

			viewRect.origin.y += (int) ((viewRect.size.height - newHeight) / 2.0);
			viewRect.size.height = newHeight;
		}
		else
		{
			// movie is taller than will fit (or equal aspect ratio), rescale
			// leave the height full size
			// make the view less wide, though.
			float newWidth = viewRect.size.height * movieRatio;

			viewRect.origin.x += (int) ((viewRect.size.width - newWidth) / 2.0);
			viewRect.size.width = newWidth;
		}
	}
	viewRect.origin.x = floor(viewRect.origin.x);
	viewRect.origin.y = floor(viewRect.origin.y);
	return viewRect;
}