/*
 *  FILE: menu.c
 *  Support routines for creating menu and menu item structures.
 *
 *  Public Domain, but keep my name in it as the original author.
 *  31-Oct-88	Jan Sven Trabandt   added to gimme.lib
 */


#define I_AM_MENU
#include "gimmelib/gimmefuncs.h"
#define GIM_BUILTIN
#include "gimmelib/macros.h"

extern struct GfxBase *GfxBase;

#define XLEEWAY     10	    /* make menu item a little visually appealing */


struct Menu *gimmeMenu( mhptr, left, width, name, flags )
    void    **mhptr;
    SHORT   left, width;
    UBYTE   *name;
    ULONG   flags;
{
    register struct Menu    *menu;

    if( menu = chainAllocMem(mhptr, (ULONG)sizeof(struct Menu),
				    MEMF_PUBLIC | MEMF_CLEAR) ) {
	menu->LeftEdge = left;
	if( width >= 0 ) {
	    menu->Width = width;
	} else {
	    menu->Width = 9 * strlen( name );
	}
	menu->Height = 9;	    /* currently ignored by Intuition */
	menu->Flags = flags;
	menu->MenuName = (BYTE *) name;
    }
    return( menu );
} /* gimmeMenu */


struct MenuItem *gimmeMenuItem( mhptr, left, width, height, command, name,
				    textattr, flags )
    void	    **mhptr;
    SHORT	    left;
    SHORT	    width, height;
    BYTE	    command;
    UBYTE	    *name;
    struct TextAttr *textattr;
    ULONG	    flags;
{
    register struct MenuItem	*item;
    SHORT			temp;
    void			*mymh = NULL;

    GUESS
	QUIF( !mhptr );
	item = chainAllocMem( &mymh, (ULONG)sizeof(struct MenuItem),
				    MEMF_PUBLIC | MEMF_CLEAR );
	QUIF( !item );
	if( flags & ITEMTEXT ) {
	    item->ItemFill = (APTR) gimmeIntuiText( &mymh, name, textattr, 0 );
	    QUIF( !item->ItemFill );
	    ((struct IntuiText *)item->ItemFill)->DrawMode |= INVERSVID;
	    if( width < 0 ) {
		width = IntuiTextLength( item->ItemFill ) + XLEEWAY;
	    }
	    if( height < 0 ) {
		if( textattr ) {
		    height = textattr->ta_YSize;
		} else {
		    height = GfxBase->DefaultFont->tf_YSize;
		}
	    }
	} else {
	    item->ItemFill = (APTR) name;
	    if( flags & HIGHIMAGE ) {
		item->SelectFill = (APTR) textattr;
	    }
	    if( width < 0 ) {
		if( (struct Image *) name ) {
		    width = ((struct Image *)name)->Width;
		}
		if( (struct Image *) item->SelectFill ) {
		    temp = ((struct Image *)item->SelectFill)->Width;
		    if( temp > width ) {
			width = temp;
		    }
		}
	    }
	    if( height < 0 ) {
		if( (struct Image *) name ) {
		    height = ((struct Image *)name)->Height;
		}
		if( (struct Image *) item->SelectFill ) {
		    temp = ((struct Image *)item->SelectFill)->Height;
		    if( temp > height ) {
			height = temp;
		    }
		}
	    }
	}
	if( flags & CHECKIT ) {
	    width += CHECKWIDTH;
	}
	if( flags & COMMSEQ ) {
	    width += COMMWIDTH + 4;	/* separate text/image from commseq */
	}
	item->LeftEdge = left;
	item->Width = width;
	item->Height = height;
	item->Flags = flags;
	item->Command = command;
	linkChainMem( mhptr, mymh );
	return( item );
    ENDGUESS
    if( mymh ) {
	chainFreeMem( mymh );
    }
    return( NULL );
} /* gimmeMenuItem */
