PXSourceList.m 30.8 KB
Newer Older
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1 2 3 4 5 6 7 8 9 10 11
//
//  PXSourceList.m
//  PXSourceList
//
//  Created by Alex Rozanski on 05/09/2009.
//  Copyright 2009-10 Alex Rozanski http://perspx.com
//
//  GC-enabled code revised by Stefan Vogt http://byteproject.net
//

#import "PXSourceList.h"
12
#import "SideBarItem.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
13 14

//Layout constants
15 16 17 18 19 20
#define MIN_BADGE_WIDTH     22.0            //The minimum badge width for each item (default 22.0)
#define BADGE_HEIGHT        14.0            //The badge height for each item (default 14.0)
#define BADGE_MARGIN        5.0             //The spacing between the badge and the cell for that row
#define ROW_RIGHT_MARGIN    5.0             //The spacing between the right edge of the badge and the edge of the table column
#define ICON_SPACING        2.0             //The spacing between the icon and it's adjacent cell
#define DISCLOSURE_TRIANGLE_SPACE   18.0    //The indentation reserved for disclosure triangles for non-group items
Felix Paul Kühne's avatar
Felix Paul Kühne committed
21 22

//Drawing constants
23 24 25 26 27 28
#define BADGE_BACKGROUND_COLOR              [NSColor colorWithCalibratedRed:(152/255.0) green:(168/255.0) blue:(202/255.0) alpha:1]
#define BADGE_HIDDEN_BACKGROUND_COLOR       [NSColor colorWithDeviceWhite:(180/255.0) alpha:1]
#define BADGE_SELECTED_TEXT_COLOR           [NSColor keyboardFocusIndicatorColor]
#define BADGE_SELECTED_UNFOCUSED_TEXT_COLOR [NSColor colorWithCalibratedRed:(153/255.0) green:(169/255.0) blue:(203/255.0) alpha:1]
#define BADGE_SELECTED_HIDDEN_TEXT_COLOR    [NSColor colorWithCalibratedWhite:(170/255.0) alpha:1]
#define BADGE_FONT                          [NSFont boldSystemFontOfSize:11]
Felix Paul Kühne's avatar
Felix Paul Kühne committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

//Delegate notification constants
NSString * const PXSLSelectionIsChangingNotification = @"PXSourceListSelectionIsChanging";
NSString * const PXSLSelectionDidChangeNotification = @"PXSourceListSelectionDidChange";
NSString * const PXSLItemWillExpandNotification = @"PXSourceListItemWillExpand";
NSString * const PXSLItemDidExpandNotification = @"PXSourceListItemDidExpand";
NSString * const PXSLItemWillCollapseNotification = @"PXSourceListItemWillCollapse";
NSString * const PXSLItemDidCollapseNotification = @"PXSourceListItemDidCollapse";
NSString * const PXSLDeleteKeyPressedOnRowsNotification = @"PXSourceListDeleteKeyPressedOnRows";

#pragma mark -
@interface PXSourceList ()

- (NSSize)sizeOfBadgeAtRow:(NSInteger)rowIndex;
- (void)drawBadgeForRow:(NSInteger)rowIndex inRect:(NSRect)badgeFrame;
- (void)registerDelegateToReceiveNotification:(NSString*)notification withSelector:(SEL)selector;

@end

#pragma mark -
@implementation PXSourceList

@synthesize iconSize = _iconSize;
@dynamic dataSource;
@dynamic delegate;

#pragma mark Init/Dealloc/Finalize

- (id)initWithCoder:(NSCoder*)decoder
58 59 60 61 62 63 64 65 66 67 68 69
{
    if(self=[super initWithCoder:decoder])
    {
        [self setDelegate:(id<PXSourceListDelegate>)[super delegate]];
        [super setDelegate:self];
        [self setDataSource:(id<PXSourceListDataSource>)[super dataSource]];
        [super setDataSource:self];

        _iconSize = NSMakeSize(16,16);
    }

    return self;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
70 71 72 73
}

- (void)dealloc
{
74 75 76 77 78 79 80 81
    //Remove ourselves as the delegate and data source to be safe
    [super setDataSource:nil];
    [super setDelegate:nil];

    //Unregister the delegate from receiving notifications
    [[NSNotificationCenter defaultCenter] removeObserver:_secondaryDelegate name:nil object:self];

    [super dealloc];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
82 83 84 85
}

