/*
 * $Id: entry.c,v 1.14 2004/09/09 01:49:11 jenglish Exp $
 *
 * DERIVED FROM: tk/generic/tkEntry.c r1.35.
 *
 * Copyright (c) 1990-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 2000 Ajuba Solutions.
 * Copyright (c) 2002 ActiveState Corporation.
 * Copyright (c) 2004 Joe English
 *
 * TODO: Validation system not completely right yet.
 */

#include <string.h>
#include <tk.h>
#include <X11/Xatom.h>

#include "tkTheme.h"
#include "widget.h"
#include "compat.h"

/*
 * Extra bits for core.flags:
 */
#define GOT_SELECTION		(WIDGET_USER_FLAG<<1)
#define UPDATE_SCROLLBAR	(WIDGET_USER_FLAG<<2)
#define SYNCING_VARIABLE	(WIDGET_USER_FLAG<<3)
#define VALIDATING		(WIDGET_USER_FLAG<<4)
#define VALIDATION_SET_VALUE	(WIDGET_USER_FLAG<<5)

/*
 * Definitions for -validate option values:
 */
typedef enum validateMode {
    VMODE_ALL, VMODE_KEY, VMODE_FOCUS, VMODE_FOCUSIN, VMODE_FOCUSOUT, VMODE_NONE
} VMODE;

static const char *validateStrings[] = {
    "all", "key", "focus", "focusin", "focusout", "none", NULL
};

/*
 * Validation reasons:
 */
typedef enum validateReason {
    VALIDATE_INSERT, VALIDATE_DELETE,
    VALIDATE_FOCUSIN, VALIDATE_FOCUSOUT,
    VALIDATE_FORCED
} VREASON;

static const char *validateReasonStrings[] = {
    "key", "key", "focusin", "focusout", "forced", NULL
};

/*------------------------------------------------------------------------
 * +++ Entry widget record.
 *
 * Dependencies:
 *
 * textVariableTrace	: textVariableObj
 * avgWidth		: fontObj
 *
 * numBytes,numChars	: string
 * displayString	: numChars, showChar
 * layoutHeight,
 * layoutWidth,
 * textLayout		: fontObj, displayString
 * layoutX, layoutY	: textLayout, justify, leftIndex
 * leftIndex		: (may be modified based on [window size])
 * rightIndex		: textLayout, justify, leftIndex, [window size]
 * [scrollbar position]	: leftIndex, rightIndex, numChars
 *
 * Invariants:
 *
 * 0 <= insertPos <= numChars
 * 0 <= selectFirst < selectLast <= numChars || selectFirst == selectLast == -1
 * displayString points to string if showChar == NULL,
 * or to malloc'ed storage if showChar != NULL.
 */

/* Style parameters:
 */
typedef struct 
{
    Tcl_Obj *foregroundObj;	/* Foreground color for normal text */
    Tcl_Obj *selBorderObj;	/* Border and background for selection */
    Tcl_Obj *selBorderWidthObj;	/* Width of selection border */
    Tcl_Obj *selForegroundObj;	/* Foreground color for selected text */
    Tcl_Obj *insertColorObj;	/* Color of insertion cursor */
    Tcl_Obj *insertWidthObj;	/* Insert cursor width */
} EntryStyleData;

typedef struct
{
    /*
     * Internal state:
     */
    char *string;		/* Storage for string (malloced) */
    int numBytes;		/* Length of string in bytes. */
    int numChars;		/* Length of string in characters. */

    int insertPos;		/* Insert index */
    int leftIndex;		/* Index of left-most visible character */
    int selectFirst;		/* Index of start of selection, or -1 */
    int selectLast;		/* Index of end of selection, or -1 */
    int selectAnchor;		/* Fixed end of selection */

    /*
     * Options managed by Tk_SetOptions:
     */
    Tcl_Obj *textVariableObj;	/* Name of linked variable */
    int exportSelection;	/* Tie internal selection to X selection? */

    char *scrollCmd;		/* Scrollbar command prefix */

    VMODE validate;		/* Validation mode */
    char *validateCmd;		/* Validation script template */
    char *invalidCmd;		/* Invalid callback script template */

    char *showChar;		/* Used to derive displayString */

    Tcl_Obj *fontObj;		/* Text font to use */
    Tcl_Obj *widthObj;		/* Desired width of window (in avgchars) */
    Tk_Justify justify;		/* Text justification */

    EntryStyleData styleData;	/* Display style data */

    Tcl_Obj *stateObj;		/* Compatibility option -- see CheckStateObj */

    /*
     * Derived resources:
     */
    TraceHandle *textVariableTrace;
    int avgWidth;		/* Average character width of text font */

    char *displayString;	/* String to use when displaying */
    Tk_TextLayout textLayout;	/* Cached text layout information. */
    int layoutWidth;		/* textLayout width */
    int layoutHeight;		/* textLayout height */

    int layoutX, layoutY;	/* Origin for text layout. */
    int rightIndex;	 	/* Index of rightmost visible character+1 */

} EntryPart;

typedef struct
{
    WidgetCore	core;
    EntryPart	entry;
    ENTRY_COMPAT_DECLS
} Entry;

/*
 * Extra mask bits for Tk_SetOptions()
 */
#define STATE_CHANGED	 	(0x100)		/* -state option changed */

/*
 * Default option values:
 */
#define DEF_SELECT_BG	"#c3c3c3"
#define DEF_SELECT_FG	"#000000"
#define DEF_INSERT_BG	"black"
#define DEF_ENTRY_WIDTH	"20"
#define DEF_ENTRY_FONT	"TkTextFont"

static Tk_OptionSpec EntryOptionSpecs[] =
{
    WIDGET_TAKES_FOCUS,

    {TK_OPTION_BOOLEAN, "-exportselection", "exportSelection",
        "ExportSelection", "1", -1, Tk_Offset(Entry, entry.exportSelection),
	0,0,0 },
    {TK_OPTION_FONT, "-font", "font", "Font",
	DEF_ENTRY_FONT, Tk_Offset(Entry, entry.fontObj),-1,
	0,0,GEOMETRY_CHANGED},
    {TK_OPTION_COLOR, "-foreground", "foreground", "Foreground",
	"black", Tk_Offset(Entry, entry.styleData.foregroundObj), -1,
	0, 0, 0},
    {TK_OPTION_COLOR, "-insertcolor", "insertColor", "Foreground",
	"black", Tk_Offset(Entry, entry.styleData.insertColorObj), -1,
	0, 0, 0},
    {TK_OPTION_PIXELS, "-insertwidth", "insertWidth", "InsertWidth",
	"1", Tk_Offset(Entry, entry.styleData.insertWidthObj), -1,
        0, 0, 0},
    {TK_OPTION_STRING, "-invalidcommand", "invalidCommand", "InvalidCommand",
	NULL, -1, Tk_Offset(Entry, entry.invalidCmd),
	TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_JUSTIFY, "-justify", "justify", "Justify",
	"left", -1, Tk_Offset(Entry, entry.justify),
	0, 0, GEOMETRY_CHANGED},
    {TK_OPTION_BORDER, "-selectbackground", "selectBackground", "Foreground",
        DEF_SELECT_BG, Tk_Offset(Entry, entry.styleData.selBorderObj), -1,
        0, 0, 0},
    {TK_OPTION_PIXELS, "-selectborderwidth","selectBorderWidth","BorderWidth",
	"0", Tk_Offset(Entry, entry.styleData.selBorderWidthObj), -1,
        0, 0, 0},
    {TK_OPTION_COLOR, "-selectforeground", "selectForeground", "Background",
	DEF_SELECT_FG, Tk_Offset(Entry, entry.styleData.selForegroundObj), -1,
	0, 0, 0},
    {TK_OPTION_STRING, "-show", "show", "Show",
        NULL, -1, Tk_Offset(Entry, entry.showChar),
	TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_STRING, "-state", "state", "State",
	"normal", Tk_Offset(Entry, entry.stateObj), -1,
        0,0,STATE_CHANGED},
    {TK_OPTION_STRING, "-textvariable", "textVariable", "Variable",
	NULL, Tk_Offset(Entry, entry.textVariableObj), -1,
	TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_STRING_TABLE, "-validate", "validate", "Validate",
	"none", -1, Tk_Offset(Entry, entry.validate),
	0, (ClientData) validateStrings, 0},
    {TK_OPTION_STRING, "-validatecommand", "validateCommand", "ValidateCommand",
	NULL, -1, Tk_Offset(Entry, entry.validateCmd),
	TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_INT, "-width", "width", "Width",
	DEF_ENTRY_WIDTH, Tk_Offset(Entry, entry.widthObj), -1,
	0,0,GEOMETRY_CHANGED},
    {TK_OPTION_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
	NULL, -1, Tk_Offset(Entry, entry.scrollCmd),
	TK_OPTION_NULL_OK, 0, 0},

    WIDGET_INHERIT_OPTIONS(CoreOptionSpecs)
};

