//		Enclosure.cpp
//		http://www-acs.ucsd.edu/~jstrout/macdev/panes/
//		last modified: 12/07/97

#include "Enclosure.h"

Enclosure::~Enclosure()
{
	if (mOwnsSubpanes) {
		// destroy all subpanes
		for (int i=0; i<mSubpanes.size(); i++) {
			if (mSubpanes[i]) delete mSubpanes[i];
		}
	}
}
	
void Enclosure::Draw()
{
	if (mHidden) return;
	
	// first, draw the border (if any)
	if (mBorder) {
		FrameRect( &mFrame );
	}
	
	
	// change drawing origin
	GrafPtr port;
	GetPort( &port );
	Point original = { port->portRect.top, port->portRect.left };	
	SetOrigin( original.h - mFrame.left, original.v - mFrame.top );
	
	// set clipping rect
	RgnHandle saveClipRgn = NewRgn();	/* get an empty region */
	GetClip( saveClipRgn );				/* save current */
	Rect r = { 0, 0, mFrame.bottom-mFrame.top, mFrame.right-mFrame.left };
	ClipRect( &r );

	// then, draw all enclosed panes
	for (int i=0; i<mSubpanes.size(); i++) {
		mSubpanes[i]->Draw();
	}
	
	// restore the port origin and clipping region
	SetOrigin( original.h, original.v );
	SetClip( saveClipRgn );				/* restore previous value */
	DisposeRgn( saveClipRgn );			/* not needed any more */
}

Boolean Enclosure::Click(Point where, short modifiers)
{
	if (mHidden) return false;
	
	// change drawing origin, in case the click response draws...
	GrafPtr port;
	GetPort( &port );
	Point original = { port->portRect.top, port->portRect.left };
	SetOrigin( original.h - mFrame.left, original.v - mFrame.top );

	// adjust for the enclosure's position
	where.h -= mFrame.left;
	where.v -= mFrame.top;
	
	// if it hit any subpane, pass the click on
	Boolean handled = false;
	for (int i=0; i<mSubpanes.size() && !handled; i++) {
		if (mSubpanes[i]->Contains(where)) {
			// respond to the click
			handled = mSubpanes[i]->Click(where,modifiers);
		}
	}
	// restore the port origin
	SetOrigin( original.h, original.v );	
	return handled;
}

Boolean Enclosure::HandleKey(char key, char keycode, short modifiers)
{
	// change drawing origin, in case the key response draws...
	GrafPtr port;
	GetPort( &port );
	Point original = { port->portRect.top, port->portRect.left };
	SetOrigin( original.h - mFrame.left, original.v - mFrame.top );

	// give each subpane a chance to handle the key
	Boolean handled = false;
	VecIterate(i, mSubpanes) {
		handled = handled or mSubpanes[i]->HandleKey(key, keycode, modifiers);
	}

	// restore the port origin
	SetOrigin( original.h, original.v );	
	return handled;
}

void Enclosure::Idle(short *maxSleep)
{
	// change drawing origin, in case the idler draws...
	GrafPtr port;
	GetPort( &port );
	Point original = { port->portRect.top, port->portRect.left };
	SetOrigin( original.h - mFrame.left, original.v - mFrame.top );

	// idle all the panes; set maxSleep to the minimum set by any subpane
	VecIterate(i, mSubpanes) {
		short sleep = 60;
		mSubpanes[i]->Idle(&sleep);
		if (maxSleep and *maxSleep > sleep) *maxSleep = sleep;
	}

	// restore the port origin
	SetOrigin( original.h, original.v );	
}
