Source

Gantt.app / GanttView.m

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 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
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
509
510
511
512
513
514
515
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/*
 * Copyright (c) 2010 David McIntosh <dmcintosh@df12.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#import "GanttView.h"

#define DEBUG_MOUSE         NO
#define DEBUG_DRAW          NO

@interface NSObject (GanttViewDelegate)
- (GanttTask *)taskAtIndex:(int)index;
- (NSInteger)rootTasks;
- (NSEnumerator *)rootTaskEnumerator;
- (void)setGanttView:(id)aGanttView;
- (void)addNewTask:(id)sender;
- (void)zoomIn:(id)sender;
- (void)zoomOut:(id)sender;
- (void)selectionDidChange:(id)sender;
@end


@interface GanttView (Private)
    
- (NSTimeInterval)_gridInterval;
- (NSTimeInterval)_subGridInterval;
- (void)_updateForZoomFactor;

@end

//
// class variables
//
static id ganttCellClass = nil;

@implementation GanttView

+ (void)initialize
{
    if (self == [GanttView class])
    {
        [self setCellClass:[GanttCell class]];
    }
}

- (id)initWithFrame:(NSRect)aFrame
{
    if ( (self=[super initWithFrame:(NSRect)aFrame]) )
    {
        [self setZoomFactor:GanttZoomMedium];
        selection = [[NSMutableSet alloc] init];
        expandedTags = [[NSMutableSet alloc] init];
        [self setOriginDate:
            [[NSDate dateWithTimeIntervalSinceNow:-60*60*24*7] 
                dateByRoundingToNearest:GanttDay]];
        sendSelectionDelegateMessages=YES;
    }
    return self;
}

+ (Class) cellClass
{
    return ganttCellClass;
}

+ (void) setCellClass: (Class)classId
{
    ganttCellClass = classId;
}

/**
 * Overriden to support zooming with ctrl-scroll
 */
- (void)scrollWheel:(NSEvent *)theEvent
{
    CGFloat deltaY = [theEvent deltaY];
    if ([theEvent modifierFlags] & NSControlKeyMask)
    {
        if (deltaY > 0.0)
            [delegate zoomIn:self];
        else
            [delegate zoomOut:self];
    } else {
        [super scrollWheel:theEvent];
    }
}

/**
 * If the requested cell does not exist, create it
 * Configure the requested cell to reflect the represented task
 * before returning
 */
- (GanttCell *)cellAtIndex:(int)index
{
    int i;
    GanttCell *aCell;
    GanttTask *task;

    if (nil == cells)
        cells = [[NSMutableArray alloc] init];

    if ([cells count] <= index)
    {
        for (i=[cells count]; i <= index; i++)
        {
            aCell = [[GanttCell alloc] initTextCell:@""];
            [aCell setTarget:delegate];
            [aCell setControlView:self];
            [aCell setBounds:[self bounds]];
            [cells addObject:aCell];
            RELEASE(aCell);
        }
    }
    aCell = [cells objectAtIndex:index];
    task = [self taskAtIndex:index];
    [aCell setTag:[task tag]];
    [aCell setGridInterval:[self _subGridInterval]];
    [aCell setOriginDate:[self originDate]];
    [aCell setStartDate:[task startDate]];
    [aCell setEndDate:[task endDate]];
    [aCell setCompletion:[task completion]];
    return aCell;
}

- (GanttTask *)taskAtIndex:(NSInteger)index withRoot:(GanttTask *)root
{
    NSInteger remainder = index+1;
    NSInteger i = 0;
    GanttTask *child;

    if ((nil == root && [delegate rootTasks] == 0) || 
        (nil != root && [root childCount] == 0))
    {
        return nil;
    }

    // UKLog(@"Called for index %d with root %@", index, root);

    while (remainder > 0)
    {
        if (nil == root)
            child = [delegate taskAtIndex:i];
        else
            child = [root childAtIndex:i];

        remainder--;
        i++;
        if (remainder > 0 && [child childCount] > 0 && 
            [expandedTags containsObject:[NSNumber numberWithInt:[child tag]]])
        {
            if ([self visibleTasksWithRoot:child] >= remainder)
            {
                // UKLog(@"  Querying index %d with root %@", remainder-1, child);
                return [self taskAtIndex:remainder-1 withRoot:child];
            } else {
                remainder -= [child childCount];
            }
        }
    }
    return child;
}