ENTRY_COMPAT_OPTIONS

/*------------------------------------------------------------------------
 * +++ Resource management.
 */

/* EntryDisplayString --
 * 	Return a malloc'ed string consisting of 'numChars' copies
 * 	of (the first character in the string) 'showChar'.
 * 	Used to compute the displayString if -show is non-NULL.
 */
static char *EntryDisplayString(const char *showChar, int numChars)
{
    char *displayString, *p;
    int size;
    Tcl_UniChar ch;
    char buf[TCL_UTF_MAX];

    Tcl_UtfToUniChar(showChar, &ch);
    size = Tcl_UniCharToUtf(ch, buf);
    p = displayString = ckalloc(numChars * size + 1);

    while (numChars--) {
	p += Tcl_UniCharToUtf(ch, p);
    }
    *p = '\0';

    return displayString;
}

/* EntryUpdateTextLayout --
 * 	Recompute textLayout, layoutWidth, and layoutHeight
 * 	from displayString and fontObj.
 *
 * See also: EntryPlaceTextLayout
 */
static void EntryUpdateTextLayout(Entry *entryPtr)
{
    Tk_FreeTextLayout(entryPtr->entry.textLayout);
    entryPtr->entry.textLayout = Tk_ComputeTextLayout(
	    Tk_GetFontFromObj(entryPtr->core.tkwin, entryPtr->entry.fontObj),
	    entryPtr->entry.displayString, entryPtr->entry.numChars,
	    0/*wraplength*/, entryPtr->entry.justify, TK_IGNORE_NEWLINES,
	    &entryPtr->entry.layoutWidth, &entryPtr->entry.layoutHeight);
    entryPtr->core.flags |= UPDATE_SCROLLBAR;
}

/* EntryEditable --
 * 	Returns 1 if the entry widget accepts user changes, 0 otherwise
 */
static int
EntryEditable(Entry *entryPtr)
{
    return !(entryPtr->core.state & (TTK_STATE_DISABLED|TTK_STATE_READONLY));
}

/*------------------------------------------------------------------------
 * +++ Selection management.
 */

/* EntryFetchSelection --
 *	Selection handler for entry widgets.
 */
static int
EntryFetchSelection(
    ClientData clientData, int offset, char *buffer, int maxBytes)
{
    Entry *entryPtr = (Entry *) clientData;
    size_t byteCount;
    const char *string;
    const char *selStart, *selEnd;

    if (entryPtr->entry.selectFirst < 0 || !entryPtr->entry.exportSelection) {
	return -1;
    }
    string = entryPtr->entry.displayString;

    selStart = Tcl_UtfAtIndex(string, entryPtr->entry.selectFirst);
    selEnd = Tcl_UtfAtIndex(selStart,
	    entryPtr->entry.selectLast - entryPtr->entry.selectFirst);
    byteCount = selEnd - selStart - offset;
    if (byteCount > (size_t)maxBytes) {
    /* @@@POSSIBLE BUG: Can transfer partial UTF-8 sequences.  Is this OK? */
	byteCount = maxBytes;
    }
    if (byteCount <= 0) {
	return 0;
    }
    memcpy(buffer, selStart + offset, byteCount);
    buffer[byteCount] = '\0';
    return byteCount;
}

/* EntryLostSelection --
 *	Tk_LostSelProc for Entry widgets; called when an entry
 *	loses ownership of the selection.
 */
static void EntryLostSelection(ClientData clientData)
{
    Entry *entryPtr = (Entry *) clientData;
    entryPtr->core.flags &= ~GOT_SELECTION;
    entryPtr->entry.selectFirst = entryPtr->entry.selectLast = -1;
    WidgetChanged(&entryPtr->core, REDISPLAY_REQUIRED);
}

/* EntryOwnSelection --
 * 	Assert ownership of the PRIMARY selection,
 * 	if -exportselection set and selection is present.
 */
static void EntryOwnSelection(Entry *entryPtr)
{
    if (entryPtr->entry.exportSelection
	&& !(entryPtr->core.flags & GOT_SELECTION)) {
	Tk_OwnSelection(entryPtr->core.tkwin, XA_PRIMARY, EntryLostSelection,
		(ClientData) entryPtr);
	entryPtr->core.flags |= GOT_SELECTION;
    }
}

/*------------------------------------------------------------------------
 * +++ Scrollbar interface.
 */

/* EntryVisibleRange --
 *	Return information about the range of the entry that is
 *	currently visible.
 *
 * Results:
 *	*firstPtr and *lastPtr are modified to hold fractions between
 *	0 and 1 identifying the range of characters visible in the
 *	entry.
 *
 * Notes:
 * 	Result may be incorrect if the widget has not been redisplayed
 * 	since leftIndex changed.
 */
static void
EntryVisibleRange(Entry *entryPtr, double *firstPtr, double *lastPtr)
{
    int numChars = entryPtr->entry.numChars;
    if (numChars == 0) {
	*firstPtr = 0.0;
	*lastPtr = 1.0;
    } else {
	*firstPtr = (double)entryPtr->entry.leftIndex / numChars;
	*lastPtr = (double)entryPtr->entry.rightIndex / numChars;
    }
}

/* EntryUpdateScrollbar --
 *	Call the -scrollcommand callback to sync the scrollbar with
 *	the entry's visible range.
 *
 * 	Returns: Whatever the -scrollcommand does.
 */
static int
EntryUpdateScrollbar(Tcl_Interp *interp, Entry *entryPtr)
{
    char args[TCL_DOUBLE_SPACE * 2];
    double first, last;
    int code;

    entryPtr->core.flags &= ~UPDATE_SCROLLBAR;
    if (entryPtr->entry.scrollCmd == NULL)
	return TCL_OK;

    EntryVisibleRange(entryPtr, &first, &last);
    sprintf(args, " %g %g", first, last);

    code = Tcl_VarEval(interp, entryPtr->entry.scrollCmd, args, NULL);

    if (WidgetDestroyed(&entryPtr->core))
	return TCL_ERROR;

    if (code != TCL_OK) {
	/* Disable the -scrollcommand, add to stack trace:
	 */
	ckfree(entryPtr->entry.scrollCmd);
	entryPtr->entry.scrollCmd = 0;

	Tcl_AddErrorInfo(interp,
		"\n    (horizontal scrolling command executed by ");
	Tcl_AddErrorInfo(interp, Tk_PathName(entryPtr->core.tkwin));
	Tcl_AddErrorInfo(interp, ")");
    }
    return code;
}

/*------------------------------------------------------------------------
 * +++ Validation.
 */

/* ExpandPercents --
 *	Expand an entry validation script template (-validatecommand
 *	or -invalidcommand).
 */
static void
ExpandPercents(
     Entry *entryPtr,		/* Entry that needs validation. */
     const char *template, 	/* Script template */
     const char *new,		/* Potential new value of entry string */
     int index,			/* index of insert/delete */
     int count,			/* #changed characters */
     VREASON reason,		/* Reason for change */
     Tcl_DString *dsPtr)	/* Result of %-substitutions */
{
    int spaceNeeded, cvtFlags;
    int number, length;
    const char *string;
    int stringLength;
    Tcl_UniChar ch;
    char numStorage[2*TCL_INTEGER_SPACE];

    while (*template) {
	/* Find everything up to the next % character and append it
	 * to the result string.
	 */
	string = Tcl_UtfFindFirst(template, '%');
	if (string == NULL) {
	    /* No more %-sequences to expand.
	     * Copy the rest of the template.
	     */
	    Tcl_DStringAppend(dsPtr, template, -1);
	    return;
	}
	if (string != template) {
	    Tcl_DStringAppend(dsPtr, template, string - template);
	    template = string;
	}

	/* There's a percent sequence here.  Process it.
	 */
	++template; /* skip over % */
	if (*template != '\0') {
	    template += Tcl_UtfToUniChar(template, &ch);
	} else {
	    ch = '%';
	}

	stringLength = -1;
	switch (ch) {
	    case 'd': /* Type of call that caused validation */
		if (reason == VALIDATE_INSERT) {
		    number = 1;
		} else if (reason == VALIDATE_DELETE) {
		    number = 0;
		} else {
		    number = -1;
		}
		sprintf(numStorage, "%d", number);
		string = numStorage;
		break;
	    case 'i': /* index of insert/delete */
		sprintf(numStorage, "%d", index);
		string = numStorage;
		break;
	    case 'P': /* 'Peeked' new value of the string */
		string = new;
		break;
	    case 's': /* Current string value */
		string = entryPtr->entry.string;
		break;
	    case 'S': /* string to be inserted/deleted, if any */
		if (reason == VALIDATE_INSERT) {
		    string = Tcl_UtfAtIndex(new, index);
		    stringLength = Tcl_UtfAtIndex(string, count) - string;
		} else if (reason == VALIDATE_DELETE) {
		    string = Tcl_UtfAtIndex(entryPtr->entry.string, index);
		    stringLength = Tcl_UtfAtIndex(string, count) - string;
		} else {
		    string = "";
		    stringLength = 0;
		}
		break;
	    case 'v': /* type of validation currently set */
		string = validateStrings[entryPtr->entry.validate];
		break;
	    case 'V': /* type of validation in effect */
		string = validateReasonStrings[reason];
		break;
	    case 'W': /* widget name */
		string = Tk_PathName(entryPtr->core.tkwin);
		break;
	    default:
		length = Tcl_UniCharToUtf(ch, numStorage);
		numStorage[length] = '\0';
		string = numStorage;
		break;
	}

	spaceNeeded = Tcl_ScanCountedElement(string, stringLength, &cvtFlags);
	length = Tcl_DStringLength(dsPtr);
	Tcl_DStringSetLength(dsPtr, length + spaceNeeded);
	spaceNeeded = Tcl_ConvertCountedElement(string, stringLength,
		Tcl_DStringValue(dsPtr) + length,
		cvtFlags | TCL_DONT_USE_BRACES);
	Tcl_DStringSetLength(dsPtr, length + spaceNeeded);
    }
}

