/*
 *  valdrawerview.pi.c
 *  PeekIt
 *
 *  Created by C.K. Haun on 11/12/05.
 *  Copyright 2005 Ravenware Software. All rights reserved.
 *
 */


// -----------------------------------------------------------------------------
// ValDrawerView API
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewCreate(                            WindowRef				inWindow);






// -----------------------------------------------------------------------------
//	constants
// -----------------------------------------------------------------------------
//

#define kValDrawerViewClassID	CFSTR( "com.Ravenware.ValDrawerView" )

// const ControlPartCode	kControlOpaqueRegionMetaPart = -3;

// -----------------------------------------------------------------------------
//	types
// -----------------------------------------------------------------------------
//
enum {kRawDecode=2323,kFormatter};
typedef struct
{
	HIViewRef			view;
    UInt16 currentPane;
    Rect    colorBoxBounds;
    UInt16 cellHeight;
    UInt16 cellWide;
	// Geometry
        WindowRef theWindow;
        UInt16 columnRightsCG[6];
        UInt16 columnRightsQD[6];
        CGRect dragRectsCG[6];
        Rect dragRectsQD[6];
        MouseTrackingRef trackingRef;

} ValDrawerViewData;

// -----------------------------------------------------------------------------
//	prototypes
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewBoundsChanged(
                                         EventRef				inEvent,
                                         ValDrawerViewData*		inData );
OSStatus ValDrawerViewRegister(void);
OSStatus ValDrawerViewHandler(
	EventHandlerCallRef		inCallRef,
	EventRef				inEvent,
	void*					inUserData );
OSStatus ValDrawerViewConstruct(
	EventRef				inEvent );
