-
Notifications
You must be signed in to change notification settings - Fork 36
/
MBTableGrid.m
1360 lines (1083 loc) · 44.1 KB
/
MBTableGrid.m
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2008 Matthew Ball - http://www.mattballdesign.com
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#import "MBTableGrid.h"
#import "MBTableGridHeaderView.h"
#import "MBTableGridHeaderCell.h"
#import "MBTableGridContentView.h"
#import "MBTableGridCell.h"
#pragma mark -
#pragma mark Constant Definitions
NSString *MBTableGridDidChangeSelectionNotification = @"MBTableGridDidChangeSelectionNotification";
NSString *MBTableGridDidMoveColumnsNotification = @"MBTableGridDidMoveColumnsNotification";
NSString *MBTableGridDidMoveRowsNotification = @"MBTableGridDidMoveRowsNotification";
#pragma mark -
#pragma mark Drag Types
NSString *MBTableGridColumnDataType = @"MBTableGridColumnDataType";
NSString *MBTableGridRowDataType = @"MBTableGridRowDataType";
@interface MBTableGrid (Drawing)
- (void)_drawColumnHeaderBackgroundInRect:(NSRect)aRect;
- (void)_drawRowHeaderBackgroundInRect:(NSRect)aRect;
- (void)_drawCornerHeaderBackgroundInRect:(NSRect)aRect;
@end
@interface MBTableGrid (DataAccessors)
- (NSString *)_headerStringForColumn:(NSUInteger)columnIndex;
- (NSString *)_headerStringForRow:(NSUInteger)rowIndex;
- (id)_objectValueForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (void)_setObjectValue:(id)value forColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (BOOL)_canEditCellAtColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
@end
@interface MBTableGrid (DragAndDrop)
- (void)_dragColumnsWithEvent:(NSEvent *)theEvent;
- (void)_dragRowsWithEvent:(NSEvent *)theEvent;
- (NSImage *)_imageForSelectedColumns;
- (NSImage *)_imageForSelectedRows;
- (NSUInteger)_dropColumnForPoint:(NSPoint)aPoint;
- (NSUInteger)_dropRowForPoint:(NSPoint)aPoint;
@end
@interface MBTableGrid (PrivateAccessors)
- (MBTableGridContentView *)_contentView;
- (void)_setStickyColumn:(MBTableGridEdge)stickyColumn row:(MBTableGridEdge)stickyRow;
- (MBTableGridEdge)_stickyColumn;
- (MBTableGridEdge)_stickyRow;
@end
@interface MBTableGridContentView (Private)
- (void)_setDraggingColumnOrRow:(BOOL)flag;
- (void)_setDropColumn:(NSInteger)columnIndex;
- (void)_setDropRow:(NSInteger)rowIndex;
@end
@implementation MBTableGrid
@synthesize allowsMultipleSelection;
@synthesize dataSource;
@synthesize delegate;
@synthesize selectedColumnIndexes;
@synthesize selectedRowIndexes;
#pragma mark -
#pragma mark Initialization & Superclass Overrides
- (id)initWithFrame:(NSRect)frameRect
{
if(self = [super initWithFrame:frameRect]) {
// Post frame changed notifications
[self setPostsFrameChangedNotifications:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewFrameDidChange:) name:NSViewFrameDidChangeNotification object:self];
// Set the default cell
MBTableGridCell *defaultCell = [[MBTableGridCell alloc] initTextCell:@""];
[defaultCell setBezeled:YES];
[defaultCell setScrollable:YES];
[defaultCell setLineBreakMode:NSLineBreakByTruncatingTail];
[self setCell:defaultCell];
[defaultCell release];
// Setup the column headers
NSRect columnHeaderFrame = NSMakeRect(MBTableGridRowHeaderWidth, 0, frameRect.size.width-MBTableGridRowHeaderWidth, MBTableGridColumnHeaderHeight);
columnHeaderScrollView = [[NSScrollView alloc] initWithFrame:columnHeaderFrame];
columnHeaderView = [[MBTableGridHeaderView alloc] initWithFrame:NSMakeRect(0,0,columnHeaderFrame.size.width,columnHeaderFrame.size.height)];
// [columnHeaderView setAutoresizingMask:NSViewWidthSizable];
[columnHeaderView setOrientation:MBTableHeaderHorizontalOrientation];
[columnHeaderScrollView setDocumentView:columnHeaderView];
[columnHeaderScrollView setAutoresizingMask:NSViewWidthSizable];
[columnHeaderScrollView setDrawsBackground:NO];
[self addSubview:columnHeaderScrollView];
// Setup the row headers
NSRect rowHeaderFrame = NSMakeRect(0, MBTableGridColumnHeaderHeight, MBTableGridRowHeaderWidth, [self frame].size.height-MBTableGridColumnHeaderHeight);
rowHeaderScrollView = [[NSScrollView alloc] initWithFrame:rowHeaderFrame];
rowHeaderView = [[MBTableGridHeaderView alloc] initWithFrame:NSMakeRect(0,0,rowHeaderFrame.size.width,rowHeaderFrame.size.height)];
//[rowHeaderView setAutoresizingMask:NSViewHeightSizable];
[rowHeaderView setOrientation:MBTableHeaderVerticalOrientation];
[rowHeaderScrollView setDocumentView:rowHeaderView];
[rowHeaderScrollView setAutoresizingMask:NSViewHeightSizable];
[rowHeaderScrollView setDrawsBackground:NO];
[self addSubview:rowHeaderScrollView];
// Setup the content view
NSRect contentFrame = NSMakeRect(MBTableGridRowHeaderWidth, MBTableGridColumnHeaderHeight, [self frame].size.width-MBTableGridRowHeaderWidth, [self frame].size.height-MBTableGridColumnHeaderHeight);
contentScrollView = [[NSScrollView alloc] initWithFrame:contentFrame];
contentView = [[MBTableGridContentView alloc] initWithFrame:NSMakeRect(0,0,contentFrame.size.width,contentFrame.size.height)];
[contentScrollView setDocumentView:contentView];
[contentScrollView setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];
[contentScrollView setHasHorizontalScroller:YES];
[contentScrollView setHasVerticalScroller:YES];
[contentScrollView setAutohidesScrollers:YES];
[self addSubview:contentScrollView];
// We want to synchronize the scroll views
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentViewDidScroll:) name:NSViewBoundsDidChangeNotification object:[contentScrollView contentView]];
// Set the default selection
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndex:0];
self.selectedRowIndexes = [NSIndexSet indexSetWithIndex:0];
self.allowsMultipleSelection = YES;
// Set the default sticky edges
stickyColumnEdge = MBTableGridLeftEdge;
stickyRowEdge = MBTableGridTopEdge;
shouldOverrideModifiers = NO;
}
return self;
}
- (void)awakeFromNib
{
// [self reloadData];
[self registerForDraggedTypes:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[columnHeaderScrollView release];
[columnHeaderView release];
[rowHeaderScrollView release];
[rowHeaderView release];
[super dealloc];
}
- (BOOL)isFlipped
{
return YES;
}
- (BOOL)canBecomeKeyView
{
return YES;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (void)drawRect:(NSRect)aRect
{
// If the view is the first responder, draw the focus ring
NSResponder *firstResponder = [[self window] firstResponder];
if (([[firstResponder class] isSubclassOfClass:[NSView class]] && [(NSView *)firstResponder isDescendantOf:self]) && [[self window] isKeyWindow]) {
[[NSGraphicsContext currentContext] saveGraphicsState];
NSSetFocusRingStyle(NSFocusRingOnly);
[[NSBezierPath bezierPathWithRect:NSMakeRect(0,0,[self frame].size.width,[self frame].size.height)] fill];
[[NSGraphicsContext currentContext] restoreGraphicsState];
[self setKeyboardFocusRingNeedsDisplayInRect:[self bounds]];
}
// Draw the corner header
NSRect cornerRect = [self headerRectOfCorner];
[self _drawCornerHeaderBackgroundInRect:cornerRect];
// Draw the column header background
NSRect columnHeaderRect = NSMakeRect(NSWidth(cornerRect), 0, [self frame].size.width-NSWidth(cornerRect), MBTableGridColumnHeaderHeight);
[self _drawColumnHeaderBackgroundInRect:columnHeaderRect];
// Draw the row header background
NSRect rowHeaderRect = NSMakeRect(0, NSMaxY(cornerRect), MBTableGridRowHeaderWidth, [self frame].size.height - MBTableGridColumnHeaderHeight);
[self _drawRowHeaderBackgroundInRect:rowHeaderRect];
}
- (void)registerForDraggedTypes:(NSArray *)pboardTypes
{
// Add the column and row types to the array
NSMutableArray *types = [NSMutableArray arrayWithArray:pboardTypes];
if (!pboardTypes) {
types = [NSMutableArray array];
}
[types addObjectsFromArray:[NSArray arrayWithObjects:MBTableGridColumnDataType, MBTableGridRowDataType, nil]];
[super registerForDraggedTypes:types];
// Register the content view for everything
[contentView registerForDraggedTypes:types];
}
#pragma mark Mouse Events
- (void)mouseDown:(NSEvent *)theEvent
{
// End editing (if necessary)
[[self cell] endEditing:[[self window] fieldEditor:NO forObject:contentView]];
// If we're not the first responder, we need to be
if([[self window] firstResponder] != self) {
[[self window] makeFirstResponder:self];
}
}
#pragma mark Keyboard Events
- (void)keyDown:(NSEvent *)theEvent
{
[self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
}
/*- (void)interpretKeyEvents:(NSArray *)eventArray
{
}*/
#pragma mark NSResponder Event Handlers
- (void)insertTab:(id)sender
{
// Pressing "Tab" moves to the next column
[self moveRight:sender];
}
- (void)insertBacktab:(id)sender
{
// We want to change the selection, not expand it
shouldOverrideModifiers = YES;
// Pressing Shift+Tab moves to the previous column
[self moveLeft:sender];
}
- (void)insertNewline:(id)sender
{
if([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) {
// Pressing Shift+Return moves to the previous row
shouldOverrideModifiers = YES;
[self moveUp:sender];
} else {
// Pressing Return moves to the next row
[self moveDown:sender];
}
}
- (void)moveUp:(id)sender
{
NSUInteger column = [self.selectedColumnIndexes firstIndex];
NSUInteger row = [self.selectedRowIndexes firstIndex];
// Accomodate for the sticky edges
if(stickyColumnEdge == MBTableGridRightEdge) {
column = [self.selectedColumnIndexes lastIndex];
}
if(stickyRowEdge == MBTableGridBottomEdge) {
row = [self.selectedRowIndexes lastIndex];
}
// If we're already at the first row, do nothing
if(row <= 0)
return;
// If the Shift key was not held, move the selection
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndex:column];
self.selectedRowIndexes = [NSIndexSet indexSetWithIndex:(row-1)];
}
- (void)moveUpAndModifySelection:(id)sender
{
if(shouldOverrideModifiers) {
[self moveLeft:sender];
shouldOverrideModifiers = NO;
return;
}
NSUInteger firstRow = [self.selectedRowIndexes firstIndex];
NSUInteger lastRow = [self.selectedRowIndexes lastIndex];
// If there is only one row selected, change the sticky edge to the bottom
if([self.selectedRowIndexes count] == 1) {
stickyRowEdge = MBTableGridBottomEdge;
}
// We can't expand past the last row
if(stickyRowEdge == MBTableGridBottomEdge && firstRow <= 0)
return;
if(stickyRowEdge == MBTableGridTopEdge) {
// If the top edge is sticky, contract the selection
lastRow--;
} else if(stickyRowEdge == MBTableGridBottomEdge) {
// If the bottom edge is sticky, expand the contraction
firstRow--;
}
self.selectedRowIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstRow, lastRow-firstRow+1)];
}
- (void)moveDown:(id)sender
{
NSUInteger column = [self.selectedColumnIndexes firstIndex];
NSUInteger row = [self.selectedRowIndexes firstIndex];
// Accomodate for the sticky edges
if(stickyColumnEdge == MBTableGridRightEdge) {
column = [self.selectedColumnIndexes lastIndex];
}
if(stickyRowEdge == MBTableGridBottomEdge) {
row = [self.selectedRowIndexes lastIndex];
}
// If we're already at the last row, do nothing
if(row >= ([self numberOfRows]-1))
return;
// If the Shift key was not held, move the selection
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndex:column];
self.selectedRowIndexes = [NSIndexSet indexSetWithIndex:(row+1)];
}
- (void)moveDownAndModifySelection:(id)sender
{
if(shouldOverrideModifiers) {
[self moveDown:sender];
shouldOverrideModifiers = NO;
return;
}
NSUInteger firstRow = [self.selectedRowIndexes firstIndex];
NSUInteger lastRow = [self.selectedRowIndexes lastIndex];
// If there is only one row selected, change the sticky edge to the top
if([self.selectedRowIndexes count] == 1) {
stickyRowEdge = MBTableGridTopEdge;
}
// We can't expand past the last row
if(stickyRowEdge == MBTableGridTopEdge && lastRow >= ([self numberOfRows]-1))
return;
if(stickyRowEdge == MBTableGridTopEdge) {
// If the top edge is sticky, contract the selection
lastRow++;
} else if(stickyRowEdge == MBTableGridBottomEdge) {
// If the bottom edge is sticky, expand the contraction
firstRow++;
}
self.selectedRowIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstRow, lastRow-firstRow+1)];
}
- (void)moveLeft:(id)sender
{
NSUInteger column = [self.selectedColumnIndexes firstIndex];
NSUInteger row = [self.selectedRowIndexes firstIndex];
// Accomodate for the sticky edges
if(stickyColumnEdge == MBTableGridRightEdge) {
column = [self.selectedColumnIndexes lastIndex];
}
if(stickyRowEdge == MBTableGridBottomEdge) {
row = [self.selectedRowIndexes lastIndex];
}
// If we're already at the first column, do nothing
if(column <= 0)
return;
// If the Shift key was not held, move the selection
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndex:(column-1)];
self.selectedRowIndexes = [NSIndexSet indexSetWithIndex:row];
}
- (void)moveLeftAndModifySelection:(id)sender
{
if(shouldOverrideModifiers) {
[self moveLeft:sender];
shouldOverrideModifiers = NO;
return;
}
NSUInteger firstColumn = [self.selectedColumnIndexes firstIndex];
NSUInteger lastColumn = [self.selectedColumnIndexes lastIndex];
// If there is only one column selected, change the sticky edge to the right
if([self.selectedColumnIndexes count] == 1) {
stickyColumnEdge = MBTableGridRightEdge;
}
// We can't expand past the first column
if(stickyColumnEdge == MBTableGridRightEdge && firstColumn <= 0)
return;
if(stickyColumnEdge == MBTableGridLeftEdge) {
// If the top edge is sticky, contract the selection
lastColumn--;
} else if(stickyColumnEdge == MBTableGridRightEdge) {
// If the bottom edge is sticky, expand the contraction
firstColumn--;
}
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstColumn, lastColumn-firstColumn+1)];
}
- (void)moveRight:(id)sender
{
NSUInteger column = [self.selectedColumnIndexes firstIndex];
NSUInteger row = [self.selectedRowIndexes firstIndex];
// Accomodate for the sticky edges
if(stickyColumnEdge == MBTableGridRightEdge) {
column = [self.selectedColumnIndexes lastIndex];
}
if(stickyRowEdge == MBTableGridBottomEdge) {
row = [self.selectedRowIndexes lastIndex];
}
// If we're already at the last column, do nothing
if(column >= ([self numberOfColumns]-1))
return;
// If the Shift key was not held, move the selection
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndex:(column+1)];
self.selectedRowIndexes = [NSIndexSet indexSetWithIndex:row];
}
- (void)moveRightAndModifySelection:(id)sender
{
if(shouldOverrideModifiers) {
[self moveRight:sender];
shouldOverrideModifiers = NO;
return;
}
NSUInteger firstColumn = [self.selectedColumnIndexes firstIndex];
NSUInteger lastColumn = [self.selectedColumnIndexes lastIndex];
// If there is only one column selected, change the sticky edge to the right
if([self.selectedColumnIndexes count] == 1) {
stickyColumnEdge = MBTableGridLeftEdge;
}
// We can't expand past the last column
if(stickyColumnEdge == MBTableGridLeftEdge && lastColumn >= ([self numberOfColumns]-1))
return;
if(stickyColumnEdge == MBTableGridLeftEdge) {
// If the top edge is sticky, contract the selection
lastColumn++;
} else if(stickyColumnEdge == MBTableGridRightEdge) {
// If the bottom edge is sticky, expand the contraction
firstColumn++;
}
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstColumn, lastColumn-firstColumn+1)];
}
- (void)selectAll:(id)sender
{
stickyColumnEdge = MBTableGridLeftEdge;
stickyRowEdge = MBTableGridTopEdge;
self.selectedColumnIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self numberOfColumns])];
self.selectedRowIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self numberOfRows])];
}
- (void)deleteBackward:(id)sender
{
// Clear the contents of every selected cell
NSUInteger column = [self.selectedColumnIndexes firstIndex];
while(column <= [self.selectedColumnIndexes lastIndex]) {
NSUInteger row = [self.selectedRowIndexes firstIndex];
while(row <= [self.selectedRowIndexes lastIndex]) {
[self _setObjectValue:nil forColumn:column row:row];
row++;
}
column++;
}
[self reloadData];
}
- (void)insertText:(id)aString
{
[contentView editSelectedCell:self];
// Insert the typed string into the field editor
NSText *fieldEditor = [[self window] fieldEditor:YES forObject:self];
[fieldEditor setString:aString];
}
#pragma mark -
#pragma mark Notifications
- (void)viewFrameDidChange:(NSNotification *)aNotification
{
//[self reloadData];
}
- (void)contentViewDidScroll:(NSNotification *)aNotification
{
NSView *changedView = [aNotification object];
// Get the origin of the NSClipView
NSPoint changedBoundsOrigin = [changedView bounds].origin;
/*
* Column Header Synchronization
*/
// Get the column headers' current origin
NSPoint curColumnOffset = [[columnHeaderScrollView contentView] bounds].origin;
NSPoint newColumnOffset = curColumnOffset;
// Column headers are synchronized in the horizontal plane
newColumnOffset.x = changedBoundsOrigin.x;
// If the synced position is different from our current position, reposition the headers view
if (!NSEqualPoints(curColumnOffset, changedBoundsOrigin))
{
[[columnHeaderScrollView contentView] scrollToPoint:newColumnOffset];
// we have to tell the NSScrollView to update its
// scrollers
[columnHeaderScrollView reflectScrolledClipView:[columnHeaderScrollView contentView]];
}
/*
* Row Header Synchronization
*/
// Get the row headers' current origin
NSPoint curRowOffset = [[rowHeaderScrollView contentView] bounds].origin;
NSPoint newRowOffset = curRowOffset;
// Row headers are synchronized in the vertical plane
newRowOffset.y = changedBoundsOrigin.y;
// If the synced position is different from our current position, reposition the headers view
if (!NSEqualPoints(curRowOffset, changedBoundsOrigin))
{
[[rowHeaderScrollView contentView] scrollToPoint:newRowOffset];
// we have to tell the NSScrollView to update its
// scrollers
[rowHeaderScrollView reflectScrolledClipView:[rowHeaderScrollView contentView]];
}
}
#pragma mark -
#pragma mark Protocol Methods
#pragma mark NSDraggingDestination
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
NSData *columnData = [pboard dataForType:MBTableGridColumnDataType];
NSData *rowData = [pboard dataForType:MBTableGridRowDataType];
if (columnData) {
return NSDragOperationMove;
} else if (rowData) {
return NSDragOperationMove;
} else {
if ([[self dataSource] respondsToSelector:@selector(tableGrid:validateDrop:proposedColumn:row:)]) {
NSPoint mouseLocation = [self convertPoint:[sender draggingLocation] fromView:nil];
NSUInteger dropColumn = [self columnAtPoint:mouseLocation];
NSUInteger dropRow = [self rowAtPoint:mouseLocation];
NSDragOperation dragOperation = [[self dataSource] tableGrid:self validateDrop:sender proposedColumn:dropColumn row:dropRow];
// If the drag is okay, highlight the appropriate cell
if (dragOperation != NSDragOperationNone) {
[contentView _setDropColumn:dropColumn];
[contentView _setDropRow:dropRow];
}
return dragOperation;
}
}
return NSDragOperationNone;
}
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
NSData *columnData = [pboard dataForType:MBTableGridColumnDataType];
NSData *rowData = [pboard dataForType:MBTableGridRowDataType];
NSPoint mouseLocation = [self convertPoint:[sender draggingLocation] fromView:nil];
if (columnData) {
// If we're dragging a column
NSUInteger dropColumn = [self _dropColumnForPoint:mouseLocation];
if (dropColumn == NSNotFound) {
return NSDragOperationNone;
}
NSIndexSet *draggedColumns = (NSIndexSet *)[NSKeyedUnarchiver unarchiveObjectWithData:columnData];
BOOL canDrop = NO;
if([[self dataSource] respondsToSelector:@selector(tableGrid:canMoveColumns:toIndex:)]) {
canDrop = [[self dataSource] tableGrid:self canMoveColumns:draggedColumns toIndex:dropColumn];
}
[contentView _setDraggingColumnOrRow:YES];
if(canDrop) {
[contentView _setDropColumn:dropColumn];
return NSDragOperationMove;
} else {
[contentView _setDropColumn:NSNotFound];
}
} else if (rowData) {
// If we're dragging a row
NSUInteger dropRow = [self _dropRowForPoint:mouseLocation];
if(dropRow == NSNotFound) {
return NSDragOperationNone;
}
NSIndexSet *draggedRows = (NSIndexSet *)[NSKeyedUnarchiver unarchiveObjectWithData:rowData];
BOOL canDrop = NO;
if([[self dataSource] respondsToSelector:@selector(tableGrid:canMoveRows:toIndex:)]) {
canDrop = [[self dataSource] tableGrid:self canMoveRows:draggedRows toIndex:dropRow];
}
[contentView _setDraggingColumnOrRow:YES];
if(canDrop) {
[contentView _setDropRow:dropRow];
return NSDragOperationMove;
} else {
[contentView _setDropRow:NSNotFound];
}
} else {
if ([[self dataSource] respondsToSelector:@selector(tableGrid:validateDrop:proposedColumn:row:)]) {
NSUInteger dropColumn = [self columnAtPoint:mouseLocation];
NSUInteger dropRow = [self rowAtPoint:mouseLocation];
[contentView _setDraggingColumnOrRow:NO];
NSDragOperation dragOperation = [[self dataSource] tableGrid:self validateDrop:sender proposedColumn:dropColumn row:dropRow];
// If the drag is okay, highlight the appropriate cell
if (dragOperation != NSDragOperationNone) {
[contentView _setDropColumn:dropColumn];
[contentView _setDropRow:dropRow];
}
return dragOperation;
}
}
return NSDragOperationNone;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
[contentView _setDropColumn:NSNotFound];
[contentView _setDropRow:NSNotFound];
}
- (void)draggingEnded:(id <NSDraggingInfo>)sender
{
[contentView _setDropColumn:NSNotFound];
[contentView _setDropRow:NSNotFound];
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
NSData *columnData = [pboard dataForType:MBTableGridColumnDataType];
NSData *rowData = [pboard dataForType:MBTableGridRowDataType];
NSPoint mouseLocation = [self convertPoint:[sender draggingLocation] fromView:nil];
if (columnData) {
// If we're dragging a column
if ([[self dataSource] respondsToSelector:@selector(tableGrid:moveColumns:toIndex:)]) {
// Get which columns are being dragged
NSIndexSet *draggedColumns = (NSIndexSet *)[NSKeyedUnarchiver unarchiveObjectWithData:columnData];
// Get the index to move the columns to
NSUInteger dropColumn = [self _dropColumnForPoint:mouseLocation];
// Tell the data source to move the columns
BOOL didDrag = [[self dataSource] tableGrid:self moveColumns:draggedColumns toIndex:dropColumn];
if (didDrag) {
NSUInteger startIndex = dropColumn;
NSUInteger length = [draggedColumns count];
if (dropColumn > [draggedColumns firstIndex]) {
startIndex -= [draggedColumns count];
}
NSIndexSet *newColumns = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(startIndex, length)];
// Post the notification
[[NSNotificationCenter defaultCenter] postNotificationName:MBTableGridDidMoveColumnsNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:draggedColumns, @"OldColumns", newColumns, @"NewColumns", nil]];
// Change the selection to reflect the newly-dragged columns
self.selectedColumnIndexes = newColumns;
}
return didDrag;
}
} else if (rowData) {
// If we're dragging a row
if ([[self dataSource] respondsToSelector:@selector(tableGrid:moveRows:toIndex:)]) {
// Get which rows are being dragged
NSIndexSet *draggedRows = (NSIndexSet *)[NSKeyedUnarchiver unarchiveObjectWithData:rowData];
// Get the index to move the rows to
NSUInteger dropRow = [self _dropRowForPoint:mouseLocation];
// Tell the data source to move the rows
BOOL didDrag = [[self dataSource] tableGrid:self moveRows:draggedRows toIndex:dropRow];
if (didDrag) {
NSUInteger startIndex = dropRow;
NSUInteger length = [draggedRows count];
if (dropRow > [draggedRows firstIndex]) {
startIndex -= [draggedRows count];
}
NSIndexSet *newRows = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(startIndex, length)];
// Post the notification
[[NSNotificationCenter defaultCenter] postNotificationName:MBTableGridDidMoveRowsNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:draggedRows, @"OldRows", newRows, @"NewRows", nil]];
// Change the selection to reflect the newly-dragged rows
self.selectedRowIndexes = newRows;
}
return didDrag;
}
} else {
if ([[self dataSource] respondsToSelector:@selector(tableGrid:acceptDrop:column:row:)]) {
NSUInteger dropColumn = [self columnAtPoint:mouseLocation];
NSUInteger dropRow = [self rowAtPoint:mouseLocation];
// Pass the drag to the data source
BOOL didPerformDrag = [[self dataSource] tableGrid:self acceptDrop:sender column:dropColumn row:dropRow];
return didPerformDrag;
}
}
return NO;
}
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender
{
[contentView _setDropColumn:NSNotFound];
[contentView _setDropRow:NSNotFound];
}
#pragma mark -
#pragma mark Subclass Methods
#pragma mark Dimensions
- (NSUInteger)numberOfRows
{
// Ask the data source
if([[self dataSource] respondsToSelector:@selector(numberOfRowsInTableGrid:)]) {
return [[self dataSource] numberOfRowsInTableGrid:self];
}
return 0;
}
- (NSUInteger)numberOfColumns
{
// Ask the data source
if([[self dataSource] respondsToSelector:@selector(numberOfColumnsInTableGrid:)]) {
return [[self dataSource] numberOfColumnsInTableGrid:self];
}
return 0;
}
#pragma mark Reloading the Grid
- (void)reloadData
{
// Update the content view's size
NSUInteger lastColumn = [self numberOfColumns]-1;
NSUInteger lastRow = [self numberOfRows]-1;
NSRect bottomRightCellFrame = [contentView frameOfCellAtColumn:lastColumn row:lastRow];
NSRect contentRect = NSMakeRect([contentView frame].origin.x, [contentView frame].origin.y, NSMaxX(bottomRightCellFrame), NSMaxY(bottomRightCellFrame));
[contentView setFrameSize:contentRect.size];
// Update the column header view's size
NSRect columnHeaderFrame = [columnHeaderView frame];
columnHeaderFrame.size.width = contentRect.size.width;
if(![[contentScrollView verticalScroller] isHidden]) {
columnHeaderFrame.size.width += [NSScroller scrollerWidth];
}
[columnHeaderView setFrameSize:columnHeaderFrame.size];
// Update the row header view's size
NSRect rowHeaderFrame = [rowHeaderView frame];
rowHeaderFrame.size.height = contentRect.size.height;
if(![[contentScrollView horizontalScroller] isHidden]) {
columnHeaderFrame.size.height += [NSScroller scrollerWidth];
}
[rowHeaderView setFrameSize:rowHeaderFrame.size];
[self setNeedsDisplay:YES];
}
#pragma mark Layout Support
- (NSRect)rectOfColumn:(NSUInteger)columnIndex
{
NSRect rect = [self convertRect:[contentView rectOfColumn:columnIndex] fromView:contentView];
rect.origin.y = 0;
rect.size.height += MBTableGridColumnHeaderHeight;
if(rect.size.height > [self frame].size.height) {
rect.size.height = [self frame].size.height;
// If the scrollbar is visible, don't include it in the rect
if(![[contentScrollView horizontalScroller] isHidden]) {
rect.size.height -= [NSScroller scrollerWidth];
}
}
return rect;
}
- (NSRect)rectOfRow:(NSUInteger)rowIndex
{
NSRect rect = [self convertRect:[contentView rectOfRow:rowIndex] fromView:contentView];
rect.origin.x = 0;
rect.size.width += MBTableGridRowHeaderWidth;
return rect;
}
- (NSRect)frameOfCellAtColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex
{
return [self convertRect:[contentView frameOfCellAtColumn:columnIndex row:rowIndex] fromView:contentView];
}
- (NSRect)headerRectOfColumn:(NSUInteger)columnIndex
{
return [self convertRect:[columnHeaderView headerRectOfColumn:columnIndex] fromView:columnHeaderView];
}
- (NSRect)headerRectOfRow:(NSUInteger)rowIndex
{
return [self convertRect:[rowHeaderView headerRectOfColumn:rowIndex] fromView:rowHeaderView];
}
- (NSRect)headerRectOfCorner
{
NSRect rect = NSMakeRect(0, 0, MBTableGridRowHeaderWidth, MBTableGridColumnHeaderHeight);
return rect;
}
- (NSInteger)columnAtPoint:(NSPoint)aPoint
{
NSInteger column = 0;
while(column < [self numberOfColumns]) {
NSRect columnFrame = [self rectOfColumn:column];
if(NSPointInRect(aPoint, columnFrame)) {
return column;
}
column++;
}
return NSNotFound;
}
- (NSInteger)rowAtPoint:(NSPoint)aPoint
{
NSInteger row = 0;
while(row < [self numberOfRows]) {
NSRect rowFrame = [self rectOfRow:row];
if(NSPointInRect(aPoint, rowFrame)) {
return row;
}
row++;
}
return NSNotFound;
}
#pragma mark Auxiliary Views
- (MBTableGridHeaderView *)columnHeaderView
{
return columnHeaderView;
}
- (MBTableGridHeaderView *)rowHeaderView
{
return rowHeaderView;
}
- (MBTableGridContentView *)contentView
{
return contentView;
}
@end
@implementation MBTableGrid (OverriddenPropertyAccessors)
- (void)setSelectedColumnIndexes:(NSIndexSet *)anIndexSet
{
if(anIndexSet == selectedColumnIndexes)
return;
if(selectedColumnIndexes) {
[selectedColumnIndexes release];
}
// Allow the delegate to validate the selection
if ([[self delegate] respondsToSelector:@selector(tableGrid:willSelectColumnsAtIndexPath:)]) {
anIndexSet = [[self delegate] tableGrid:self willSelectColumnsAtIndexPath:anIndexSet];
}
selectedColumnIndexes = [anIndexSet retain];
[self setNeedsDisplay:YES];
// Post the notification
[[NSNotificationCenter defaultCenter] postNotificationName:MBTableGridDidChangeSelectionNotification object:self];
}
- (void)setSelectedRowIndexes:(NSIndexSet *)anIndexSet
{
if(anIndexSet == selectedColumnIndexes)
return;
if(selectedRowIndexes) {
[selectedRowIndexes release];
}
// Allow the delegate to validate the selection
if ([[self delegate] respondsToSelector:@selector(tableGrid:willSelectRowsAtIndexPath:)]) {
anIndexSet = [[self delegate] tableGrid:self willSelectRowsAtIndexPath:anIndexSet];
}
selectedRowIndexes = [anIndexSet retain];
[self setNeedsDisplay:YES];
// Post the notification
[[NSNotificationCenter defaultCenter] postNotificationName:MBTableGridDidChangeSelectionNotification object:self];
}
- (void)setDelegate:(id <MBTableGridDelegate>)anObject
{
if (anObject == delegate)