/* 
 * tkFrame.c --
 *
 *	This module implements "frame"  and "toplevel" widgets for
 *	the Tk toolkit.  Frames are windows with a background color
 *	and possibly a 3-D effect, but not much else in the way of
 *	attributes.
 *
 * Copyright (c) 1990-1994 The Regents of the University of California.
 * Copyright (c) 1994 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

/* TkWin version 0.3 -- Tk for Windows
 * Copyright (C) 1994 K. K. Kubota
 * Mathematical Sciences Computing Facility, University of Kentucky,
 * Lexington, KY 40506, USA (e-mail: ken@ms.uky.edu)
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose is granted without fee, provided that the above copyright notice
 * and the following paragraph appear in all copies of this software
 * and supporting documentation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY, even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  In no event shall the author be
 * liable to any party for direct, indirect, special, incidental, or
 * consequential damages arising out of the use of this software and its
 * documentation.
 */

static char sccsid[] = "@(#) tkFrame.c 1.49 94/12/19 08:53:09";

#include "default.h"
#include "tkPort.h"
#include "tkInt.h"

/*
 * 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. */
#ifndef TCL_MSDOS_PORT
    Display *display;		/* Display containing widget.  Used, among
				 * other things, so that resources can be
				 * freed even after tkwin has gone away. */
#endif
    Tcl_Interp *interp;		/* Interpreter associated with
				 * widget.  Used to delete widget
				 * command. */
    char *className;		/* Class name for widget (from configuration
				 * option).  Malloc-ed. */
    int mask;			/* Either FRAME or TOPLEVEL;  used to select
				 * which configuration options are valid for
				 * widget. */
    char *screenName;		/* Screen on which widget is created.  Non-null
				 * only for top-levels.  Malloc-ed, may be
				 * NULL. */
    char *visualName;		/* Textual description of visual for window,
				 * from -visual option.  Malloc-ed, may be
				 * NULL. */
    char *colormapName;		/* Textual description of colormap for window,
				 * from -colormap option.  Malloc-ed, may be
				 * NULL. */
#ifndef TCL_MSDOS_PORT
    Colormap colormap;		/* If not None, identifies a colormap
				 * allocated for this window, which must be
				 * freed when the window is deleted. */
#endif
    Tk_3DBorder border;		/* Structure used to draw 3-D border and
				 * background.  NULL means no background
				 * or border. */
    int borderWidth;		/* Width of 3-D border (if any). */
    int relief;			/* 3-d effect: TK_RELIEF_RAISED etc. */
    int highlightWidth;		/* Width in pixels of highlight to draw
				 * around widget when it has the focus.
				 * 0 means don't draw a highlight. */
    XColor *highlightColorPtr;	/* Color for drawing traversal highlight. */
#ifdef TCL_MSDOS_PORT
    HBRUSH highlightHBr;
#else
    GC highlightGC;		/* For drawing traversal highlight. */
#endif
    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. */
    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.
 * GOT_FOCUS:			Non-zero means this widget currently
 *				has the input focus.
 */

#define REDRAW_PENDING		1
#define CLEAR_NEEDED		2
#define GOT_FOCUS		4

/*
 * The following flag bits are used so that there can be separate
 * defaults for some configuration options for frames and toplevels.
 */

#define FRAME		TK_CONFIG_USER_BIT
#define TOPLEVEL	(TK_CONFIG_USER_BIT << 1)
#define BOTH		(FRAME | TOPLEVEL)

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_BORDER, "-background", "background", "Background",
	DEF_FRAME_BG_COLOR, Tk_Offset(Frame, border),
	BOTH|TK_CONFIG_COLOR_ONLY|TK_CONFIG_NULL_OK},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
	DEF_FRAME_BG_MONO, Tk_Offset(Frame, border),
	BOTH|TK_CONFIG_MONO_ONLY|TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL,
	(char *) NULL, 0, BOTH},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL,
	(char *) NULL, 0, BOTH},
    {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
	DEF_FRAME_BORDER_WIDTH, Tk_Offset(Frame, borderWidth), BOTH},
    {TK_CONFIG_STRING, "-class", "class", "Class",
	DEF_FRAME_CLASS, Tk_Offset(Frame, className), FRAME},
    {TK_CONFIG_STRING, "-class", "class", "Class",
	DEF_TOPLEVEL_CLASS, Tk_Offset(Frame, className), TOPLEVEL},