/* RunValidationScript --
 * 	Build and evaluate an entry validation script.
 * 	If the script raises an error, disable validation
 * 	by setting '-validate none'
 */
static int RunValidationScript(
    Tcl_Interp *interp, 	/* Interpreter to use */
    Entry *entryPtr,		/* Entry being validated */
    const char *template,	/* Script template */
    const char *optionName,	/* "-validatecommand", "-invalidcommand" */
    const char *new,		/* Potential new value of entry string */
    int index,			/* index of insert/delete */
    int count,			/* #changed characters */
    VREASON reason)		/* Reason for change */
{
    Tcl_DString script;
    int code;

    Tcl_DStringInit(&script);
    ExpandPercents(entryPtr, template, new, index, count, reason, &script);
    code = Tcl_EvalEx(interp,
		Tcl_DStringValue(&script), Tcl_DStringLength(&script),
		TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    Tcl_DStringFree(&script);
    if (WidgetDestroyed(&entryPtr->core))
	return TCL_ERROR;

    if (code != TCL_OK && code != TCL_RETURN) {
	Tcl_AddErrorInfo(interp, "\n\t(in ");
	Tcl_AddErrorInfo(interp, optionName);
	Tcl_AddErrorInfo(interp, " validation command executed by ");
	Tcl_AddErrorInfo(interp, Tk_PathName(entryPtr->core.tkwin));
	Tcl_AddErrorInfo(interp, ")");
	entryPtr->entry.validate = VMODE_NONE;
	return TCL_ERROR;
    }
    return TCL_OK;
}

/* EntryNeedsValidation --
 * 	Determine whether the specified VREASON should trigger validation
 * 	in the current VMODE.
 */
static int EntryNeedsValidation(VMODE vmode, VREASON reason)
{
    return (reason == VALIDATE_FORCED)
	|| (vmode == VMODE_ALL)
	|| (reason == VALIDATE_FOCUSIN
	    && (vmode == VMODE_FOCUSIN || vmode == VMODE_FOCUS))
	|| (reason == VALIDATE_FOCUSOUT
	    && (vmode == VMODE_FOCUSOUT || vmode == VMODE_FOCUS))
	|| (reason == VALIDATE_INSERT && vmode == VMODE_KEY)
	|| (reason == VALIDATE_DELETE && vmode == VMODE_KEY)
	;
}

/* EntryValidateChange --
 *	Validate a proposed change to the entry widget's value if required.
 *	Call the -invalidcommand if validation fails.
 *
 * Returns:
 *	TCL_OK if the change is accepted
 *	TCL_BREAK if the change is rejected
 *      TCL_ERROR if any errors occured
 *
 * The change will be rejected if the -validatecommand returns 0,
 * or if -validatecommand or -invalidcommand modifies the value.
 */
static int
EntryValidateChange(
    Entry *entryPtr,		/* Entry that needs validation. */
    const char *new,		/* Potential new value of entry string */
    int index,			/* index of insert/delete, -1 otherwise */
    int count,			/* #changed characters */
    VREASON reason)		/* Reason for change */
{
    Tcl_Interp *interp = entryPtr->core.interp;
    VMODE vmode = entryPtr->entry.validate;
    int code, ok;

    if (   (entryPtr->entry.validateCmd == NULL)
	|| (entryPtr->core.flags & VALIDATING)
	|| !EntryNeedsValidation(vmode, reason) )
    {
	return TCL_OK;
    }

    entryPtr->core.flags |= VALIDATING;

    /* Run -validatecommand and check return value:
     */
    code = RunValidationScript(interp, entryPtr,
	    entryPtr->entry.validateCmd, "-validatecommand",
	    new, index, count, reason);
    if (code != TCL_OK)
	goto done;

    code = Tcl_GetBooleanFromObj(interp,Tcl_GetObjResult(interp), &ok);
    if (code != TCL_OK) {
	entryPtr->entry.validate = VMODE_NONE;	/* Disable validation */
	Tcl_AddErrorInfo(interp,
		"\n(validation command did not return valid boolean)");
	goto done;
    }

    /* Run the -invalidcommand if validation failed:
     */
    if (!ok && entryPtr->entry.invalidCmd != NULL) {
	code = RunValidationScript(interp, entryPtr,
		entryPtr->entry.invalidCmd, "-invalidcommand",
		new, index, count, reason);
	if (code != TCL_OK)
	    goto done;
    }

    /* If validation failed, or if a validation script changed the value,
     * reject the pending change.
     */
    if (!ok || (entryPtr->core.flags & VALIDATION_SET_VALUE))
	code = TCL_BREAK;

done:
    entryPtr->core.flags &= ~(VALIDATING|VALIDATION_SET_VALUE);
    return code;
}

/* EntryRevalidate --
 * 	Revalidate the contents of an entry widget.
 */
static void EntryRevalidate(Entry *entryPtr, VREASON reason)
{
    Tcl_Interp *interp = entryPtr->core.interp;
    int code;

    code = EntryValidateChange(entryPtr, entryPtr->entry.string, -1,0, reason);

    if (code == TCL_BREAK) {
	/* @@@ What should happen here? There's no change to reject. */
    } else if (code == TCL_ERROR) {
	Tcl_BackgroundError(interp);
    }
}

/*------------------------------------------------------------------------
 * +++ Entry widget modification.
 */

/* AdjustIndex --
 * 	Adjust index to account for insertion (nChars > 0)
 * 	or deletion (nChars < 0) at specified index.
 */
static int AdjustIndex(int i0, int index, int nChars)
{
    if (i0 >= index) {
	i0 += nChars;
	if (i0 < index) { /* index was inside deleted range */
	    i0 = index;
	}
    }
    return i0;
}

/* AdjustIndices --
 * 	Adjust all internal entry indexes to account for change.
 * 	Note that insertPos, selectFirst, and selectAnchor have "right gravity",
 * 	while leftIndex and selectLast have "left gravity".
 */
static void AdjustIndices(Entry *entryPtr, int index, int nChars)
{
    EntryPart *e = &entryPtr->entry;
    int g = nChars > 0;		/* left gravity adjustment */

    e->insertPos    = AdjustIndex(e->insertPos, index, nChars);
    e->selectFirst  = AdjustIndex(e->selectFirst, index, nChars);
    e->leftIndex    = AdjustIndex(e->leftIndex, index+g, nChars);
    e->selectLast   = AdjustIndex(e->selectLast, index+g, nChars);
    e->selectAnchor = AdjustIndex(e->selectAnchor, index, nChars);

    if (e->selectLast <= e->selectFirst)
	e->selectFirst = e->selectLast = -1;
}

/* EntryStoreValue --
 *	Replace the contents of a text entry with a given value,
 *	recompute dependent resources, and schedule a redisplay.
 *
 *	See also: EntrySetValue().
 */
static void
EntryStoreValue(Entry *entryPtr, const char *value)
{
    size_t numBytes = strlen(value);
    int numChars = Tcl_NumUtfChars(value, numBytes);

    if (entryPtr->core.flags & VALIDATING)
	entryPtr->core.flags |= VALIDATION_SET_VALUE;

    /* Make sure all indices remain in bounds:
     */
    if (numChars < entryPtr->entry.numChars)
	AdjustIndices(entryPtr, numChars, numChars - entryPtr->entry.numChars);

    /* Free old value:
     */
    if (entryPtr->entry.displayString != entryPtr->entry.string)
	ckfree(entryPtr->entry.displayString);
    ckfree(entryPtr->entry.string);

    /* Store new value:
     */
    entryPtr->entry.string = ckalloc(numBytes + 1);
    strcpy(entryPtr->entry.string, value);
    entryPtr->entry.numBytes = numBytes;
    entryPtr->entry.numChars = numChars;

    entryPtr->entry.displayString
	= entryPtr->entry.showChar
	? EntryDisplayString(entryPtr->entry.showChar, numChars)
	: entryPtr->entry.string
	;

    /* Update layout, schedule redisplay:
     */
    EntryUpdateTextLayout(entryPtr);
    WidgetChanged(&entryPtr->core, REDISPLAY_REQUIRED);
}

/* EntrySetValue --
 * 	Stores a new value in the entry widget and updates the
 * 	linked -textvariable, if any.  The write trace on the
 * 	text variable is temporarily disabled; however, other
 * 	write traces may change the value of the variable.
 * 	If so, the new value is used instead (bypassing validation).
 *
 * Returns:
 * 	TCL_OK if successful, TCL_ERROR otherwise.
 */
static int EntrySetValue(Entry *entryPtr, const char *value)
{
    if (entryPtr->entry.textVariableObj) {
	const char *textVarName =
	    Tcl_GetString(entryPtr->entry.textVariableObj);
	if (textVarName && *textVarName) {
	    entryPtr->core.flags |= SYNCING_VARIABLE;
	    value = Tcl_SetVar(entryPtr->core.interp, textVarName,
		    value, TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG);
	    entryPtr->core.flags &= ~SYNCING_VARIABLE;
	    if (!value || WidgetDestroyed(&entryPtr->core))
		return TCL_ERROR;
	}
    }

    EntryStoreValue(entryPtr, value);
    return TCL_OK;
}

/* EntryTextVariableTrace --
 *	Variable trace procedure for entry -textvariable
 */
static int
EntryTextVariableTrace(
    Tcl_Interp *interp, void *recordPtr, const char *value)
{
    Entry *entryPtr = recordPtr;

    if (WidgetDestroyed(&entryPtr->core))
	return TCL_ERROR;

    if (entryPtr->core.flags & SYNCING_VARIABLE) {
	/* Trace was fired due to Tcl_SetVar call in EntrySetValue.
	 * Don't do anything.
	 */
	return TCL_OK;
    }

    /* HERE: Schedule revalidation.  Maybe. */

    EntryStoreValue(entryPtr, value);
    return TCL_OK;
}

/*------------------------------------------------------------------------
 * +++ Insertion and deletion.
 */

/* InsertChars --
 *	Add new characters to an entry widget.
 */
static int
InsertChars(
    Entry *entryPtr,		/* Entry that is to get the new elements. */
    int index,			/* Insert before this index */
    const char *value)		/* New characters to add */
{
    char *string = entryPtr->entry.string;
    size_t byteIndex = Tcl_UtfAtIndex(string, index) - string;
    size_t byteCount = strlen(value);
    int charsAdded = Tcl_NumUtfChars(value, byteCount);
    size_t newByteCount = entryPtr->entry.numBytes + byteCount + 1;
    char *new;
    int code;

    if (byteCount == 0) {
	return TCL_OK;
    }

    new =  ckalloc(newByteCount);
    memcpy(new, string, byteIndex);
    strcpy(new + byteIndex, value);
    strcpy(new + byteIndex + byteCount, string + byteIndex);

    code = EntryValidateChange(
	    entryPtr, new, index, charsAdded, VALIDATE_INSERT);

    if (code == TCL_OK) {
	AdjustIndices(entryPtr, index, charsAdded);
	code = EntrySetValue(entryPtr, new);
    } else if (code == TCL_BREAK) {
	code = TCL_OK;
    }

    ckfree(new);
    return code;
}

/* DeleteChars --
 *	Remove one or more characters from an entry widget.
 */
static int
DeleteChars(
    Entry *entryPtr,		/* Entry widget to modify. */
    int index,			/* Index of first character to delete. */
    int count)			/* How many characters to delete. */
{
    char *string = entryPtr->entry.string;
    size_t byteIndex, byteCount, newByteCount;
    char *new;
    int code;

    if (index < 0) {
	index = 0;
    }
    if (count > entryPtr->entry.numChars - index) {
	count = entryPtr->entry.numChars - index;
    }
    if (count <= 0) {
	return TCL_OK;
    }

    byteIndex = Tcl_UtfAtIndex(string, index) - string;
    byteCount = Tcl_UtfAtIndex(string+byteIndex, count) - (string+byteIndex);

    newByteCount = entryPtr->entry.numBytes + 1 - byteCount;
    new =  ckalloc(newByteCount);
    memcpy(new, string, byteIndex);
    strcpy(new + byteIndex, string + byteIndex + byteCount);

    code = EntryValidateChange(
	    entryPtr, new, index, count, VALIDATE_DELETE);

    if (code == TCL_OK) {
	AdjustIndices(entryPtr, index, -count);
	code = EntrySetValue(entryPtr, new);
    } else if (code == TCL_BREAK) {
	code = TCL_OK;
    }
    ckfree(new);

    return code;
}

/*------------------------------------------------------------------------
 * +++ Event handler.
 */

/* EntryEventProc --
 *	Extra event handling for entry widgets:
 *
 *	+ Triggers validation on FocusIn and FocusOut events
 *	+ Schedules a scrollbar update when widget is resized
 */
#define EntryEventMask (FocusChangeMask|StructureNotifyMask)
static void
EntryEventProc(ClientData clientData, XEvent *eventPtr)
{
    Entry *entryPtr = (Entry *) clientData;

    Tcl_Preserve(clientData);
    switch (eventPtr->type) {
	case DestroyNotify:
	    Tk_DeleteEventHandler(entryPtr->core.tkwin,
		    EntryEventMask, EntryEventProc, clientData);
	    break;
	case ConfigureNotify:
	    entryPtr->core.flags |= UPDATE_SCROLLBAR;
	    break;
	case FocusIn:
	    EntryRevalidate(entryPtr, VALIDATE_FOCUSIN);
	    break;
	case FocusOut:
	    EntryRevalidate(entryPtr, VALIDATE_FOCUSOUT);
	    break;
    }
    Tcl_Release(clientData);
}

/*------------------------------------------------------------------------
 * +++ Initialization and cleanup.
 */

static int
EntryInitialize(Tcl_Interp *interp, void *recordPtr)
{
    Entry *entryPtr = recordPtr;

    Tk_CreateEventHandler(
	entryPtr->core.tkwin, EntryEventMask, EntryEventProc, entryPtr);
    Tk_CreateSelHandler(entryPtr->core.tkwin, XA_PRIMARY, XA_STRING,
	EntryFetchSelection, (ClientData) entryPtr, XA_STRING);
    BlinkCursor(&entryPtr->core);

    entryPtr->entry.string		= ckalloc(1);
    *entryPtr->entry.string 		= '\0';
    entryPtr->entry.displayString	= entryPtr->entry.string;
    entryPtr->entry.textVariableTrace 	= 0;
    entryPtr->entry.numBytes = entryPtr->entry.numChars = 0;

    entryPtr->entry.insertPos		= 0;
    entryPtr->entry.leftIndex		= 0;
    entryPtr->entry.rightIndex		= 0;
    entryPtr->entry.selectFirst 	= -1;
    entryPtr->entry.selectLast		= -1;

    entryPtr->entry.selectAnchor	= 0;	/* COMPAT */

    return TCL_OK;
}

static void
EntryCleanup(void *recordPtr)
{
    Entry *entryPtr = recordPtr;

    if (entryPtr->entry.textVariableTrace)
	UntraceVariable(entryPtr->entry.textVariableTrace);

    Tk_DeleteSelHandler(entryPtr->core.tkwin, XA_PRIMARY, XA_STRING);

    Tk_FreeTextLayout(entryPtr->entry.textLayout);
    if (entryPtr->entry.displayString != entryPtr->entry.string)
	ckfree(entryPtr->entry.displayString);
    ckfree(entryPtr->entry.string);
}

/* EntryConfigure --
 * 	Configure hook for Entry widgets.
 */
static int
EntryConfigure(Tcl_Interp *interp, void *recordPtr, int mask)
{
    Entry *entryPtr = recordPtr;
    Tcl_Obj *textVarName = entryPtr->entry.textVariableObj;
    TraceHandle *vt = 0;
    Tk_Window tkwin = entryPtr->core.tkwin;
    Tk_Font font;

    if (textVarName && *Tcl_GetString(textVarName)) {
	vt = TraceVariable(interp,textVarName,EntryTextVariableTrace,entryPtr);
	if (!vt) return TCL_ERROR;
    }

    if (CoreConfigure(interp, recordPtr, mask) != TCL_OK) {
	if (vt) UntraceVariable(vt);
	return TCL_ERROR;
    }

    /* Update derived resources:
     */
    if (entryPtr->entry.textVariableTrace)
	UntraceVariable(entryPtr->entry.textVariableTrace);
    entryPtr->entry.textVariableTrace = vt;

    font = Tk_GetFontFromObj(tkwin, entryPtr->entry.fontObj);
    entryPtr->entry.avgWidth = Tk_TextWidth(font, "0", 1);
    if (entryPtr->entry.avgWidth == 0) {
	entryPtr->entry.avgWidth = 1;
    }

    /* Claim the selection, in case we've suddenly started exporting it.
     */
    if (entryPtr->entry.exportSelection && entryPtr->entry.selectFirst != -1) {
	EntryOwnSelection(entryPtr);
    }

    /* Handle -state compatibility option:
     */
    if (mask & STATE_CHANGED) {
	CheckStateOption(&entryPtr->core, entryPtr->entry.stateObj);
    }

    /* Recompute the displayString, in case showChar changed:
     */
    if (entryPtr->entry.displayString != entryPtr->entry.string)
	ckfree(entryPtr->entry.displayString);

    entryPtr->entry.displayString
	= entryPtr->entry.showChar
	? EntryDisplayString(entryPtr->entry.showChar, entryPtr->entry.numChars)
	: entryPtr->entry.string
	;

    /* Update textLayout:
     */
    EntryUpdateTextLayout(entryPtr);
    return TCL_OK;
}

/* EntryPostConfigure --
 * 	Post-configuration hook for entry widgets.
 */
static int
EntryPostConfigure(Tcl_Interp *interp, void *recordPtr, int mask)
{
    Entry *entryPtr = recordPtr;
    int status = TCL_OK;

    if (entryPtr->entry.textVariableTrace)
	status = FireTrace(entryPtr->entry.textVariableTrace);

    /* @@@ Possibly: Revalidate if '-validatecommand' or '-validate' changed */

    return status;
}

/*------------------------------------------------------------------------
 * +++ Layout and display.
 */

/* EntryTextArea --
 * 	Return bounding box of entry display ("owner-draw") area.
 */
static TTK_Box
EntryTextArea(Entry *entryPtr)
{
    WidgetCore *corePtr = &entryPtr->core;
    TTK_LayoutNode *node = TTK_LayoutFindNode(corePtr->layout, "textarea");
    return node
	? TTK_LayoutNodeParcel(node)
	: TTK_MakeBox(0,0,Tk_Width(corePtr->tkwin),Tk_Height(corePtr->tkwin))
	;
}

/* EntryPlaceTextLayout -
 * 	Determine position of textLayout based on leftIndex, justify,
 * 	and display area (computed indirectly by EntryDoLayout).
 *
 * 	Recalculates layoutX, layoutY, and rightIndex;
 * 	may adjust leftIndex to ensure the maximum #characters are onscreen.
 */
static void
EntryPlaceTextLayout(Entry *entryPtr)
{
    TTK_Box textarea = EntryTextArea(entryPtr);
    int leftIndex = entryPtr->entry.leftIndex;
    int rightIndex = entryPtr->entry.rightIndex;

    /* Center the text vertically within the available parcel:
     */
    entryPtr->entry.layoutY = textarea.y +
	(textarea.height - entryPtr->entry.layoutHeight)/2;

    /* Recompute where the leftmost character on the display will
     * be drawn (layoutX) and adjust leftIndex if necessary.
     */
    if (entryPtr->entry.layoutWidth <= textarea.width) {
	/* Everything fits.  Set leftIndex to zero (no need to scroll),
	 * and compute layoutX based on -justify.
	 */
	int extraSpace = textarea.width - entryPtr->entry.layoutWidth;
	leftIndex = 0;
	rightIndex = entryPtr->entry.numChars;
	entryPtr->entry.layoutX = textarea.x;
	if (entryPtr->entry.justify == TK_JUSTIFY_RIGHT) {
	    entryPtr->entry.layoutX += extraSpace;
	} else if (entryPtr->entry.justify == TK_JUSTIFY_CENTER) {
	    entryPtr->entry.layoutX += extraSpace / 2;
	}
    } else {
	/* The whole string doesn't fit in the window.
	 * Limit leftIndex to leave at most one character's worth
	 * of empty space on the right.
	 */
	int leftX;
	int overflow = entryPtr->entry.layoutWidth - textarea.width;
	int maxLeftIndex =
	    1 + Tk_PointToChar(entryPtr->entry.textLayout, overflow, 0);

	if (leftIndex > maxLeftIndex)
	    leftIndex = maxLeftIndex;

	/* Compute layoutX and rightIndex.
	 */
	Tk_CharBbox(entryPtr->entry.textLayout, leftIndex,
		&leftX, NULL, NULL, NULL);
	entryPtr->entry.layoutX = textarea.x - leftX;
	rightIndex = Tk_PointToChar(entryPtr->entry.textLayout,
		leftX + textarea.width, 0);
	if (rightIndex < entryPtr->entry.numChars)
	    ++rightIndex;
    }

    if (   leftIndex != entryPtr->entry.leftIndex
	|| rightIndex != entryPtr->entry.rightIndex)
    {
	entryPtr->entry.leftIndex = leftIndex;
	entryPtr->entry.rightIndex = rightIndex;
	entryPtr->core.flags |= UPDATE_SCROLLBAR;
    }
}

/* EntryUpdateScrollbarBG --
 * 	Idle handler to update the scrollbar.
 */
static void EntryUpdateScrollbarBG(ClientData clientData)
{
    Entry *entryPtr = (Entry *)clientData;
    Tcl_Interp *interp = entryPtr->core.interp;
    int code;

    if (WidgetDestroyed(&entryPtr->core)) {
	Tcl_Release(clientData);
	return;
    }

    Tcl_Preserve((ClientData) interp);
    code = EntryUpdateScrollbar(interp, entryPtr);
    if (code == TCL_ERROR && !Tcl_InterpDeleted(interp)) {
	Tcl_BackgroundError(interp);
    }
    Tcl_Release((ClientData) interp);
    Tcl_Release(clientData);
}

/* EntryDoLayout --
 * 	Layout hook for entry widgets.
 */
static void
EntryDoLayout(void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    WidgetCore *corePtr = &entryPtr->core;

    TTK_PlaceLayout(corePtr->layout,corePtr->state,TTK_WinBox(corePtr->tkwin));

    EntryPlaceTextLayout(entryPtr);

    /* Update the scrollbar if required, now that we have the position.
     * It's not safe to enter the interpreter at this point, so schedule
     * it as an idle handler.
     */
    if (entryPtr->core.flags & UPDATE_SCROLLBAR) {
	entryPtr->core.flags &= ~UPDATE_SCROLLBAR;
	Tcl_Preserve(recordPtr);
	Tcl_DoWhenIdle(EntryUpdateScrollbarBG, recordPtr);
    }
}

/* EntryGetGC -- Helper routine.
 *      Get a GC using the specified foreground color and the entry's font.
 *      Result must be freed with Tk_FreeGC().
 */
static GC EntryGetGC(Entry *entryPtr, Tcl_Obj *colorObj)
{
    Tk_Window tkwin = entryPtr->core.tkwin;
    XColor *colorPtr = Tk_GetColorFromObj(tkwin, colorObj);
    Tk_Font font = Tk_GetFontFromObj(tkwin, entryPtr->entry.fontObj);
    unsigned long mask = GCForeground | GCFont;
    XGCValues gcValues;
    gcValues.foreground = colorPtr->pixel;
    gcValues.font = Tk_FontId(font);
    return Tk_GetGC(entryPtr->core.tkwin, mask, &gcValues);
}

/*
 * EntryInitStyleData --
 * 	Look up style-specific data for an entry widget.
 *
 * NOTES: 
 * 	Precedence logic is backwards: widget option is used
 * 	as a fallback instead of overriding style default.
 *
 * 	This is a rather awkward way of doing things;
 * 	needs to be redone.
 */
static void EntryInitStyleData(Entry *entryPtr, EntryStyleData *es)
{
    TTK_Style style = TTK_LayoutStyle(entryPtr->core.layout);
    unsigned long state = entryPtr->core.state;
    TTK_ResourceCache cache = TTK_GetResourceCache(entryPtr->core.interp);
    Tk_Window tkwin = entryPtr->core.tkwin;
    Tcl_Obj *tmp;

    /* Defaults from widget: */
    *es = entryPtr->entry.styleData;

#   define INIT(member, name) \
    	if ((tmp=TTK_QueryStyle(style,name,state,0))) es->member=tmp;
    INIT(foregroundObj, "-foreground");
    INIT(selBorderObj, "-selectbackground")
    INIT(selBorderWidthObj, "-selectborderwidth")
    INIT(selForegroundObj, "-selectforeground")
    INIT(insertColorObj, "-insertcolor")
    INIT(insertWidthObj, "-insertwidth")

    /* Reacquire color & border resources from resource cache.
     */
    es->foregroundObj = TTK_UseColor(cache, tkwin, es->foregroundObj);
    es->selForegroundObj = TTK_UseColor(cache, tkwin, es->selForegroundObj);
    es->insertColorObj = TTK_UseColor(cache, tkwin, es->insertColorObj);
    es->selBorderObj = TTK_UseBorder(cache, tkwin, es->selBorderObj);
}

/* EntryDisplay --
 *	Redraws the contents of an entry window.
 */
static void EntryDisplay(void *clientData, Drawable d)
{
    Entry *entryPtr = clientData;
    Tk_Window tkwin = entryPtr->core.tkwin;
    EntryStyleData es;
    GC gc;
    TTK_Box textarea = EntryTextArea(entryPtr);
    int selFirst = entryPtr->entry.selectFirst,
	selLast = entryPtr->entry.selectLast;
    int showSelection, showCursor;

    EntryInitStyleData(entryPtr, &es);

    showSelection =
	   (entryPtr->core.state & TTK_STATE_DISABLED) == 0
	&& selFirst > -1
	&& selLast > entryPtr->entry.leftIndex
	&& selFirst <= entryPtr->entry.rightIndex
	;
    showCursor = (entryPtr->core.flags & CURSOR_ON) && EntryEditable(entryPtr);

    /* Adjust selection range to keep in display bounds.
     */
    if (showSelection) {
	if (selFirst < entryPtr->entry.leftIndex)
	    selFirst = entryPtr->entry.leftIndex;
	if (selLast > entryPtr->entry.rightIndex)
	    selLast = entryPtr->entry.rightIndex;
    }

    /* Draw widget background & border
     */
    TTK_DrawLayout(entryPtr->core.layout,d,entryPtr->core.state);

    /* Draw selection background
     */
    if (showSelection) {
	int bw = 1;
	Tk_3DBorder selBorder;
	int selStartX, selEndX;

	Tcl_GetIntFromObj(NULL, es.selBorderWidthObj, &bw);

	Tk_CharBbox(entryPtr->entry.textLayout, selFirst,
		    &selStartX, NULL, NULL, NULL);
	selStartX += entryPtr->entry.layoutX;
	Tk_CharBbox(entryPtr->entry.textLayout, selLast,
		    &selEndX, NULL, NULL, NULL);
	selEndX += entryPtr->entry.layoutX;

	selBorder = Tk_Alloc3DBorderFromObj(NULL, tkwin, es.selBorderObj);
	if (selBorder) {
	    Tk_Fill3DRectangle(tkwin, d, selBorder,
		selStartX - bw, entryPtr->entry.layoutY - bw,
		selEndX - selStartX + 2*bw,
		entryPtr->entry.layoutHeight + 2*bw,
		bw, TK_RELIEF_RAISED);
	    Tk_Free3DBorderFromObj(tkwin, es.selBorderObj);
	}
    }

    /* Draw cursor:
     */
    if (showCursor) {
	int cursorX;
	Tk_CharBbox(entryPtr->entry.textLayout, entryPtr->entry.insertPos,
		&cursorX, NULL, NULL, NULL);
	cursorX += entryPtr->entry.layoutX;

	/* @@@ should: maybe: SetCaretPos even when blinked off */
	/* @@@ should: maybe: don't SetCaretPos when out of bounds */

	Tk_SetCaretPos(tkwin, cursorX, entryPtr->entry.layoutY,
		entryPtr->entry.layoutHeight);

	if (textarea.x <= cursorX && cursorX <= textarea.x + textarea.width) {
	    int insertWidth = 1, x = cursorX;

	    gc = EntryGetGC(entryPtr, es.insertColorObj);
	    Tcl_GetIntFromObj(NULL,es.insertWidthObj,&insertWidth);
	    if (insertWidth <= 0)
		insertWidth = 1;

	    x -= insertWidth/2;
	    while (insertWidth--) {
		XDrawLine(Tk_Display(tkwin), d, gc,
		    x, entryPtr->entry.layoutY,
		    x, entryPtr->entry.layoutY + entryPtr->entry.layoutHeight);
		++x;
	    }
	}
    }

    /* Draw the text:
     */
    gc = EntryGetGC(entryPtr, es.foregroundObj);
    Tk_DrawTextLayout(
	Tk_Display(tkwin), d, gc, entryPtr->entry.textLayout,
	entryPtr->entry.layoutX, entryPtr->entry.layoutY,
	entryPtr->entry.leftIndex, entryPtr->entry.rightIndex);
    Tk_FreeGC(Tk_Display(tkwin), gc);

    /* Overwrite the selected portion (if any) in the -selectforeground color:
     */
    if (showSelection) {
	gc = EntryGetGC(entryPtr, es.selForegroundObj);
	Tk_DrawTextLayout(Tk_Display(tkwin), d, gc, entryPtr->entry.textLayout,
		entryPtr->entry.layoutX, entryPtr->entry.layoutY,
		selFirst, selLast);
	Tk_FreeGC(Tk_Display(tkwin), gc);
    }
}

/*------------------------------------------------------------------------
 * +++ Widget commands.
 */

/* EntryIndex --
 *	Parse an index into an entry and return either its value
 *	or an error.
 *
 * Results:
 *	A standard Tcl result.  If all went well, then *indexPtr is
 *	filled in with the character index (into entryPtr) corresponding to
 *	string.  The index value is guaranteed to lie between 0 and
 *	the number of characters in the string, inclusive.  If an
 *	error occurs then an error message is left in the interp's result.
 */
static int
EntryIndex(
    Tcl_Interp *interp,		/* For error messages. */
    Entry *entryPtr,		/* Entry widget to query */
    Tcl_Obj *indexObj,		/* Symbolic index name */
    int *indexPtr)		/* Return value */
{
#   define EntryWidth(e) (Tk_Width(entryPtr->core.tkwin)) /* Not Right */
    int length;
    const char *string = Tcl_GetStringFromObj(indexObj, &length);

    if (strncmp(string, "end", length) == 0) {
	*indexPtr = entryPtr->entry.numChars;
    } else if (strncmp(string, "insert", length) == 0) {
	*indexPtr = entryPtr->entry.insertPos;
    } else if (strncmp(string, "left", length) == 0) {	/* for debugging */
	*indexPtr = entryPtr->entry.leftIndex;
    } else if (strncmp(string, "right", length) == 0) {	/* for debugging */
	*indexPtr = entryPtr->entry.rightIndex;
    } else if (strncmp(string, "anchor", length) == 0) { /* COMPAT */
	*indexPtr = entryPtr->entry.selectAnchor;
    } else if (strncmp(string, "sel.", 4) == 0) {
	if (entryPtr->entry.selectFirst < 0) {
	    Tcl_ResetResult(interp);
	    Tcl_AppendResult(interp, "selection isn't in widget ",
		    Tk_PathName(entryPtr->core.tkwin), NULL);
	    return TCL_ERROR;
	}
	if (strncmp(string, "sel.first", length) == 0) {
	    *indexPtr = entryPtr->entry.selectFirst;
	} else if (strncmp(string, "sel.last", length) == 0) {
	    *indexPtr = entryPtr->entry.selectLast;
	} else {
	    goto badIndex;
	}
    } else if (string[0] == '@') {
	int roundUp = 0;
	int maxWidth = EntryWidth(entryPtr);
	int x;

	if (Tcl_GetInt(interp, string + 1, &x) != TCL_OK) {
	    goto badIndex;
	}
	if (x > maxWidth) {
	    x = maxWidth;
	    roundUp = 1;
	}
	*indexPtr = Tk_PointToChar(entryPtr->entry.textLayout,
		x - entryPtr->entry.layoutX, 0);

	if (*indexPtr < entryPtr->entry.leftIndex) {
	    *indexPtr = entryPtr->entry.leftIndex;
	}

	/*
	 * Special trick:  if the x-position was off-screen to the right,
	 * round the index up to refer to the character just after the
	 * last visible one on the screen.  This is needed to enable the
	 * last character to be selected, for example.
	 */

	if (roundUp && (*indexPtr < entryPtr->entry.numChars)) {
	    *indexPtr += 1;
	}
    } else {
	if (Tcl_GetInt(interp, string, indexPtr) != TCL_OK) {
	    goto badIndex;
	}
	if (*indexPtr < 0) {
	    *indexPtr = 0;
	} else if (*indexPtr > entryPtr->entry.numChars) {
	    *indexPtr = entryPtr->entry.numChars;
	}
    }
    return TCL_OK;

badIndex:
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, "bad entry index \"", string, "\"", NULL);
    return TCL_ERROR;
}

