/* 
 * The following is a modified version of
 *
 * tkFrame.c --
 *
 * Modifications are copyright (c) 1994 Malcolm Beattie.
 * You may distribute under the terms of the GNU General Public License,
 * as specified in the README file.
 *
 *	This module implements "frame" widgets for the Tk
 *	toolkit.  Frames are windows with a background color
 *	and possibly a 3-D effect, but no other attributes.
 *
 * Copyright (c) 1990-1993 The Regents of the University of California.
 * All rights reserved.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and its documentation for any purpose, provided that the
 * above copyright notice and the following two paragraphs appear in
 * all copies of this software.
 * 
 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

#ifndef lint
static char rcsid[] = "$Id: tkpFrame.c,v 1.1 1994/09/05 16:03:30 mbeattie Exp $";
#endif

/* $Log: tkpFrame.c,v $
 * Revision 1.1  1994/09/05  16:03:30  mbeattie
 * Initial revision
 *
 */

#include "default.h"
#include "tkConfig.h"
#include "tkInt.h"
#include "tkperl.h"

WidgetClass frameClassRec;
I32 frameMethods[] =
{
    IX_ACTIVATE, IX_ADD, IX_CONFIGURE, IX_GET, IX_SET, IX_EOL
};

WidgetClass toplevelClassRec;
/* same methods as frame */

/*
 * A data structure of the following type is kept for each
 * frame that currently exists for this process:
 */

typedef struct {
    Tk_Window tkwin;		/* Window that embodies the frame.  NULL
				 * means that the window has been destroyed
				 * but the data structures haven't yet been
				 * cleaned up.*/
    Display *display;		/* Display containing widget.  Used, among
				 * other things, so that resources can be
				 * freed even after tkwin has gone away. */
    Tk_Uid screenName;		/* If this window isn't a toplevel window
				 * then this is NULL;  otherwise it gives
				 * the name of the screen on which window
				 * is displayed. */
    Tk_3DBorder border;		/* Structure used to draw 3-D border and
				 * background. */
    int borderWidth;		/* Width of 3-D border (if any). */
    int relief;			/* 3-d effect: TK_RELIEF_RAISED etc. */
    int width;			/* Width to request for window.  <= 0 means
				 * don't request any size. */
    int height;			/* Height to request for window.  <= 0 means
				 * don't request any size. */
    char *geometry;		/* Geometry that user requested.  NULL
				 * means use width and height instead. 
				 * Malloc'ed. */
    Cursor cursor;		/* Current cursor for window, or None. */
    int flags;			/* Various flags;  see below for
				 * definitions. */
} Frame;

/*
 * Flag bits for frames:
 *
 * REDRAW_PENDING:		Non-zero means a DoWhenIdle handler
 *				has already been queued to redraw
 *				this window.
 * CLEAR_NEEDED;		Need to clear the window when redrawing.
 */

#define REDRAW_PENDING		1
#define CLEAR_NEEDED		2

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_BORDER, "-background", "background", "Background",
	DEF_FRAME_BG_COLOR, Tk_Offset(Frame, border), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
	DEF_FRAME_BG_MONO, Tk_Offset(Frame, border), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
	DEF_FRAME_BORDER_WIDTH, Tk_Offset(Frame, borderWidth), 0},
    {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor",
	DEF_FRAME_CURSOR, Tk_Offset(Frame, cursor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-geometry", "geometry", "Geometry",
	DEF_FRAME_GEOMETRY, Tk_Offset(Frame, geometry), TK_CONFIG_NULL_OK},
    {TK_CONFIG_PIXELS, "-height", "height", "Height",
	DEF_FRAME_HEIGHT, Tk_Offset(Frame, height), 0},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief",
	DEF_FRAME_RELIEF, Tk_Offset(Frame, relief), 0},
    {TK_CONFIG_PIXELS, "-width", "width", "Width",
	DEF_FRAME_WIDTH, Tk_Offset(Frame, width), 0},
    {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
	(char *) NULL, 0, 0}
};


/*
 * Forward declarations for procedures defined later in this file:
 */

STATIC void	TkpConfigureFrame _ANSI_ARGS_((Frame *framePtr, int sp,
                    int items, int flags));
STATIC void	DestroyFrame _ANSI_ARGS_((ClientData clientData));
STATIC void	DisplayFrame _ANSI_ARGS_((ClientData clientData));
STATIC void	FrameEventProc _ANSI_ARGS_((ClientData clientData,
		    XEvent *eventPtr));
