//
//  ExternalDragTableView.m
//  DocYouMeant2
//
#import "ExternalDragTableView.h"

/*!
 * An enhanced table view that allows dragging outside of an application, as well as 
 * not moving to the next line automatically and putting up contextual menus specific
 * to the clicked cell.
 */
@implementation ExternalDragTableView
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal {
	id delegate = [self delegate];
	if (delegate != nil && [delegate respondsToSelector:@selector(tableView:draggingSourceOperationMaskForLocal:)]) {
		return [delegate tableView:self draggingSourceOperationMaskForLocal:isLocal];
		
	} else {
		return [super draggingSourceOperationMaskForLocal:isLocal];
	}
}

- (void)textDidEndEditing:(NSNotification *)notification; 
{ 
	if ([[[notification userInfo] objectForKey:@"NSTextMovement"] intValue] == NSReturnTextMovement) { 
		// This is ugly, but just about the only way to do it. 
		// NSTableView is determined to select and edit something else, even the 
		// text field that it just finished editing, unless we mislead it about 
		// what key was pressed to end editing. 
		NSMutableDictionary *newUserInfo; 
		NSNotification *newNotification; 

		newUserInfo = [NSMutableDictionary dictionaryWithDictionary:[notification userInfo]]; 
		[newUserInfo setObject:[NSNumber numberWithInt:NSIllegalTextMovement] forKey:@"NSTextMovement"]; 
		newNotification = [NSNotification notificationWithName:[notification name] object:[notification object] userInfo:newUserInfo]; 
		[super textDidEndEditing:newNotification]; 
		
		// For some reason we lose firstResponder status when when we do the above.
		[[self window] makeFirstResponder:self];
	} else { 
		[super textDidEndEditing:notification]; 
	} 
}

- (NSMenu *)menuForEvent:(NSEvent *)theEvent
{
	NSPoint localPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
	int column = [self columnAtPoint:localPoint];
	int row = [self rowAtPoint:localPoint];
	if (column == -1 || row == -1) {
		return [self menu];
	} else {
		id delegate = [self delegate];
		if (delegate != nil && (![delegate respondsToSelector:@selector(tableView:shouldSelectRow:)] || [delegate tableView:self shouldSelectRow:row])) {
			if (![[self selectedRowIndexes] containsIndex:row]) {
				[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
			}
			NSCell *cell = [[[self tableColumns] objectAtIndex:column] dataCellForRow:row];
			return [cell menu];
		} else {
			return [self menu];
		}
	}
}
@end