- (GanttTask *)taskAtIndex:(NSInteger)index
{
    return [self taskAtIndex:index withRoot:nil];
}

- (NSInteger)visibleTasksWithRoot:(GanttTask *)root
{
    NSInteger count = 0;
    id child;
    NSEnumerator *e;

    if (nil == root)
        e = [delegate rootTaskEnumerator];
    else
        e = [[root children] objectEnumerator];

    while ((child = [e nextObject]))
    {
        count++;
        if ([expandedTags containsObject:[NSNumber numberWithInt:[child tag]]])
            count += [self visibleTasksWithRoot:child];
    }
    return count;
}

- (NSInteger)visibleTasks
{
    return [self visibleTasksWithRoot:nil];
}

/**
 * Ensure that the cell bounds are updated to reflect the view bounds
 */
- (void)setBounds:(NSRect)bounds
{
    NSEnumerator *e = [cells objectEnumerator];
    GanttCell *aCell;
    while (( aCell = [e nextObject] ))
        [aCell setBounds:bounds];
    [super setBounds:bounds];
}

/**
 * Draws the grid lines representing the major hash marks
 * at the current zoom level
 */
- (void)drawGridInRect:(NSRect)rect 
{
    NSRect bounds, frame;
    NSTimeInterval notchIntv;
    int notches, i;
    NSPoint notch;
    NSBezierPath *p;
    float notchHours, notchWidth;

    bounds = [self bounds];
    frame = [self frame];

    // determine time interval represented by each notch
    notchIntv = [self _gridInterval];

    notch.y = rect.origin.y;
    notch.x = rect.origin.x;

    notchHours = ( notchIntv / (60.0 * 60.0) );
    notchWidth = notchHours * GanttPointsPerHour;
    notches = rect.size.width / notchWidth;

    // if the rectangle being drawn does not start on a grid line
    if ( fmod(notch.x, notchWidth) > 0.0 )
    {
        notch.x -= fmod(notch.x, notchWidth);
    }

    [[NSColor grayColor] set];

    // For each visible notch
    for (i = 0; i <= notches; i++)
    {
        notch.x += notchWidth;
        p = [NSBezierPath bezierPath];

        // Adjust grid line thickness to compensate for zoom
        switch ([self zoomFactor]) {
            case GanttZoomClose:
                [p setLineWidth:0.7]; break;
            case GanttZoomMedium:
                [p setLineWidth:1.0]; break;
            case GanttZoomWide:
                [p setLineWidth:2.0]; break;
        }

        [p moveToPoint:notch];
        [p lineToPoint:NSMakePoint(notch.x, notch.y+rect.size.height)];
        [p stroke];
    }
}