- (void)finalize
{
86 87 88 89 90 91 92 93
    //Remove ourselves as the delegate and data source to be safe
    [super setDataSource:nil];
    [super setDelegate:nil];

    //Unregister the delegate from receiving notifications
    [[NSNotificationCenter defaultCenter] removeObserver:_secondaryDelegate name:nil object:self];

    [super finalize];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
94 95 96 97 98 99 100
}

#pragma mark -
#pragma mark Custom Accessors

- (void)setDelegate:(id<PXSourceListDelegate>)aDelegate
{
101 102 103 104 105 106 107 108 109 110 111 112
    //Unregister the old delegate from receiving notifications
    [[NSNotificationCenter defaultCenter] removeObserver:_secondaryDelegate name:nil object:self];

    _secondaryDelegate = aDelegate;
    //Register the new delegate to receive notifications
    [self registerDelegateToReceiveNotification:PXSLSelectionIsChangingNotification withSelector:@selector(sourceListSelectionIsChanging:)];
    [self registerDelegateToReceiveNotification:PXSLSelectionDidChangeNotification withSelector:@selector(sourceListSelectionDidChange:)];
    [self registerDelegateToReceiveNotification:PXSLItemWillExpandNotification withSelector:@selector(sourceListItemWillExpand:)];
    [self registerDelegateToReceiveNotification:PXSLItemDidExpandNotification withSelector:@selector(sourceListItemDidExpand:)];
    [self registerDelegateToReceiveNotification:PXSLItemWillCollapseNotification withSelector:@selector(sourceListItemWillCollapse:)];
    [self registerDelegateToReceiveNotification:PXSLItemDidCollapseNotification withSelector:@selector(sourceListItemDidCollapse:)];
    [self registerDelegateToReceiveNotification:PXSLDeleteKeyPressedOnRowsNotification withSelector:@selector(sourceListDeleteKeyPressedOnRows:)];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
113 114 115 116 117
}


- (void)setDataSource:(id<PXSourceListDataSource>)aDataSource
{
118 119 120
    _secondaryDataSource = aDataSource;

    [self reloadData];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
121 122 123 124
}

- (void)setIconSize:(NSSize)newIconSize
{
125 126 127 128 129 130 131 132 133
    _iconSize = newIconSize;
    CGFloat rowHeight = [self rowHeight];

    //Make sure icon height does not exceed row height; if so constrain, keeping width and height in proportion
    if(_iconSize.height>rowHeight)
    {
        _iconSize.width = _iconSize.width * (rowHeight/_iconSize.height);
        _iconSize.height = rowHeight;
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
134 135 136 137 138 139 140
}

#pragma mark -
#pragma mark Data Management

- (void)reloadData
{
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    [super reloadData];

    //Expand items that are displayed as always expanded
    if([_secondaryDataSource conformsToProtocol:@protocol(PXSourceListDataSource)] &&
       [_secondaryDelegate respondsToSelector:@selector(sourceList:isGroupAlwaysExpanded:)])
    {
        for(NSUInteger i=0;i<[self numberOfGroups];i++)
        {
            id item = [_secondaryDataSource sourceList:self child:i ofItem:nil];

            if([self isGroupAlwaysExpanded:item]) {
                [self expandItem:item expandChildren:NO];
            }
        }
    }

    //If there are selected rows and the item hierarchy has changed, make sure a Group row isn't
    //selected
    if([self numberOfSelectedRows]>0) {
        NSIndexSet *selectedIndexes = [self selectedRowIndexes];
        NSUInteger firstSelectedRow = [selectedIndexes firstIndex];

        //Is a group item selected?
        if([self isGroupItem:[self itemAtRow:firstSelectedRow]]) {
            //Work backwards to find the first non-group row
            BOOL foundRow = NO;
            for(NSUInteger i=firstSelectedRow;i>0;i--)
            {
                if(![self isGroupItem:[self itemAtRow:i]]) {
                    [self selectRowIndexes:[NSIndexSet indexSetWithIndex:i] byExtendingSelection:NO];
                    foundRow = YES;
                    break;
                }
            }

            //If there is no non-group row preceding the currently selected group item, remove the selection
            //from the Source List
            if(!foundRow) {
                [self deselectAll:self];
            }
        }
    }
    else if(![self allowsEmptySelection]&&[self numberOfSelectedRows]==0)
    {
        //Select the first non-group row if no rows are selected, and empty selection is disallowed
        for(NSUInteger i=0;i<[self numberOfRows];i++)
        {
            if(![self isGroupItem:[self itemAtRow:i]]) {
                [self selectRowIndexes:[NSIndexSet indexSetWithIndex:i] byExtendingSelection:NO];
                break;
            }
        }
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
194 195 196
}

- (NSUInteger)numberOfGroups
197 198 199 200 201
{
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:numberOfChildrenOfItem:)]) {
        return [_secondaryDataSource sourceList:self numberOfChildrenOfItem:nil];
    }
    return 0;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