/* EntryCompatCommand --
 * 	Compatibility subcommands.  See entry.tcl for details.
 */
static int
EntryCompatCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    int status;
    Tcl_Obj *cmdName = Tcl_NewStringObj("::tile::entry::compat", -1);
    Tcl_Obj *cmd = Tcl_NewListObj(objc, objv);

    Tcl_ListObjReplace(interp, cmd, 0,0, 1,&cmdName);

    Tcl_IncrRefCount(cmdName); Tcl_IncrRefCount(cmd);
    status = Tcl_EvalObjEx(interp, cmd, 0);
    Tcl_DecrRefCount(cmdName); Tcl_DecrRefCount(cmd);

    return status;
}

/* $entry bbox $index --
 * 	Return the bounding box of the character at the specified index.
 */
static int
EntryBBoxCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int index, x, y, width, height;
    char buf[TCL_INTEGER_SPACE * 4];

    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "index");
	return TCL_ERROR;
    }
    if (EntryIndex(interp, entryPtr, objv[2], &index) != TCL_OK) {
	return TCL_ERROR;
    }
    if ((index == entryPtr->entry.numChars) && (index > 0)) {
	index--;
    }
    Tk_CharBbox(entryPtr->entry.textLayout, index, &x, &y, &width, &height);
    sprintf(buf, "%d %d %d %d",
		 x + entryPtr->entry.layoutX, y + entryPtr->entry.layoutY,
		 width, height);
    Tcl_SetResult(interp, buf, TCL_VOLATILE);
    return TCL_OK;
}