STATIC void	MapFrame _ANSI_ARGS_((ClientData clientData));
ClientData	TkpInitFrame _ANSI_ARGS_((Tk_Window tkwin, int toplevel,
		    int sp, int items));

int
Tk_FrameCmd(clientData, interp, argc, argv)
    ClientData clientData;	/* Main window associated with
				 * interpreter. */
    Tcl_Interp *interp;		/* Current interpreter. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings. */
{
    croak("shouldn't call Tk_FrameCmd");
    /* NOTREACHED */
}

/*
 *--------------------------------------------------------------
 *
 * TkpFrameCmd --
 *
 *	This procedure is invoked to process the "frame" and
 *	"toplevel" commands.  See the user documentation for
 *	details on what it does.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

int
TkpFrameCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    register Frame *framePtr;
    Tk_Window new;
    char *pathname, *className, *screen;    
    int i;
    Tk_Uid screenUid;
    WidgetClass *classptr;
    
    if (items < 1)
	croak("wrong # args for frame or toplevel");


    classptr = (ix == 't') ? &toplevelClassRec : &frameClassRec;
    
    /*
     * The code below is a special hack that extracts a few key
     * options from the stack now, rather than letting
     * TkpConfigureFrame do it.  This is necessary because we have
     * to know the window's screen (if it's top-level) and its
     * class before creating the window.
     */

    screen = NULL;
    className = classptr->package;
    for (i = 2; i < items; i++) {
	if (strcmp(SvPV(st[i], na), "-class") == 0)
	{
	    className = SvPV(st[i + 1], na);
	    st[i] = &sv_undef;
	    st[i + 1] = &sv_undef;
	}
	else if (ix == 't' && strcmp(SvPV(st[i], na), "-screen") == 0)
	{
	    screen = SvPV(st[i + 1], na);
	    st[i] = &sv_undef;
	    st[i + 1] = &sv_undef;
	}	
    }
    
    /*
     * Provide a default screen for top-level windows (same as screen
     * of parent window).
     */

    if (ix == 't' && screen == NULL)
	screen = "";

    screenUid = screen ? Tk_GetUid(screen) : NULL;

    /*
     * Create the window.
     */

    pathname = TkpGenPathname(st[1]);
    new = Tk_CreateWindowFromPath(tclinterp, mainwin, pathname, screenUid);
    if (!new)
        croak("failed to create window");
    
    Tk_SetClass(new, className);
#if 0
    framePtr = (Frame *) ckalloc(sizeof(Frame));
    framePtr->tkwin = new;
    framePtr->display = Tk_Display(new);
    framePtr->screenName = screenUid;
    framePtr->border = NULL;
    framePtr->borderWidth = 0;
    framePtr->relief = TK_RELIEF_FLAT;
    framePtr->width = 0;
    framePtr->height = 0;
    framePtr->geometry = NULL;
    framePtr->cursor = None;
    framePtr->flags = 0;
    Tk_CreateEventHandler(framePtr->tkwin, ExposureMask|StructureNotifyMask,
	    FrameEventProc, (ClientData) framePtr);
    TkpCreateWidgetHash(framePtr->tkwin, (ClientData) framePtr);
    TkpConfigureFrame(framePtr, sp + 1, items - 1, 0);

    /*
     * If the above fails, we ought to Tk_DestroyWindow(framePtr->tkwin)
     * but I've mucked up error propagation. Oops.
     */

#endif
    framePtr = (Frame *) TkpInitFrame(new, (screenUid != NULL),
				      sp + 1, items - 1);
#if 0
    if (screenUid)
	Tk_DoWhenIdle(MapFrame, (ClientData) framePtr);
#endif

    st[0] = sv_2mortal(NewWidgetRef(Tk_PathName(framePtr->tkwin),
				    classptr->stash));
    return sp;
}
/*
 *----------------------------------------------------------------------
 *
 * TkpInitFrame --
 *
 *	This procedure initializes a frame or toplevel widget.  It's
 *	separate from TkpFrameCmd so that it can be used for the
 *	main window, which has already been created elsewhere.
 *
 * Side effects:
 *	A widget record gets allocated, handlers get set up, etc..
 *
 *----------------------------------------------------------------------
 */

