
//	Copyright not only by H. Giesen, University of Koblenz-Landau 1996


#import "BibBrowser.h"
#import "MyBrowserCell.h"

#define searchStringLength 128
static	unsigned char searchString[searchStringLength];


@implementation BibBrowser


- initFrame: (const NXRect *) frameRect
{	
	[super initFrame: frameRect];
	inputTimeOut = 0.5;
	return self;
}


//	 Timed Entry Methods (Private)

void Search (timedEntry, now, self)
	DPSTimedEntry	timedEntry;
	double			now;
	void*			self;
{
	[(id)self perform: @selector (_search)];
}


- _addTimedEntry
{
	timedEntry =
		DPSAddTimedEntry(
			inputTimeOut, Search, (void *)self, NX_MODALRESPTHRESHOLD
		);
	NXPing();
	return self;
}


- _removeTimedEntry
{
	if ( !timedEntry) return self;
	DPSRemoveTimedEntry (timedEntry);
	timedEntry = 0;
	return self;
}


- _search
{
	//  Searches current search column for first occurrence of searchString
	
	int		iterator;
	char	path[1024];
	int		len;
	int		numRows, numCols;
	int		searchColumn = [self lastColumn];
	Matrix	*matrix = [self matrixInColumn: searchColumn];
	MyBrowserCell	*currentCell = nil;
	BOOL	found = NO;
	
	[self _removeTimedEntry];

	[matrix getNumRows:&numRows numCols:&numCols];
	for(iterator = 0; iterator < numRows; iterator++){
		currentCell = [matrix cellAt:iterator :0];
		if( [currentCell isEnabled]==NO ) continue;
		if (NXOrderStrings([currentCell stringValue], searchString, 
			NO, strlen (searchString), NULL) == 0){
			[matrix selectCellAt: -1 :-1];
			[matrix selectCellAt:iterator :0];
			found = YES;
			break;
		}
	}

	searchString[0] = '\0';
	if (! found){ NXBeep(); return self; }

	[matrix scrollCellToVisible:iterator :0];
	[self getPath:path toColumn:searchColumn];
	len = strlen( path );
	sprintf( &path[len], "/%s/", [currentCell stringValue] );
	[self doClick:matrix];
	return self;
}


- selectAll:sender	// sender is a matrix
{
	int	last = [self lastColumn];
	Matrix	*matrix = [self matrixInColumn:last];

	//[matrix selectAll:sender];
	[super selectAll:sender];
	if( [[self delegate] respondsTo:@selector(selectAllIn:column:)] ){
		[[self delegate]
			perform:@selector(selectAllIn:column:)
			with:matrix with:(id)last];
	}
	return self;
}

#define RETURN		13
#define LEFTARROW	172
#define UPARROW		173
#define RIGHTARROW	174
#define DOWNARROW	175

- keyDown:(NXEvent *) theEvent
{
	[self _removeTimedEntry];

	if ([self isEnabled] == NO) return self;

	if( [[self window] isDisplayEnabled]==NO )[[self window] reenableDisplay];

	switch (theEvent->data.key.charCode) {
		case LEFTARROW	:
		case UPARROW	:
		case DOWNARROW	:
		case RIGHTARROW	:	[super keyDown:theEvent];
							if(0)[self doClick:
								[self matrixInColumn:[self lastColumn]]]; //??
							break;
		case RETURN		:
		default			:
			if(theEvent->data.key.repeat) return self;
			if( strlen(searchString)<searchStringLength )
				sprintf(searchString, "%s%c",
					searchString, theEvent->data.key.charCode);
			[self _addTimedEntry];
			break;
	}
		
	return self;
}


@end
