/*
 *  FILE: window.c
 *  Support routines for dynamic (de)allocation of (new)windows.
 *
 *  Public Domain, but keep my name in it as the original author.
 *  31-Aug-88	Jan Sven Trabandt   first release version
 */


#define I_AM_WINDOW
#include "gimmelib/gimmefuncs.h"
#include "gimmelib/window.h"
#include <graphics/gfxbase.h>

extern struct GfxBase *GfxBase;


struct NewWindow *gimmeNewWindow( title, screen, leftedge, topedge,
				    IDCMPflags, flags )
    UBYTE	    *title;
    struct Screen   *screen;
    SHORT	    leftedge, topedge;
    ULONG	    IDCMPflags, flags;
{
    register struct NewWindow	*nw;

    nw = (struct NewWindow *) AllocMem( (ULONG)sizeof(struct NewWindow),
					MEMF_PUBLIC | MEMF_CLEAR );
    if( !nw ) {
	return( NULL );
    }
    nw->DetailPen = GNW_DETAIL_PEN;
    nw->BlockPen  = GNW_BLOCK_PEN;
    nw->IDCMPFlags= IDCMPflags;
    nw->Flags	  = flags;
    nw->Title	  = title;
    nw->MinWidth  = GNW_MIN_WIDTH;
    nw->MinHeight = GNW_MIN_HEIGHT;
    nw->LeftEdge  = leftedge;
    nw->TopEdge   = topedge;
    if( screen ) {
	nw->Type = CUSTOMSCREEN;
	nw->Screen = screen;
	nw->MaxWidth  = screen->Width;
	nw->MaxHeight = screen->Height;
    } else {
	nw->Type = WBENCHSCREEN;
	nw->MaxWidth  = GfxBase->NormalDisplayColumns;
	nw->MaxHeight = GfxBase->NormalDisplayRows;
    }
    nw->Width  = nw->MaxWidth - nw->LeftEdge;
    nw->Height = nw->MaxHeight - nw->TopEdge;
    return( nw );
} /* gimmeNewWindow */


short getRidOfNewWindow( nw )
    struct NewWindow	*nw;
{
#ifdef GIMME_WIMPY
    if( !nw ) {
	return( -1 );
    }
#endif
    FreeMem( nw, (ULONG)sizeof(struct NewWindow) );
    return( 0 );
} /* getRidOfNewWindow */


struct Window *gimmeWindow( nw, depth, width, height )
    struct NewWindow	*nw;
    SHORT   depth, width, height;
{
    struct Window	*window;
    struct NewWindow	*mynw;

    if( !(mynw = nw) ) {
	nw = gimmeNewWindow( NULL, NULL, 0, 1, IDCMP_DEFAULT, FLAGS_DEFAULT );
    }
    for( ;; ) {         /* dummy loop with break at end */
	if( nw ) {
	    if( nw->Flags & SUPER_BITMAP ) {
		if( !(nw->BitMap = gimmeBitMap(depth, width, height)) ) {
		    break;
		}
	    }
	    window = OpenWindow( nw );
	    if( !window ) {
		if( nw->Flags & SUPER_BITMAP ) {
		    getRidOfBitMap( nw->BitMap );
		}
	    } else {
		window->UserData = (BYTE *) nw->BitMap;
	    }
	}
	break;
    } /* for */
    if( !mynw && nw ) {
	getRidOfNewWindow( nw );
    }
    return( window );
} /* gimmeWindow */


short getRidOfWindow( window )
    struct Window   *window;
{
    struct BitMap	*bm = NULL;
    struct IntuiMessage *imsg;

#ifdef GIMME_WIMPY
    if( !window ) {
	return( -1 );
    }
#endif
    if( window->Flags & SUPER_BITMAP ) {
	bm = (struct BitMap *) window->UserData;
    }
    if( window->MenuStrip ) {
	ClearMenuStrip( window );
    }
    while( imsg = (struct IntuiMessage *) GetMsg(window->UserPort) ) {
	ReplyMsg( imsg );
    } /* while */
    CloseWindow( window );
    if( bm ) {
	getRidOfBitMap( bm );
    }
} /* getRidOfWindow */