202 203 204 205 206
}


- (BOOL)isGroupItem:(id)item
{
207 208
    //Groups are defined as root items (at level 0)
    return 0==[self levelForItem:item];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
209 210 211 212 213
}


- (BOOL)isGroupAlwaysExpanded:(id)group
{
214 215 216 217 218 219 220 221 222
    //Make sure that the item IS a group to prevent unwanted queries sent to the data source
    if([self isGroupItem:group]) {
        //Query the data source
        if([_secondaryDelegate respondsToSelector:@selector(sourceList:isGroupAlwaysExpanded:)]) {
            return [_secondaryDelegate sourceList:self isGroupAlwaysExpanded:group];
        }
    }

    return NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
223 224 225 226 227
}


- (BOOL)itemHasBadge:(id)item
{
228 229 230 231 232
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:itemHasBadge:)]) {
        return [_secondaryDataSource sourceList:self itemHasBadge:item];
    }

    return NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
233 234 235
}

- (NSInteger)badgeValueForItem:(id)item
236 237 238 239 240 241 242 243 244 245 246
{
    //Make sure that the item has a badge
    if(![self itemHasBadge:item]) {
        return NSNotFound;
    }

    if([_secondaryDataSource respondsToSelector:@selector(sourceList:badgeValueForItem:)]) {
        return [_secondaryDataSource sourceList:self badgeValueForItem:item];
    }

    return NSNotFound;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
247 248 249 250 251 252 253
}

#pragma mark -
#pragma mark Selection Handling

- (void)selectRowIndexes:(NSIndexSet*)indexes byExtendingSelection:(BOOL)extend
{
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    NSUInteger numberOfIndexes = [indexes count];

    //Prevent empty selection if we don't want it
    if(![self allowsEmptySelection]&&0==numberOfIndexes) {
        return;
    }

    //Would use blocks but we're also targeting 10.5...
    //Get the selected indexes
    NSUInteger *selectedIndexes = malloc(sizeof(NSUInteger)*numberOfIndexes);
    [indexes getIndexes:selectedIndexes maxCount:numberOfIndexes inIndexRange:nil];

    //Loop through the indexes and only add non-group row indexes
    //Allows selection across groups without selecting the group rows
    NSMutableIndexSet *newSelectionIndexes = [NSMutableIndexSet indexSet];
    for(NSInteger i=0;i<numberOfIndexes;i++)
    {
        if(![self isGroupItem:[self itemAtRow:selectedIndexes[i]]]) {
            [newSelectionIndexes addIndex:selectedIndexes[i]];
        }
    }

    //If there are any non-group rows selected
    if([newSelectionIndexes count]>0) {
        [super selectRowIndexes:newSelectionIndexes byExtendingSelection:extend];
    }

    //C memory management... *sigh*
    free(selectedIndexes);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
283 284 285 286 287 288
}

#pragma mark -
#pragma mark Layout

- (NSRect)frameOfOutlineCellAtRow:(NSInteger)row
289 290 291 292 293 294 295
{
    //Return a zero-rect if the item is always expanded (a disclosure triangle will not be drawn)
    if([self isGroupAlwaysExpanded:[self itemAtRow:row]]) {
        return NSZeroRect;
    }

    return [super frameOfOutlineCellAtRow:row];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
296 297 298 299 300
}