/* $entry delete $from ?$to? --
 *	Delete the characters in the range [$from,$to).
 *	$to defaults to $from+1 if not specified.
 */
static int
EntryDeleteCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int first, last;

    if ((objc < 3) || (objc > 4)) {
	Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
	return TCL_ERROR;
    }
    if (EntryIndex(interp, entryPtr, objv[2], &first) != TCL_OK) {
	return TCL_ERROR;
    }
    if (objc == 3) {
	last = first + 1;
    } else if (EntryIndex(interp, entryPtr, objv[3], &last) != TCL_OK) {
	return TCL_ERROR;
    }

    if (last >= first && EntryEditable(entryPtr)) {
	return DeleteChars(entryPtr, first, last - first);
    }
    return TCL_OK;
}

/* $entry get --
 * 	Return the current value of the entry widget.
 */
static int
EntryGetCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, NULL);
	return TCL_ERROR;
    }
    Tcl_SetResult(interp, entryPtr->entry.string, TCL_VOLATILE);
    return TCL_OK;
}

/* $entry icursor $index --
 * 	Set the insert cursor position.
 */
static int
EntryICursorCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "pos");
	return TCL_ERROR;
    }
    if (EntryIndex(interp, entryPtr, objv[2],
	    &entryPtr->entry.insertPos) != TCL_OK) {
	return TCL_ERROR;
    }
    WidgetChanged(&entryPtr->core, REDISPLAY_REQUIRED);
    return TCL_OK;
}

