forked from mikecsh/mbtablegrid
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMBTableGridContentView.m
1661 lines (1301 loc) · 58 KB
/
MBTableGridContentView.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 "MBTableGridContentView.h"
#import "MBTableGrid.h"
#import "MBTableGridCell.h"
#import "MBPopupButtonCell.h"
#import "MBButtonCell.h"
#import "MBImageCell.h"
#import "MBLevelIndicatorCell.h"
#import "MBAutoCompleteWindow.h"
#define kGRAB_HANDLE_HALF_SIDE_LENGTH 3.0f
#define kGRAB_HANDLE_SIDE_LENGTH 6.0f
#define kCELL_EDIT_HORIZONTAL_PADDING 4.0f
NSString * const MBTableGridTrackingPartKey = @"part";
@interface MBTableGrid (Private)
- (id)_objectValueForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (NSFormatter *)_formatterForColumn:(NSUInteger)columnIndex;
- (NSCell *)_cellForColumn:(NSUInteger)columnIndex;
- (NSImage *)_accessoryButtonImageForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (void)_accessoryButtonClicked:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (NSArray *)_availableObjectValuesForColumn:(NSUInteger)columnIndex;
- (NSArray *)_autocompleteValuesForEditString:(NSString *)editString column:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (void)_setObjectValue:(id)value forColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex undoTitle:(NSString *)undoTitle;
- (BOOL)_canEditCellAtColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (BOOL)_canFillCellAtColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (void)_fillInColumn:(NSUInteger)column fromRow:(NSUInteger)row numberOfRowsWhenStarting:(NSUInteger)numberOfRowsWhenStartingFilling;
- (void)_setStickyColumn:(MBTableGridEdge)stickyColumn row:(MBTableGridEdge)stickyRow;
- (float)_widthForColumn:(NSUInteger)columnIndex;
- (id)_backgroundColorForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (id)_frozenBackgroundColorForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (id)_groupSummaryBackgroundColorForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (id)_textColorForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (MBTableGridEdge)_stickyColumn;
- (MBTableGridEdge)_stickyRow;
- (void)_userDidEnterInvalidStringInColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex errorDescription:(NSString *)errorDescription;
- (NSCell *)_footerCellForColumn:(NSUInteger)columnIndex;
- (id)_footerValueForColumn:(NSUInteger)columnIndex;
- (void)_setFooterValue:(id)value forColumn:(NSUInteger)columnIndex;
- (BOOL)_isGroupHeadingRow:(NSUInteger)rowIndex;
- (BOOL)_isGroupSummaryRow:(NSUInteger)rowIndex;
- (BOOL)_isGroupRow:(NSUInteger)rowIndex;
- (NSCell *)_groupSummaryCellForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (void)_updateGroupSummaryCell:(NSCell *)cell forColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
- (id)_groupSummaryValueForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
@end
@interface MBTableGridContentView (Cursors)
- (NSCursor *)_cellSelectionCursor;
- (NSImage *)_cellSelectionCursorImage;
- (NSCursor *)_cellExtendSelectionCursor;
- (NSImage *)_cellExtendSelectionCursorImage;
- (NSImage *)_grabHandleImage;
- (NSCursor *)_cellFillCursor;
@end
@interface MBTableGridContentView (DragAndDrop)
- (void)_setDraggingColumnOrRow:(BOOL)flag;
- (void)_setDropColumn:(NSInteger)columnIndex;
- (void)_setDropRow:(NSInteger)rowIndex;
- (void)_timerAutoscrollCallback:(NSTimer *)aTimer;
@end
@interface MBTableGridContentView ()<MBAutoSelectDelegate>
@property (nonatomic, weak) MBTableGrid *cachedTableGrid;
@property (nonatomic, readonly) BOOL frozen;
@property (nonatomic, strong) MBAutoCompleteWindow *autoCompleteWindow;
@property (nonatomic) NSInteger completionsCount;
@property (nonatomic) NSInteger fieldEditorLength;
@end
@implementation MBTableGridContentView
#pragma mark -
#pragma mark Initialization & Superclass Overrides
- (id)initWithFrame:(NSRect)frameRect
{
if(self = [super initWithFrame:frameRect]) {
mouseDownColumn = NSNotFound;
mouseDownRow = NSNotFound;
editedColumn = NSNotFound;
editedRow = NSNotFound;
dropColumn = NSNotFound;
dropRow = NSNotFound;
grabHandleImage = [self _grabHandleImage];
grabHandleRect = NSZeroRect;
// Cache the cursor image
cursorImage = [self _cellSelectionCursorImage];
cursorExtendSelectionImage = [self _cellExtendSelectionCursorImage];
cursorFillImage = [NSImage imageNamed:@"VerticalResizeCursor"];
isCompleting = NO;
isDraggingColumnOrRow = NO;
shouldDrawFillPart = MBTableGridTrackingPartNone;
self.wantsLayer = true;
self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;
self.layer.drawsAsynchronously = YES;
_defaultCell = [[MBTableGridCell alloc] initTextCell:@""];
[_defaultCell setBordered:YES];
[_defaultCell setScrollable:YES];
[_defaultCell setLineBreakMode:NSLineBreakByTruncatingTail];
_cellRowHeight = 20;
_groupRowColor = [NSColor windowBackgroundColor];
_groupRowFont = [NSFont boldSystemFontOfSize:[NSFont systemFontSizeForControlSize:NSControlSizeRegular]];
_groupRowTextColor = [NSColor headerTextColor];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mylistener:) name:NSMenuDidChangeItemNotification object:self];
}
return self;
}
- (BOOL)isOpaque {
return YES;
}
- (void)setDefaultCellFont:(NSFont *)defaultCellFont {
_defaultCellFont = defaultCellFont;
NSDictionary *fontAttributes = @{NSFontAttributeName : defaultCellFont,
NSFontSizeAttribute : @(defaultCellFont.pointSize)};
CGSize textSize = [@"ABCWjxyz1230" sizeWithAttributes:fontAttributes];
_cellRowHeight = ceilf(textSize.height) + 4;
_groupRowFont = [NSFont boldSystemFontOfSize:defaultCellFont.pointSize];
[self setNeedsDisplay:YES];
}
- (void)mylistener:(id)sender
{
NSInteger selectedColumn = [[self tableGrid].selectedColumnIndexes firstIndex];
NSCell *selectedCell = [[self tableGrid] _cellForColumn:selectedColumn];
MBPopupButtonCell *popupCell = (MBPopupButtonCell *)selectedCell;
if ([popupCell isKindOfClass:[MBPopupButtonCell class]])
{
[popupCell synchronizeTitleAndSelectedItem];
//[popupCell setTitle:[[popupCell selectedItem] title]];
//[popupCell selectItemWithTitle:[[popupCell selectedItem] title]];
}
}
- (void)cacheGroupRows {
if (!_groupHeadingRowIndexes || !_groupSummaryRowIndexes) {
_groupHeadingRowIndexes = [NSMutableDictionary dictionary];
_groupSummaryRowIndexes = [NSMutableDictionary dictionary];
NSUInteger numberOfRows = [self tableGrid].numberOfRows;
NSUInteger row = 0;
while (row < numberOfRows) {
if ([[self tableGrid] _isGroupHeadingRow:row]) {
NSRect groupRowRect = [self rectOfRow:row];
_groupHeadingRowIndexes[@(row)] = [NSValue valueWithRect:groupRowRect];
} else if ([[self tableGrid] _isGroupSummaryRow:row]) {
NSRect groupRowRect = [self rectOfRow:row];
_groupSummaryRowIndexes[@(row)] = [NSValue valueWithRect:groupRowRect];
}
row++;
}
}
}
- (void)drawRect:(NSRect)rect
{
// NSColor *layerBackgroundColour = nil;
// if (@available(macOS 10.13, *)) {
// layerBackgroundColour = [NSColor colorNamed:@"grid-view-background"];
// } else {
// // Fallback on earlier versions
// layerBackgroundColour = [NSColor colorWithCalibratedWhite:0.98 alpha:1.0];
// }
NSRect backgroundRect = rect;
// solves a problem with a grey bar appearing at the right of the grid view.
backgroundRect.size.width += 1;
[[NSColor controlBackgroundColor] set];
NSRectFill(backgroundRect);
NSIndexSet *selectedColumns = [[self tableGrid] selectedColumnIndexes];
NSIndexSet *selectedRows = [[self tableGrid] selectedRowIndexes];
NSUInteger numberOfColumns = [self tableGrid].numberOfColumns;
NSUInteger numberOfRows = [self tableGrid].numberOfRows;
if (numberOfRows == 0 || numberOfColumns == 0) {
return;
}
NSUInteger firstColumn = NSNotFound;
NSUInteger lastColumn = numberOfColumns - 1;
NSUInteger firstRow = NSNotFound;
NSUInteger lastRow = numberOfRows - 1;
// Find the columns to draw
NSUInteger column = 0;
while (column < numberOfColumns) {
NSRect columnRect = [self rectOfColumn:column];
if (firstColumn == NSNotFound && NSMinX(rect) >= NSMinX(columnRect) && NSMinX(rect) <= NSMaxX(columnRect)) {
firstColumn = column;
} else if (firstColumn != NSNotFound && NSMaxX(rect) >= NSMinX(columnRect) && NSMaxX(rect) <= NSMaxX(columnRect)) {
lastColumn = column;
break;
}
column++;
}
// Cache group rows
[self cacheGroupRows];
// Find the rows to draw
NSUInteger row = 0;
while (row < numberOfRows) {
NSRect rowRect = [self rectOfRow:row];
if (firstRow == NSNotFound && NSMinY(rect) >= rowRect.origin.x && NSMinY(rect) <= NSMaxY(rowRect)) {
firstRow = row;
} else if (firstRow != NSNotFound && NSMaxY(rect) >= NSMinY(rowRect) && NSMaxY(rect) <= NSMaxY(rowRect)) {
lastRow = row;
break;
}
row++;
}
NSRect selectionInsetRect = NSZeroRect;
NSBezierPath *selectionPath = nil;
if([selectedColumns count] && [selectedRows count] && [self tableGrid].numberOfColumns > 0 && [self tableGrid].numberOfRows > 0) {
selectionInsetRect = NSInsetRect(self.selectionRect, 1, 1);
selectionPath = [NSBezierPath bezierPathWithRect:selectionInsetRect];
NSAffineTransform *translate = [NSAffineTransform transform];
[translate translateXBy:-0.5 yBy:-0.5];
[selectionPath transformUsingAffineTransform:translate];
[[NSColor controlBackgroundColor] set];
[selectionPath fill];
}
NSRect lastColumnRect = [self rectOfColumn:numberOfColumns - 1];
row = firstRow;
while (row <= lastRow) {
NSValue *rowRectValue = _groupHeadingRowIndexes[@(row)];
if (rowRectValue) {
NSRect rowFrame = [self rectOfRow:row];
rowFrame.size.width = NSMaxX(lastColumnRect);
if ([NSApplication sharedApplication].userInterfaceLayoutDirection == NSUserInterfaceLayoutDirectionLeftToRight && self != [self tableGrid].frozenContentView) {
// rowFrame.size.width -= MBTableGridContentViewPadding + 10;
} else if ([self tableGrid].frozenContentView) {
rowFrame.size.width += NSWidth([self rectOfColumn:numberOfColumns - 1]);
}
id objectValue = [[self tableGrid] _objectValueForColumn:0 row:row];
_defaultCell.font = _groupRowFont;
_defaultCell.textColor = _groupRowTextColor;
_defaultCell.objectValue = objectValue;
_defaultCell.isGroupRow = YES;
[_defaultCell drawWithFrame:rowFrame inView:self withBackgroundColor:_groupRowColor textColor:[NSColor labelColor]];
} else {
_defaultCell.isGroupRow = NO;
column = firstColumn;
while (column <= lastColumn) {
NSRect cellFrame = [self frameOfCellAtColumn:column row:row];
NSCell *_cell = nil;
BOOL isGroupSummary = self.groupSummaryRowIndexes[@(row)] != nil;
if (isGroupSummary) {
_cell = [[self tableGrid] _groupSummaryCellForColumn:column row:row];
_cell.font = [NSFont boldSystemFontOfSize:_defaultCell.font.pointSize];
} else {
_cell = [[self tableGrid] _cellForColumn:column];
if (_defaultCellFont) {
_cell.font = _defaultCellFont;
}
}
// If we need to draw then check if we're a popup button. This may be a bit of
// a hack, but it seems to clear up the problem with the popup button clearing
// if you don't select a value. It's the editedRow and editedColumn bits that
// cause the problem. However, if you remove the row and column condition, then
// if you type into a text field, the text doesn't get cleared first before you
// start typing. So this seems to make both conditions work.
// checking for class MBPopupButtonCell causes a severe performance problem.
// if ([self needsToDrawRect:cellFrame] && (!(row == editedRow && column == editedColumn))) {
if ([self needsToDrawRect:cellFrame] && (!(row == editedRow && column == editedColumn) || ((row == editedRow && column == editedColumn) && [_cell isKindOfClass:[MBPopupButtonCell class]]))) {
NSColor *backgroundColor = nil;
BOOL isFrozenColumn = [[self tableGrid] isFrozenColumn:column];
if (isFrozenColumn) {
backgroundColor = [[self tableGrid] _frozenBackgroundColorForColumn:column row:row] ?: [NSColor windowBackgroundColor];
} else if (isGroupSummary) {
backgroundColor = [[self tableGrid] _groupSummaryBackgroundColorForColumn:column row:row] ?: [NSColor controlBackgroundColor];
} else {
backgroundColor = [[self tableGrid] _backgroundColorForColumn:column row:row] ?: [NSColor controlBackgroundColor];
}
if (!_cell) {
_cell = _defaultCell;
}
[_cell setFormatter:nil]; // An exception is raised if the formatter is not set to nil before changing at runtime
[_cell setFormatter:[[self tableGrid] _formatterForColumn:column]];
id objectValue = nil;
isFrozenColumn = self != [self tableGrid].frozenContentView && isFrozenColumn;
if (isGroupSummary) {
objectValue = [[self tableGrid] _groupSummaryValueForColumn:column row:row];
} else if (isFilling && [selectedColumns containsIndex:column] && [selectedRows containsIndex:row]) {
objectValue = [[self tableGrid] _objectValueForColumn:mouseDownColumn row:mouseDownRow];
} else {
objectValue = [[self tableGrid] _objectValueForColumn:column row:row];
}
if (isFrozenColumn) {
[_cell setObjectValue:nil];
} else if ([_cell isKindOfClass:[MBPopupButtonCell class]]) {
[_cell setObjectValue:objectValue];
} else {
if ([_cell isKindOfClass:[MBImageCell class]] && ![objectValue isKindOfClass:[NSImage class]]) {
[_cell setObjectValue:nil];
} else {
[_cell setObjectValue:objectValue];
}
}
NSColor *darkLightTextColor = nil;
BOOL isLight = NO;
if ([self isLightColour:backgroundColor]) {
darkLightTextColor = [NSColor blackColor];
isLight = YES;
} else {
darkLightTextColor = [NSColor whiteColor];
isLight = NO;
}
if ([_cell isKindOfClass:[MBPopupButtonCell class]]) {
MBPopupButtonCell *cell = (MBPopupButtonCell *)_cell;
NSColor *textColor = [[self tableGrid] _textColorForColumn:column row:row] ?: darkLightTextColor;
[cell setTextColor:textColor];
if (isLight) {
cell.arrowImage = [NSImage imageNamed:@"popup-indicator"];
} else {
cell.arrowImage = [NSImage imageNamed:@"popup-indicator-white"];
}
[cell drawWithFrame:cellFrame inView:self withBackgroundColor:backgroundColor textColor:textColor];// Draw background color
} else if ([_cell isKindOfClass:[MBImageCell class]]) {
MBImageCell *cell = (MBImageCell *)_cell;
cell.accessoryButtonImage = [[self tableGrid] _accessoryButtonImageForColumn:column row:row];
[cell drawWithFrame:cellFrame inView:self withBackgroundColor:backgroundColor];// Draw background color
} else if ([_cell isKindOfClass:[MBLevelIndicatorCell class]]) {
MBLevelIndicatorCell *cell = (MBLevelIndicatorCell *)_cell;
cell.target = self;
cell.action = @selector(updateLevelIndicator:);
[cell drawWithFrame:cellFrame inView:[self tableGrid] withBackgroundColor:backgroundColor];// Draw background color
} else if ([_cell isKindOfClass:[MBButtonCell class]]) {
MBButtonCell *cell = (MBButtonCell *)_cell;
[cell drawWithFrame:cellFrame inView:self withBackgroundColor:backgroundColor];// Draw background color
} else {
MBTableGridCell *cell = (MBTableGridCell *)_cell;
NSColor *textColor = [[self tableGrid] _textColorForColumn:column row:row] ?: darkLightTextColor;
[cell setTextColor:textColor];
if (isGroupSummary) {
if (cell.objectValue != nil) {
cell.title = cell.objectValue;
}
if (column == lastColumn) {
cell.isLastColumn = YES;
} else {
cell.isLastColumn = NO;
}
[[self tableGrid] _updateGroupSummaryCell:cell forColumn:column row:row];
} else {
cell.accessoryButtonImage = [[self tableGrid] _accessoryButtonImageForColumn:column row:row];
}
if (cell.font == nil) {
cell.font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
}
[cell drawWithFrame:cellFrame inView:self withBackgroundColor:backgroundColor textColor:textColor];// Draw background color
}
}
column++;
}
}
row++;
}
// Draw the selection rectangle
if([selectedColumns count] && [selectedRows count] && [self tableGrid].numberOfColumns > 0 && [self tableGrid].numberOfRows > 0) {
NSColor *selectionColor = [NSColor alternateSelectedControlColor];
// If the view is not the first responder, then use a gray selection color
NSResponder *firstResponder = [[self window] firstResponder];
BOOL disabled = (![[firstResponder class] isSubclassOfClass:[NSView class]] || ![(NSView *)firstResponder isDescendantOf:[self tableGrid]] || ![[self window] isKeyWindow]);
if (disabled) {
selectionColor = [[selectionColor colorUsingColorSpaceName:NSDeviceWhiteColorSpace] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
} else if (isFilling) {
if (@available(macOS 10.13, *)) {
selectionColor = [NSColor colorNamed:@"fill-background"];
} else {
// Fallback on earlier versions
selectionColor = [NSColor colorWithCalibratedRed:0.996 green:0.827 blue:0.176 alpha:1.000];
}
}
[selectionColor set];
[selectionPath setLineWidth: 1.0];
[selectionPath stroke];
[[selectionColor colorWithAlphaComponent:0.2f] set];
[selectionPath fill];
if (disabled || [selectedColumns count] > 1) {
grabHandleRect = NSZeroRect;
}
else if (shouldDrawFillPart != MBTableGridTrackingPartNone) {
// Draw grab handle
grabHandleRect = NSMakeRect(NSMidX(selectionInsetRect) - kGRAB_HANDLE_HALF_SIDE_LENGTH - 2, (shouldDrawFillPart == MBTableGridTrackingPartFillTop ? NSMinY(selectionInsetRect) : NSMaxY(selectionInsetRect)) - kGRAB_HANDLE_HALF_SIDE_LENGTH - 2, kGRAB_HANDLE_SIDE_LENGTH + 4, kGRAB_HANDLE_SIDE_LENGTH + 4);
[grabHandleImage drawInRect:grabHandleRect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0];
}
// Inavlidate cursors so we use the correct cursor for the selection in the right place
[[self window] invalidateCursorRectsForView:self];
}
// Draw the column drop indicator
if (isDraggingColumnOrRow && dropColumn != NSNotFound && dropColumn <= [self tableGrid].numberOfColumns && dropRow == NSNotFound) {
NSRect columnBorder;
if(dropColumn < [self tableGrid].numberOfColumns) {
columnBorder = [self rectOfColumn:dropColumn];
} else {
columnBorder = [self rectOfColumn:dropColumn-1];
columnBorder.origin.x += columnBorder.size.width;
}
columnBorder.origin.x = NSMinX(columnBorder)-2.0;
columnBorder.size.width = 4.0;
NSColor *selectionColor = [NSColor alternateSelectedControlColor];
NSBezierPath *borderPath = [NSBezierPath bezierPathWithRect:columnBorder];
[borderPath setLineWidth:2.0];
[selectionColor set];
[borderPath stroke];
}
// Draw the row drop indicator
if (isDraggingColumnOrRow && dropRow != NSNotFound && dropRow <= [self tableGrid].numberOfRows && dropColumn == NSNotFound) {
NSRect rowBorder;
if(dropRow < [self tableGrid].numberOfRows) {
rowBorder = [self rectOfRow:dropRow];
} else {
rowBorder = [self rectOfRow:dropRow-1];
rowBorder.origin.y += rowBorder.size.height;
}
rowBorder.origin.y = NSMinY(rowBorder)-2.0;
rowBorder.size.height = 4.0;
NSColor *selectionColor = [NSColor alternateSelectedControlColor];
NSBezierPath *borderPath = [NSBezierPath bezierPathWithRect:rowBorder];
[borderPath setLineWidth:2.0];
[selectionColor set];
[borderPath stroke];
}
// Draw the cell drop indicator
if (!isDraggingColumnOrRow && dropRow != NSNotFound && dropRow <= [self tableGrid].numberOfRows && dropColumn != NSNotFound && dropColumn <= [self tableGrid].numberOfColumns) {
NSRect cellFrame = [self frameOfCellAtColumn:dropColumn row:dropRow];
cellFrame.origin.x -= 2.0;
cellFrame.origin.y -= 2.0;
cellFrame.size.width += 3.0;
cellFrame.size.height += 3.0;
NSBezierPath *borderPath = [NSBezierPath bezierPathWithRect:NSInsetRect(cellFrame, 2, 2)];
NSColor *dropColor = [NSColor alternateSelectedControlColor];
[dropColor set];
[borderPath setLineWidth:2.0];
[borderPath stroke];
}
[self updateTrackingAreas];
}
- (void)updateCell:(id)sender {
// This is here just to satisfy NSLevelIndicatorCell because
// when this view is the controlView for the NSLevelIndicatorCell,
// it calls updateCell on this controlView.
}
- (void)updateLevelIndicator:(NSNumber *)value {
NSInteger selectedColumn = [[self tableGrid].selectedColumnIndexes firstIndex];
NSInteger selectedRow = [[self tableGrid].selectedRowIndexes firstIndex];
// sanity check to make sure we have an NSNumber.
// I've observed that when the user lets go of the mouse,
// the value parameter becomes the MBTableGridContentView
// object for some reason.
if ([value isKindOfClass:[NSNumber class]]) {
[[self tableGrid] _setObjectValue:value forColumn:selectedColumn row:selectedRow undoTitle:@"Change Rating"];
NSRect cellFrame = [[self tableGrid] frameOfCellAtColumn:selectedColumn row:selectedRow];
[[self tableGrid] setNeedsDisplayInRect:cellFrame];
}
}
- (BOOL)isFlipped
{
return YES;
}
- (void)mouseDown:(NSEvent *)theEvent
{
if (!self.isEditable) {
[super mouseDown:theEvent];
return;
}
if (self.autoCompleteWindow) {
[self.window removeChildWindow:self.autoCompleteWindow];
[self.autoCompleteWindow close];
self.autoCompleteWindow = nil;
}
// Setup the timer for autoscrolling
// (the simply calling autoscroll: from mouseDragged: only works as long as the mouse is moving)
autoscrollTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(_timerAutoscrollCallback:) userInfo:nil repeats:YES];
NSPoint mouseLocationInContentView = [self convertPoint:[theEvent locationInWindow] fromView:nil];
mouseDownColumn = [self columnAtPoint:mouseLocationInContentView];
mouseDownRow = [self rowAtPoint:mouseLocationInContentView];
if (mouseDownColumn < 0 || mouseDownColumn == NSNotFound) {
return;
}
if (mouseDownRow < 0 || mouseDownRow == NSNotFound) {
return;
}
if (_groupHeadingRowIndexes[@(mouseDownRow)] || _groupSummaryRowIndexes[@(mouseDownRow)]) {
mouseDownRow = NSNotFound;
return;
}
// If the column wasn't found, probably need to flush the cached column rects
if (mouseDownColumn == NSNotFound) {
[[self tableGrid].columnRects removeAllObjects];
mouseDownColumn = [self columnAtPoint:mouseLocationInContentView];
}
NSCell *cell = [[self tableGrid] _cellForColumn:mouseDownColumn];
BOOL cellEditsOnFirstClick = ([cell respondsToSelector:@selector(editOnFirstClick)] && [(id<MBTableGridEditable>)cell editOnFirstClick]);
isFilling = NO;
if (theEvent.clickCount == 1) {
// Pass the event back to the MBTableGrid (Used to give First Responder status)
[[self tableGrid] mouseDown:theEvent];
NSUInteger selectedColumn = [[self tableGrid].selectedColumnIndexes firstIndex];
NSUInteger selectedRow = [[self tableGrid].selectedRowIndexes firstIndex];
isFilling = NSPointInRect(mouseLocationInContentView, grabHandleRect);
if (isFilling) {
numberOfRowsWhenStartingFilling = [self tableGrid].numberOfRows;
if (mouseDownRow == selectedRow - 1 || mouseDownRow == selectedRow + 1) {
mouseDownRow = selectedRow;
}
}
// Edit an already selected cell if it doesn't edit on first click
if (selectedColumn == mouseDownColumn && selectedRow == mouseDownRow && !cellEditsOnFirstClick && !isFilling) {
if ([[self tableGrid] _accessoryButtonImageForColumn:mouseDownColumn row:mouseDownRow]) {
NSRect cellFrame = [self frameOfCellAtColumn:mouseDownColumn row:mouseDownRow];
NSCellHitResult hitResult = [cell hitTestForEvent:theEvent inRect:cellFrame ofView:self];
if (hitResult != NSCellHitNone) {
[[self tableGrid] _accessoryButtonClicked:mouseDownColumn row:mouseDownRow];
}
} else if ([cell isKindOfClass:[MBLevelIndicatorCell class]]) {
NSRect cellFrame = [self frameOfCellAtColumn:mouseDownColumn row:mouseDownRow];
[cell trackMouse:theEvent inRect:cellFrame ofView:self untilMouseUp:YES];
} else {
[self editSelectedCell:self text:nil];
}
// Expand a selection when the user holds the shift key
} else if (([theEvent modifierFlags] & NSEventModifierFlagShift) && [self tableGrid].allowsMultipleSelection && !isFilling) {
// If the shift key was held down, extend the selection
NSUInteger stickyColumn = [[self tableGrid].selectedColumnIndexes firstIndex];
NSUInteger stickyRow = [[self tableGrid].selectedRowIndexes firstIndex];
MBTableGridEdge stickyColumnEdge = [[self tableGrid] _stickyColumn];
MBTableGridEdge stickyRowEdge = [[self tableGrid] _stickyRow];
// Compensate for sticky edges
if (stickyColumnEdge == MBTableGridRightEdge) {
stickyColumn = [[self tableGrid].selectedColumnIndexes lastIndex];
}
if (stickyRowEdge == MBTableGridBottomEdge) {
stickyRow = [[self tableGrid].selectedRowIndexes lastIndex];
}
NSRange selectionColumnRange = NSMakeRange(stickyColumn, mouseDownColumn-stickyColumn+1);
NSRange selectionRowRange = NSMakeRange(stickyRow, mouseDownRow-stickyRow+1);
if (mouseDownColumn < stickyColumn) {
selectionColumnRange = NSMakeRange(mouseDownColumn, stickyColumn-mouseDownColumn+1);
stickyColumnEdge = MBTableGridRightEdge;
} else {
stickyColumnEdge = MBTableGridLeftEdge;
}
if (mouseDownRow < stickyRow) {
selectionRowRange = NSMakeRange(mouseDownRow, stickyRow-mouseDownRow+1);
stickyRowEdge = MBTableGridBottomEdge;
} else {
stickyRowEdge = MBTableGridTopEdge;
}
// Select the proper cells
[self tableGrid].selectedColumnIndexes = [NSIndexSet indexSetWithIndexesInRange:selectionColumnRange];
[self tableGrid].selectedRowIndexes = [NSMutableIndexSet indexSetWithIndexesInRange:selectionRowRange];
// Set the sticky edges
[[self tableGrid] _setStickyColumn:stickyColumnEdge row:stickyRowEdge];
// First click on a cell without shift key modifier
} else {
// No modifier keys, so change the selection
if (mouseDownColumn != NSNotFound) {
[self tableGrid].selectedColumnIndexes = [NSIndexSet indexSetWithIndex:mouseDownColumn];
if (![[self tableGrid].selectedRowIndexes containsIndex:mouseDownRow] || (self.tableGrid.selectedRowIndexes.count > 1 && mouseDownRow != NSNotFound)) {
[self tableGrid].selectedRowIndexes = [NSMutableIndexSet indexSetWithIndex:mouseDownRow];
}
[[self tableGrid] _setStickyColumn:MBTableGridLeftEdge row:MBTableGridTopEdge];
}
}
// Edit cells on double click if they don't already edit on first click
} else if (theEvent.clickCount == 2 && !cellEditsOnFirstClick && ![cell isKindOfClass:[MBLevelIndicatorCell class]]) {
// Double click
[self editSelectedCell:self text:nil];
}
// Any cells that should edit on first click are handled here
if (cellEditsOnFirstClick) {
NSRect cellFrame = [[self tableGrid] frameOfCellAtColumn:mouseDownColumn row:mouseDownRow];
cellFrame = NSOffsetRect(cellFrame, -self.enclosingScrollView.frame.origin.x, -self.enclosingScrollView.frame.origin.y);
BOOL mouseEventHitButton = [cell hitTestForEvent:theEvent inRect:cellFrame ofView:self] == NSCellHitContentArea;
if (mouseEventHitButton) {
[self editSelectedCell:self text:nil];
}
}
NSRect cellFrame = [[self tableGrid] frameOfCellAtColumn:mouseDownColumn row:mouseDownRow];
[[self tableGrid] setNeedsDisplayInRect:cellFrame];
[self setNeedsDisplay:YES];
}
- (void)mouseDragged:(NSEvent *)theEvent
{
if (mouseDownColumn != NSNotFound && mouseDownRow != NSNotFound && [self tableGrid].allowsMultipleSelection) {
NSPoint loc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
NSInteger column = [self columnAtPoint:loc];
NSInteger row = [self rowAtPoint:loc];
NSInteger numberOfRows = [self tableGrid].numberOfRows;
// While filling, if dragging beyond the size of the table, add more rows
// If rows were added, tell the delegate
NSUInteger flags = [[NSApp currentEvent] modifierFlags];
if ((flags & NSEventModifierFlagCommand) && isFilling && loc.y > 0.0 && row == NSNotFound && [[self tableGrid].dataSource respondsToSelector:@selector(tableGrid:addRows:)]) {
NSRect rowRect = [self rectOfRow:numberOfRows];
NSInteger numberOfRowsToAdd = ((loc.y - rowRect.origin.y) / rowRect.size.height) + 1;
if (numberOfRowsToAdd > 0 && [[self tableGrid].dataSource tableGrid:[self tableGrid] addRows:numberOfRowsToAdd]) {
row = [self rowAtPoint:loc];
}
[self resetCursorRects];
}
// While filling, if dragging upwards, remove any rows added during the fill operation
if (isFilling && row < numberOfRows && [[self tableGrid].dataSource respondsToSelector:@selector(tableGrid:removeRows:)]) {
NSInteger firstRowToRemove = row + 1;
if (firstRowToRemove < numberOfRowsWhenStartingFilling) {
firstRowToRemove = numberOfRowsWhenStartingFilling;
}
NSIndexSet *rowIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstRowToRemove, numberOfRows - firstRowToRemove)];
[[self tableGrid].dataSource tableGrid:[self tableGrid] removeRows:rowIndexes];
[self resetCursorRects];
}
MBTableGridEdge columnEdge = MBTableGridLeftEdge;
MBTableGridEdge rowEdge = MBTableGridTopEdge;
// Select the appropriate number of columns
if(column != NSNotFound && !isFilling) {
NSInteger firstColumnToSelect = mouseDownColumn;
NSInteger numberOfColumnsToSelect = column-mouseDownColumn+1;
if(column < mouseDownColumn) {
firstColumnToSelect = column;
numberOfColumnsToSelect = mouseDownColumn-column+1;
// Set the sticky edge to the right
columnEdge = MBTableGridRightEdge;
}
[self tableGrid].selectedColumnIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstColumnToSelect,numberOfColumnsToSelect)];
}
// Select the appropriate number of rows
if(row != NSNotFound) {
NSInteger firstRowToSelect = mouseDownRow;
NSInteger numberOfRowsToSelect = row-mouseDownRow+1;
if(row < mouseDownRow) {
firstRowToSelect = row;
numberOfRowsToSelect = mouseDownRow-row+1;
// Set the sticky row to the bottom
rowEdge = MBTableGridBottomEdge;
}
[self tableGrid].selectedRowIndexes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(firstRowToSelect,numberOfRowsToSelect)];
}
// Set the sticky edges
[[self tableGrid] _setStickyColumn:columnEdge row:rowEdge];
if (mouseDownColumn < column) {
[[self tableGrid] scrollForFrozenColumnsFromColumn:column - 1 right:YES];
} else if (mouseDownColumn > column) {
[[self tableGrid] scrollForFrozenColumnsFromColumn:column + 1 right:NO];
}
[self setNeedsDisplay:YES];
}
// [self autoscroll:theEvent];
}
- (void)mouseUp:(NSEvent *)theEvent
{
[autoscrollTimer invalidate];
autoscrollTimer = nil;
if (isFilling) {
[[self tableGrid] _fillInColumn:mouseDownColumn fromRow:mouseDownRow numberOfRowsWhenStarting:numberOfRowsWhenStartingFilling];
isFilling = NO;
[[self tableGrid] setNeedsDisplay:YES];
}
mouseDownColumn = NSNotFound;
mouseDownRow = NSNotFound;
}
- (void)mouseEntered:(NSEvent *)theEvent
{
NSDictionary *dict = theEvent.userData;
MBTableGridTrackingPart part = [dict[MBTableGridTrackingPartKey] integerValue];
if (shouldDrawFillPart != part) {
// NSLog(@"mouseEntered: %@", part == MBTableGridTrackingPartFillTop ? @"top" : @"bottom"); // log
shouldDrawFillPart = part;
[self setNeedsDisplay:YES];
}
}
- (void)mouseExited:(NSEvent *)theEvent
{
if (shouldDrawFillPart != MBTableGridTrackingPartNone) {
// NSLog(@"mouseExited: %@", shouldDrawFillPart == MBTableGridTrackingPartFillTop ? @"top" : @"bottom"); // log
shouldDrawFillPart = MBTableGridTrackingPartNone;
[self setNeedsDisplay:YES];
}
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark Cursor Rects
- (NSRect)selectionRect
{
NSIndexSet *selectedColumns = [self tableGrid].selectedColumnIndexes;
NSIndexSet *selectedRows = [self tableGrid].selectedRowIndexes;
NSRect selectionRect = NSZeroRect;
if (selectedColumns.firstIndex != NSNotFound && selectedRows.firstIndex != NSNotFound) {
NSRect selectionTopLeft = [self frameOfCellAtColumn:[selectedColumns firstIndex] row:[selectedRows firstIndex]];
NSRect selectionBottomRight = [self frameOfCellAtColumn:[selectedColumns lastIndex] row:[selectedRows lastIndex]];
selectionRect.origin = selectionTopLeft.origin;
selectionRect.size.width = NSMaxX(selectionBottomRight)-selectionTopLeft.origin.x;
selectionRect.size.height = NSMaxY(selectionBottomRight)-selectionTopLeft.origin.y;
}
return selectionRect;
}
- (void)resetCursorRects
{
//NSLog(@"%s - %f %f %f %f", __func__, grabHandleRect.origin.x, grabHandleRect.origin.y, grabHandleRect.size.width, grabHandleRect.size.height);
// The main cursor should be the cell selection cursor
// NSIndexSet *selectedColumns = [self tableGrid].selectedColumnIndexes;
// NSIndexSet *selectedRows = [self tableGrid].selectedRowIndexes;
NSRect selectionRect = [self selectionRect];
if (!isFilling) {
[self addCursorRect:selectionRect cursor:[NSCursor arrowCursor]];
[_groupHeadingRowIndexes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSRect rectOfRow = [self rectOfRow:[key integerValue]];
[self addCursorRect:rectOfRow cursor:[NSCursor arrowCursor]];
}];
[_groupSummaryRowIndexes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSRect rectOfRow = [self rectOfRow:[key integerValue]];
[self addCursorRect:rectOfRow cursor:[NSCursor arrowCursor]];
}];
[self addCursorRect:grabHandleRect cursor:[self _cellFillCursor]];
[self addCursorRect:[self visibleRect] cursor:[self _cellSelectionCursor]];
} else {
[self addCursorRect:[self visibleRect] cursor:[self _cellFillCursor]];
}
}
- (void)updateTrackingAreas {
[super updateTrackingAreas];
NSIndexSet *selectedColumns = [self tableGrid].selectedColumnIndexes;
NSIndexSet *selectedRows = [self tableGrid].selectedRowIndexes;
NSRect selectionRect = [self selectionRect];
for (NSTrackingArea *trackingArea in self.trackingAreas) {
[self removeTrackingArea:trackingArea];
}
if (selectedColumns.count == 1) {
BOOL canFill = [[self tableGrid] _canFillCellAtColumn:[selectedColumns firstIndex] row:[selectedRows firstIndex]];
if (canFill) {
NSRect fillTrackingRect = [self rectOfColumn:[selectedColumns firstIndex]];
fillTrackingRect.size.height = self.frame.size.height;
NSRect topFillTrackingRect, bottomFillTrackingRect;
NSDivideRect(fillTrackingRect, &topFillTrackingRect, &bottomFillTrackingRect, selectionRect.origin.y + (selectionRect.size.height / 2.0), NSMinYEdge);
[self addTrackingArea:[[NSTrackingArea alloc] initWithRect:topFillTrackingRect options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow owner:self userInfo:@{MBTableGridTrackingPartKey : @(MBTableGridTrackingPartFillTop)}]];
[self addTrackingArea:[[NSTrackingArea alloc] initWithRect:bottomFillTrackingRect options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow owner:self userInfo:@{MBTableGridTrackingPartKey : @(MBTableGridTrackingPartFillBottom)}]];
}
}
}
#pragma mark -
#pragma mark Notifications
#pragma mark Field Editor
- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
if (self.autoCompleteWindow) {
if (commandSelector == @selector(moveDown:)) {
[self.autoCompleteWindow moveRowDown:textView];
} else if (commandSelector == @selector(moveUp:)) {
[self.autoCompleteWindow moveRowUp:textView];
} else if (commandSelector == @selector(insertTab:)) {
[self.window removeChildWindow:self.autoCompleteWindow];
[self.autoCompleteWindow close];
self.autoCompleteWindow = nil;
} else if (commandSelector == @selector(insertNewline:)) {
[self.window removeChildWindow:self.autoCompleteWindow];
[self.autoCompleteWindow close];
self.autoCompleteWindow = nil;
} else {
return NO;
}
} else {
return NO;
}
return YES;
}
- (void)textDidBeginEditingWithEditor:(NSText *)editor
{
isAutoEditing = YES;
self.fieldEditorLength = [[editor string] length];
[self showCompletionsForTextView:(NSTextView *)editor];
}
- (void)textDidBeginEditing:(NSNotification *)notification
{
if (!isAutoEditing) {
[self showCompletionsForTextView:notification.object];
}
self.fieldEditorLength = [[notification.object string] length];
isAutoEditing = NO;
}
- (void)textDidChange:(NSNotification *)notification
{
self.fieldEditorLength = [[notification.object string] length];
isAutoEditing = NO;
[self showCompletionsForTextView:notification.object];
}
- (void)textDidEndEditing:(NSNotification *)aNotification