#ifndef TCL_MSDOS_PORT
    {TK_CONFIG_STRING, "-colormap", "colormap", "Colormap",
	DEF_FRAME_COLORMAP, Tk_Offset(Frame, colormapName),
	BOTH|TK_CONFIG_NULL_OK},
#endif
    {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor",
	DEF_FRAME_CURSOR, Tk_Offset(Frame, cursor), BOTH|TK_CONFIG_NULL_OK},
    {TK_CONFIG_PIXELS, "-height", "height", "Height",
	DEF_FRAME_HEIGHT, Tk_Offset(Frame, height), BOTH},
    {TK_CONFIG_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
	DEF_FRAME_HIGHLIGHT, Tk_Offset(Frame, highlightColorPtr), BOTH},
    {TK_CONFIG_PIXELS, "-highlightthickness", "highlightThickness",
	"HighlightThickness",
	DEF_FRAME_HIGHLIGHT_WIDTH, Tk_Offset(Frame, highlightWidth), BOTH},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief",
	DEF_FRAME_RELIEF, Tk_Offset(Frame, relief), BOTH},
    {TK_CONFIG_STRING, "-screen", "screen", "Screen",
	DEF_TOPLEVEL_SCREEN, Tk_Offset(Frame, screenName),
	TOPLEVEL|TK_CONFIG_NULL_OK},
#ifndef TCL_MSDOS_PORT
    {TK_CONFIG_STRING, "-visual", "visual", "Visual",
	DEF_FRAME_VISUAL, Tk_Offset(Frame, visualName),
	BOTH|TK_CONFIG_NULL_OK},
#endif
    {TK_CONFIG_PIXELS, "-width", "width", "Width",
	DEF_FRAME_WIDTH, Tk_Offset(Frame, width), BOTH},
    {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
	(char *) NULL, 0, 0}
};

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

static int	ConfigureFrame _ANSI_ARGS_((Tcl_Interp *interp,
		    Frame *framePtr, int argc, char **argv, 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 int	FrameWidgetCmd _ANSI_ARGS_((ClientData clientData,
		    Tcl_Interp *interp, int argc, char **argv));
static void	MapFrame _ANSI_ARGS_((ClientData clientData));

/*
 *--------------------------------------------------------------
 *
 * Tk_FrameCmd --
 *
 *	This procedure is invoked to process the "frame" and
 *	"toplevel" Tcl commands.  See the user documentation for
 *	details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

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. */
{
    Tk_Window tkwin = (Tk_Window) clientData;
    Frame *framePtr;
    Tk_Window new = NULL;
#ifdef TCL_MSDOS_PORT
    char *className, *screenName, *arg;
#else
    char *className, *screenName, *visualName, *colormapName, *arg;
#endif
    int i, c, length, toplevel, depth;
#ifndef TCL_MSDOS_PORT
    Colormap colormap;
    Visual *visual;
    Display *display;
#endif

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # args: should be \"",
		argv[0], " pathName ?options?\"", (char *) NULL);
	return TCL_ERROR;
    }

    /*
     * Pre-process the argument list.  Scan through it to find any
     * "-class", "-screen", "-visual", and "-newcmap" options.  These
     * arguments need to be processed specially, before the window
     * is configured using the usual Tk mechanisms.
     */

    toplevel = (argv[0][0] == 't');
#ifdef TCL_MSDOS_PORT
    className = screenName = NULL;
#else
    className = colormapName = screenName = visualName = NULL;
#endif
    for (i = 2; i < argc; i += 2) {
	arg = argv[i];
	length = strlen(arg);
	if (length < 2) {
	    continue;
	}
	c = arg[1];
	if ((c == 'c') && (strncmp(arg, "-class", strlen(arg)) == 0)
		&& (length >= 3)) {
	    className = argv[i+1];
#ifndef TCL_MSDOS_PORT
	} else if ((c == 'c')
		&& (strncmp(arg, "-colormap", strlen(arg)) == 0)) {
	    colormapName = argv[i+1];
#endif
	} else if ((c == 's') && toplevel
		&& (strncmp(arg, "-screen", strlen(arg)) == 0)) {
	    screenName = argv[i+1];
#ifndef TCL_MSDOS_PORT
	} else if ((c == 'v')
		&& (strncmp(arg, "-visual", strlen(arg)) == 0)) {
	    visualName = argv[i+1];
#endif
	}
    }

    /*
     * Create the window, and deal with the special options -classname,
     * -colormap, -screenname, and -visual.  The order here is tricky,
     * because we want to allow values for these options to come from
     * the database, yet we can't do that until the window is created.
     */

    if (screenName == NULL) {
	screenName = (toplevel) ? "" : NULL;
    }
    new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], screenName);
    if (new == NULL) {
	goto error;
    }
    if (className == NULL) {
	className = Tk_GetOption(new, "class", "Class");
	if (className == NULL) {
	    className = (toplevel) ? "Toplevel" : "Frame";
	}
    }
    Tk_SetClass(new, className);