OSStatus ValDrawerViewInitialize(
	EventHandlerCallRef		inCallRef,
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewDestruct(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewDraw(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewHitTest(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewTrack(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewChanged(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewGetData(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewSetData(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
OSStatus ValDrawerViewGetRegion(
	EventRef				inEvent,
	ValDrawerViewData*		inData );
ControlPartCode ValDrawerViewFindPart(
	const HIRect*			inBounds,
	const HIPoint*			inWhere,
	ValDrawerViewData*		inData );
void ValDrawerViewDefaultDrawPart(
	ControlPartCode			inPart,
	const HIRect*			inPartRect
	);
void ValDrawerViewDefaultDrawPartLabel(
	ControlPartCode			inPart,
	const HIRect*			inPartRect
	);
void ValDrawerViewSetUpData(
	ValDrawerViewData*		inData );

// -----------------------------------------------------------------------------
//	globals
// -----------------------------------------------------------------------------
//

// -----------------------------------------------------------------------------
//	ValDrawerViewCreate
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewCreate(	WindowRef			theWindow )
{
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    Rect rectR;
    
	OSStatus			err=noErr;
	ControlRef			root;
	EventRef			event;
	
	// Make sure this type of view is registered
	ValDrawerViewRegister();

	// Make the initialization event
	err = CreateEvent( NULL, kEventClassHIObject, kEventHIObjectInitialize,
			GetCurrentEventTime(), 0, &event );
	
	// Set the bounds into the event
        rectR.top=rectR.left=0;
rectR.right=        nowCD->valDrawerViewRect.size.width;
      rectR.bottom=  nowCD->valDrawerViewRect.size.height;
        err = SetEventParameter( event, 'Boun', typeQDRectangle,
                                 sizeof( Rect ), &rectR );

        err = SetEventParameter(event,'MYWR',typeVoidPtr,sizeof(WindowRef),&theWindow);
	err = HIObjectCreate( kValDrawerViewClassID, event, (HIObjectRef*) &nowCD->valDrawerView );

	// Get the content root
	err = GetRootControl( theWindow, &root );
	
	// And stick this view into it
	err = HIViewAddSubview( root, nowCD->valDrawerView );
	
	ReleaseEvent( event );

             

	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewRegister
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewRegister(void)
{
	OSStatus				err = noErr;
	static HIObjectClassRef	sValDrawerViewClassRef = NULL;

	if ( sValDrawerViewClassRef == NULL )
	{
		EventTypeSpec		eventList[] = {
			{ kEventClassHIObject, kEventHIObjectConstruct },
			{ kEventClassHIObject, kEventHIObjectInitialize },
			{ kEventClassHIObject, kEventHIObjectDestruct },
			{ kEventClassControl, kEventControlInitialize },
			{ kEventClassControl, kEventControlDraw },
			{ kEventClassControl, kEventControlHitTest },
			{ kEventClassControl, kEventControlTrack },
			{ kEventClassControl, kEventControlValueFieldChanged },
			{ kEventClassControl, kEventControlHiliteChanged },
			{ kEventClassControl, kEventControlGetData },
			{ kEventClassControl, kEventControlSetData },
			{ kEventClassControl, kEventControlGetPartRegion },
                {kEventClassControl,kEventControlBoundsChanged},
                {                    kEventClassScrollable,kEventScrollableInfoChanged}

                };

   
		err = HIObjectRegisterSubclass(
			kValDrawerViewClassID,		// class ID
			kHIViewClassID,				// base class ID
			NULL,						// option bits
			ValDrawerViewHandler,		// construct proc
			GetEventTypeCount( eventList ),
			eventList,
			NULL,						// construct data,
			&sValDrawerViewClassRef );
	}
	
	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewHandler
// -----------------------------------------------------------------------------
//	This is the bottleneck for incoming events
//
OSStatus ValDrawerViewHandler(
	EventHandlerCallRef		inCallRef,
	EventRef				inEvent,
	void*					inUserData )
{
	OSStatus				err = eventNotHandledErr;
	UInt32					eventClass = GetEventClass( inEvent );
	UInt32					eventKind = GetEventKind( inEvent );
	ValDrawerViewData*		data = (ValDrawerViewData*) inUserData;

	switch ( eventClass )
	{
		case kEventClassHIObject:
		{
			switch ( eventKind )
			{
				case kEventHIObjectConstruct:
					err = ValDrawerViewConstruct( inEvent );
					break;

				case kEventHIObjectInitialize:
					err = ValDrawerViewInitialize( inCallRef, inEvent, data );
					break;

				case kEventHIObjectDestruct:
					// don't CallNextEventHandler!
					err = ValDrawerViewDestruct( inEvent, data );
					break;
			}
		}
		break;
		
		case kEventClassControl:
		{
			switch ( eventKind )
			{
				case kEventControlInitialize:
					err = noErr;
					break;

				case kEventControlDraw:
// err=                                    ValDrawerViewDrawQuartz( inEvent, data );
                                   err=                                    ValDrawerViewDraw( inEvent, data );

                                    break;
				
				case kEventControlHitTest:
					err = ValDrawerViewHitTest( inEvent, data );
					break;
				
				case kEventControlTrack:
					err = ValDrawerViewTrack( inEvent, data );
					break;
				
				case kEventControlValueFieldChanged:
				case kEventControlHiliteChanged:
					err = ValDrawerViewChanged( inEvent, data );
					break;

				case kEventControlGetData:
					err = ValDrawerViewGetData( inEvent, data );
					break;

				case kEventControlSetData:
					err = ValDrawerViewSetData( inEvent, data );
					break;
				
				case kEventControlGetPartRegion:
					err = ValDrawerViewGetRegion( inEvent, data );
					break;
                                                                                                        case kEventControlBoundsChanged:
                                                                                                                err = ValDrawerViewBoundsChanged( inEvent, data );
                                                                                                            
                                                                                                            break;
			}
		}
		break;
                case kEventClassScrollable:
                    // kEventScrollableInfoChanged
                    DoAbout();
                    break;
        }
	
	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewConstruct
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewConstruct(
	EventRef			inEvent )
{
    OSStatus			err=noErr;
	ValDrawerViewData*	data;
        
	// don't CallNextEventHandler!
	data = (ValDrawerViewData*) calloc( 1,sizeof( ValDrawerViewData ) );
	// Set up the default drawing callbacks
        data->currentPane = kRawDecode;
	
	// Keep a copy of the created HIViewRef
	err = GetEventParameter( inEvent, kEventParamHIObjectInstance, typeHIObjectRef,
			NULL, sizeof( HIObjectRef ), NULL, (HIObjectRef*) &data->view );
  
        
	// Set the userData that will be used with all subsequent eventHandler calls
	err = SetEventParameter( inEvent, kEventParamHIObjectInstance, typeVoidPtr,
			sizeof( ValDrawerViewData* ), &data ); 

        
        
	if ( err != noErr )
		free( data );

	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewDestruct
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewDestruct(
	EventRef			inEvent,
	ValDrawerViewData*	inData )
{
#pragma unused( inEvent )
	// Clean up any allocated data
	free( inData );

	return noErr;
}


    

// -----------------------------------------------------------------------------
//	ValDrawerViewInitialize
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewInitialize(
	EventHandlerCallRef	inCallRef,
	EventRef			inEvent,
	ValDrawerViewData*	inData )
{
	OSStatus			err;
    CGContextRef cgRef;
	Rect				bounds;
	UInt32				features = kControlSupportsDataAccess+/* kControlHasSpecialBackground+*/ kControlSupportsDragAndDrop;
	// Let the base class initialization occur
	err = CallNextEventHandler( inCallRef, inEvent );
	require_noerr( err, TroubleInSuperClass );

	// Extract the initial view bounds from the event
	err = GetEventParameter( inEvent, 'Boun', typeQDRectangle,
			NULL, sizeof( Rect ), NULL, &bounds );
	require_noerr( err, ParameterMissing );
	       err = GetEventParameter(inEvent,'MYWR',typeVoidPtr,0,sizeof(WindowRef),NULL,&inData->theWindow);

               err = GetEventParameter( inEvent, kEventParamCGContextRef, typeCGContextRef,
                                        NULL, sizeof( CGContextRef ), NULL, &cgRef );

#if 0
               // an I set the text paramters here?
               CGContextSetRGBFillColor (cgRef, 0, 0, 0, 1); 
               Str255 fontName="\pCourier";
               fontName[fontName[0] + 1] = 0;  // make (char*)&fontName[1] a C-string
               CGContextSelectFont(cgRef, (char*)&fontName[1], 18, kCGEncodingMacRoman);
               
               CGContextSetTextMatrix(cgRef, CGAffineTransformMakeScale(1, -1));
#endif               
	// Set up this view's feature bits
	err = SetEventParameter( inEvent, kEventParamControlFeatures, typeUInt32,
			sizeof( UInt32 ), &features );

	SetControlBounds( inData->view, &bounds );
        inData->columnRightsCG[0] = (bounds.right - bounds.left)/3;
        {
            WindowRef theWindow=inData->theWindow; // GetControlOwner(inData->view);
            WCH tempWC = (WCH)GetWRefCon(theWindow);
            ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
// set a flag
            

        }
        
ParameterMissing:
TroubleInSuperClass:
	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewDraw
// -----------------------------------------------------------------------------
//            RGBColor bleu = gDrawerValColor;
OSStatus             ValDrawerDrawFormattedData(      CGContextRef cgRef,float hPos,float vPos,PIDataFormatterPtr theDataFormatter,Ptr theData,UInt32 *offsetIntoData,ValDrawerViewData*	inData)
{OSStatus myErr = noErr;
                RGBColor bleu = gDrawerValColor;
                Ptr fromHere=theData;
                
                UInt32 length = theDataFormatter->length;
    CGContextSetTextPosition(cgRef,hPos,vPos);
    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    if(theData && length >0){
    
    } else {
    // see what when 
    }
    
//    CGWriteNum(cgRef,theDataFormatter->length);
    
    return(myErr);
    
}
// this can be called recursively.  Updates vert drawing position and position in file 
OSStatus ValDrawerViewDrawFormatter(      CGContextRef cgRef,UInt16 hPos,UInt16  *vPos,UInt16 vInc,PIDataFormatterPtr theDataFormatter,Ptr theData,UInt32 *offsetIntoData,UInt32 *realAmount,ValDrawerViewData* inData,CGRect nameClip,CGRect valueClip)
{
//    theDataFormatter
    OSStatus myErr = 0;
    UInt16 functionSwitchedCount = 0;
    WCH tempWC = (WCH)GetWRefCon( inData->theWindow);
    ValDrawerDataP  nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    // and the parent parent
    PIMainWDataP parentNowCD=nowCD->parentNowCD;
    
while(theDataFormatter){

    if(theDataFormatter->dataType !=        kFormatterValPadding)
        *vPos =(* vPos) + vInc;

        CGContextSaveGState(cgRef);			
    CGContextClipToRect (cgRef,nameClip );    
    RGBColor indentColor = gDrawerValColor;

    // if this is an embedded formatter then draw teh title in some other color, then recurse.  This is gonna hurt.
    switch(theDataFormatter->dataType){
        case kFormatterValPadding:
            // do nothing

            
            break;
        case kFormatterValPlugIn:
            CGDrawCFStringAt(cgRef,theDataFormatter->title,hPos,*vPos);
            // colonoscopy
            CGDrawCFString(cgRef,CFSTR(": "));
            break;
    case kFormatterValEmbedded:

        CGContextSetRGBFillColor (cgRef, indentColor.red, indentColor.green, indentColor.blue, 1); 

//        CGDrawCFStringAt(cgRef,theDataFormatter->embeddedFormatter->title,hPos,*vPos);
        CGDrawCFStringAt(cgRef,theDataFormatter->title,hPos,*vPos);
        // colonoscopy
        CGDrawCFString(cgRef,CFSTR(": "));
        
        // now the embedded name
        CGDrawCFString(cgRef,theDataFormatter->embeddedFormatter->title);


        break;
    default:
        CGContextSetRGBFillColor (cgRef, gBlack.red, gBlack.green, gBlack.blue, 1); 
        CGDrawCFStringAt(cgRef,theDataFormatter->title,hPos,*vPos);
        break;
    }

    CGContextRestoreGState(cgRef);
    // now the data
        // move inna position
        UInt16 pushedhPos  =hPos;
        CGContextSaveGState(cgRef);			
        CGContextClipToRect (cgRef,valueClip );    
        hPos = valueClip.origin.x+2;
        
        if((*realAmount) > *offsetIntoData){
            CGContextSetTextPosition(cgRef, hPos,*vPos);

            CGContextSetRGBFillColor (cgRef, gDrawerValColor.red, gDrawerValColor.green, gDrawerValColor.blue, 1); 

        switch(theDataFormatter->dataType){
            case kFormatterValPlugIn:
                // call the plugin
            {
                FormPlugPtr theThing = (FormPlugPtr)theDataFormatter->embeddedFormatter;
//(const Ptr inputByteStream,UInt16 numberBytesProvided,Ptr *outputTextStream,UInt16 *outputTextStreamLen,UInt32 *bytesConsumed,UInt32 outputFormatFlags);
                Ptr thisPointer = theData + *offsetIntoData;
                OSStatus plugError = 0;
                Ptr newPtr;
                Ptr textBack=0;
                UInt16                textBackLen=0;
                UInt32 bytesConsumed=0; // UInt32 outputFormatFlags);
                // actually duplicate the pointer so they can't touch the real data
                UInt16 bytesSent = theDataFormatter->length;
                if(theDataFormatter->length == -1){
                 if(*realAmount - *offsetIntoData < 1024)
                     bytesSent = *realAmount - *offsetIntoData;
                     else
                    bytesSent = 1024;
                }
                newPtr = malloc(bytesSent);
                BlockMoveData(thisPointer,newPtr,bytesSent);


// a new do-while for rotating the function results
                Boolean functionSwitched=false;
                do{
                    functionSwitched = false;
                if(theThing->drawFunc){

                    // make up the flag word
                    HIRect theR;
                    UInt32 flagWord = 0;
                    if(theDataFormatter->flags & kPIDataFormatterSigned)
                        flagWord |=kPIPIDisplayAsSigned;
                    if(theDataFormatter->flags &kPIDataFormatterDisplayHex)
                        flagWord |= kPIPIDisplayAsHex;
                    if(theDataFormatter->flags & kPIDataFormatterLittleEndian)
                        flagWord |=    kPIPIDisplayAsLittleEndian;
                    theR.origin.x = hPos-2;
                    theR.origin.y = (*vPos) - vInc+2 ; // vPos is for text, so take it up one
                    theR.size.width = valueClip.size.width;
                    theR.size.height = vInc+2;

        CGContextSaveGState(cgRef);	
        do{
        plugError= (theThing->drawFunc)(newPtr,bytesSent,&bytesConsumed,cgRef,theR,flagWord);
            switch(plugError){
                default:
                    break;
                case kPIFDisableThisFunction:
                    theThing->drawFunc = 0;
                    plugError = 0;            
                    break;
                case kPIFExpandDrawingArea:
                    if((flagWord & kPIFUnableToResizeDrawingArea ) == 0){
                        theR.size.height += (vInc+2);
                    } else {
                        // they asked again even though the flag was set and they were called, go away
                    plugError = 0;
                    }
                    break;
                case kPIFCompressDrawingArea:
                    if((flagWord & kPIFUnableToResizeDrawingArea ) == 0){
                    if( theR.size.height > vInc+2){
                    theR.size.height += (vInc+2);
                    
                    } else {
                        flagWord |= kPIFUnableToResizeDrawingArea;
                        
                    }
                    } else {
                        // they asked again even though the flag was set and they were called, go away

                        plugError = 0;
                    }

                    break;
                case kPIFRotateFunctions:
                    // see if there is one, first
                    if(functionSwitchedCount == 0){
                    if(theThing->formatFunc || theThing->cachedformatFunc){
                        // dim us
                        theThing->cacheddrawFunc = theThing->drawFunc; 
                        theThing->drawFunc = 0;
                        if(theThing->formatFunc == 0)theThing->formatFunc =theThing->cachedformatFunc;
                        // and go around again
                        functionSwitched = true;
                        functionSwitchedCount++;
                    } else {
                    //well, uhhh, do nothing
                        // actually I should draw three dashes.  Is everything set up for that? We'll see
                        CGDrawString(cgRef,"\p---");

                    }
                    } else {
                    // don't keep swtching!
                        CGDrawString(cgRef,"\p---");

                    }
                    break;
            }
        }while(plugError);
        CGContextRestoreGState(cgRef);

                } else {

                    if(theThing->formatFunc){
                        // make up the flag word
                        UInt32 flagWord = 0;
                        functionSwitched = false;
                        if(theDataFormatter->flags & kPIDataFormatterSigned)
                            flagWord |=kPIPIDisplayAsSigned;
                        if(theDataFormatter->flags &kPIDataFormatterDisplayHex)
                            flagWord |= kPIPIDisplayAsHex;
                        if(theDataFormatter->flags & kPIDataFormatterLittleEndian)
                            flagWord |=    kPIPIDisplayAsLittleEndian;
                        plugError= (theThing->formatFunc)(newPtr,bytesSent,&textBack,&textBackLen,&bytesConsumed,flagWord);
                        switch(plugError){
                            case noErr:
                             if( textBackLen){
                            CGContextShowText( cgRef, textBack,textBackLen);  
                                } else {
                                    CGDrawString(cgRef,"\p---");
                                }
                                break;
                            case kPIFDisableThisFunction:
                                theThing->formatFunc = 0;
                                break;
                            case kPIFRotateFunctions:
                                // see if there is one, first
                                if(functionSwitchedCount== 0){
                                if(theThing->drawFunc || theThing->cacheddrawFunc){
                                    // dim us
                                    theThing->cachedformatFunc = theThing->formatFunc; 
                                    theThing->formatFunc = 0;
                                    if(theThing->drawFunc == 0)theThing->drawFunc =theThing->cacheddrawFunc;
                                    // and go around again
                                    functionSwitched = true;
                                    functionSwitchedCount++;
                                } else {
                                    //well, uhhh, do nothing
                                    // actually I should draw three dashes.  Is everything set up for that? We'll see
                                    CGDrawString(cgRef,"\p---");
                                    
                                } 
                                } else {
                                // dont switch more than once!
                                    CGDrawString(cgRef,"\p---");

                                }
                                break;
                                
                                
                        }
                        if(textBack)free(textBack);
                        
                    }
                }
                }while(functionSwitched);

// finish arbitration                
                free(newPtr);
                *offsetIntoData = (*offsetIntoData)+bytesConsumed;

            }
                break;
            case  kFormatterValEmbedded:
                hPos +=10;
                if( ValDrawerViewDrawFormatter(       cgRef, hPos,vPos, vInc, theDataFormatter->embeddedFormatter->formatters, theData,offsetIntoData,realAmount, inData, nameClip, valueClip) != 0){
                }
                    hPos -=10;
                
                break;
            case kFormatterValByte:
            {
                char theByte =0;// *(theData + *offsetIntoData);
                theByte = *(theData + *offsetIntoData);
                *offsetIntoData = (*offsetIntoData)+1;  // advanmce the counter
//                    if(theDataFormatter->flags & kPIDataFormatterLittleEndian)
                    if(theDataFormatter->flags & kPIDataFormatterDisplayHex){
                    CGWriteHexByteStream( cgRef,  1, &theByte);
                    } else {
                        if(theDataFormatter->flags & kPIDataFormatterSigned){
                        CGWriteNum(cgRef,theByte);
                        } else {
                            UInt32 theByteL = 0;
                          theByteL =theByte & 0xff;
                            CGWriteNumUL(cgRef,theByteL);
                        }
                    }                            
            }                    
     break;

 case kFormatterValWord:
 {
     UInt16 theWord =0;// *(theData + *offsetIntoData);
     UInt16 makeUp;
     Byte xx,yy;
     theWord = *((short *)(theData + *offsetIntoData));
     if(theDataFormatter->flags & kPIDataFormatterDisplayHex){
    
         if(theDataFormatter->flags & kPIDataFormatterLittleEndian){
             makeUp =*((theData + ((*offsetIntoData) +1)));
             makeUp = makeUp <<8;
             makeUp &=0xff00;
             xx=*((theData + ((*offsetIntoData))));
             theWord = makeUp | xx;
             
    }
         CGWriteHexByteStream( cgRef,  2, &theWord);
    
         
     } else {
         if(theDataFormatter->flags & kPIDataFormatterLittleEndian){
// flip it
             makeUp =*((theData + ((*offsetIntoData) +1)));
             makeUp = makeUp <<8;
             makeUp &=0xff00;
             yy=*((theData + ((*offsetIntoData))));
             theWord = makeUp | yy ;
         }

         if(theDataFormatter->flags & kPIDataFormatterSigned){
             CGWriteNum(cgRef,theWord);
         } else {
             CGWriteNumUL(cgRef,theWord);
         }
     }                            
     *offsetIntoData = (*offsetIntoData)+2;  // advanmce the counter

 }                    
     
     break;

 case kFormatterValLong:
 {
     UInt32 theLong =0;// *(theData + *offsetIntoData);
     UInt32 makeUpL;
     UInt16 xx;
     char buffer[5];
     theLong = *((unsigned long *)(theData + *offsetIntoData));
     if(theDataFormatter->flags & kPIDataFormatterDisplayHex){
         
         if(theDataFormatter->flags & kPIDataFormatterLittleEndian){
                 buffer[0]=*(theData + ((*offsetIntoData)+3));
                 buffer[1]= *(theData + ((*offsetIntoData)+2));
                 buffer[2]= *(theData + ((*offsetIntoData)+1));
                 buffer[3]= *(theData + (*offsetIntoData));    
                              CGWriteHexByteStream( cgRef,  4, &buffer);

         } else {
         CGWriteHexByteStream( cgRef,  4, &theLong);
         }
         
     } else {
         if(theDataFormatter->flags & kPIDataFormatterLittleEndian){
             // flip it
             buffer[0]=*(theData + ((*offsetIntoData)+3));
             buffer[1]= *(theData + ((*offsetIntoData)+2));
             buffer[2]= *(theData + ((*offsetIntoData)+1));
             buffer[3]= *(theData + (*offsetIntoData));    
             theLong = *(long*)buffer;
         }
         
         if(theDataFormatter->flags & kPIDataFormatterSigned){
             CGWriteNumL(cgRef,theLong);
         } else {
             CGWriteNumUL(cgRef,theLong);
         }
     }                            
     *offsetIntoData = (*offsetIntoData)+4;  // advanmce the counter
     
 }
     break;

 case kFormatterValBytePtr:
 {
   // to be safe, I'm going to use a seperate ptr for this  
     Ptr nextPtr = malloc(theDataFormatter->length);
     Ptr holdIt = nextPtr;
     UInt32 leng = theDataFormatter->length;
     while(leng--){
*holdIt=     *(theData + (*offsetIntoData));
         holdIt++;
     *offsetIntoData = (*offsetIntoData) +1;    
     }
    CGWriteHexByteStream( cgRef,  theDataFormatter->length, nextPtr);  
 }
     break;
 case     kFormatterValCString:
// ok. walk the plank until you get to the end.  And watch the total lenght, might have to bail
     // maximmum is 1024
 {
     UInt32  counter =      0;
     while( *(theData + (*offsetIntoData))){
//         CGWriteHexByteNoDollar(cgRef,    *(theData + (*offsetIntoData)));
     CGContextShowText( cgRef, (theData + (*offsetIntoData)), 1);
         counter++;
         *offsetIntoData = *offsetIntoData +1;
         if(counter == 1024)break;
     }
    *offsetIntoData = *offsetIntoData +1; // consume the zero
 }
     
     break;
 case         kFormatterValPString:
     // current byte.
 {
 unsigned char counter =      *(theData + (*offsetIntoData));
     *offsetIntoData = (*offsetIntoData) +1;    
     Ptr theString;
     counter = MIN(counter,*realAmount);
// CGWriteHexByteStream( cgRef, counter, (theData + (*offsetIntoData)));
     CGContextShowText( cgRef,  (theData + (*offsetIntoData)),counter);  

*offsetIntoData = (*offsetIntoData)+counter;
 }
     break;
 case         kFormatterValPadding:
 {
// same thing as a pointer, but don't show nobody
     UInt32 leng = theDataFormatter->length;
     while(leng-- && *offsetIntoData <*realAmount ){
         *offsetIntoData = (*offsetIntoData) +1;    
     }
 }
     
     break;

        }
        } else {
        // draw dashes
                 CGDrawCFStringAt(cgRef,CFSTR("----"),hPos,*vPos);
        }
        CGContextRestoreGState(cgRef);

        hPos=        pushedhPos ;
#if 0    
    }
#endif    
theDataFormatter= theDataFormatter->next;
}
    return( myErr);
}
#pragma mark Drawing
OSStatus ValDrawerViewDraw(
	EventRef			inEvent,
	ValDrawerViewData*	inData )
{
	OSStatus			err;
	HIRect				bounds;
        ControlID theID;
        CGrafPtr thePort;
        UInt16 vInc,vPos,hPos;
        CGContextRef cgRef;
        char buffer[10];
        RGBColor theColor;
        Rect    innerRect;
        LoopVar qq,ii;
        UInt16 vSize,hSize;
        
        WCH tempWC = (WCH)GetWRefCon( inData->theWindow);
        ValDrawerDataP  nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
// and the parent parent
        PIMainWDataP parentNowCD=nowCD->parentNowCD;
        UInt32 realAmount=0;
        Ptr theData=0; //  now setting this later because the formatter needs a different length = malloc(100);
        err = GetEventParameter( inEvent, kEventParamCGContextRef, typeCGContextRef,
                                 NULL, sizeof( CGContextRef ), NULL, &cgRef );
                
        // an I set the text paramters here?
        // yes
        CGContextSetRGBFillColor (cgRef, 0, 0, 0, 1); 
        Str255 fontName="\pCourier";        
        fontName[fontName[0] + 1] = 0;  // make (char*)&fontName[1] a C-string
        CGContextSelectFont(cgRef, (char*)&fontName[1],  parentNowCD->fontSize, kCGEncodingMacRoman);
        
        CGContextSetTextMatrix(cgRef, CGAffineTransformMakeScale(1, -1));
        err = HIViewGetBounds( inData->view, &bounds );

        vInc = parentNowCD->fontSize + 2;
        vPos = /* theContRect.top +*/ vInc;
        hPos = /* theContRect.left +*/ 6;        

        switch(inData->currentPane){
            case kRawDecode:
            {
                Byte unsignIt;
                UInt16 unsignIt2=0;
                theData = malloc(100);
                realAmount =     PIWindowGiveMeBytesAtSelection(parentNowCD,theData,100);

                CGDrawStringAtRGBColor(cgRef,"\pByte  val:   ",hPos,vPos,&gBlack);
            RGBColor bleu = gDrawerValColor;
        CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
        CGWriteNum(cgRef,*theData);
        unsignIt = 0;
        unsignIt = *theData;
        vPos +=vInc;

        CGDrawStringAtRGBColor(cgRef,"\p unsigned:   ",hPos,vPos,&gBlack);
        unsignIt &=0xff;
        CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 

        CGWriteNum(cgRef,unsignIt);
                /*********/
        /***************/
            vPos +=vInc+4;

            CGDrawStringAtRGBColor(cgRef,"\pWord  val:   ",hPos,vPos,&gBlack);
            
CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
if(realAmount >=1){
    CGWriteNum(cgRef,*((short *)theData));
    // now little endian signed word
    vPos +=vInc;

    CGDrawStringAtRGBColor(cgRef,"\p little end: ",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 

    buffer[0]= *(theData+1);
    buffer[1]= *(theData);
    
    CGWriteNum(cgRef,*((short *)(&buffer)));
    //****
    
} else {
    CopyString(    "\p--",gTempString);
    CGContextShowText(cgRef,&gTempString[1],gTempString[0]);
    vPos +=vInc;

    CGDrawStringAtRGBColor(cgRef,"\p little end: ",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    
    
    
}

vPos +=vInc;
CGContextSetRGBFillColor (cgRef, gBlack.red, gBlack.green, gBlack.blue, 1); 

unsignIt2 = *((short *)theData);
CGDrawStringAtRGBColor(cgRef,"\p Unsigned:  ",hPos,vPos,&gBlack);

 
CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
if(realAmount>=1){
    
    CGWriteNumL(cgRef,unsignIt2);
    // now little endian signed word
    vPos +=vInc;
    CGDrawStringAtRGBColor(cgRef,"\p little end:",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    buffer[0]=0;
    buffer[1]=0;
    buffer[2]= *(theData+1);
    buffer[3]= *(theData);
    CGWriteNumL(cgRef,*((unsigned long  *)(&buffer)));
    

} else {
    CGDrawString(cgRef,"\p--");
    vPos +=vInc;
    CGDrawStringAtRGBColor(cgRef,"\p little end:",hPos,vPos,&gBlack);

    
    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    CGDrawString(cgRef,"\p----");
    
    
}



    /***************/


vPos +=vInc+4;
CGDrawStringAtRGBColor(cgRef,"\pLong  val:  ",hPos,vPos,&gBlack);

CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
if(realAmount>=3){
    CGWriteNumL(cgRef,*((long *)theData));
    vPos +=vInc;

    CGDrawStringAtRGBColor(cgRef,"\p little end:",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    buffer[0]= *(theData+3);
    buffer[1]= *(theData+2);
    buffer[2]= *(theData+1);
    buffer[3]= *(theData);
    CGWriteNumL(cgRef,*((long  *)(&buffer)));


} else {
    CGDrawString(cgRef,"\p----");
    vPos +=vInc;
    CGDrawStringAtRGBColor(cgRef,"\p little end:",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    CGDrawString(cgRef,"\p----");

}
vPos +=vInc;
UInt32 unsignIt3 =*((long *)theData);    
CGDrawStringAtRGBColor(cgRef,"\p unsigned:  ",hPos,vPos,&gBlack);


CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
if(realAmount>=3){
    CGWriteNumUL(cgRef,unsignIt3);
    
    vPos +=vInc;
    CGDrawStringAtRGBColor(cgRef,"\p little end:",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    buffer[0]= *(theData+3);
    buffer[1]= *(theData+2);
    buffer[2]= *(theData+1);
    buffer[3]= *(theData);
    CGWriteNumUL(cgRef,*((unsigned long  *)(&buffer)));
    
    
    
} else {
    CGDrawString(cgRef,"\p----");
    vPos +=vInc;
    CGDrawStringAtRGBColor(cgRef,"\p little end:",hPos,vPos,&gBlack);

    CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
    CGDrawString(cgRef,"\p----");
    
}
/************/        
vPos +=vInc+4;
CGDrawStringAtRGBColor(cgRef,"\pAs a string of hex bytes:",hPos,vPos,&gBlack);


CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
vPos +=vInc;
// MoveTo(hPos,vPos);
CGContextSetTextPosition(cgRef, hPos,vPos);

CGWriteHexByteStream( cgRef,  MIN(realAmount,100), theData);

/***********/
CGContextSetRGBFillColor (cgRef, gBlack.red, gBlack.green, gBlack.blue, 1); 
Rect BoundingBox;  // putting in sope for color box

{
    BoundingBox.top = 0;
    BoundingBox.left=0;
    BoundingBox.right=bounds.size.width;
    BoundingBox.bottom=bounds.size.height;
    
        vPos +=vInc+4;
        CGDrawStringAtRGBColor(cgRef,"\pAs a string of text:",hPos,vPos,&gBlack);

        //    vPos +=vInc+4;
        CGContextSetRGBFillColor (cgRef, bleu.red, bleu.green, bleu.blue, 1); 
//        RGBForeColor(&bleu);
        CFStringRef theTextBlock =  CFStringCreateWithBytes (
                                                             0,
                                                             theData,
                                                             MIN(realAmount,500),
                                                             kCFStringEncodingMacRoman,
                                                             false );
        BoundingBox.top = vPos;
        BoundingBox.left+=6;
        BoundingBox.bottom = BoundingBox.top +(vInc* 3 /* 4 */ );
        DrawThemeTextBox(
                         theTextBlock,
                         0,
                         0,
                         true, // Boolean          inWrapToWidth,
                         &BoundingBox,
                         0,
                         cgRef); // void *           inContext) 
        CFRelease(theTextBlock);
}
/**********/
// lets pull this up some to allow for a control at the bottom

{
// now make some pretty colors

    BoundingBox.top = BoundingBox.bottom+2;
//    BoundingBox.top = 0;
    BoundingBox.left=0;
    BoundingBox.right=bounds.size.width;
    BoundingBox.bottom=bounds.size.height;
    // move this into the header for hit-testing later
    inData->colorBoxBounds = BoundingBox;
    
    // figure out the size of the pixels.
    hSize = (BoundingBox.right - BoundingBox.left)/parentNowCD->numColumns;
    // taking some height out to fit in the scroll bar
    vSize = ((BoundingBox.bottom- BoundingBox.top)-1)/parentNowCD->numRows ;
    vSize = MAX(vSize,kColorDataVisPixSize);
    hSize= MAX(hSize,kColorDataVisPixSize);
    inData->cellHeight = vSize;
    inData->cellWide = hSize;
    BoundingBox.bottom = BoundingBox.top  + (parentNowCD->numRows * vSize); //
    BoundingBox.right = BoundingBox.left  + (parentNowCD->numColumns * hSize); //
                                                                               // now draw the buffer in Color
    CGRect theRect;
    theRect.size.height = vSize; // innerRect.bottom - innerRect.top;
    theRect.size.width = hSize;//  innerRect.right - innerRect.left;

    {
        Ptr realPtr = parentNowCD->displaying.fileBuffer;
        char theByte;
		UInt32 selPos = parentNowCD->startSel->totalPos;
        ULong lilCounter = parentNowCD->displaying.offsetInBuffer;
        ULong tempVar1,tempVar2;
		UInt32 whereAreWe=        parentNowCD->displaying.bufStartInFile -1;
        if(parentNowCD->forkShowing==0){
            tempVar2 =parentNowCD->theFT->dataForkLen; 
        } else {
            tempVar2 =parentNowCD->theFT->resForkLen; 
            
        }
        for(qq=0;qq<parentNowCD->numRows ;qq++){
            for(ii=0;ii<parentNowCD->numColumns ;ii++){

                theByte = *(realPtr + lilCounter);
                lilCounter++;
                switch (gAddPrefs.valDGraphicColor){
                    case 0:
                        mSetColor(theColor,(theByte*0x100)+theByte,(theByte*0x100)+theByte,(0x100)+theByte);
                        break;   
                    case 1:
                        mSetColor(theColor,(theByte*0x100)+theByte,0,0);
                        break;   
                    case 2:
                        mSetColor(theColor,0,(theByte*0x100)+theByte,0);
                        break;   
                    case 3:
                        mSetColor(theColor,0,0,(theByte*0x100)+theByte);
                        break;   
                        
                        
                }
                theRect.origin.y = BoundingBox.top + (qq* vSize);
                theRect.origin.x =BoundingBox.left + (ii* hSize);
                
                
                PaintCGRectWithRGBColorPtr(cgRef, theRect,&theColor);
// and if this is the current selection
				if(whereAreWe + lilCounter == selPos){
					mSetColor(theColor,0xffff,0,0);
                                    
                                    FrameCGRectWithRGBColorPtr(cgRef,2,theRect,&theColor);


				}
            }
            
        }}
/*
    theRect.origin.x=BoundingBox.left;
    theRect.origin.y=BoundingBox.top;
    theRect.size.width=BoundingBox.right-BoundingBox.left;
    
    theRect.size.height=BoundingBox.bottom-BoundingBox.top;
 */
//    FrameCGRectWithRGBColorPtr(cgRef,1,theRect,&theColor);

}
}
break;
#pragma mark FormatterDrawing
case kFormatter:
{Ptr intoDataPtr=0;
    UInt32 index=0;
    UInt32 totalFormatterStructLength=0;
    UInt32 thisFormatLength=0;
    PeekitStructFormatterPtr theFormatter = nowCD->theFormatter;
    if(theFormatter){
    totalFormatterStructLength = GetFormatterStructDataCount(theFormatter);
        if(totalFormatterStructLength){
            CGRect        nameClipRect,valueClipRect;
            UInt32 offsetIntoData = 0;
            PIDataFormatterPtr theDataFormatter = theFormatter->formatters;
            theData = malloc(totalFormatterStructLength);
// this cannot be accurate with pascal and C strings included.  Have to come up with some other thinkingirst 
            realAmount =     PIWindowGiveMeBytesAtSelection(parentNowCD,theData,totalFormatterStructLength);

            //the real work is here  AHAHAHAHHA!!! And I ain't gonna start it tonight, let me write the docs on what I have so far now
            
// clipitandstripit
        nameClipRect=bounds;
        nameClipRect.origin.y = vPos;
        nameClipRect.size.width = inData->columnRightsCG[0];
        valueClipRect = nameClipRect;
        valueClipRect.origin.x = (bounds.origin.x + valueClipRect.size.width)+2;
        valueClipRect.size.width = bounds.size.width - valueClipRect.origin.x;

        vPos+=vInc;         

        CGContextSetRGBFillColor (cgRef, gBlack.red, gBlack.green, gBlack.blue, 1); 
        CGContextSaveGState(cgRef);			
        CGContextClipToRect (cgRef,nameClipRect  );
        CGDrawCFStringAt(cgRef,theFormatter->title,hPos,vPos);

        CGContextRestoreGState(cgRef);
#if 0
        CGContextSaveGState(cgRef);			
        CGContextClipToRect (cgRef,valueClipRect  );
//        CGDrawCFStringAt(cgRef,CFSTR("Value"),valueClipRect.origin.x,vPos);
        CGContextRestoreGState(cgRef);
#endif
        // we need to hand the whole thing off, inlucude the while, so it can recurse
        ValDrawerViewDrawFormatter( cgRef, hPos,&vPos, vInc,theDataFormatter, theData,&offsetIntoData,&realAmount,inData, nameClipRect,valueClipRect);
        
        // grey line
        {  CGRGBColor draggerGrey={0,0,0,.5};
                CGContextSetRGBStrokeColor(cgRef,draggerGrey.red, draggerGrey.green, draggerGrey.blue, draggerGrey.alpha); 	
        CGContextBeginPath(cgRef);
        CGContextMoveToPoint(cgRef,inData->columnRightsCG[0]+1,bounds.origin.y+vInc);
        CGContextAddLineToPoint(cgRef, inData->columnRightsCG[0]+1, bounds.origin.y +bounds.size.height);
        CGContextStrokePath(cgRef);
        }
    
        }
    } else {
        vPos+=16;  // below the popup 
        CopyString("\pNo formatter selected   ",gTempString);
        CGContextShowTextAtPoint(cgRef,hPos,vPos,&gTempString[1],gTempString[0]);
    }
}
// end formatter drawing
break;
}

/***************/
if(theData)free(theData);

	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewHitTest
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewHitTest(
	EventRef			inEvent,
	ValDrawerViewData*	inData )
{
	OSStatus			err=0;
	HIRect				bounds;
	HIPoint				where;
	ControlPartCode		part;

	err = GetEventParameter( inEvent, kEventParamMouseLocation, typeHIPoint,
			NULL, sizeof( HIPoint ), NULL, &where );
	require_noerr( err, ParameterMissing );

	err = HIViewGetBounds( inData->view, &bounds );

	part = ValDrawerViewFindPart( &bounds, &where, inData );

	err = SetEventParameter( inEvent, kEventParamControlPart, typeControlPartCode,
			sizeof( ControlPartCode ), &part ); 


ParameterMissing:
	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewTrack
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewTrack(
	EventRef			inEvent,
	ValDrawerViewData*	inData )
{	ControlID theID;
    RgnHandle r1;
	OSStatus			err;
	ControlPartCode		part;
	Point				qdPt;
	MouseTrackingResult	mouseResult;
        Rect controlBounds;
        CGrafPtr thePorter;
        WCH tempWC;
        ValDrawerDataP nowCD;
        WindowRef theWindow = inData->theWindow;
        piCell theCell,tempCell;
        piCell *origCell;
        Rect tempRect;
            PIMainWDataP    parentNowCD;
        tempWC = (WCH)GetWRefCon(theWindow);
        nowCD = (ValDrawerDataP)(*tempWC)->dataStore;

        parentNowCD = nowCD->parentNowCD;
        theWindow=GetControlOwner(inData->view);
        thePorter = GetWindowPort(theWindow);
        mPushPort(theWindow);
        GetMouse(&qdPt);
        GetControlBounds(inData->view,&controlBounds);
        mPullPort;
        /*****/
        switch(inData->currentPane){
case kRawDecode:
{
        if(PtInRect(qdPt,&inData->colorBoxBounds )){
            // figure out where
            Point nother = qdPt;
            UInt32 totalPos=0;

            UInt16 row,col;
            nother.v -= inData->colorBoxBounds.top;
            nother.h-= inData->colorBoxBounds.left;
            
            
            row = nother.v / inData->cellHeight;
            col = nother.h / inData->cellWide;
            
            {UInt32 ocurrentVal =0;
                short nRow = row;
                do{
                    if(nRow == 0){
                        ocurrentVal +=col;
                    } else {
                        ocurrentVal +=  parentNowCD->numColumns;
                    }
                }while(nRow -- >0);
                totalPos =ocurrentVal+ parentNowCD->displaying.offsetInBuffer+parentNowCD->displaying.bufStartInFile;
        
                
                
                /******/
                if(totalPos < 0)
                    totalPos = 0;
                UInt32 theTrueLen ;
                if(parentNowCD->forkShowing==0){
                    theTrueLen = parentNowCD->theFT->dataForkLen; 
                } else {
                    theTrueLen = parentNowCD->theFT->resForkLen; 
                    
                }
                
                if(totalPos >theTrueLen)
                    
                    totalPos =theTrueLen;
                
                /******/
                
                
                
                
                pimwMoveToThisByte(parentNowCD->us, totalPos);
            }
        }
        
        /***********/
        
        
        
        
do	{

            
		err = TrackMouseLocation(thePorter, &qdPt, &mouseResult );
//    ZeroCell(&theCell);
// kMouseTrackingMouseMoved later
  switch(mouseResult){
      case kMouseTrackingMouseDragged:
/***************/
          // sheesh, I need to see if it's in the color box
          /***********/
          if(PtInRect(qdPt,&inData->colorBoxBounds )){
          // figure out where
              Point nother = qdPt;
              UInt32 totalPos=0;
              UInt16 row,col;
              nother.v -= inData->colorBoxBounds.top;
              nother.h-= inData->colorBoxBounds.left;


              row = nother.v / inData->cellHeight;
              col = nother.h / inData->cellWide;
              
              {UInt32 ocurrentVal =0;
                  short nRow = row;
                  do{
                      if(nRow == 0){
                          ocurrentVal +=col;
                      } else {
                          ocurrentVal +=  parentNowCD->numColumns;
                      }
                  }while(nRow -- >0);
                  totalPos =ocurrentVal+ parentNowCD->displaying.offsetInBuffer+parentNowCD->displaying.bufStartInFile;
                  
                  
                  /******/
                  if(totalPos < 0)
                      totalPos = 0;
                  UInt32 theTrueLen ;
                  if(parentNowCD->forkShowing==0){
                      theTrueLen = parentNowCD->theFT->dataForkLen; 
                  } else {
                      theTrueLen = parentNowCD->theFT->resForkLen; 
                      
                  }
                  
                  if(totalPos >theTrueLen)
     
                      totalPos =theTrueLen;
                  
                  /******/
                  
                  
                  pimwMoveToThisByte(parentNowCD->us, totalPos);
              }
          }
          break;        
  

  }
}while( mouseResult != kMouseTrackingMouseUp);
}
break;
case kFormatter:
do{
    
    err = TrackMouseLocation(thePorter, &qdPt, &mouseResult );
    //    ZeroCell(&theCell);
    // kMouseTrackingMouseMoved later
    switch(mouseResult){
        case kMouseTrackingMouseDragged:
            inData->columnRightsCG[0]= qdPt.h - controlBounds.left;
            // I'm actually going to stuff this on the window side too
            nowCD->valDrawerFViewLine = inData->columnRightsCG[0];
            nowCD->valDrawerFViewLineChanged = true;
            ValDrawerViewBoundsChanged(0 ,inData );
            HIViewSetNeedsDisplay( inData->view, true );

            break;
    }
    }while( mouseResult != kMouseTrackingMouseUp);
    SetThemeCursor(kThemeArrowCursor);

    
    
break;
        }

    err = SetEventParameter( inEvent, kEventParamControlPart, typeControlPartCode,
			sizeof( ControlPartCode ), &part ); 

	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewChanged
// -----------------------------------------------------------------------------
//

void valdrawermousecallback(EventKind eventKind,EventRef inEvent,MouseTrackingRef theRef, void * refCon)
{
    
    switch(eventKind){
        case  kEventMouseEntered:
            SetThemeCursor(kThemeResizeLeftRightCursor);
            break;
        case kEventMouseExited :
            SetThemeCursor(kThemeArrowCursor);
            break;
    }
}



OSStatus ValDrawerViewBoundsChanged(
                                         EventRef				inEvent,
                                         ValDrawerViewData*		inData )
{
#pragma unused( inEvent )
    OSStatus			err = noErr;
    HIRect				bounds;
    WCH tempWC = (WCH)GetWRefCon( inData->theWindow);
    ValDrawerDataP  nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    // and the parent parent
    PIMainWDataP parentNowCD=nowCD->parentNowCD;
Rect    controlRect;
    UInt16    vInc = parentNowCD->fontSize + 2;
    Point  qdOrigin;
    err = HIViewGetBounds( inData->view, &bounds );
    GetControlBounds(inData->view,&controlRect);
    qdOrigin.h = controlRect.left;
    qdOrigin.v = controlRect.top;
    
    if(inEvent != 0){
  
    inData->columnRightsCG[0] =( (bounds.size.width)/3)*2;
    } 
    // the worst this second check will do is put the same number in the same place again
    if(  nowCD->valDrawerFViewLineChanged == true) {
        inData->columnRightsCG[0] =nowCD->valDrawerFViewLine;
    }
    
    inData->dragRectsCG[0].origin.y = bounds.origin.y +vInc;
    inData->dragRectsCG[0].origin.x = inData->columnRightsCG[0]-2;
    inData->dragRectsCG[0].size.height = bounds.size.height - vInc;
    inData->dragRectsCG[0].size.width = 4;
    
    CGRectToQDRect(inData->dragRectsCG[0],&inData->dragRectsQD[0],&qdOrigin);
/**************/
    // do initial mousetracking setup
    {MouseTrackingRegionID inID;
        RgnHandle  inRegion = NewRgn();
        LoopVar qq;
        OSStatus err =0;
        inID.signature = 'PEEK';
        inID.id = 2;
        
        if(inData->trackingRef){
            ReleaseMouseTrackingRegion(inData->trackingRef);
            inData->trackingRef=0;
        }
        
        mPushPort(inData->theWindow);
        OpenRgn();
            FrameRect(&inData->dragRectsQD[0]);
        CloseRgn(inRegion);
        mPullPort;
        slibMouseTrackerDataBlockPtr theRefCon = calloc(1,sizeof(slibMouseTrackerDataBlock));
        theRefCon->refCon = inData;
        theRefCon->callMe = valdrawermousecallback;
        err = CreateMouseTrackingRegion (inData->theWindow, 
                                         inRegion,
                                         0,
                                         kMouseTrackingOptionsLocalClip,
                                         inID,
                                         theRefCon,
                                         0,
                                         &inData->trackingRef);
    }
    
    /***********/
    
    HIViewSetNeedsDisplay( inData->view, true );
    
    return err;
}





OSStatus ValDrawerViewChanged(
	EventRef			inEvent,
	ValDrawerViewData*	inData )
{
#pragma unused( inEvent )
	OSStatus			err = noErr;
    HIRect				bounds;

    err = HIViewGetBounds( inData->view, &bounds );

                inData->columnRightsCG[0] = (bounds.size.width)/3;

	HIViewSetNeedsDisplay( inData->view, true );

	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewGetData
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewGetData(
	EventRef				inEvent,
	ValDrawerViewData*		inData )
{
	OSStatus				err;
	ControlPartCode			part;
	OSType					tag;
	Ptr						ptr;
	Size					size;
	Size					outSize;
	
	err = GetEventParameter( inEvent, kEventParamControlPart, typeControlPartCode,
			NULL, sizeof( ControlPartCode ), NULL, &part );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlDataTag, typeEnumeration,
			NULL, sizeof( OSType ), NULL, &tag );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlDataBuffer, typePtr,
			NULL, sizeof( Ptr ), NULL, &ptr );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlDataBufferSize, typeLongInteger,
			NULL, sizeof( Size ), NULL, &size );
	require_noerr( err, ParameterMissing );


	if ( err == noErr )
		err = SetEventParameter( inEvent, kEventParamControlDataBufferSize, typeLongInteger,
				sizeof( Size ), &outSize );

ParameterMissing:
	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewSetData
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewSetData(
	EventRef				inEvent,
	ValDrawerViewData*		inData )
{
	OSStatus				err;
	ControlPartCode			part;
	OSType					tag;
	Ptr						ptr;
            Ptr aLong=0;
UInt32  yesL=0;
            Size					size;
	err = GetEventParameter( inEvent, kEventParamControlDataTag, typeEnumeration,
                                 NULL, sizeof( OSType ), NULL, &tag );
        if(tag == 'VIWP'){

            err = GetEventParameter( inEvent, kEventParamControlDataBufferSize, typeLongInteger,
                                     NULL, sizeof( Size ), NULL, &size );
            err = GetEventParameter( inEvent, kEventParamControlDataBuffer, typePtr,
                                     NULL, sizeof( Ptr ), NULL, &aLong );
                    inData-> currentPane = *((long *)aLong);

        }
#if 0
	
	err = GetEventParameter( inEvent, kEventParamControlPart, typeControlPartCode,
			NULL, sizeof( ControlPartCode ), NULL, &part );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlDataTag, typeEnumeration,
			NULL, sizeof( OSType ), NULL, &tag );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlDataBuffer, typePtr,
			NULL, sizeof( Ptr ), NULL, &ptr );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlDataBufferSize, typeLongInteger,
			NULL, sizeof( Size ), NULL, &size );
	require_noerr( err, ParameterMissing );


ParameterMissing:
#endif            
	return err;
}

// -----------------------------------------------------------------------------
//	ValDrawerViewGetRegion
// -----------------------------------------------------------------------------
//
OSStatus ValDrawerViewGetRegion(
	EventRef				inEvent,
	ValDrawerViewData*		inData )
{
	OSStatus				err;
	ControlPartCode			part;
	RgnHandle				outRegion;
	HIRect					bounds;
	Rect					qdBounds;
	
	err = GetEventParameter( inEvent, kEventParamControlPart, typeControlPartCode,
			NULL, sizeof( ControlPartCode ), NULL, &part );
	require_noerr( err, ParameterMissing );

	err = GetEventParameter( inEvent, kEventParamControlRegion, typeQDRgnHandle,
			NULL, sizeof( RgnHandle ), NULL, &outRegion );

	if ( part == kControlContentMetaPart
			|| part == kControlStructureMetaPart
	) //		 || part == kControlOpaqueRegionMetaPart  )
	{
		HIViewGetBounds( inData->view, &bounds );
		qdBounds.top = (SInt16) CGRectGetMinY( bounds );
		qdBounds.left = (SInt16) CGRectGetMinX( bounds );
		qdBounds.bottom = (SInt16) CGRectGetMaxY( bounds );
		qdBounds.right = (SInt16) CGRectGetMaxX( bounds );
	
		RectRgn( outRegion, &qdBounds );
	}
	
ParameterMissing:
	return err;
}

// -----------------------------------------------------------------------------
//	FindPart
// -----------------------------------------------------------------------------
//
ControlPartCode ValDrawerViewFindPart(
	const HIRect*		inBounds,
	const HIPoint*		inWhere,
	ValDrawerViewData*	inData )
{
	ControlPartCode		part;
// don't really have parts.
        // so just say 1
	part = 1;

	return part;
}
#if 0
// -----------------------------------------------------------------------------
//	ValDrawerViewDefaultDrawPart
// -----------------------------------------------------------------------------
//
void ValDrawerViewDefaultDrawPart(
	ControlPartCode			inPart,
	const HIRect*			inPartRect
	 )
{
	switch ( inPart )
	{
	}
}

// -----------------------------------------------------------------------------
//	ValDrawerViewDefaultDrawPartLabel
// -----------------------------------------------------------------------------
//
void ValDrawerViewDefaultDrawPartLabel(
	ControlPartCode			inPart,
	const HIRect*			inPartRect
	 )
{
	
}

// -----------------------------------------------------------------------------
//	ValDrawerViewSetUpData
// -----------------------------------------------------------------------------
//
void ValDrawerViewSetUpData(
	ValDrawerViewData*	inData )
{
}
#endif

void SizeValDrawerViews(WindowRef theWindow,ValDrawerDataP nowCD)
{
    Rect thisRect;
    HIRect   inRect;
    /*     CGPoint origin;
    CGSize size */
    if(nowCD->valDrawerView){
/*
        thisRect = nowCD->valDrawerViewRect;

        inRect.origin.x =thisRect.left;
        inRect.origin.y =thisRect.top ;
        inRect.size.width =thisRect.right - thisRect.left;
            inRect.size.height = thisRect.bottom- thisRect.top;
 */
        HIViewSetFrame(
                       nowCD->valDrawerView,
                       &nowCD->valDrawerViewRect);
            HIViewSetNeedsDisplay(  nowCD->valDrawerView, true );
    }


}



#if 0
err = CreateEvent( NULL, kEventClassScrollable, kEventScrollableInfoChanged,
                   GetCurrentEventTime(), 0, &event );

#endif
/*
 *  ValDrawer.pi.c
 *  PeekIt
 *
 *  Created by C.K. Haun on 1/8/05.
 *  Copyright 2005 Ravenware Software. All rights reserved.
 *
 */
#define kColorDataVisPixSize 4
extern PeekitStructFormatterPtr gFormatters;




void HitValDrawerIND(WindowRef theWindow, Point *thePoint);

struct ValDrawerindData {
    WindowRef mommy;
    UInt32 largest;
    HIRect valDrawerViewRect;
    PIMainWDataP    parentNowCD;
    ControlRef  valDrawerView;
    PeekitStructFormatterPtr theFormatter; // current formatter
    ControlRef formatterPopUp;
    UInt16 viewShowing;
    UInt16 valDrawerFViewLine;
    Boolean valDrawerFViewLineChanged;
    short buddy;
};

typedef struct ValDrawerindData ValDrawerindData;
typedef ValDrawerindData *ValDrawerDataP;
/* protos */

void innerValDrawSizer(WindowRef theWindow,ValDrawerDataP nowCD);

#include "valdrawerview.pi.c"

OSStatus ValDrawerDrawingCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
    CallNextEventHandler(
                         inHandlerCallRef,
                         inEvent);

    return(myStatus);

}
OSStatus ValDrawerClickCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
// extract the mouse
    Point theMouse;
    mPushPort((WindowRef)inUserData)

        GetEventParameter (inEvent, kEventParamMouseLocation, typeQDPoint,
                           NULL, sizeof(Point), NULL, &theMouse);
    
// now hand off
// TEST TEMP get the mouse
// GetMouse(&theMouse);  // I should not have to get the mouse again
    HitValDrawerIND((WindowRef)inUserData,&theMouse);
    mPullPort

        CallNextEventHandler(
                             inHandlerCallRef,
                             inEvent);

    return(myStatus);

}
void TellValWindowAboutChange(WindowRef valWindow)
{    WCH tempWC = (WCH)GetWRefCon((WindowRef)valWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    HIViewSetNeedsDisplay( 
                           nowCD->valDrawerView,
                           true);
    
}
OSStatus ValDrawerStateChangeCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
    UInt32 theKind;
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    
    
    theKind = GetEventKind(inEvent);

//    ZapPort((WindowRef)inUserData);
    switch(theKind){

        case        kEventWindowActivated:
        {                WCH parentTempWC = (WCH)GetWRefCon(nowCD->mommy);
            PIMainWDataP parentNowCD= (PIMainWDataP)(*parentTempWC)->dataStore;

            if(           nowCD->theFormatter &&  nowCD->theFormatter->flags & kPIStructChanged){
                HIViewSetNeedsDisplay(      
                                            nowCD->valDrawerView,
                                            true);
                
            }
        }
            break;
       case kEventWindowDeactivated:

           break;
           }
    CallNextEventHandler(
                         inHandlerCallRef,
                         inEvent);

    return(myStatus);

}
#pragma mark Sizing
void innerValDrawSizer(WindowRef theWindow,ValDrawerDataP nowCD)
{    Rect wRect;
    mPushPort(theWindow)
        GetWindowPortBounds(theWindow,&wRect );
    nowCD-> valDrawerViewRect.origin.x = wRect.left;
    nowCD-> valDrawerViewRect.origin.y = wRect.top;
    nowCD-> valDrawerViewRect.size.width = wRect.right-wRect.left;
    nowCD-> valDrawerViewRect.size.height = (wRect.bottom-wRect.top);
    
    wRect.bottom-=10; //bottom controls
    
    if(nowCD->viewShowing == 1){
//        wRect.top+=12;
    }
    SetControlBounds(
                     nowCD->valDrawerView,
                     &wRect);
    
    
    /***********/
#if 0
    {Rect nowRect;
        UInt16 wide,hi;
        GetControlBounds(
                         SnatchCRef(theWindow,'VALD',kValDrawerPopUp),
                         &nowRect);
        wide = nowRect.right-nowRect.left;
        hi = nowRect.bottom-nowRect.top;
        
        nowRect.bottom = wRect.bottom;
        nowRect.right =wRect.right;
        nowRect.top = nowRect.bottom-hi;
        nowRect.left = nowRect.right-wide;
        /*
         SetControlBounds(
                          SnatchCRef(theWindow,'VALD',5561),
                          &nowRect);
         */
    }
    /***********/
    
    
    
    /*    
        SetControlBounds(
                         theCont,
                         &wRect);
    */
#endif    
    mPullPort
}

OSStatus ValDrawerSizeCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
    WindowRef theWindow = (WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    innerValDrawSizer( theWindow, nowCD);

    CallNextEventHandler(
                         inHandlerCallRef,
                         inEvent);

    return(myStatus);

}
OSStatus ValDrawerCloseCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;
// just hide the window


    HideWindow((WindowRef)inUserData);

    return(myStatus);

}

OSStatus ValDrawerSpecialCode(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
    OSStatus myStatus = noErr;

    HICommand commandStruct;
    GetEventParameter (inEvent, kEventParamDirectObject,
                       kEventClassWindow, NULL, sizeof(HICommand),
                       NULL, &commandStruct);

    CallNextEventHandler(
                         inHandlerCallRef,
                         inEvent);

    return(myStatus);

}





OSStatus InstallValDrawerHandlers(
                                     WindowRef theWindow,
                                     void * refCon,
                                     ULong flags)

{
    OSStatus myErr = noErr;
    long realRefCon = 0;
    EventHandlerRef windowOutRef;
    EventTypeSpec  windowDrawEventList[1]={{kEventClassWindow,kEventWindowDrawContent}};

    EventTypeSpec  windowStateEventList[2]={{kEventClassWindow,kEventWindowActivated},{kEventClassWindow,kEventWindowDeactivated}};

    EventTypeSpec  windowSizeEventList[1]={{kEventClassWindow,kEventWindowBoundsChanged}};

    EventTypeSpec  windowCloseEventList[1]={{kEventClassWindow,kEventWindowClose}};
    
//    EventTypeSpec  windowSpecialEventList[1]={{kEventClassWindow,kEventWindowContextualMenuSelect}};

//    EventTypeSpec  windowClickEventList[1]={   {kEventClassWindow,kEventWindowHandleContentClick}};

    if(refCon == NULL)realRefCon = (long)theWindow;
// we should collect all these event refs in the window data struct
    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(ValDrawerDrawingCode),     sizeof(windowDrawEventList)/sizeof(EventTypeSpec),  (EventTypeSpec *)  &windowDrawEventList,     (void *)theWindow,   &windowOutRef);

//    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(ValDrawerClickCode),     sizeof(windowClickEventList)/sizeof(EventTypeSpec),    (EventTypeSpec *)&windowClickEventList, (void *)theWindow,      &windowOutRef);

    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(ValDrawerStateChangeCode),     sizeof(windowStateEventList)/sizeof(EventTypeSpec),    (EventTypeSpec *)&windowStateEventList, (void *)theWindow,      &windowOutRef);

    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(ValDrawerSizeCode),     sizeof(windowSizeEventList)/sizeof(EventTypeSpec),   (EventTypeSpec *) &windowSizeEventList, (void *)theWindow,      &windowOutRef);

    myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(ValDrawerCloseCode),     sizeof(windowCloseEventList)/sizeof(EventTypeSpec),    (EventTypeSpec *)&windowCloseEventList, (void *)theWindow,      &windowOutRef);
    
// taking the special out for a miunutes
// myErr = InstallEventHandler (GetWindowEventTarget (theWindow), NewEventHandlerUPP(ValDrawerSpecialCode),     sizeof(windowSpecialEventList)/sizeof(EventTypeSpec),
// &windowSizeEventList, (void *)theWindow,      &windowOutRef);
    myErr = InstallStandardEventHandler(GetWindowEventTarget (theWindow));



    return(myErr);

}





// ****************************
// pascal void Contdevloop(short depth, short deviceFlags, GDHandle targetDevice, long userData)
// going back through and removing all the offscreen stuff in this.


void DrawValDrawerIND(WindowRef theWindow, EventRecord *theEvent)
{
}



void HitValDrawerIND(WindowRef theWindow, Point *thePoint)
{

    WCH tempWC = (WCH)GetWRefCon(theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    Point theP;
    GetMouse(&theP);
}


void PrepEditValDrawerIND(WindowRef theWindow, Boolean *theEdits)
{
#if 0
#pragma unused (theEdits )
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    /* file */
    // EnableItem(GetMHandle(kFileMenu),kSave);
    EnableItem(GetMenuHandle(kFileMenu), kSaveAs);
    EnableItem(GetMenuHandle(kFileMenu), kPrint);
    /* edit */

    if ((*(*tempWC)->undoAction)->undoWhat)
        EnableItem(GetMenuHandle(kEditMenu), kUndo);
//    if (objSelected(theWindow)) {
// cut/copy the screen text on demand
    EnableItem(GetMenuHandle(kEditMenu), kCut);
    EnableItem(GetMenuHandle(kEditMenu), kCopy);
//        EnableItem(GetMenuHandle(kEditMenu), kClear);
//    }
    EnableItem(GetMenuHandle(kEditMenu), kSelectAll);
    EnableItem(GetMenuHandle(kEditMenu), kClipBoard);
    EnableItem(GetMenuHandle(kCompanionMenu),1);

#endif
}

void SizeValDrawerIND(WindowRef theWindow, EventRecord *theEvent, short how)
{
#pragma unused (theEvent )
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;

}

//  save the current screen snapshot
void SaveValDrawerIND(WindowRef theWindow, Boolean as)
{

}

void IdleValDrawerIND(WindowRef theWindow, Boolean front)
{

#pragma unused (front )
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    LoopVar qq;

    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;

}

void KeyValDrawerIND(WindowRef theWindow, EventRecord *theEvent)
{

}

#if 0
Boolean EdittheWindow(WindowRef theWindow, EventRecord *theEvent, short editAction)
{
#pragma unused (theEvent )
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    Boolean retVal = false;

    switch (editAction) {
        case kCut:
        case kCopy:
	// spit the screen text to the clipboard
 //	PutScrap(320,'TEXT',&nowCD->alltext[0]);
 // PutScrapFlavor(  0,  'TEXT',  0,  320, &nowCD->alltext[0]);


            return(retVal);
    }
    return(retVal);
}
#endif
void SendValDrawerINDBoard(void)
{

}


OSErr AEValDrawerIND(WindowRef theWindow, AppleEvent *Event)
{
#pragma unused (theWindow,Event )
    OSErr  myErr = noErr;

    return(myErr);
}
void  CommandValDrawerIND(WindowRef theWindow, EventRef inEvent,void *inUserData,HICommand *commandStruct)
{
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
// switch on the command
    switch((commandStruct->commandID)){
deafult:
#ifndef __FINAL__
        DebugStr("\p command in AboutW window defaulted");
#endif
        break;
    }

}
void GenValDrawerIND(WindowRef theWindow, UShort selector, void *theData)
{
#pragma unused (theWindow,theData )
    WCH tempWC = (WCH)GetWRefCon(theWindow);
    WindowPrefStructHdl thePrefs;
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    LoopVar qq;
    switch (selector) {
        case kMenuGeneral:
            break;
        case kwmgActContHit:
		// coming forward mouse hit, so use it as well
            SetPort(theWindow);
            HitValDrawerIND( theWindow,nil);
            break;
        case kwmgUpdatePrefs: 
	// no prefs
            break;
    }
}

void CloseValDrawerIND(WindowRef theWindow, Boolean kill)
{
#pragma unused (kill )
    CloseDrawer(theWindow,true);

}



static  OSStatus ValDrawerPopupEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
    WindowRef theWindow=(WindowRef)inUserData;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    PIMainWDataP parentNowCD;
    UInt32 formatterUniqueID=0;
    UInt16 theVal=     GetControlValue(SnatchCRef(theWindow,'VALD',kValDrawerPopUp));
    PeekitStructFormatterPtr startHere = gFormatters;
MenuRef theMenu = GetControlPopupMenuHandle(SnatchCRef(theWindow,'VALD',kValDrawerPopUp));
    // get this formatter
    // nope, this isn't right.  We're not adding empty formatters to the list.  So we have to grab the uniqueID
GetMenuItemProperty(
                    theMenu,
                    theVal,
                    'PEEK',
                    'UNID',
                    sizeof(UInt32),
                    0,
                    &formatterUniqueID) ;
// now find this one and add it to the thingie
startHere = GetPIStructFormatterByID(formatterUniqueID);    


    nowCD->theFormatter = startHere;
    HIViewSetNeedsDisplay(      
                           nowCD->valDrawerView,
                           true);
    
    
    return(0);
}

UInt16 xxGiveMeDividerPosition(WindowRef theWindow)
{
    WCH tempWC = (WCH)GetWRefCon((WindowRef)theWindow);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    
    return(nowCD->    valDrawerFViewLine);
}


static  OSStatus ValDrawerScrollEventHandlerProc( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{Ptr theData = malloc(100);
    WindowRef theWindow=(WindowRef)inUserData;
    LoopVar qq,ii;
    WCH tempWC = (WCH)GetWRefCon((WindowRef)inUserData);
    ValDrawerDataP nowCD = (ValDrawerDataP)(*tempWC)->dataStore;
    PIMainWDataP parentNowCD;

    ControlRef theCont;
    ControlID theID;
    GetEventParameter (inEvent, kEventParamDirectObject, typeControlRef,
                       NULL, sizeof(ControlRef), NULL, &theCont);
    GetControlID(
                 theCont,
                 &theID); 
    
    SetControlValue(    SnatchCRef(theWindow,'VALD',2323),false);
    SetControlValue(    SnatchCRef(theWindow,'VALD',2324),false);
    SetControlValue(    SnatchCRef(theWindow,'VALD',theID.id),true);
    nowCD->viewShowing = theID.id-2323;
    switch(theID.id){
case 2323:
//        HideControl(SnatchCRef(theWindow,'VALD',5560));
        HideControl(SnatchCRef(theWindow,'VALD',kValDrawerPopUp));
    break;
case 2324:
// ShowControl(SnatchCRef(theWindow,'VALD',5560));
    ShowControl(SnatchCRef(theWindow,'VALD',kValDrawerPopUp));

    
    
    {   
    MenuRef theMenu = GetControlPopupMenuHandle(SnatchCRef(theWindow,'VALD',kValDrawerPopUp));
        EnableAllMenuItems(theMenu);
    }
    
    break;

    }
    SetControlData(
                   nowCD->valDrawerView ,
                   0,
                   'VIWP',
                   sizeof(theID.id),
                   &theID.id);
// size it again
    innerValDrawSizer(theWindow,nowCD);
    HIViewSetNeedsDisplay( 
                           nowCD->valDrawerView,
                           true);
    
    
    //    UInt32 theS= GetControlValue(SnatchCRef(theWindow,'VALD',2323));
    Ptr thePtr;
/*
    GetControlDataSize(
                       nowCD->valDrawerView ,
                       5,
                       kControlEditTextTextTag,
                       &theS 
                       );
    thePtr = malloc(theS+1);
    GetControlData(
                   nowCD->valDrawerView ,
                   5,
                   kControlEditTextTextTag,
                   theS,
                   thePtr,
                   0);
    */
    

    
    return(0);
}






// this doesn't do much.  Just displays the drawer contents, no clicking or typing  No controls
#pragma mark creation
WindowRef AddPIValueDrawer(WindowRef inWindow)
{
    
    LoopVar qq;
    EventTypeSpec	aboutlControlEvents[] =
    {
    {kEventClassControl,    kEventControlHit}
    };
    EventTypeSpec	posControlEvents[] =    {    {kEventClassControl,    kEventControlDraw}    };
    PIMainWDataP parentNowCD;
    WCH tempWC;
    ValDrawerDataP nowCD;
    OSErr myErr = 0;
    AliasHandle theA;
    WindowRef theWindow = nil;
    
    EventTypeSpec	vscControlEvents[] ={    {kEventClassControl,    kEventControlHit}    };

    WCH parentTempWC = (WCH)GetWRefCon(inWindow);
    parentNowCD = (PIMainWDataP)(*parentTempWC)->dataStore;

    
    // see if it exists yet
    
    
    myErr = CreateWindowFromNib(gNibRef, CFSTR("ValDrawer"), & theWindow);
    
    // NEW
    InstallValDrawerHandlers(
                             theWindow,
                             0,
                             0);
    
    tempWC = (WCH)NewHandleClear(sizeof(windowControl));
    
    nowCD = (ValDrawerDataP)calloc(1,sizeof(ValDrawerindData));
    mPushPort( theWindow)
        TextSize(9);
    
    mPullPort
        (*tempWC)->undoAction = (UndoHand)NewHandleClear(sizeof(UndoControl));
    (*tempWC)->dataStore = (Handle)nowCD;
    SetWRefCon( theWindow, (long)tempWC);
    AddWindowID( theWindow);
    
    /* set these goddam things */
    (*tempWC)->drawMe = DrawValDrawerIND;
    (*tempWC)->clickMe = HitValDrawerIND;
    (*tempWC)->saveMe = SaveValDrawerIND;
    (*tempWC)->closeMe = CloseValDrawerIND;
    (*tempWC)->keyMe = KeyValDrawerIND;
    //    (*tempWC)->prepEdit = PrepEditValDrawerIND;
    //    (*tempWC)->activateMe = ActivateValDrawerIND;
    //    (*tempWC)->deactMe = DeActivateValDrawerIND;
    (*tempWC)->sizeMe = SizeValDrawerIND;
    (*tempWC)->idleMe = IdleValDrawerIND;
    (*tempWC)->appleEventMe = AEValDrawerIND;
    (*tempWC)->generalMe = GenValDrawerIND;
    (*tempWC)->commandMe = CommandValDrawerIND;
    // new way Jose
    
    
    nowCD->mommy = inWindow;
    nowCD->parentNowCD = parentNowCD;
    
    
   
    nowCD-> valDrawerViewRect.origin.x = 0;
    nowCD-> valDrawerViewRect.origin.y = 0;
    nowCD-> valDrawerViewRect.size.width =50;
    nowCD-> valDrawerViewRect.size.height = 50;
   
    // see if there is a divider line position
    {
        CFStringRef colsrKey = CFSTR("ValDColRight");
        // get saved columnright
        CFDataRef   colDataRs  = CFPreferencesCopyAppValue(colsrKey,
                                                               kCFPreferencesCurrentApplication);
            if(colDataRs){
                UInt8 * dataIn;
                dataIn = CFDataGetBytePtr (
                                           colDataRs
                                           );
                BlockMoveData(dataIn,&nowCD->valDrawerFViewLine,(sizeof(UInt16)));
                nowCD->valDrawerFViewLineChanged = true;

                CFRelease(colDataRs);
            }
                }
    
    ValDrawerViewCreate(                              theWindow );
//      HIViewSetVisible((HIViewRef)nowCD->valDrawerView,true);
    //    HIViewSetVisible((HIViewRef)nowCD->transScroll,true);
    // add control IDs.  Why?  Dunno.  Then don't do it.  well, nevermind

      {  const ControlID	kCalendarID = { 'VALD', 9500 };
        SetControlID( nowCD->valDrawerView, &kCalendarID );
        ShowControl(nowCD->valDrawerView);
        
    }
/*      
      EmbedControl(
          SnatchCRef(theWindow,'VALD',5560),nowCD->valDrawerView);
*/
      EmbedControl(
                   SnatchCRef(theWindow,'VALD',kValDrawerPopUp),nowCD->valDrawerView);

      HIViewSetZOrder(
   SnatchCRef(theWindow,'VALD',kValDrawerPopUp),
                      kHIViewZOrderAbove,
                      0) ;

      
      
          InstallControlEventHandler(    SnatchCRef(theWindow,'VALD',2323),  ValDrawerScrollEventHandlerProc , GetEventTypeCount(vscControlEvents),vscControlEvents, theWindow, NULL );
      InstallControlEventHandler(    SnatchCRef(theWindow,'VALD',2324),  ValDrawerScrollEventHandlerProc , GetEventTypeCount(vscControlEvents),vscControlEvents, theWindow, NULL );

InstallControlEventHandler(    SnatchCRef(theWindow,'VALD',kValDrawerPopUp),  ValDrawerPopupEventHandlerProc , GetEventTypeCount(vscControlEvents),vscControlEvents, theWindow, NULL );




      //      HideControl(SnatchCRef(theWindow,'VALD',5560));
      HideControl(SnatchCRef(theWindow,'VALD',kValDrawerPopUp));

      
      // I'm hiding this one for a while now
//     HideControl (SnatchCRef(theWindow,'VALD',2323));

      SetDrawerParent (
                     theWindow,
                     inWindow
                     );
    SetDrawerPreferredEdge(
                           theWindow,
                           kWindowEdgeRight);
    SetControlValue(    SnatchCRef(theWindow,'VALD',2323),true);

    // and the formatter popup
    UpdateAllValDrawerPopups();
    return( theWindow);
    
}
void    UpdateValDrawer(WindowRef theWindow)
{
    TellValWindowAboutChange(theWindow);

}

void xxUpdateValDrawerPopupMenu(void)
{
    /*
MenuRef theMenu = GetControlPopupMenuHandle (
                                            SnatchCRef(theWindow,'VALD',kValDrawerPopUp)
                                             );

 AddFormattersToMenu( theMenu);
     */
}
