/* igadgets.c -- common gadget building utilities	:ts=4 */

/*
Copyright (c) 1989 Commodore-Amiga, Inc.

Executables based on this information may be used in software
for Commodore Amiga computers. All other rights reserved.
This information is provided "as is"; no warranties are made.
All use is at your own risk, and no liability or responsibility
is assumed.
*/

#include "sysall.h"

#define D(x)	;
#define DF(x)	;

struct Gadget	*CreateGadget();

/*
 * doesn't setup Activation field, except for BOOLEXTEND
 * image parameter is required
 */
struct Gadget *
CreateBoolGadget( image, mask, id, str )
struct Image	*image;
UWORD			*mask;
int				id;			/* user ID	*/
UBYTE			*str;		/* create intuitext, position 0,0 */
{
	struct Gadget	*g = NULL;
	struct BoolInfo	*bi;
	int				bisize;

	bisize = mask? (sizeof (struct BoolInfo)): 0;

	if (image &&	
		(g=CreateGadget(image->Width, image->Height, id, str, bisize)))
	{
		g->GadgetType = BOOLGADGET;
		g->Flags = GADGHCOMP | GADGIMAGE;
		g->GadgetRender = (APTR) image;

		/* init BoolInfo	*/
		if ( mask )
		{
			bi = (struct BoolInfo *) g->SpecialInfo;
			D( printf("CBG: mask at %lx bi: %lx\n", mask, bi ));
			g->Activation |= BOOLEXTEND;
			bi->Flags = BOOLMASK;
			bi->Mask = mask;
			bi->Reserved = 0;
		}
	}

	D( printf("CBG returns %lx\n", g ) );
	return ( g );
}


#define GTSIZE (sizeof(struct Gadget)+sizeof(struct IntuiText))
#define GSIZE (sizeof(struct Gadget))

#define GADGET_SIZE( text ) ( (text)? GTSIZE: GSIZE )

struct Gadget	*
CreateGadget( w, h, id, str, sisize )
UBYTE	*str;
{
	UWORD			*gheader;
    struct Gadget	*g;
    struct IntuiText	*it = NULL;
	APTR			sinfo = NULL;
	int				totalsize;

	totalsize = GADGET_SIZE( str ) + sizeof ( UWORD * ) + sisize;
	D( printf("CG: w %d, h %d, id %d\n", w, h, id ) );
	D( printf("CG: totalsize = %d\n", totalsize ) );

    if ( gheader=(UWORD *) AllocMem((long) totalsize,(long) MEMF_CLEAR))
    {
		*gheader = totalsize;

		g = (struct Gadget *) ( gheader + 1 );	/* gadget follow header	*/

		if ( str )
		{
			it = (struct IntuiText *) ( g + 1 );

			initText( it, str );

			sinfo = (APTR) (it + 1);	/* follows itext ... */
		}
		else  sinfo = (APTR) (g + 1);	/* or gadget, if no itext */

		/* now init the gadget itself	*/
		g->Width = w;
		g->Height = h;

		g->GadgetText = it;
		g->SpecialInfo = sinfo;

		g->GadgetID = id;
    }
    return ( g );
}

FreeGadgets( g )
struct Gadget *g;
{
	UWORD			*sizeword;
	struct Gadget	*nextg;

	while ( g )
	{
		nextg = g->NextGadget;

		sizeword = (UWORD *) g;
		sizeword--;

		DF( printf("freeing gadget %lx, size %d\n", g, *sizeword ) );

		FreeMem( g, (LONG) *sizeword );
		g = nextg;
	}
}

static initText( it, str )
struct IntuiText	*it;
UBYTE			*str;
{
    it->FrontPen = 1;
    it->DrawMode = JAM1;
    it->IText = str;
    it->LeftEdge = 0;
    it->TopEdge = 0;
}