#ifndef TCL_MSDOS_PORT
    if (visualName == NULL) {
	visualName = Tk_GetOption(new, "visual", "Visual");
    }
    if (colormapName == NULL) {
	colormapName = Tk_GetOption(new, "colormap", "Colormap");
    }
    colormap = None;
    if (visualName != NULL) {
	visual = Tk_GetVisual(interp, new, visualName, &depth,
		(colormapName == NULL) ? &colormap : (Colormap *) NULL);
	if (visual == NULL) {
	    goto error;
	}
	Tk_SetWindowVisual(new, visual, depth, colormap);
    }
    if (colormapName != NULL) {
	colormap = Tk_GetColormap(interp, new, colormapName);
	if (colormap == None) {
	    goto error;
	}
	Tk_SetWindowColormap(new, colormap);
    }
#endif

    /*
     * Create the widget record, process configuration options, and
     * create event handlers.  Then fill in a few additional fields
     * in the widget record from the special options.
     */

#ifndef TCL_MSDOS_PORT
    display = Tk_Display(new);
#endif
    framePtr = (Frame *) TkInitFrame(interp, new, toplevel, argc-2, argv+2);
    if (framePtr == NULL) {
#ifndef TCL_MSDOS_PORT
	if (colormap != None) {
	    Tk_FreeColormap(display, colormap);
	}
#endif
	return TCL_ERROR;
    }
#ifndef TCL_MSDOS_PORT
    framePtr->colormap = colormap;