ClientData
TkpInitFrame(tkwin, toplevel, sp, items)
    Tk_Window tkwin;			/* Window to use for frame or
					 * top-level.   Caller must already
					 * have set window's class. */
    int toplevel;			/* Non-zero means that this is a
					 * top-level window, 0 means it's a
					 * frame. */
    int sp;
    int items;
{
    register Frame *framePtr;

    framePtr = (Frame *) ckalloc(sizeof(Frame));
    framePtr->tkwin = tkwin;
    framePtr->display = Tk_Display(tkwin);
    framePtr->border = NULL;
    framePtr->borderWidth = 0;
    framePtr->relief = TK_RELIEF_FLAT;
    framePtr->width = 0;
    framePtr->height = 0;
    framePtr->geometry = NULL;
    framePtr->cursor = None;
    framePtr->flags = 0;
    Tk_CreateEventHandler(framePtr->tkwin, ExposureMask|StructureNotifyMask,
	    FrameEventProc, (ClientData) framePtr);
    TkpCreateWidgetHash(framePtr->tkwin, (ClientData) framePtr);
    TkpConfigureFrame(framePtr, sp, items, 0);

    /*
     * If the above fails, we ought to Tk_DestroyWindow(framePtr->tkwin)
     * but I've mucked up error propagation. Oops.
     */

    if (toplevel)
	Tk_DoWhenIdle(MapFrame, (ClientData) framePtr);
    return (ClientData) framePtr;
}

/*
 *--------------------------------------------------------------
 *
 * TkpFrameWidgetCmd --
 *
 *	This procedure is invoked to process the command
 *	that corresponds to a frame widget.  See the user
 *	documentation for details on what it does.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */


I32 TkpFrameWidgetCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    static char *wanted = "Frame";
    static U32 wantedlen = 5;
    Frame *framePtr;
    
    if (items < 1)
        croak("wrong # args");
    
    if (!WrefToWidget(st[1], 0, (ClientData *) &framePtr, wanted, wantedlen))
        croak("non-widget argument passed");
    
    Tk_Preserve((ClientData) framePtr);

    switch (ix)
    {
      case IX_CONFIGURE:
        if (items == 1)
            sp = TkpConfigureInfo(sp, framePtr->tkwin, configSpecs,
				  (char *) framePtr, (char *) NULL, 0);
        else if (items == 2)
            sp = TkpConfigureInfo(sp, framePtr->tkwin, configSpecs,
				  (char *) framePtr, SvPV(st[2], na), 0);
	else
	    TkpConfigureFrame(framePtr, sp + 1, items - 1,
			      TK_CONFIG_ARGV_ONLY);

	break;

      default:
        croak("bad ix passed");
        /* NOTREACHED */
    }

    RECOVERSTACK;
    Tk_Release((ClientData) framePtr);
    return sp;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyFrame --
 *
 *	This procedure is invoked by Tk_EventuallyFree or Tk_Release
 *	to clean up the internal structure of a frame at a safe time
 *	(when no-one is using it anymore).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Everything associated with the frame is freed up.
 *
 *----------------------------------------------------------------------
 */

