
#import "DNDArrayController.h"

static NSString * const kDraggedRowsType = @"com.belkadan.utils.kDraggedRowsType";

/*!
 * Simple subclass of NSArrayController that supports drag-and-drop. Connect
 * the <code>dataSource</code> outlet of your table view to this class, and
 * ignore the "improper data source" warning that comes up occasionally.
 * Modified by Belkadan Software.
 *
 * @author Malcolm Crawford
 * @since 10.3
 */
@implementation DNDArrayController

/*
 Copyright (c) 2004, Apple Computer, Inc., all rights reserved.
 
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation, 
 modification or redistribution of this Apple software constitutes acceptance of these 
 terms.  If you do not agree with these terms, please do not use, install, modify or 
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and subject to these 
 terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in 
 this original Apple software (the "Apple Software"), to use, reproduce, modify and 
 redistribute the Apple Software, with or without modifications, in source and/or binary 
 forms; provided that if you redistribute the Apple Software in its entirety and without 
 modifications, you must retain this notice and the following text and disclaimers in all 
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks 
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from 
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your 
 derivative works or by other works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES, 
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, 
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS 
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL 
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
		  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, 
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND 
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR 
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

static NSArray *typesArray = nil;

/*!
 * Registers this table's drag type.
 * Don't forget to call <code>[super awakeFromNib]</code> when subclassing.
 */
- (void)awakeFromNib
{
    // register for drag and drop
	typesArray = [[NSArray alloc] initWithObjects:kDraggedRowsType, nil];
    [tableView registerForDraggedTypes:typesArray];
}

#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
/*!
 * Begins a drag by saving the NSNumbers in <code>rows</code> as the index set of dragged rows.
 * @deprecated Mac OS 10.4
 */
- (BOOL)tableView:(NSTableView *)tv writeRows:(NSArray *)rows toPasteboard:(NSPasteboard *)pboard
{
	// declare our own pasteboard types	
	[pboard declareTypes:typesArray owner:self];
	
    // add rows array for local move
//    [pboard setPropertyList:rows forType:kDraggedRowsType];
	draggedIndexes = [[NSIndexSet alloc] initWithIndexesInArray:rows];
	
    return YES;
}
#endif

/*!
 * Begins a drag by saving <code>rowIndexes</code> as the index set of dragged rows.
 * @since Mac OS 10.4
 */
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard
{
	// declare our own pasteboard types
	[pboard declareTypes:typesArray owner:self];
	
	draggedIndexes = [rowIndexes retain];
	
	return YES;
}

/*!
 * Makes sure that the dragged row is dropped between rows, instead of on top of one. Returns the default
 * drag operation, <code>NSDragOperationMove</code>. Override if you want to support other drag operations.
 */
- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op
{
    // we want to put the object at, not over,
    // the current row (contrast NSTableViewDropOn) 
    [tv setDropRow:row dropOperation:NSTableViewDropAbove];
	
    return NSDragOperationMove;
}

/*!
 * Accepts the drag/drop only if it came from this table. Moves the rows that were saved earlier, then
 * selects them.
 *
 * @see #moveObjectsInArrangedObjectsFromIndexes:toIndex:
 */
- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)op
{
	if (row < 0)
	{
		row = 0;
	}
    
    // if drag source is self, it's a move
    if ([info draggingSource] == tableView)
    {
//		NSArray *rows = [[info draggingPasteboard] propertyListForType:kDraggedRowsType];
//		NSIndexSet *indexSet = [self createIndexSetFromRows:rows];
		NSIndexSet *selectionIndexes;
		int rowsAbove;
		NSRange range;
		
		[self moveObjectsInArrangedObjectsFromIndexes:draggedIndexes toIndex:row];
		
		// set selected rows to those that were just moved
		// Need to work out what moved where to determine proper selection...
		rowsAbove = [self rowsAboveRow:row inIndexSet:draggedIndexes];
		
		range = NSMakeRange(row - rowsAbove, [draggedIndexes count]);
		selectionIndexes = [[NSIndexSet alloc] initWithIndexesInRange:range];
		[self setSelectionIndexes:selectionIndexes];
		
		[selectionIndexes release];
		[draggedIndexes release];
		
		return YES;
    }
	return NO;
}

/*!
 * Uses NSArrayController methods to move the rows at the indexes in <code>indexSet</code> to
 * <code>insertIndex</code>. So far there is not an efficient way to do this, so the method
 * basically loops through the objects, removes them, and adds them one by one.
 */
- (void)moveObjectsInArrangedObjectsFromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned int)insertIndex
{
    NSArray		*objects = [[self arrangedObjects] copy];
	int			index = [indexSet lastIndex];
	
    int			aboveInsertIndexCount = 0;
    id			object;
    int			removeIndex;
	
    while (NSNotFound != index)
	{
		if (index >= insertIndex) {
			removeIndex = index + aboveInsertIndexCount;
			aboveInsertIndexCount += 1;
		}
		else
		{
			removeIndex = index;
			insertIndex -= 1;
		}
		
		object = [objects objectAtIndex:index];
		[self removeObjectAtArrangedObjectIndex:removeIndex];
		[self insertObject:object atArrangedObjectIndex:insertIndex];
		
		index = [indexSet indexLessThanIndex:index];
    }
	
	[objects release];
}

/*!
 * Basically, counts the number of indexes in <code>indexSet</code> that are numerically before <code>row</code>.
 */
- (int)rowsAboveRow:(int)row inIndexSet:(NSIndexSet *)indexSet
{
    unsigned currentIndex = [indexSet firstIndex];
    int i = 0;
    while (currentIndex != NSNotFound && currentIndex < row)
    {
		i++;
		currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
    }
    return i;
}

@end