#include "Initalisation.h"
globals g;

/*** INITALISE NEW EDITOR INSTANCE ***/
OSStatus Plug_InitInstance( Plug_PlugInRef plug, Plug_ResourceRef resource )
{
	// get system version
	OSStatus error = Gestalt( gestaltSystemVersion, &g.systemVersion );
	if( error ) return error;
	
	// create window
	Rect creationBounds;
	WindowRef window;
	SetRect( &creationBounds, 0, 0, kDefaultWindowWidth, kDefaultWindowHeight );
	OffsetRect( &creationBounds, 8, 48 );
	WindowAttributes					attributes = kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowStandardHandlerAttribute | kWindowInWindowMenuAttribute;
	if( g.systemVersion >= kMacOSX )	attributes |= kWindowLiveResizeAttribute;
	error = CreateNewWindow( kDocumentWindowClass, attributes, &creationBounds, &window );
	
	// register mac window with host and retrieve plug window
	Plug_WindowRef plugWindow = Host_RegisterWindow( plug, resource, window );
	
	// cerate new pict window class
	PictWindowPtr pictWindow = new PictWindow( window );
	
	// set window refCon to my class
	Host_SetWindowRefCon( plugWindow, (UInt32) pictWindow );
	
	// set the window pic to the data handle
	PicHandle picture = (PicHandle) Host_GetResourceData( resource );
	if( picture == null ) Host_DisplayError( "\pNo picture could be obtained.", "\p", 0 );
	
	// get pict rect
	PictInfo pictInfo;
	GetPictInfo( picture, &pictInfo, 0, 0, 0, 0 );
	Rect pictRect;
	pictRect.top = 0;
	pictRect.left = 0;
	pictRect.right = pictInfo.sourceRect.right - pictInfo.sourceRect.left;
	pictRect.bottom = pictInfo.sourceRect.bottom - pictInfo.sourceRect.top;
	SizeWindow( window, pictRect.right, pictRect.bottom, false );
	
#if TARGET_API_MAC_CARBON
	ControlRef picControl;						// this is better than SetWindowPic() in Carbon
	ControlButtonContentInfo content;
	content.contentType = kControlContentPictHandle;
	content.u.picture = picture;	// bug: if handle dissapears, control is fucked
	CreatePictureControl( window, &pictRect, &content, true, &picControl );
//	DrawOneControl( picControl );	// bug: work around for bug in ControlManager
/*	HLockHi( picture );
	SetControlData( picControl, kControlPicturePart, kControlPictureHandleTag, sizeof(picture), *picture );	*/
#else
	SetWindowPic( window, picture );	// this doesn't work properly on X
#endif
	
	// show window
	ShowWindow( window );
	SelectWindow( window );
	return error;
}