/* $entry index $index --
 * 	Return numeric value (0..numChars) of the specified index.
 */
static int
EntryIndexCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int index;

    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "string");
	return TCL_ERROR;
    }
    if (EntryIndex(interp, entryPtr, objv[2], &index) != TCL_OK) {
	return TCL_ERROR;
    }
    Tcl_SetObjResult(interp, Tcl_NewIntObj(index));
    return TCL_OK;
}

/* $entry insert $index $text --
 * 	Insert $text after position $index.
 * 	Silent no-op if the entry is disabled or read-only.
 */
static int
EntryInsertCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int index;

    if (objc != 4) {
	Tcl_WrongNumArgs(interp, 2, objv, "index text");
	return TCL_ERROR;
    }
    if (EntryIndex(interp, entryPtr, objv[2], &index) != TCL_OK) {
	return TCL_ERROR;
    }
    if (EntryEditable(entryPtr)) {
	return InsertChars(entryPtr, index, Tcl_GetString(objv[3]));
    }
    return TCL_OK;
}

/* selection clear --
 * 	Clear selection.
 */
static int EntrySelectionClearCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;

    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 3, objv, NULL);
	return TCL_ERROR;
    }
    entryPtr->entry.selectFirst = entryPtr->entry.selectLast = -1;
    WidgetChanged(&entryPtr->core, REDISPLAY_REQUIRED);
    return TCL_OK;
}