static void
DestroyFrame(clientData)
    ClientData clientData;	/* Info about frame widget. */
{
    register Frame *framePtr = (Frame *) clientData;

    Tk_FreeOptions(configSpecs, (char *) framePtr, framePtr->display, 0);
    ckfree((char *) framePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkpConfigureFrame --
 *
 *	This procedure is called to process the perl stack, plus
 *	the Tk option database, in order to configure (or
 *	reconfigure) a frame widget.
 *
 * Side effects:
 *	Configuration information, such as text string, colors, font,
 *	etc. get set for framePtr;  old resources get freed, if there
 *	were any.
 *
 *----------------------------------------------------------------------
 */

static void
TkpConfigureFrame(framePtr, sp, items, flags)
    register Frame *framePtr;	/* Information about widget;  may or may
				 * not already have values for some fields. */
    int sp;
    int items;
    int flags;			/* Flags to pass to Tk_ConfigureWidget. */
{
    TkpConfigureWidget(framePtr->tkwin, configSpecs,
		       sp, items, (char *) framePtr, flags);

    Tk_SetBackgroundFromBorder(framePtr->tkwin, framePtr->border);
    Tk_SetInternalBorder(framePtr->tkwin, framePtr->borderWidth);
    if (framePtr->geometry != NULL)
    {
	int height, width;

	if (sscanf(framePtr->geometry, "%dx%d", &width, &height) != 2)
	    croak("bad geometry specification");
	Tk_GeometryRequest(framePtr->tkwin, width, height);
    }
    else if ((framePtr->width > 0) && (framePtr->height > 0))
	Tk_GeometryRequest(framePtr->tkwin, framePtr->width, framePtr->height);

    if (Tk_IsMapped(framePtr->tkwin)
	    && !(framePtr->flags & REDRAW_PENDING)) {
	Tk_DoWhenIdle(DisplayFrame, (ClientData) framePtr);
	framePtr->flags |= REDRAW_PENDING|CLEAR_NEEDED;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DisplayFrame --
 *
 *	This procedure is invoked to display a frame widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the frame in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

static void
DisplayFrame(clientData)
    ClientData clientData;	/* Information about widget. */
{
    register Frame *framePtr = (Frame *) clientData;
    register Tk_Window tkwin = framePtr->tkwin;

    framePtr->flags &= ~REDRAW_PENDING;
    if ((framePtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
	return;
    }

    if (framePtr->flags & CLEAR_NEEDED) {
	XClearWindow(framePtr->display, Tk_WindowId(tkwin));
	framePtr->flags &= ~CLEAR_NEEDED;
    }
    if ((framePtr->border != NULL)
	    && (framePtr->relief != TK_RELIEF_FLAT)) {
	Tk_Draw3DRectangle(framePtr->display, Tk_WindowId(tkwin),
		framePtr->border, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin),
		framePtr->borderWidth, framePtr->relief);
    }
}

/*
 *--------------------------------------------------------------
 *
 * FrameEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher on
 *	structure changes to a frame.  For frames with 3D
 *	borders, this procedure is also invoked for exposures.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get
 *	cleaned up.  When it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
FrameEventProc(clientData, eventPtr)
    ClientData clientData;	/* Information about window. */
    register XEvent *eventPtr;	/* Information about event. */
{
    register Frame *framePtr = (Frame *) clientData;

    if ((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) {
	if ((framePtr->relief != TK_RELIEF_FLAT) && (framePtr->tkwin != NULL)
		&& !(framePtr->flags & REDRAW_PENDING)) {
	    Tk_DoWhenIdle(DisplayFrame, (ClientData) framePtr);
	    framePtr->flags |= REDRAW_PENDING;
	}
    } else if (eventPtr->type == DestroyNotify) {
	TkpDeleteWidgetHash(framePtr->tkwin);
	framePtr->tkwin = NULL;
	if (framePtr->flags & REDRAW_PENDING) {
	    Tk_CancelIdleCall(DisplayFrame, (ClientData) framePtr);
	}
	Tk_CancelIdleCall(MapFrame, (ClientData) framePtr);
	Tk_EventuallyFree((ClientData) framePtr, DestroyFrame);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MapFrame --
 *
 *	This procedure is invoked as a when-idle handler to map a
 *	newly-created top-level frame.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The frame given by the clientData argument is mapped.
 *
 *----------------------------------------------------------------------
 */

static void
MapFrame(clientData)
    ClientData clientData;		/* Pointer to frame structure. */
{
    Frame *framePtr = (Frame *) clientData;

    /*
     * Wait for all other background events to be processed before
     * mapping window.  This ensures that the window's correct geometry
     * will have been determined before it is first mapped, so that the
     * window manager doesn't get a false idea of its desired geometry.
     */

    Tk_Preserve((ClientData) framePtr);
    while (1) {
	if (Tk_DoOneEvent(TK_IDLE_EVENTS) == 0) {
	    break;
	}

	/*
	 * After each event, make sure that the window still exists
	 * and quit if the window has been destroyed.
	 */

	if (framePtr->tkwin == NULL) {
	    Tk_Release((ClientData) framePtr);
	    return;
	}
    }
    Tk_MapWindow(framePtr->tkwin);
    Tk_Release((ClientData) framePtr);
}

void bootC_Frame _((void))
{
    char *file = __FILE__;

    frameClassRec.package = "Frame";
    frameClassRec.stash = Nullhv; /* filled in by init_widget */
    frameClassRec.newwidgetproc = TkpFrameCmd;
    frameClassRec.newix = 'f';
    frameClassRec.widgetcmdproc = TkpFrameWidgetCmd;
    frameClassRec.methods = frameMethods;
    frameClassRec.filename = file;
    init_widget(&frameClassRec);

    toplevelClassRec.package = "Toplevel";
    toplevelClassRec.stash = Nullhv; /* filled in by init_widget */
    toplevelClassRec.newwidgetproc = TkpFrameCmd;
    toplevelClassRec.newix = 't';
    toplevelClassRec.widgetcmdproc = TkpFrameWidgetCmd;
    toplevelClassRec.methods = frameMethods; /* sic */
    toplevelClassRec.filename = file;
    init_widget(&toplevelClassRec);
}