- (void)drawRect:(NSRect)rect
{
    NSPoint origin = rect.origin;
    float rowHeight = GanttRowHeight;;
    NSRect cellFrame;
    int rows = [self visibleTasks];
    int row;
    GanttCell *aCell;
    NSArray *rowBGColors = [NSArray arrayWithObjects:
        [NSColor colorWithDeviceRed:0.89 green:0.92 blue:0.96 alpha:1], 
        [NSColor whiteColor], 
        nil];
    NSColor *color;
    NSInteger tag;

    row = (int)( rect.origin.y / rowHeight );
    origin.y = row * rowHeight;
    while (origin.y < rect.origin.y+rect.size.height)
    {
        // draw the row
        cellFrame = NSMakeRect(origin.x, origin.y, 
            rect.size.width, rowHeight);
        
        color = [rowBGColors objectAtIndex:(row % [rowBGColors count])];
        if (row < rows)
        {
            tag = [[self taskAtIndex:row] tag];
            if ([selection containsObject:[NSNumber numberWithInt:tag]])
                color = [color shadowWithLevel:0.4];
        }
        [color set];
        [NSBezierPath fillRect:cellFrame];
        row++;
        origin.y += rowHeight;
    }

    [self drawGridInRect:rect];

    row = (int)( rect.origin.y / rowHeight );
    origin.y = row * rowHeight;
    while (origin.y < rect.origin.y+rect.size.height)
    {
        // draw the row
        cellFrame = NSMakeRect(origin.x, origin.y, 
            rect.size.width, rowHeight);
        
        if (row < rows)
        {
            aCell = [self cellAtIndex:row];
            [aCell drawWithFrame:cellFrame inView:self];
        }
        row++;
        origin.y += rowHeight;
    }
}

- (void)clearSelection
{
    [selection removeAllObjects];
    if (sendSelectionDelegateMessages)
        [delegate selectionDidChange:self];
}

/**
 * Adds a tag to the selected tags list
 */
- (void)selectTag:(NSInteger)tag
{
    [selection addObject:[NSNumber numberWithInt:tag]];
    if (sendSelectionDelegateMessages)
        [delegate selectionDidChange:self];
}

/**
 * Removes a tag from the selected tags list
 */
- (void)deselectTag:(NSInteger)tag
{
    [selection removeObject:[NSNumber numberWithInt:tag]];
    if (sendSelectionDelegateMessages)
        [delegate selectionDidChange:self];
}

- (NSInteger)selectedTag
{
    if ([selection count] != 1)
        return -1;
    return [[selection anyObject] intValue];
}

- (NSSet *)selectedTags
{
    return [NSSet setWithSet:selection];
}

- (void)selectRowIndexes:(NSIndexSet *)indexes byExtendingSelection:(BOOL)extend;
{
    int i;

    if ([indexes isEqualToIndexSet:[self selectedRowIndexes]])
        return;

    sendSelectionDelegateMessages=NO;

    if (!extend)
        [self clearSelection];

    for (i=0; i<[self visibleTasks]; i++)
    {
        if ([indexes containsIndex:i])
            [self selectTag:[[self taskAtIndex:i] tag]];
    }
    sendSelectionDelegateMessages=YES;
    [self setNeedsDisplay:YES];
}

- (NSIndexSet *)selectedRowIndexes
{
    NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
    int i;

    for (i=0; i<[self visibleTasks]; i++)
    {
        if ([selection 
                containsObject:[NSNumber numberWithInt:[[self taskAtIndex:i] tag]]])
        {
            [indexes addIndex:i];
        }
    }
    return indexes;
}

- (void)mouseDown:(NSEvent *)theEvent
{
    GanttCell *theCell;
    NSPoint thePoint = [self 
        convertPoint:[theEvent locationInWindow] 
            fromView:nil];
    float rowHeight = GanttRowHeight;;
    int rows = [self visibleTasks];
    int row = (int)( thePoint.y / rowHeight );
    NSDate *pointDate = 
        [originDate dateByAddingTimeInterval:(thePoint.x*60.0*60.0)];

    if (DEBUG_MOUSE)
        UKLog(@"MouseDown %@ Date %@", NSStringFromPoint(thePoint), pointDate);

    // check we are not exceeding the last row
    if (row+1 > rows)
    {
        // double click here is synonymn for "add task"
        if ([theEvent clickCount] == 2)
            [delegate addNewTask:self];
        else {
            [self clearSelection];
            [self setCell:nil];
            [self setNeedsDisplay:YES];
        }
        return;
    }

    theCell = [self cellAtIndex:row];

    if (([theEvent modifierFlags] & NSControlKeyMask) &&
        [selection count] > 0)
    {
        NSInteger tag = [theCell tag];
        if ( [selection containsObject:[NSNumber numberWithInt:tag]] )
        {
            if (DEBUG_MOUSE)
                UKLog(@"Shrinking selection");
            [self deselectTag:tag];
        } else {
            if (DEBUG_MOUSE)
                UKLog(@"Expanding selection");
            [self selectTag:tag];
        }
        [self setNeedsDisplay:YES];

    } else {

        [self clearSelection];
        [self selectTag:[theCell tag]];
        [self setCell:theCell]; // only used for tracking
        [self setNeedsDisplay:YES];
        [theCell trackMouse:theEvent 
            inRect:[self bounds] 
            ofView:self 
            untilMouseUp:YES];
    }
}