- (NSRect)frameOfCellAtColumn:(NSInteger)column row:(NSInteger)row
{
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    id item = [self itemAtRow:row];

    NSCell *cell = [self preparedCellAtColumn:column row:row];
    NSSize cellSize = [cell cellSize];
    if (!([cell type] == NSImageCellType) && !([cell type] == NSTextCellType))
        cellSize = [cell cellSizeForBounds:[super frameOfCellAtColumn:column row:row]];

    NSRect cellFrame = [super frameOfCellAtColumn:column row:row];
    NSRect rowRect = [self rectOfRow:row];

    if([self isGroupItem:item])
    {
        CGFloat minX = NSMinX(cellFrame);

        //Set the origin x-coord; if there are no children of the group at current, there will still be a
        //margin to the left of the cell (in cellFrame), which we don't want
        if([self isGroupAlwaysExpanded:[self itemAtRow:row]]) {
            minX = 7;
        }

    return NSMakeRect(minX, NSMidY(cellFrame)-(cellSize.height/2.0), NSWidth(rowRect)-minX, cellSize.height);
    }
    else
    {
        CGFloat leftIndent = ([self levelForRow:row] -1)*[self indentationPerLevel]+DISCLOSURE_TRIANGLE_SPACE;

        //Calculate space left for a badge if need be
        CGFloat rightIndent = [self sizeOfBadgeAtRow:row].width+ROW_RIGHT_MARGIN;

        //Allow space for an icon if need be
        if(![self isGroupItem:item]&&[_secondaryDataSource respondsToSelector:@selector(sourceList:itemHasIcon:)])
        {
            if([_secondaryDataSource sourceList:self itemHasIcon:item]) {
                leftIndent += [self iconSize].width+(ICON_SPACING*2);
            }
        }
    return NSMakeRect(leftIndent, NSMidY(rowRect)-(cellSize.height/2.0), NSWidth(rowRect)-rightIndent-leftIndent, cellSize.height);
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
339 340 341 342 343 344 345
}


//This method calculates and returns the size of the badge for the row index passed to the method. If the
//row for the row index passed to the method does not have a badge, then NSZeroSize is returned.
- (NSSize)sizeOfBadgeAtRow:(NSInteger)rowIndex
{
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    id rowItem = [self itemAtRow:rowIndex];

    //Make sure that the item has a badge
    if(![self itemHasBadge:rowItem]) {
        return NSZeroSize;
    }

    NSAttributedString *badgeAttrString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", [self badgeValueForItem:rowItem]] attributes:[NSDictionary dictionaryWithObjectsAndKeys:BADGE_FONT, NSFontAttributeName, nil]];
    NSSize stringSize = [badgeAttrString size];

    //Calculate the width needed to display the text or the minimum width if it's smaller
    CGFloat width = stringSize.width+(2*BADGE_MARGIN);

    if(width<MIN_BADGE_WIDTH) {
        width = MIN_BADGE_WIDTH;
    }

    [badgeAttrString release];

    return NSMakeSize(width, BADGE_HEIGHT);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
366 367 368 369 370 371 372
}


#pragma mark -
#pragma mark Drawing

- (void)drawRow:(NSInteger)rowIndex clipRect:(NSRect)clipRect
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
{
    [super drawRow:rowIndex clipRect:clipRect];
    id item = [self itemAtRow:rowIndex];

    //Draw an icon if the item has one
    if(![self isGroupItem:item]&&[_secondaryDataSource respondsToSelector:@selector(sourceList:itemHasIcon:)])
    {
        if([_secondaryDataSource sourceList:self itemHasIcon:item])
        {
            NSRect cellFrame = [self frameOfCellAtColumn:0 row:rowIndex];
            NSSize iconSize = [self iconSize];
            NSRect iconRect = NSMakeRect(NSMinX(cellFrame)-iconSize.width-ICON_SPACING, NSMidY(cellFrame)-(iconSize.width/2.0f), iconSize.width, iconSize.height);

            if([_secondaryDataSource respondsToSelector:@selector(sourceList:iconForItem:)])
            {
                NSImage *icon = [_secondaryDataSource sourceList:self iconForItem:item];
                if(icon!=nil)
                {
                    NSSize actualIconSize = [icon size];
                    //If the icon is *smaller* than the size retrieved from the -iconSize property, make sure we
                    //reduce the size of the rectangle to draw the icon in, so that it is not stretched.
                    if((actualIconSize.width<iconSize.width)||(actualIconSize.height<iconSize.height))
                    {
                        iconRect = NSMakeRect(NSMidX(iconRect)-(actualIconSize.width/2.0f), NSMidY(iconRect)-(actualIconSize.height/2.0f), actualIconSize.width, actualIconSize.height);
                    }

Felix Paul Kühne's avatar
Felix Paul Kühne committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
                    //Use 10.6 NSImage drawing if we can
                    if([icon respondsToSelector:@selector(drawInRect:fromRect:operation:fraction:respectFlipped:hints:)]) {
                        [icon drawInRect:iconRect
                                fromRect:NSZeroRect
                               operation:NSCompositeSourceOver
                                fraction:1
                          respectFlipped:YES hints:nil];
                    }
                    else {
                        [icon setFlipped:[self isFlipped]];
                        [icon drawInRect:iconRect
                                fromRect:NSZeroRect
                               operation:NSCompositeSourceOver
                                fraction:1];
                    }
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
                }
            }
        }
    }

    //Draw the badge if the item has one
    if([self itemHasBadge:item])
    {
        NSRect rowRect = [self rectOfRow:rowIndex];
        NSSize badgeSize = [self sizeOfBadgeAtRow:rowIndex];

        NSRect badgeFrame = NSMakeRect(NSMaxX(rowRect)-badgeSize.width-ROW_RIGHT_MARGIN,
                                       NSMidY(rowRect)-(badgeSize.height/2.0),
                                       badgeSize.width,
                                       badgeSize.height);
        [self drawBadgeForRow:rowIndex inRect:badgeFrame];
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
431 432 433 434
}

- (void)drawBadgeForRow:(NSInteger)rowIndex inRect:(NSRect)badgeFrame
{
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    id rowItem = [self itemAtRow:rowIndex];
    NSBezierPath *badgePath = [NSBezierPath bezierPathWithRoundedRect:badgeFrame
                                                              xRadius:(BADGE_HEIGHT/2.0)
                                                              yRadius:(BADGE_HEIGHT/2.0)];

    //Get window and control state to determine colours used
    BOOL isVisible = [[NSApp mainWindow] isVisible];
    BOOL isFocused = [[[self window] firstResponder] isEqual:self];
    NSInteger rowBeingEdited = [self editedRow];

    //Set the attributes based on the row state
    NSDictionary *attributes;
    NSColor *backgroundColor;

    if([[self selectedRowIndexes] containsIndex:rowIndex])
    {
        backgroundColor = [NSColor whiteColor];
        //Set the text color based on window and control state
        NSColor *textColor;
        if(isVisible && (isFocused || rowBeingEdited==rowIndex)) {
            textColor = BADGE_SELECTED_TEXT_COLOR;
        }
        else if(isVisible && !isFocused) {
            textColor = BADGE_SELECTED_UNFOCUSED_TEXT_COLOR;
        }
        else {
            textColor = BADGE_SELECTED_HIDDEN_TEXT_COLOR;
        }

        attributes = [[NSDictionary alloc] initWithObjectsAndKeys:BADGE_FONT, NSFontAttributeName, textColor, NSForegroundColorAttributeName, nil];
    }
    else
    {
        //Set the text colour based on window and control state
        NSColor *badgeColor = [NSColor whiteColor];

        if(isVisible) {
            //If the data source returns a custom colour..
            if([_secondaryDataSource respondsToSelector:@selector(sourceList:badgeBackgroundColorForItem:)]) {
                backgroundColor = [_secondaryDataSource sourceList:self badgeBackgroundColorForItem:rowItem];

            if(backgroundColor==nil)
                backgroundColor = BADGE_BACKGROUND_COLOR;
        }
        else { //Otherwise use the default (purple-blue colour)
            backgroundColor = BADGE_BACKGROUND_COLOR;
        }

        //If the delegate wants a custom badge text colour..
        if([_secondaryDataSource respondsToSelector:@selector(sourceList:badgeTextColorForItem:)]) {
            badgeColor = [_secondaryDataSource sourceList:self badgeTextColorForItem:rowItem];

            if(badgeColor==nil)
                badgeColor = [NSColor whiteColor];
        }
    }
    else { //Gray colour
        backgroundColor = BADGE_HIDDEN_BACKGROUND_COLOR;
        }
    attributes = [[NSDictionary alloc] initWithObjectsAndKeys:BADGE_FONT, NSFontAttributeName, badgeColor, NSForegroundColorAttributeName, nil];
    }

    [backgroundColor set];
    [badgePath fill];

    //Draw the badge text
    NSAttributedString *badgeAttrString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", [self badgeValueForItem:rowItem]] attributes:attributes];

    NSSize stringSize = [badgeAttrString size];
    NSPoint badgeTextPoint = NSMakePoint(NSMidX(badgeFrame)-(stringSize.width/2.0), //Center in the badge frame
                                         NSMidY(badgeFrame)-(stringSize.height/2.0)); //Center in the badge frame
    [badgeAttrString drawAtPoint:badgeTextPoint];
    [attributes release];
    [badgeAttrString release];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
509 510 511 512 513 514 515
}

#pragma mark -
#pragma mark Keyboard Handling

- (void)keyDown:(NSEvent *)theEvent
{
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    NSIndexSet *selectedIndexes = [self selectedRowIndexes];
    NSString *keyCharacters = [theEvent characters];

    //Make sure we have a selection
    if([selectedIndexes count]>0)
    {
        if([keyCharacters length]>0)
        {
            unichar firstKey = [keyCharacters characterAtIndex:0];
            if(firstKey==NSUpArrowFunctionKey||firstKey==NSDownArrowFunctionKey)
            {
                //Handle keyboard navigation across groups
                if([selectedIndexes count]==1&&!([theEvent modifierFlags] & NSShiftKeyMask))
                {
                    int delta = firstKey==NSDownArrowFunctionKey?1:-1;
                    //Search "backwards" if up arrow, "forwards" if down

                    NSInteger newRow = [selectedIndexes firstIndex];
                    //Keep incrementing/decrementing the row until a non-header row is reached
                    do {
                        newRow+=delta;

                        //If out of bounds of the number of rows..
                        if(newRow<0||newRow==[self numberOfRows])
                            break;
                    } while([self isGroupItem:[self itemAtRow:newRow]]);

                    [self selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];

                    return;
                }
            }
            else if(firstKey==NSDeleteCharacter||firstKey==NSBackspaceCharacter)
            {
                //Post the notification
                [[NSNotificationCenter defaultCenter] postNotificationName:PXSLDeleteKeyPressedOnRowsNotification object:self  userInfo:[NSDictionary dictionaryWithObject:selectedIndexes forKey:@"rows"]];

                return;

            }

        }

    }

    //We don't care about it
    [super keyDown:theEvent];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
563 564 565 566 567 568 569 570
}

#pragma mark -
#pragma mark Menu Handling


- (NSMenu *)menuForEvent:(NSEvent *)theEvent
{
571 572 573 574 575 576 577
    NSMenu * m = nil;

    if([_secondaryDelegate respondsToSelector:@selector(sourceList:menuForEvent:item:)]) {
        NSPoint clickPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
        NSInteger row = [self rowAtPoint:clickPoint];
        id clickedItem = [self itemAtRow:row];

578 579 580 581
        if ([clickedItem sdtype] > 0)
            m = [_secondaryDelegate sourceList:self menuForEvent:theEvent item:clickedItem];
        else
            m = [super menuForEvent:theEvent];
582 583 584 585 586 587 588
    }

    if (m == nil) {
        m = [super menuForEvent:theEvent];
    }

    return m;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
589 590 591 592 593 594
}

#pragma mark -
#pragma mark NSOutlineView Data Source methods

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
595 596 597 598 599 600
{
    if([_secondaryDataSource conformsToProtocol:@protocol(PXSourceListDataSource)]) {
        return [_secondaryDataSource sourceList:self numberOfChildrenOfItem:item];
    }

    return 0;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
601 602 603 604
}


- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item
605 606 607 608 609 610
{
    if([_secondaryDataSource conformsToProtocol:@protocol(PXSourceListDataSource)]) {
        return [_secondaryDataSource sourceList:self child:index ofItem:item];
    }

    return nil;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
611 612 613 614
}


- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
615 616 617 618 619 620
{
    if([_secondaryDataSource conformsToProtocol:@protocol(PXSourceListDataSource)]) {
        return [_secondaryDataSource sourceList:self isItemExpandable:item];
    }

    return NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
621 622 623 624 625
}


- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
626 627 628 629 630
    if([_secondaryDataSource conformsToProtocol:@protocol(PXSourceListDataSource)]) {
        return [_secondaryDataSource sourceList:self objectValueForItem:item];
    }

    return nil;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
631 632 633 634
}


- (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
635 636 637 638
{
    if([_secondaryDataSource conformsToProtocol:@protocol(PXSourceListDataSource)]) {
        [_secondaryDataSource sourceList:self setObjectValue:object forItem:item];
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
639 640 641 642 643
}


- (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
{
644 645 646 647 648
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:itemForPersistentObject:)]) {
        return [_secondaryDataSource sourceList:self itemForPersistentObject:object];
    }

    return nil;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
649 650 651 652
}

- (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
{
653 654 655 656 657
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:persistentObjectForItem:)]) {
        return [_secondaryDataSource sourceList:self persistentObjectForItem:item];
    }

    return nil;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
