
#import "TypeaheadTableView.h"

@implementation TypeaheadTableView

- (void)dealloc
{
	[mStringToFind release];
	[super dealloc];
}

- (id) typeaheadDisplay
{
	return typeaheadDisplay;
}

- (void)keyDown:(NSEvent*)inEvent
{
	// invoking -[NSResponder interpretKeyEvents] will cause insertText: to be invoked.
	// Improvement:  Allow function keys to still work....
	[self interpretKeyEvents:[NSArray arrayWithObject:inEvent]];
}

- (void)insertText:(id)inString
{
	// Make sure delegate will handle type-ahead
	if ([[self delegate] respondsToSelector:@selector(typeAheadString:inTableView:)])
	{
		// We clear it out after two times the key repeat rate "InitialKeyRepeat" user default.
		// (converted from sixtieths of a second to seconds), but no more than two seconds.
		// This behavior is determined based on Inside Macintosh documentation on the List Manager.

		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		int keyThreshTicks = [defaults integerForKey:@"InitialKeyRepeat"];
		NSTimeInterval clearDelay;
		if (0 == keyThreshTicks)	// missing value in defaults?  Probably not overridden by user
		{
			keyThreshTicks = 35;	// If not yet set by user, this appears to be the default value.
		}
		clearDelay = MIN(2.0/60.0*keyThreshTicks, 2.0);
		
		if ( nil == mStringToFind )
		{
			mStringToFind = [[NSMutableString alloc] init]; // lazily allocate the mutable string if needed.
		}
		[mStringToFind appendString:inString];
	
		// Cancel any previously queued future invocations of clearAccumulatingTypeahead
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(clearAccumulatingTypeahead) object:nil];
	
		// queue an invocation of clearAccumulatingTypeahead for the near future.
		[self performSelector:@selector(clearAccumulatingTypeahead) withObject:nil afterDelay:clearDelay];
	
		// Let the table's delegate do something with the string.
		// We use stringWithString to make an autoreleased copy so for its use,
		// since we may clear out the original string below before it can be used.
		[[self delegate] typeAheadString:[NSString stringWithString:mStringToFind] inTableView:self];

		// Show the current typeahead string in the optional display field, like CodeWarrior does
		[[self typeaheadDisplay] setObjectValue:mStringToFind];
	}
}

- (void) clearAccumulatingTypeahead
{
	[mStringToFind setString:@""];	// clear out the queued string to find
	[[self typeaheadDisplay] setObjectValue:nil];	// clear out the optional display of what's typed

}

// ----------------------------------------------------------------------------------------
// Drag & Drop Support
// ----------------------------------------------------------------------------------------

/*"	This allows dragging out of the application.
"*/

- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
{
	if (isLocal) return NSDragOperationEvery;
	else return NSDragOperationCopy;
}




@end