- (void)resetCursorRects
{
    int rows = [self visibleTasks];
    int row;
    float rowHeight = GanttRowHeight;
    NSRect visibleRect = [self visibleRect];
    NSRect cellFrame;
    GanttCell *theCell;

    // check if visible
    if (NSEqualRects(visibleRect, NSZeroRect))
        return;

    row = (int)(visibleRect.origin.y / rowHeight);
    cellFrame.origin.x = visibleRect.origin.x;
    cellFrame.origin.y = (float)row * rowHeight;
    cellFrame.size.width = visibleRect.size.width;
    cellFrame.size.height = rowHeight;

    while (row < rows && cellFrame.origin.y < NSMaxY(visibleRect))
    {
        theCell = [self cellAtIndex:row];
        if (NSMaxY(cellFrame) > NSMaxY(visibleRect))
            cellFrame = NSIntersectionRect(visibleRect, cellFrame);
        [theCell resetCursorRectsForFrame:cellFrame
                   inView:self];

        row++;
        cellFrame.origin.y += rowHeight;
    }

    if (rows == 0)
        [self addCursorRect:[self frame]
                         cursor:[NSCursor arrowCursor]];
}

- (BOOL)isFlipped
{
    return YES;
}

- (void)windowDidResize:(NSNotification *)note
{
    if ([self isDescendantOf:[note object]])
    {
        [self _updateForZoomFactor];
    }
}

- (void)taskDidExpand:(NSNotification *)note
{
    NSDictionary *userInfo = [note userInfo];
    GanttTask *task = [userInfo objectForKey:@"NSObject"];
    [expandedTags addObject:[NSNumber numberWithInt:[task tag]]];
    [self setNeedsDisplay:YES];
}

- (void)taskDidCollapse:(NSNotification *)note
{
    NSDictionary *userInfo = [note userInfo];
    GanttTask *task = [userInfo objectForKey:@"NSObject"];
    [expandedTags removeObject:[NSNumber numberWithInt:[task tag]]];
    [self setNeedsDisplay:YES];
}

- (void)awakeFromGSMarkup
{
    NSScrollView *scrollView;
    GanttRulerView *rulerView;
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

    [nc addObserver:self 
        selector:@selector(windowDidResize:) 
        name:NSWindowDidResizeNotification 
        object:[self window]];
    [nc addObserver:self 
        selector:@selector(windowDidResize:) 
        name:NSSplitViewDidResizeSubviewsNotification
        object:nil];
    scrollView = [self enclosingScrollView];
    rulerView = [[GanttRulerView alloc] 
        initWithScrollView:scrollView orientation:NSHorizontalRuler];
    [scrollView setRulersVisible:YES];
    [scrollView setHorizontalRulerView:rulerView];
    [scrollView setHasHorizontalRuler:YES];
    [rulerView setOriginDate:[self originDate]];
    [rulerView setZoomFactor:[self zoomFactor]];
    if (_tableView)
    {
        [nc addObserver:self 
            selector:@selector(taskDidCollapse:) 
            name:NSOutlineViewItemDidCollapseNotification
            object:_tableView];
        [nc addObserver:self 
            selector:@selector(taskDidExpand:) 
            name:NSOutlineViewItemDidExpandNotification
            object:_tableView];
        float headerHeight = [[_tableView headerView] frame].size.height;
        [rulerView setRuleThickness:headerHeight];
        [_tableView setRowHeight:GanttRowHeight];
    }
    [rulerView setReservedThicknessForMarkers:0];
    AUTORELEASE(rulerView);
    [self setCell:nil];
}

