/*
QueryFieldEditor.m - Copyright (c) 1992 NeXT Computer, Inc.

You may freely copy, distribute and reuse the code in this example.
NeXT Computer, Inc. disclaims any warranty of any kind, expressed 
or implied, as to its fitness for any particular use.
*/

#define	ESCAPE	0x1B
#define	SPACE	0x20

#import	<appkit/NXCType.h>
#import	"QueryFieldEditor.h"

@implementation QueryFieldEditor

static unsigned short
QueryFilter(register unsigned short theChar, 
    int flags, unsigned short charSet)
{
    if (theChar == ESCAPE) return 0;
    if (theChar == SPACE && (flags & NX_COMMANDMASK)) return 0;
    return NXFieldFilter(theChar, flags, charSet);
}

- initFrame:(NXRect *)frameRect text:(char *)theText alignment:(int)mode
{
    [super initFrame:frameRect text:theText alignment:mode];
    charFilterFunc = QueryFilter;
    return self;
}

- setCursor:(id <IXCursorPositioning>)aCursor
{
    cursor = aCursor;
    return self;
}

- complete
{
    char		word[1024];
    char		*key;
    unsigned		keyLength;
    int			len;
    NXSelPt		start, end;
    
    /* Check for error conditions */
    if (cursor == nil) {
	NXBeep();
	return nil;
    }
    
    len = [self textLength];
    [self getSubstring:word start:0 length:len];
    word[len] = '\0';
    for (key = word; *key; ++key)
	if (NXIsUpper(*key)) *key = NXToLower(*key);

    /* Probe for the word -- if it exists take the next word */
    if ([cursor setKey:(const void *)wordW)Length:len])
	[cursor setNext];

    /* Check for suffix selection */ 
    [self getSel:&start :&end];
    if ((end.cp != len) || (start.cp == 0)) {
	[self setSel:len :len];
	[self getSel:&start :&end];
    } else {
	len = start.cp;
    }

    /* Cycle through keys */
    [cursor getKey:(void **)&key andLength:&keyLength];
    if (len < keyLength && !strncmp( word, key, len)) {
	[self replaceSel:key + len length:keyLength - len];
	[self setSel:len :[self textLength]];
    } else {
	if (len == end.cp) {
	    NXBeep();
	    return self;
	}
	[self replaceSel:""];
	return [self complete]; 
    }

    return self;
}
	
- keyDown:(NXEvent *)theEvent
{
    if (theEvent->data.key.charCode == ESCAPE
	|| (theEvent->data.key.charCode == ' '
	    && (theEvent->flags & NX_COMMANDMASK)))
	return[self complete];

    return [super keyDown:theEvent];
}

@end