/* $entry selection from $index (COMPAT)
 * 	Set the selection anchor.
 */
static int EntrySelectionFromCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    if (objc != 4) {
	Tcl_WrongNumArgs(interp, 3, objv, "index");
	return TCL_ERROR;
    }
    return EntryIndex(interp,entryPtr,objv[3],&entryPtr->entry.selectAnchor);
}

/* $entry selection present --
 * 	Returns 1 if any characters are selected, 0 otherwise.
 */
static int EntrySelectionPresentCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 3, objv, NULL);
	return TCL_ERROR;
    }
    Tcl_SetObjResult(interp,
	    Tcl_NewBooleanObj(entryPtr->entry.selectFirst >= 0));
    return TCL_OK;
}

/* $entry selection range $start $end --
 * 	Explicitly set the selection range.
 */
static int EntrySelectionRangeCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int start, end;
    if (objc != 5) {
	Tcl_WrongNumArgs(interp, 3, objv, "start end");
	return TCL_ERROR;
    }
    if (    EntryIndex(interp, entryPtr, objv[3], &start) != TCL_OK
         || EntryIndex(interp, entryPtr, objv[4], &end) != TCL_OK) {
	return TCL_ERROR;
    }
    if (entryPtr->core.state & TTK_STATE_DISABLED) {
	return TCL_OK;
    }

    if (start >= end) {
	entryPtr->entry.selectFirst = entryPtr->entry.selectLast = -1;
    } else {
	entryPtr->entry.selectFirst = start;
	entryPtr->entry.selectLast = end;
	EntryOwnSelection(entryPtr);
    }
    WidgetChanged(&entryPtr->core, REDISPLAY_REQUIRED);
    return TCL_OK;
}

/* $entry selection $command ?arg arg...?
 *	Ensemble, see above.
 */
static int EntrySelectionCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    static WidgetCommandSpec EntrySelectionCommands[] = {
	{ "clear", EntrySelectionClearCommand },
	{ "present", EntrySelectionPresentCommand },
	{ "range", EntrySelectionRangeCommand },

	{ "adjust", EntryCompatCommand },
	{ "from", EntrySelectionFromCommand },
	{ "to", EntryCompatCommand },
	{0,0}
    };
    return WidgetEnsembleCommand(
	    EntrySelectionCommands, 2, interp, objc, objv, recordPtr);
}

/* $entry set $value
 * 	Sets the value of an entry widget.
 */
static int EntrySetCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "value");
	return TCL_ERROR;
    }
    /* @@@ TODO: validate? */
    EntrySetValue(entryPtr, Tcl_GetString(objv[2]));
    return TCL_OK;
}

/* $entry validate --
 * 	Trigger forced validation.  Returns 1/0 if validation succeeds/fails
 * 	or error status from -validatecommand / -invalidcommand.
 */
static int EntryValidateCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int code;

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 2, objv, NULL);
	return TCL_ERROR;
    }

    code = EntryValidateChange(
	    entryPtr, entryPtr->entry.string, -1, 0, VALIDATE_FORCED);

    if (code == TCL_ERROR)
	return code;

    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(code == TCL_OK));
    return TCL_OK;
}

/* $entry xview	-- return current view region
 * $entry xview $index -- set leftIndex
 * $entry xview moveto $fraction
 * $entry xview scroll $number $what -- scrollbar interface
 */
