/* Copyright (c) 2004, Noah Sorscher
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 	¥ 	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * 	¥ 	Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * 	¥ 	Neither the name of the Noah Sorscher nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
#import "tTableView.h"

@implementation tTableView
/*
- (BOOL)performKeyEquivalent:(NSEvent *)theEvent
{
    return [super performKeyEquivalent:theEvent];
}

- (void)keyDown:(NSEvent *)theEvent
{
    [super keyDown:theEvent];
}
*/


- (void)textDidEndEditing:(NSNotification *)aNotification
{
    //NSLog(@"tTableView textDidEndEditing");
    int keyType = [[[aNotification userInfo] objectForKey:@"NSTextMovement"] intValue];
    int row = [self editedRow];
    //int col = [self editedColumn];
   // NSString *string = [[aNotification object] string];
    //[[self dataSource] tableView:self setObjectValue:string forTableColumn:[[self tableColumns] objectAtIndex:col] row:row];
    //[[aNotification object] setString:string];
    //[self selectRow:-1 byExtendingSelection:NO];
    //[self selectRow:0 byExtendingSelection:NO];
    [super textDidEndEditing:aNotification];
    if (NSReturnTextMovement == keyType) {
        //[self selectRow:[self selectedRow] byExtendingSelection:NO];
        [self selectColumn:0 byExtendingSelection:NO];
        [self selectRow:row byExtendingSelection:NO];
        [self scrollRowToVisible:row];
    }
}



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

- (id) typeaheadDisplay
{
	return typeaheadDisplay;
}

- (void)keyDown:(NSEvent*)inEvent
{
        unichar uch = [[inEvent characters] characterAtIndex:0];
        if (uch == NSUpArrowFunctionKey || uch == NSDownArrowFunctionKey || uch == '\t')
            [super keyDown:inEvent];
        else
            // 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 (!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 (!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];
                
                if ([mStringToFind length] % 5 == 0 && [mStringToFind length])
                    if ([[self delegate] respondsToSelector:@selector(willClearTypeAheadString:inTableView:)])
                        [[self delegate] willClearTypeAheadString:mStringToFind inTableView:self];
	}
}

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

}


@end