#endif
    return TCL_OK;

    error:
    if (new != NULL) {
	Tk_DestroyWindow(new);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * TkInitFrame --
 *
 *	This procedure initializes a frame or toplevel widget.  It's
 *	separate from Tk_FrameCmd so that it can be used for the
 *	main window, which has already been created elsewhere.
 *
 * Results:
 *	Returns NULL if an error occurred while initializing the
 *	frame.  Otherwise returns a pointer to the frame's widget
 *	record (for use by Tk_FrameCmd, if it was the caller).
 *
 * Side effects:
 *	A widget record gets allocated, handlers get set up, etc..
 *
 *----------------------------------------------------------------------
 */

char *
TkInitFrame(interp, tkwin, toplevel, argc, argv)
    Tcl_Interp *interp;			/* Interpreter associated with the
					 * application. */
    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 argc;				/* Number of configuration arguments
					 * (not including class command and
					 * window name). */
    char *argv[];			/* Configuration arguments. */
{
    register Frame *framePtr;

    framePtr = (Frame *) ckalloc(sizeof(Frame));
    framePtr->tkwin = tkwin;
#ifndef TCL_MSDOS_PORT
    framePtr->display = Tk_Display(tkwin);
#endif
    framePtr->interp = interp;
    framePtr->className = NULL;
    framePtr->mask = (toplevel) ? TOPLEVEL : FRAME;
    framePtr->screenName = NULL;
#ifndef TCL_MSDOS_PORT
    framePtr->visualName = NULL;
    framePtr->colormapName = NULL;
    framePtr->colormap = None;
#endif
    framePtr->border = NULL;
    framePtr->borderWidth = 0;
    framePtr->relief = TK_RELIEF_FLAT;
    framePtr->highlightWidth = 0;
    framePtr->highlightColorPtr = NULL;
#ifdef TCL_MSDOS_PORT
    framePtr->highlightHBr = None;
#else
    framePtr->highlightGC = None;
#endif
    framePtr->width = 0;
    framePtr->height = 0;
    framePtr->cursor = None;
    framePtr->flags = 0;
    Tk_CreateEventHandler(framePtr->tkwin,
	    ExposureMask|StructureNotifyMask|FocusChangeMask,
	    FrameEventProc, (ClientData) framePtr);
    Tcl_CreateCommand(interp, Tk_PathName(framePtr->tkwin),
	    FrameWidgetCmd, (ClientData) framePtr, (void (*)()) NULL);

    if (ConfigureFrame(interp, framePtr, argc, argv, 0) != TCL_OK) {
	Tk_DestroyWindow(framePtr->tkwin);
	return NULL;
    }
    if (toplevel) {
	Tk_DoWhenIdle(MapFrame, (ClientData) framePtr);
    }
    interp->result = Tk_PathName(framePtr->tkwin);
    return (char *) framePtr;
}

/*
 *--------------------------------------------------------------
 *
 * FrameWidgetCmd --
 *
 *	This procedure is invoked to process the Tcl command
 *	that corresponds to a frame widget.  See the user
 *	documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
FrameWidgetCmd(clientData, interp, argc, argv)
    ClientData clientData;	/* Information about frame widget. */
    Tcl_Interp *interp;		/* Current interpreter. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings. */
{
    register Frame *framePtr = (Frame *) clientData;
    int result = TCL_OK;
    int length;
    char c, i;

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # args: should be \"",
		argv[0], " option ?arg arg ...?\"", (char *) NULL);
	return TCL_ERROR;
    }
    Tk_Preserve((ClientData) framePtr);
    c = argv[1][0];
    length = strlen(argv[1]);
    if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0)
	    && (length >= 2)) {
	if (argc != 3) {
	    Tcl_AppendResult(interp, "wrong # args: should be \"",
		    argv[0], " cget option\"",
		    (char *) NULL);
	    result = TCL_ERROR;
	    goto done;
	}
	result = Tk_ConfigureValue(interp, framePtr->tkwin, configSpecs,
		(char *) framePtr, argv[2], framePtr->mask);
    } else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)
	    && (length >= 2)) {
	if (argc == 2) {
	    result = Tk_ConfigureInfo(interp, framePtr->tkwin, configSpecs,
		    (char *) framePtr, (char *) NULL, framePtr->mask);
	} else if (argc == 3) {
	    result = Tk_ConfigureInfo(interp, framePtr->tkwin, configSpecs,
		    (char *) framePtr, argv[2], framePtr->mask);
	} else {
	    /*
	     * Don't allow the options -class, -newcmap, -screen,
	     * or -visual to be changed.
	     */

	    for (i = 2; i < argc; i++) {
		length = strlen(argv[i]);
		if (length < 2) {
		    continue;
		}
		c = argv[i][1];
		if (((c == 'c') && (strncmp(argv[i], "-class", length) == 0)
			&& (length >= 2))
			|| ((c == 'c') && (framePtr->mask == TOPLEVEL)
			&& (strncmp(argv[i], "-colormap", length) == 0))
			|| ((c == 's') && (framePtr->mask == TOPLEVEL)
			&& (strncmp(argv[i], "-screen", length) == 0))
			|| ((c == 'v') && (framePtr->mask == TOPLEVEL)
			&& (strncmp(argv[i], "-visual", length) == 0))) {
		    Tcl_AppendResult(interp, "can't modify ", argv[i],
			    " option after widget is created", (char *) NULL);
		    result = TCL_ERROR;
		    goto done;
		}
	    }
	    result = ConfigureFrame(interp, framePtr, argc-2, argv+2,
		    TK_CONFIG_ARGV_ONLY);
	}
    } else {
	Tcl_AppendResult(interp, "bad option \"", argv[1],
		"\":  must be cget or configure", (char *) NULL);
	result = TCL_ERROR;
    }

    done:
    Tk_Release((ClientData) framePtr);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * 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;