static int EntryXViewCommand(
    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], void *recordPtr)
{
    Entry *entryPtr = recordPtr;
    int index;

    if (objc == 2) {
	double first, last;
	char buf[TCL_DOUBLE_SPACE * 2];

	EntryPlaceTextLayout(entryPtr);	/* Ensure up-to-date */
	EntryVisibleRange(entryPtr, &first, &last);
	sprintf(buf, "%g %g", first, last);
	Tcl_SetResult(interp, buf, TCL_VOLATILE);
	return TCL_OK;
    } else if (objc == 3) {
	if (EntryIndex(interp, entryPtr, objv[2], &index) != TCL_OK) {
	    return TCL_ERROR;
	}
    } else {
	double fraction;
	int count;

	index = entryPtr->entry.leftIndex;
	switch (Tk_GetScrollInfoObj(interp, objc, objv, &fraction, &count)) {
	    case TK_SCROLL_ERROR:
		return TCL_ERROR;
	    case TK_SCROLL_MOVETO:
		index = (int) ((fraction * entryPtr->entry.numChars) + 0.5);
		break;
	    case TK_SCROLL_UNITS:
		index += count;
		break;
	    case TK_SCROLL_PAGES: {
		int charsPerPage = (
		    EntryWidth(entryPtr) / entryPtr->entry.avgWidth)
		    - 2;
		if (charsPerPage < 1) {
		    charsPerPage = 1;
		}
		index += count * charsPerPage;
		break;
	    }
	}
    }
    if (index >= entryPtr->entry.numChars) {
	index = entryPtr->entry.numChars - 1;
    }
    if (index < 0) {
	index = 0;
    }
    entryPtr->entry.leftIndex = index;

    EntryPlaceTextLayout(entryPtr);
    WidgetChanged(&entryPtr->core, REDISPLAY_REQUIRED);
    return TCL_OK;
}

static WidgetCommandSpec EntryCommands[] =
{
    { "bbox", 		EntryBBoxCommand },
    { "cget", 		WidgetCgetCommand },
    { "configure", 	WidgetConfigureCommand },
    { "delete", 	EntryDeleteCommand },
    { "get", 		EntryGetCommand },
    { "icursor", 	EntryICursorCommand },
    { "index", 		EntryIndexCommand },
    { "insert", 	EntryInsertCommand },
    { "instate",	WidgetInstateCommand },
    { "scan", 		EntryCompatCommand },
    { "selection", 	EntrySelectionCommand },
    { "state",  	WidgetStateCommand },
    { "validate", 	EntryValidateCommand },
    { "xview", 		EntryXViewCommand },
    {0,0}
};

/*------------------------------------------------------------------------
 * +++ Entry widget definition.
 */

WidgetSpec EntryWidgetSpec =
{
    "TEntry",			/* className */
    sizeof(Entry), 		/* recordSize */
    EntryCompatOptionSpecs,	/* optionSpecs */
    EntryCommands,  		/* subcommands */
    EntryInitialize,     	/* initializeProc */
    EntryCleanup,		/* cleanupProc */
    EntryConfigure,		/* configureProc */
    EntryPostConfigure,  	/* postConfigureProc */
    WidgetGetLayout, 		/* getLayoutProc */
    WidgetSize, 		/* sizeProc */
    EntryDoLayout,		/* layoutProc */
    EntryDisplay,		/* displayProc */
    WIDGET_SPEC_END		/* sentinel */
};

/*------------------------------------------------------------------------
 * +++ Combobox widget record.
 */

typedef struct {
    Tcl_Obj *postCommandObj;
    Tcl_Obj *valuesObj;
} ComboboxPart;

typedef struct {
    WidgetCore core;
    EntryPart entry;
    ComboboxPart combobox;
} Combobox;

static Tk_OptionSpec ComboboxOptionSpecs[] =
{
    {TK_OPTION_STRING, "-postcommand", "postCommand", "PostCommand",
        "", Tk_Offset(Combobox, combobox.postCommandObj), -1,
	0,0,0 },
    {TK_OPTION_STRING, "-values", "values", "Values",
        "", Tk_Offset(Combobox, combobox.valuesObj), -1,
	0,0,0 },
    WIDGET_INHERIT_OPTIONS(EntryOptionSpecs)
};

/* ComboboxInitialize --
 * 	Initialization hook for combobox widgets.
 */

static int
ComboboxInitialize(Tcl_Interp *interp, void *recordPtr)
{
    WidgetCore *corePtr = recordPtr;
    TrackElementState(corePtr);
    return EntryInitialize(interp, recordPtr);
}

/* ComboboxConfigure --
 * 	Configuration hook for combobox widgets.
 */
static int
ComboboxConfigure(Tcl_Interp *interp, void *recordPtr, int mask)
{
    Combobox *cbPtr = recordPtr;
    int unused; 

    /* Make sure -values is a valid list:
     */
    if (Tcl_ListObjLength(interp,cbPtr->combobox.valuesObj,&unused) != TCL_OK)
	return TCL_ERROR;

    return EntryConfigure(interp, recordPtr, mask);
}

/*------------------------------------------------------------------------
 * +++ Combobox widget definition.
 */
static WidgetCommandSpec ComboboxCommands[] =
{
    { "bbox", 		EntryBBoxCommand },
    { "cget", 		WidgetCgetCommand },
    { "configure", 	WidgetConfigureCommand },
    { "delete", 	EntryDeleteCommand },
    { "get", 		EntryGetCommand },
    { "icursor", 	EntryICursorCommand },
    { "identify",	WidgetIdentifyCommand },
    { "index", 		EntryIndexCommand },
    { "insert", 	EntryInsertCommand },
    { "instate",	WidgetInstateCommand },
    { "selection", 	EntrySelectionCommand },
    { "state",  	WidgetStateCommand },
    { "set", 		EntrySetCommand },
    { "xview", 		EntryXViewCommand },
    {0,0}
};

WidgetSpec ComboboxWidgetSpec =
{
    "TCombobox",		/* className */
    sizeof(Combobox), 		/* recordSize */
    ComboboxOptionSpecs,	/* optionSpecs */
    ComboboxCommands,  		/* subcommands */
    ComboboxInitialize,     	/* initializeProc */
    EntryCleanup,		/* cleanupProc */
    ComboboxConfigure,		/* configureProc */
    EntryPostConfigure,  	/* postConfigureProc */
    WidgetGetLayout, 		/* getLayoutProc */
    WidgetSize, 		/* sizeProc */
    EntryDoLayout,		/* layoutProc */
    EntryDisplay,		/* displayProc */
    WIDGET_SPEC_END		/* sentinel */
};


/*------------------------------------------------------------------------
 * +++ Textarea element.
 *
 * Text display area for Entry widgets.
 * Just computes requested size; display is handled by the widget itself.
 */

typedef struct {
    Tcl_Obj	*fontObj;
    Tcl_Obj	*widthObj;
} TextareaElement;

static TTK_ElementOptionSpec TextareaElementOptions[] = {
    { "-font", TK_OPTION_FONT,
	Tk_Offset(TextareaElement,fontObj), DEF_ENTRY_FONT },
    { "-width", TK_OPTION_INT,
	Tk_Offset(TextareaElement,widthObj), "20" },
    {0,0,0}
};

static void TextareaElementGeometry(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *widthPtr, int *heightPtr, TTK_Padding *paddingPtr)
{
    TextareaElement *textarea = elementRecord;
    Tk_Font font = Tk_GetFontFromObj(tkwin, textarea->fontObj);
    int avgWidth = Tk_TextWidth(font, "0", 1);
    Tk_FontMetrics fm;
    int prefWidth = 1;

    Tk_GetFontMetrics(font, &fm);
    Tcl_GetIntFromObj(NULL, textarea->widthObj, &prefWidth);
    if (prefWidth <= 0)
	prefWidth = 1;

    *heightPtr = fm.linespace;
    *widthPtr = prefWidth * avgWidth;
}

static TTK_ElementSpec TextareaElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(TextareaElement),
    TextareaElementOptions,
    TextareaElementGeometry,
    NullElementDraw
};

TTK_BEGIN_LAYOUT(ComboboxLayout)
    TTK_NODE("Combobox.background", TTK_FILL_BOTH)
    TTK_GROUP("Combobox.field", TTK_FILL_BOTH,
	TTK_NODE("Combobox.downarrow", TTK_PACK_RIGHT|TTK_FILL_Y)
	TTK_GROUP("Combobox.padding", TTK_FILL_BOTH|TTK_PACK_LEFT|TTK_EXPAND,
	    TTK_NODE("Combobox.textarea", TTK_FILL_BOTH)))
TTK_END_LAYOUT

/* EntryWidget_Init --
 * 	Register entry-based widgets and related resources.
 */
int EntryWidget_Init(Tcl_Interp *interp)
{
    TTK_Theme themePtr =  TTK_GetDefaultTheme(interp);

    TTK_RegisterElementSpec(themePtr, "textarea", &TextareaElementSpec, 0);

    TTK_RegisterLayout(themePtr, "TCombobox", ComboboxLayout);

    RegisterWidget(interp, "tentry", &EntryWidgetSpec);
    RegisterWidget(interp, "tcombobox", &ComboboxWidgetSpec);

    return TCL_OK;
}

/*EOF*/