- (void)setDelegate:(id)obj
{
    delegate=obj;
}

- (void)setTableView:(NSTableView *)tableView
{
    ASSIGN(_tableView, tableView);
}

- (void)setOriginDate:(NSDate *)aDate
{
    ASSIGN(originDate, aDate);
}

- (NSDate *)originDate
{
    return originDate;
}

- (void)setZoomFactor:(GanttZoomFactor)zoomFactor
{
    _zoomFactor = zoomFactor;
    [self _updateForZoomFactor];
}

- (void)_updateForZoomFactor
{
    NSSize contentSize;
    float taskHeight = [self visibleTasks] * GanttRowHeight;
    NSRect frame=[self frame];
    NSString *zoomFactorName;
    contentSize = [[self enclosingScrollView] contentSize];

    frame.size.width=contentSize.width;

    if (contentSize.height < taskHeight)
        frame.size.height=taskHeight;
    else
        frame.size.height=contentSize.height;
        
    [self setFrame:frame];
    if (DEBUG_DRAW)
        UKLog(@"Frame width: %f", frame.size.width);
    
    switch (_zoomFactor)
    {
        case GanttZoomWide:
            // [rulerView setMeasurementUnits:@"GanttDay"];
            [self setBoundsSize:
                NSMakeSize(frame.size.width*7.0, frame.size.height)];
            zoomFactorName=@"Wide";
            break;
        case GanttZoomMedium:
            // [rulerView setMeasurementUnits:@"GanttDay"];
            // the 0.01 is there to work around a GNUstep bug where if 
            // bounds == frame when setting bounds, the  scale of the 
            // view is not adjusted
            [self setBoundsSize:
                NSMakeSize(frame.size.width+0.01, frame.size.height)];
            zoomFactorName=@"Medium";
            break;
        case GanttZoomClose:
            // [rulerView setMeasurementUnits:@"GanttDay"];
            [self setBoundsSize:
                NSMakeSize(frame.size.width/2.0, frame.size.height)];
            zoomFactorName=@"Close";
            break;
    }
    
    NSScrollView *scrollView = [self enclosingScrollView];
    if (scrollView)
    {
        id rulerView = [scrollView horizontalRulerView];
        if (rulerView && 
            [rulerView respondsToSelector:@selector(setZoomFactor:)])
        {
            [rulerView setZoomFactor:[self zoomFactor]];
        }
    }
    [[self window] invalidateCursorRectsForView:self];
    [self setNeedsDisplay:YES];
}

- (GanttZoomFactor)zoomFactor
{
    return _zoomFactor;
}

- (NSTimeInterval)_gridInterval
{
    GanttZoomFactor zoomFactor = [self zoomFactor];
    switch (zoomFactor)
    {
        case GanttZoomWide:
            return GanttWeek;
        case GanttZoomMedium:
            return GanttDay;
        case GanttZoomClose:
            return GanttHalfDay;
    }
    return 0.0;
}

- (NSTimeInterval)_subGridInterval
{
    GanttZoomFactor zoomFactor = [self zoomFactor];
    switch (zoomFactor)
    {
        case GanttZoomWide:
            return GanttDay;
        case GanttZoomMedium:
            return GanttHalfDay;
        case GanttZoomClose:
            return GanttHalfDay;
    }
    return 0.0;
}

// The bounds interval in seconds
- (NSTimeInterval)extentInterval
{
    float extentHours = ([self bounds].size.width / GanttPointsPerHour);
    return extentHours / (60.0 * 60.0);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] 
            removeObserver:self ];
    DESTROY(emptyCell);
    DESTROY(cells);
    DESTROY(originDate);
    DESTROY(_tableView);
    DESTROY(selection);
    DESTROY(expandedTags);
    [super dealloc];
}

@end