#ifdef TCL_MSDOS_PORT
    if (framePtr->highlightHBr != NULL) {
	DeleteObject(framePtr->highlightHBr);
    }
#else
    if (framePtr->colormap != None) {
	Tk_FreeColormap(framePtr->display, framePtr->colormap);
    }
    if (framePtr->highlightGC != None) {
	Tk_FreeGC(framePtr->display, framePtr->highlightGC);
    }
#endif
#ifdef TCL_MSDOS_PORT
    Tk_FreeOptions(configSpecs, (char *) framePtr,
	    framePtr->mask);
#else
    Tk_FreeOptions(configSpecs, (char *) framePtr, framePtr->display,
	    framePtr->mask);
#endif
    ckfree((char *) framePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureFrame --
 *
 *	This procedure is called to process an argv/argc list, plus
 *	the Tk option database, in order to configure (or
 *	reconfigure) a frame widget.
 *
 * Results:
 *	The return value is a standard Tcl result.  If TCL_ERROR is
 *	returned, then interp->result contains an error message.
 *
 * Side effects:
 *	Configuration information, such as text string, colors, font,
 *	etc. get set for framePtr;  old resources get freed, if there
 *	were any.
 *
 *----------------------------------------------------------------------
 */

static int
ConfigureFrame(interp, framePtr, argc, argv, flags)
    Tcl_Interp *interp;		/* Used for error reporting. */
    register Frame *framePtr;	/* Information about widget;  may or may
				 * not already have values for some fields. */
    int argc;			/* Number of valid entries in argv. */
    char **argv;		/* Arguments. */
    int flags;			/* Flags to pass to Tk_ConfigureWidget. */
{
#ifndef TCL_MSDOS_PORT
    XGCValues gcValues;
    GC newGC;
#endif

    if (Tk_ConfigureWidget(interp, framePtr->tkwin, configSpecs,
	    argc, argv, (char *) framePtr, flags | framePtr->mask) != TCL_OK) {
	return TCL_ERROR;
    }

    if (framePtr->border != NULL) {
	Tk_SetBackgroundFromBorder(framePtr->tkwin, framePtr->border);
    }
    if (framePtr->highlightWidth < 0) {
	framePtr->highlightWidth = 0;
    }
    Tk_SetInternalBorder(framePtr->tkwin,
	    framePtr->borderWidth + framePtr->highlightWidth);
    if (framePtr->highlightWidth > 0) {
#ifdef TCL_MSDOS_PORT
	XColor *cp = framePtr->highlightColorPtr;
	if(framePtr->highlightHBr != NULL)
	   DeleteObject(framePtr->highlightHBr);
	framePtr->highlightHBr =
	   CreateSolidBrush(RGB(cp->peRed, cp->peGreen, cp->peBlue));
#else
	gcValues.foreground = framePtr->highlightColorPtr->pixel;
	newGC = Tk_GetGC(framePtr->tkwin, GCForeground, &gcValues);
	if (framePtr->highlightGC != None) {
	    Tk_FreeGC(framePtr->display, framePtr->highlightGC);
	}
	framePtr->highlightGC = newGC;
#endif
    }
    if ((framePtr->width > 0) || (framePtr->height > 0)) {
	Tk_GeometryRequest(framePtr->tkwin, framePtr->width,
		framePtr->height);
    }

    if (Tk_IsMapped(framePtr->tkwin)) {
	if (!(framePtr->flags & REDRAW_PENDING)) {
	    Tk_DoWhenIdle(DisplayFrame, (ClientData) framePtr);
	}
	framePtr->flags |= REDRAW_PENDING|CLEAR_NEEDED;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * 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;
#ifdef TCL_MSDOS_PORT
    HWND hwnd =((TkWindow *)tkwin)->window;
    HDC hdc=0;
    HBRUSH brush=0, hbrOld;
#ifdef NOTDEF
    BringWindowToTop(hwnd);
#endif
    hdc = GetDC(hwnd);
    SetBkMode(hdc, OPAQUE);
#else
    GC gc;
#endif

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

    if (framePtr->flags & CLEAR_NEEDED) {
#ifdef TCL_MSDOS_PORT
	RECT rect;
	PALETTEENTRY pe = ((TkWindow *)tkwin)->atts.background_pixel;
        brush = CreateSolidBrush(RGB(pe.peRed, pe.peGreen, pe.peBlue));
	UnrealizeObject(brush);
	if((hbrOld = SelectObject(hdc, brush)) == NULL)
	    panic("DisplayFrame: can't select brush");
	GetClientRect(hwnd, &rect);
	FillRect(hdc, &rect, brush);
	SelectObject(hdc, hbrOld);
	DeleteObject(brush);
#else
	XClearWindow(framePtr->display, Tk_WindowId(tkwin));
#endif
	framePtr->flags &= ~CLEAR_NEEDED;
    }
    if ((framePtr->border != NULL)
	    && (framePtr->relief != TK_RELIEF_FLAT)) {
#ifdef TCL_MSDOS_PORT
	Tk_Draw3DRectangle(hdc,
		framePtr->border, framePtr->highlightWidth,
		framePtr->highlightWidth,
		Tk_Width(tkwin) - 2*framePtr->highlightWidth,
		Tk_Height(tkwin) - 2*framePtr->highlightWidth,
		framePtr->borderWidth, framePtr->relief);
#else
	Tk_Draw3DRectangle(framePtr->display, Tk_WindowId(tkwin),
		framePtr->border, framePtr->highlightWidth,
		framePtr->highlightWidth,
		Tk_Width(tkwin) - 2*framePtr->highlightWidth,
		Tk_Height(tkwin) - 2*framePtr->highlightWidth,
		framePtr->borderWidth, framePtr->relief);
#endif
    }
    if (framePtr->highlightWidth != 0) {
#ifdef TCL_MSDOS_PORT
	HBRUSH brush;
	if (framePtr->flags & GOT_FOCUS) {
	    XColor *cp = framePtr->highlightColorPtr;
	    brush = CreateSolidBrush(RGB(cp->peRed, cp->peGreen, cp->peBlue));
	} else {
	    brush = Tk_3DBorderGC(framePtr->border, TK_3D_FLAT_GC);
	}
	TkDrawFocusHighlight(tkwin, brush, framePtr->highlightWidth, hdc);
	if (framePtr->flags & GOT_FOCUS) DeleteObject(brush);
#else
	if (framePtr->flags & GOT_FOCUS) {
	    gc = framePtr->highlightGC;
	} else {
	    gc = Tk_3DBorderGC(framePtr->border, TK_3D_FLAT_GC);
	}
	TkDrawFocusHighlight(tkwin, gc, framePtr->highlightWidth,
		Tk_WindowId(tkwin));
#endif
    }
}

/*
 *--------------------------------------------------------------
 *
 * 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)) {
	goto redraw;
    } else if (eventPtr->type == DestroyNotify) {
	Tcl_DeleteCommand(framePtr->interp, Tk_PathName(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);
    } else if (eventPtr->type == FocusIn) {
	if (eventPtr->xfocus.detail != NotifyPointer) {
	    framePtr->flags |= GOT_FOCUS;
	    if (framePtr->highlightWidth > 0) {
		goto redraw;
	    }
	}
    } else if (eventPtr->type == FocusOut) {
	if (eventPtr->xfocus.detail != NotifyPointer) {
	    framePtr->flags &= ~GOT_FOCUS;
	    if (framePtr->highlightWidth > 0) {
		goto redraw;
	    }
	}
    }
    return;

    redraw:
    if ((framePtr->tkwin != NULL) && !(framePtr->flags & REDRAW_PENDING)) {
	Tk_DoWhenIdle(DisplayFrame, (ClientData) framePtr);
	framePtr->flags |= REDRAW_PENDING;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * 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);
}