658 659 660 661
}

- (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard
{
662 663 664 665 666
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:writeItems:toPasteboard:)]) {
        return [_secondaryDataSource sourceList:self writeItems:items toPasteboard:pasteboard];
    }

    return NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
667 668 669 670
}

- (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
{
671 672 673 674 675
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:validateDrop:proposedItem:proposedChildIndex:)]) {
        return [_secondaryDataSource sourceList:self validateDrop:info proposedItem:item proposedChildIndex:index];
    }

    return NSDragOperationNone;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
676 677 678 679
}

- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
{
680 681 682 683 684
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:acceptDrop:item:childIndex:)]) {
        return [_secondaryDataSource sourceList:self acceptDrop:info item:item childIndex:index];
    }

    return NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
685 686 687
}
- (NSArray *)outlineView:(NSOutlineView *)outlineView namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedItems:(NSArray *)items
{
688 689 690 691 692
    if([_secondaryDataSource respondsToSelector:@selector(sourceList:namesOfPromisedFilesDroppedAtDestination:forDraggedItems:)]) {
        return [_secondaryDataSource sourceList:self namesOfPromisedFilesDroppedAtDestination:dropDestination forDraggedItems:items];
    }

    return nil;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
693 694 695 696 697 698 699 700
}


#pragma mark -
#pragma mark NSOutlineView Delegate methods

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
{
701 702 703 704 705
    if([_secondaryDelegate respondsToSelector:@selector(sourceList:shouldExpandItem:)]) {
        return [_secondaryDelegate sourceList:self shouldExpandItem:item];
    }

    return YES;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
706 707 708 709
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldCollapseItem:(id)item
{
710 711 712 713 714 715 716 717 718 719 720 721 722
    //Make sure the item isn't displayed as always expanded
    if([self isGroupItem:item])
    {
        if([self isGroupAlwaysExpanded:item]) {
            return NO;
        }
    }

    if([_secondaryDelegate respondsToSelector:@selector(sourceList:shouldCollapseItem:)]) {
        return [_secondaryDelegate sourceList:self shouldCollapseItem:item];
    }

    return YES;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
723 724 725 726
}

- (NSCell *)outlineView:(NSOutlineView *)outlineView dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
727 728 729 730 731 732 733 734
    if([_secondaryDelegate respondsToSelector:@selector(sourceList:dataCellForItem:)]) {
        return [_secondaryDelegate sourceList:self dataCellForItem:item];
    }

    NSInteger row = [self rowForItem:item];

    //Return the default table column
    return [[[self tableColumns] objectAtIndex:0] dataCellForRow:row];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
735 736 737 738
}

- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
739 740 741
    if([_secondaryDelegate respondsToSelector:@selector(sourceList:willDisplayCell:forItem:)]) {
        [_secondaryDelegate sourceList:self willDisplayCell:cell forItem:item];
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
742 743 744
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item
745 746 747 748 749 750 751 752 753 754 755 756
{
    //Make sure that the item isn't a group as they can't be selected
    if(![self isGroupItem:item]) {
        if([_secondaryDelegate respondsToSelector:@selector(sourceList:shouldSelectItem:)]) {
            return [_secondaryDelegate sourceList:self shouldSelectItem:item];
        }
    }
    else {
        return NO;
    }

    return YES;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
757 758 759 760
}


- (NSIndexSet *)outlineView:(NSOutlineView *)outlineView selectionIndexesForProposedSelection:(NSIndexSet *)proposedSelectionIndexes
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
{
    //The outline view will try to select the first row if -[allowsEmptySelection:] is set to NO – if this is a group row
    //stop it from doing so and leave it to our implementation of-[reloadData] which will select the first non-group row
    //for us.
    if([self numberOfSelectedRows]==0) {
        if([self isGroupItem:[self itemAtRow:[proposedSelectionIndexes firstIndex]]]) {
            return [NSIndexSet indexSet];
        }
    }

    if([_secondaryDelegate respondsToSelector:@selector(sourceList:selectionIndexesForProposedSelection:)]) {
        return [_secondaryDelegate sourceList:self selectionIndexesForProposedSelection:proposedSelectionIndexes];
    }

    //Since we implement this method, something must be returned to the outline view
        return proposedSelectionIndexes;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
777 778 779 780
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
781 782 783 784 785 786 787 788 789
    //Group titles can't be edited
    if([self isGroupItem:item])
        return NO;

    if([_secondaryDelegate respondsToSelector:@selector(sourceList:shouldEditItem:)]) {
        return [_secondaryDelegate sourceList:self shouldEditItem:item];
    }

    return YES;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
790 791 792 793
}


- (BOOL)outlineView:(NSOutlineView *)outlineView shouldTrackCell:(NSCell *)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
794 795 796 797 798 799
{
    if([_secondaryDelegate respondsToSelector:@selector(sourceList:shouldTrackCell:forItem:)]) {
        return [_secondaryDelegate sourceList:self shouldTrackCell:cell forItem:item];
    }

    return NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
800 801 802 803
}

- (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
{
804 805 806 807 808
    if([_secondaryDelegate respondsToSelector:@selector(sourceList:heightOfRowByItem:)]) {
        return [_secondaryDelegate sourceList:self heightOfRowByItem:item];
    }

    return [self rowHeight];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
809 810 811 812
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item
{
813
    return [self isGroupItem:item];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
814 815 816 817 818 819 820 821
}

#pragma mark -
#pragma mark Notification handling

/* Notification wrappers */
- (void)outlineViewSelectionIsChanging:(NSNotification *)notification
{
822
    [[NSNotificationCenter defaultCenter] postNotificationName:PXSLSelectionIsChangingNotification object:self];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
823 824 825 826 827
}


- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{
828
    [[NSNotificationCenter defaultCenter] postNotificationName:PXSLSelectionDidChangeNotification object:self];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
829 830 831 832
}

- (void)outlineViewItemWillExpand:(NSNotification *)notification
{
833
    [[NSNotificationCenter defaultCenter] postNotificationName:PXSLItemWillExpandNotification object:self userInfo:[notification userInfo]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
834 835 836 837
}

- (void)outlineViewItemDidExpand:(NSNotification *)notification
{
838
    [[NSNotificationCenter defaultCenter] postNotificationName:PXSLItemDidExpandNotification object:self userInfo:[notification userInfo]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
839 840 841 842
}

- (void)outlineViewItemWillCollapse:(NSNotification *)notification
{
843
    [[NSNotificationCenter defaultCenter] postNotificationName:PXSLItemWillCollapseNotification object:self userInfo:[notification userInfo]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
844 845 846 847
}

- (void)outlineViewItemDidCollapse:(NSNotification *)notification
{
848
    [[NSNotificationCenter defaultCenter] postNotificationName:PXSLItemDidCollapseNotification object:self userInfo:[notification userInfo]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
849 850 851 852
}

- (void)registerDelegateToReceiveNotification:(NSString*)notification withSelector:(SEL)selector
{
853 854 855 856 857 858
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];

    //Set the delegate as a receiver of the notification if it implements the notification method
    if([_secondaryDelegate respondsToSelector:selector]) {
        [defaultCenter addObserver:_secondaryDelegate selector:selector name:notification object:self];
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
859 860 861
}

@end