forked from mikecsh/mbtablegrid
-
Notifications
You must be signed in to change notification settings - Fork 3
/
MBTableGridController.m
1055 lines (790 loc) · 35.7 KB
/
MBTableGridController.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 "MBTableGridController.h"
#import "MBTableGridCell.h"
#import "MBPopupButtonCell.h"
#import "MBButtonCell.h"
#import "MBImageCell.h"
#import "MBLevelIndicatorCell.h"
#import "MBGroupSummaryCell.h"
#import "MBFooterTextCell.h"
#import "MBFooterPopupButtonCell.h"
NSString* kAutosavedColumnWidthKey = @"AutosavedColumnWidth";
NSString* kAutosavedColumnIndexKey = @"AutosavedColumnIndex";
NSString* kAutosavedColumnHiddenKey = @"AutosavedColumnHidden";
NSString * const PasteboardTypeColumnClass = @"pasteboardTypeColumnClass";
NSString * const ColumnCurrency = @"currency";
NSString * const ColumnDate = @"date";
NSString * const ColumnPopup = @"popup";
NSString * const ColumnCheckbox = @"checkbox";
NSString * const ColumnText1 = @"text1";
NSString * const ColumnText2 = @"text2";
NSString * const ColumnImage = @"image";
NSString * const ColumnText3 = @"text3";
NSString * const ColumnRating = @"rating";
NSString * const ColumnText4 = @"text4";
@interface NSMutableArray (SwappingAdditions)
- (void)moveObjectsAtIndexes:(NSIndexSet *)indexes toIndex:(NSUInteger)index;
@end
@interface MBTableGridController()
@property (nonatomic, strong) MBPopupButtonCell *popupCell;
@property (nonatomic, strong) MBTableGridCell *textCell;
@property (nonatomic, strong) MBButtonCell *checkboxCell;
@property (nonatomic, strong) MBImageCell *imageCell;
@property (nonatomic, strong) MBLevelIndicatorCell *ratingCell;
@property (nonatomic, strong) MBGroupSummaryCell *groupSummaryCell;
@property (nonatomic, strong) MBFooterTextCell *footerTextCell;
@property (nonatomic, strong) MBFooterPopupButtonCell *footerPopupCell;
@property (nonatomic, strong) NSDictionary *columnWidths;
@property (nonatomic, strong) NSMutableArray *columnIdentifiers;
@end
@implementation MBTableGridController
- (void)awakeFromNib
{
columnSampleWidths = @[@40, @50, @60, @70, @80, @90, @100, @110, @120, @130];
columns = [[NSMutableArray alloc] initWithCapacity:10];
self.columnIdentifiers = [@[ColumnCurrency, ColumnDate, ColumnPopup, ColumnCheckbox, ColumnText1, ColumnText2, ColumnImage, ColumnText3, ColumnRating, ColumnText4] mutableCopy];
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
NSString *gridComponentID = [infoDict objectForKey:@"GridComponentID"];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"MBTableGrid Group Summary Rows" : @YES}];
tableGrid.autosaveName = [NSString stringWithFormat:@"MBTableGrid Columns records-table-%@", gridComponentID];
tableGrid.defaultCellFont = [NSFont userFontOfSize:12.0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.columnWidths = [defaults objectForKey:tableGrid.autosaveName];
NSNumberFormatter *decimalFormatter = [[NSNumberFormatter alloc] init];
decimalFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
decimalFormatter.lenient = YES;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterShortStyle;
dateFormatter.timeStyle = NSDateFormatterNoStyle;
formatters = @{ColumnCurrency : decimalFormatter, ColumnDate : dateFormatter};
// Add 10 columns & rows
[self tableGrid:tableGrid addColumns:10 shouldReload:NO];
[self tableGrid:tableGrid addRows:50 shouldReload:NO];
[self tableGrid:tableGrid changeFrozenColumns:[defaults integerForKey:@"MBTableGrid Frozen Columns"] shouldReload:NO];
[self tableGrid:tableGrid freezeColumns:[defaults boolForKey:@"MBTableGrid Freeze Columns"] shouldReload:NO];
[self tableGrid:tableGrid includeGroupSummaryRows:[defaults boolForKey:@"MBTableGrid Group Summary Rows"] shouldReload:NO];
[tableGrid setSortAscendingImage:[NSImage imageNamed:@"sort-asc"] sortDescendingImage:[NSImage imageNamed:@"sort-desc"] sortUndeterminedImage:nil];
[tableGrid reloadData];
// Register to receive text strings
[tableGrid registerForDraggedTypes:@[NSStringPboardType]];
self.popupCell = [[MBPopupButtonCell alloc] initTextCell:@""];
self.popupCell.bordered = NO;
self.popupCell.controlSize = NSSmallControlSize;
self.popupCell.font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
NSArray *availableObjectValues = @[ @"Action & Adventure", @"Comedy", @"Romance", @"Thriller" ];
NSMenu *menu = [[NSMenu alloc] init];
menu.font = self.popupCell.font;
for (NSString *objectValue in availableObjectValues) {
NSMenuItem *item = [menu addItemWithTitle:objectValue action:@selector(cellPopupMenuItemSelected:) keyEquivalent:@""];
[item setTarget:self];
}
self.popupCell.menu = menu;
self.textCell = [[MBTableGridCell alloc] initTextCell:@""];
self.checkboxCell = [[MBButtonCell alloc] init];
self.checkboxCell.state = NSOffState;
[self.checkboxCell setButtonType:NSSwitchButton];
self.imageCell = [[MBImageCell alloc] init];
self.ratingCell = [[MBLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSRatingLevelIndicatorStyle];
self.ratingCell.editable = YES;
self.groupSummaryCell = [[MBGroupSummaryCell alloc] initTextCell:@""];
self.footerTextCell = [[MBFooterTextCell alloc] initTextCell:@""];
self.footerPopupCell = [[MBFooterPopupButtonCell alloc] initTextCell:@""];
self.footerPopupCell.bordered = NO;
self.footerPopupCell.controlSize = NSSmallControlSize;
self.footerPopupCell.font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
menu = [NSMenu new];
menu.font = self.footerPopupCell.font;
[menu addItemWithTitle:@"No Options" action:nil keyEquivalent:@""];
self.footerPopupCell.menu = menu;
}
-(NSString *) genRandStringLength: (int) len
{
// Create alphanumeric table
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// Create mutable string
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
// Add random character to string
for (int i=0; i<len; i++) {
[randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
// return string
return randomString;
}
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
SEL action = menuItem.action;
BOOL enabled = YES;
if (action == @selector(changeFrozenColumns:)) {
menuItem.state = menuItem.tag == tableGrid.numberOfFrozenColumns;
} else if (action == @selector(freezeColumns:)) {
menuItem.state = tableGrid.freezeColumns;
} else if (action == @selector(includeGroupSummaryRows:)) {
menuItem.state = tableGrid.includeGroupSummaryRows;
}
return enabled;
}
#pragma mark -
#pragma mark Protocol Methods
#pragma mark MBTableGridDataSource
- (NSUInteger)numberOfRowsInTableGrid:(MBTableGrid *)aTableGrid
{
if ([columns count] > 0) {
return [columns[0] count];
}
return 0;
}
- (NSUInteger)numberOfColumnsInTableGrid:(MBTableGrid *)aTableGrid
{
return [columns count];
}
- (NSString *)tableGrid:(MBTableGrid *)aTableGrid headerStringForColumn:(NSUInteger)columnIndex {
return [NSString stringWithFormat:@"Column %lu", columnIndex];
}
- (id)tableGrid:(MBTableGrid *)aTableGrid objectValueForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex
{
if (columnIndex >= [columns count]) {
return nil;
}
NSMutableArray *column = columns[columnIndex];
if (rowIndex >= [column count]) {
return nil;
}
id value = nil;
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnImage) {
value = [NSImage imageNamed:@"rose.jpg"];
} else {
value = column[rowIndex];
}
return value;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid shouldEditColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex {
// can't edit the sample image column
// if (columnIndex == 6) {
// return NO;
// } else {
// return YES;
// }
return YES;
}
- (NSFormatter *)tableGrid:(MBTableGrid *)aTableGrid formatterForColumn:(NSUInteger)columnIndex
{
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
return formatters[columnIdentifier];
}
- (NSCell *)tableGrid:(MBTableGrid *)aTableGrid cellForColumn:(NSUInteger)columnIndex {
NSCell *cell = nil;
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnPopup) {
cell = self.popupCell;
} else if (columnIdentifier == ColumnCheckbox) {
cell = self.checkboxCell;
} else if (columnIdentifier == ColumnImage) {
cell = self.imageCell;
} else if (columnIdentifier == ColumnRating) {
cell = self.ratingCell;
} else {
cell = self.textCell;
}
return cell;
}
- (NSImage *)tableGrid:(MBTableGrid *)aTableGrid accessoryButtonImageForColumn:(NSUInteger)columnIndex row:(NSUInteger)row {
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier != ColumnImage) {
return nil;
}
if (tableGrid.selectedRowIndexes.count == 1 && [tableGrid.selectedRowIndexes containsIndex:row]) {
NSImage *buttonImage = [NSImage imageNamed:@"acc-quicklook"];
return buttonImage;
} else {
return nil;
}
}
- (NSArray *)tableGrid:(MBTableGrid *)aTableGrid availableObjectValuesForColumn:(NSUInteger)columnIndex {
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnPopup) {
return @[ @"Action & Adventure", @"Comedy", @"Romance", @"Thriller" ];
}
return nil;
}
- (NSArray *)tableGrid:(MBTableGrid *)aTableGrid autocompleteValuesForEditString:(NSString *)editString column:(NSUInteger)columnIndex row:(NSUInteger)rowIndex {
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnCurrency || columnIdentifier == ColumnDate || columnIdentifier == ColumnPopup || columnIdentifier == ColumnCheckbox || columnIdentifier == ColumnImage || columnIdentifier == ColumnRating || columnIndex >= [columns count]) {
return nil;
}
NSMutableArray *completions = [NSMutableArray array];
NSMutableArray *column = columns[columnIndex];
for (NSString *value in column) {
if ([[value lowercaseString] hasPrefix:[editString lowercaseString]]) {
[completions addObject:value];
}
}
return completions;
}
- (void)tableGrid:(MBTableGrid *)aTableGrid setObjectValue:(id)anObject forColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex {
if (columnIndex >= [columns count]) {
return;
}
NSMutableArray *column = columns[columnIndex];
if (rowIndex >= [column count]) {
return;
}
if (anObject == nil) {
anObject = @"";
}
column[rowIndex] = anObject;
// NSLog(@"col: %lu, row: %lu, obj: %@", columnIndex, rowIndex, anObject);
}
- (float)tableGrid:(MBTableGrid *)aTableGrid setWidthForColumn:(NSUInteger)columnIndex {
// return (columnIndex < columnSampleWidths.count) ? [columnSampleWidths[columnIndex] floatValue] : 60;
CGFloat width = 80;
NSString *columnName = [NSString stringWithFormat:@"C-%lu", (long)columnIndex];
NSDictionary *columnProperty = self.columnWidths[columnName];
if (columnProperty) {
width = [columnProperty[kAutosavedColumnWidthKey] floatValue];
}
return width;
}
-(NSColor *)tableGrid:(MBTableGrid *)aTableGrid backgroundColorForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex {
if (rowIndex % 2)
return [NSColor colorWithDeviceWhite:0.950 alpha:1.000];
else
return nil;
}
-(NSColor *)tableGrid:(MBTableGrid *)aTableGrid frozenBackgroundColorForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex {
if (rowIndex % 2)
return [NSColor colorWithDeviceWhite:0.9 alpha:1.000];
else
return [NSColor colorWithDeviceWhite:0.96 alpha:1.000];
}
- (MBSortDirection)tableGrid:(MBTableGrid *)aTableGrid sortDirectionForColumn:(NSUInteger)columnIndex {
if (columnIndex == 1) {
return MBSortAscending;
} else if (columnIndex == 3) {
return MBSortDescending;
} else {
return MBSortUndetermined;
}
}
#pragma mark Group
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid isGroupRow:(NSUInteger)rowIndex {
if (rowIndex == 0 || rowIndex == 5) {
return YES;
}
return NO;
}
- (id)valueForTableGrid:(MBTableGrid *)aTableGrid groupSummaryColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
{
NSUInteger footerItem = [[NSUserDefaults standardUserDefaults] integerForKey:[self footerDefaultsKeyForColumn:columnIndex]];
NSUInteger headingIndex = [aTableGrid groupHeadingRowForRow:rowIndex];
if (headingIndex == NSNotFound) {
return nil;
}
NSRange range = NSMakeRange(headingIndex + 1, rowIndex - headingIndex - 1);
NSArray *column = [columns[columnIndex] subarrayWithRange:range];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self != ''"];
NSArray *group = [column filteredArrayUsingPredicate:predicate];
switch (footerItem) {
case 0:
return [group valueForKeyPath:@"@sum.floatValue"];
break;
case 1:
return [group valueForKeyPath:@"@min.floatValue"];
break;
case 2:
return [group valueForKeyPath:@"@max.floatValue"];
break;
case 3:
return [group valueForKeyPath:@"@avg.floatValue"];
break;
default:
return [group valueForKeyPath:@"@count"];
break;
}
}
- (NSCell *)tableGrid:(MBTableGrid *)aTableGrid groupSummaryCellForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
{
return self.groupSummaryCell;
}
- (void)tableGrid:(MBTableGrid *)aTableGrid updateGroupSummaryCell:(MBGroupSummaryCell *)cell forColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
{
// Cell defaults have been set; this is an opportunity to update the cell to override the font, color, etc
cell.font = [NSFont boldSystemFontOfSize:12.0];
id value = [self valueForTableGrid:aTableGrid groupSummaryColumn:columnIndex row:rowIndex];
if ([value integerValue] < 0) {
cell.textColor = [NSColor redColor];
}
}
- (id)tableGrid:(MBTableGrid *)aTableGrid groupSummaryValueForColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex;
{
if (columnIndex >= [columns count]) {
return nil;
}
id value = nil;
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnDate || columnIdentifier == ColumnPopup || columnIdentifier == ColumnCheckbox || columnIdentifier == ColumnImage || columnIdentifier == ColumnRating) {
// Date, popup, checkbox, image, rating: nothing to show
value = nil;
} else {
// All others: the Total, Average, etc, as chosen in the footer popup
NSUInteger footerItem = [[NSUserDefaults standardUserDefaults] integerForKey:[self footerDefaultsKeyForColumn:columnIndex]];
value = [self valueForTableGrid:aTableGrid groupSummaryColumn:columnIndex row:rowIndex];
if (value == nil) {
return nil;
}
if (footerItem == 4) {
value = [NSString stringWithFormat:@"%li", [value integerValue]];
} else {
value = [self formattedPrefix:nil value:value forTableGrid:aTableGrid column:columnIndex];
}
}
return value;
}
#pragma mark Footer
- (void)addItemToMenu:(NSMenu *)menu withTitle:(NSString *)title;
{
[menu addItemWithTitle:title action:@selector(cellPopupMenuItemSelected:) keyEquivalent:@""];
}
- (NSString *)formattedPrefix:(NSString *)prefix value:(id)value forTableGrid:(MBTableGrid *)aTableGrid column:(NSUInteger)columnIndex;
{
NSFormatter *formatter = [self tableGrid:aTableGrid formatterForColumn:columnIndex];
if (formatter) {
value = [formatter stringForObjectValue:value];
} else {
value = [NSString stringWithFormat:@"%.0f", [value floatValue]];
}
if (prefix.length) {
return [NSString stringWithFormat:@"%@: %@", prefix, value];
} else {
return value;
}
}
- (NSString *)footerDefaultsKeyForColumn:(NSUInteger)columnIndex;
{
return [NSString stringWithFormat:@"TableGrid-Footer-%ld", columnIndex];
}
- (NSCell *)tableGrid:(MBTableGrid *)aTableGrid footerCellForColumn:(NSUInteger)columnIndex;
{
NSCell *cell = nil;
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnDate || columnIdentifier == ColumnPopup || columnIdentifier == ColumnCheckbox) {
// Date, popup & checkbox: just showing the count
cell = self.footerTextCell;
} else if (columnIdentifier == ColumnImage) {
// Image: nothing to show
cell = nil;
} else if (columnIdentifier == ColumnRating) {
// Rating: average as a rating
cell = self.ratingCell;
} else if (columnIndex >= [columns count]) {
// Invalid column
return nil;
} else {
// All others: a popup of Total, Average, etc
cell = self.footerPopupCell;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self != ''"];
NSArray *column = [columns[columnIndex] filteredArrayUsingPredicate:predicate];
// Rebuild the menu with dynamic values
[cell.menu removeAllItems];
[self addItemToMenu:cell.menu withTitle:[self formattedPrefix:@"Total" value:[column valueForKeyPath:@"@sum.floatValue"] forTableGrid:aTableGrid column:columnIndex]];
[self addItemToMenu:cell.menu withTitle:[self formattedPrefix:@"Minimum" value:[column valueForKeyPath:@"@min.floatValue"] forTableGrid:aTableGrid column:columnIndex]];
[self addItemToMenu:cell.menu withTitle:[self formattedPrefix:@"Maximum" value:[column valueForKeyPath:@"@max.floatValue"] forTableGrid:aTableGrid column:columnIndex]];
[self addItemToMenu:cell.menu withTitle:[self formattedPrefix:@"Average" value:[column valueForKeyPath:@"@avg.floatValue"] forTableGrid:aTableGrid column:columnIndex]];
[self addItemToMenu:cell.menu withTitle:[NSString stringWithFormat:@"Count: %li", [[column valueForKeyPath:@"@count"] integerValue]]];
}
return cell;
}
- (id)tableGrid:(MBTableGrid *)aTableGrid footerValueForColumn:(NSUInteger)columnIndex;
{
if (columnIndex >= [columns count]) {
return nil;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self != ''"];
NSArray *column = [columns[columnIndex] filteredArrayUsingPredicate:predicate];
id value = nil;
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnDate || columnIdentifier == ColumnPopup || columnIdentifier == ColumnCheckbox) {
// Date, popup & checkbox: just showing the count
value = [NSString stringWithFormat:@"Count: %li", [[column valueForKeyPath:@"@count"] integerValue]];
} else if (columnIdentifier == ColumnImage) {
// Image: nothing to show
value = nil;
} else if (columnIdentifier == ColumnRating) {
// Rating: average as a rating
value = [column valueForKeyPath:@"@avg.floatValue"];
} else {
// All others: a popup of Total, Average, etc
NSCell *cell = [self tableGrid:aTableGrid footerCellForColumn:columnIndex];
NSUInteger itemIndex = [[NSUserDefaults standardUserDefaults] integerForKey:[self footerDefaultsKeyForColumn:columnIndex]];
value = [cell.menu itemAtIndex:itemIndex].title;
if (!value) {
value = [cell.menu itemAtIndex:0].title;
}
}
return value;
}
- (void)tableGrid:(MBTableGrid *)aTableGrid setFooterValue:(id)anObject forColumn:(NSUInteger)columnIndex;
{
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnDate || columnIdentifier == ColumnPopup || columnIdentifier == ColumnCheckbox || columnIdentifier == ColumnImage || columnIdentifier == ColumnRating || columnIndex >= [columns count]) {
return;
}
NSCell *cell = [self tableGrid:aTableGrid footerCellForColumn:columnIndex];
NSInteger itemIndex = [cell.menu indexOfItemWithTitle:anObject];
// NSLog(@"set footer value: %@ (%@); for column: %@", anObject, @(itemIndex), @(columnIndex)); // log
if (itemIndex >= 0) {
[[NSUserDefaults standardUserDefaults] setInteger:itemIndex forKey:[self footerDefaultsKeyForColumn:columnIndex]];
}
}
#pragma mark Dragging
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid writeColumnsWithIndexes:(NSIndexSet *)columnIndexes toPasteboard:(NSPasteboard *)pboard
{
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid canMoveColumns:(NSIndexSet *)columnIndexes toIndex:(NSUInteger)index
{
// Allow any column movement
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid moveColumns:(NSIndexSet *)columnIndexes toIndex:(NSUInteger)index
{
[columns moveObjectsAtIndexes:columnIndexes toIndex:index];
[self.columnIdentifiers moveObjectsAtIndexes:columnIndexes toIndex:index];
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard
{
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid canMoveRows:(NSIndexSet *)rowIndexes toIndex:(NSUInteger)index
{
// Allow any row movement
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid moveRows:(NSIndexSet *)rowIndexes toIndex:(NSUInteger)index
{
for (NSMutableArray *column in columns) {
[column moveObjectsAtIndexes:rowIndexes toIndex:index];
}
return YES;
}
- (NSDragOperation)tableGrid:(MBTableGrid *)aTableGrid validateDrop:(id <NSDraggingInfo>)info proposedColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex
{
return NSDragOperationCopy;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid acceptDrop:(id <NSDraggingInfo>)info column:(NSUInteger)columnIndex row:(NSUInteger)rowIndex
{
NSPasteboard *pboard = [info draggingPasteboard];
NSString *value = [pboard stringForType:NSStringPboardType];
[self tableGrid:aTableGrid setObjectValue:value forColumn:columnIndex row:rowIndex];
return YES;
}
#pragma mark Copy & Paste
- (void)tableGrid:(MBTableGrid *)aTableGrid copyCellsAtColumns:(NSIndexSet *)columnIndexes rows:(NSIndexSet *)rowIndexes
{
NSMutableArray *colClasses = [NSMutableArray arrayWithCapacity:columnIndexes.count];
[columnIndexes enumerateIndexesUsingBlock:^(NSUInteger columnIndex, BOOL *stop) {
[colClasses addObject:[[self tableGrid:aTableGrid cellForColumn:columnIndex] className]];
}];
NSMutableArray *rowData = [NSMutableArray arrayWithCapacity:rowIndexes.count];
[rowIndexes enumerateIndexesUsingBlock:^(NSUInteger rowIndex, BOOL *stop) {
NSMutableArray *colData = [NSMutableArray arrayWithCapacity:columnIndexes.count];
[columnIndexes enumerateIndexesUsingBlock:^(NSUInteger columnIndex, BOOL *stop) {
NSArray *row = columns[columnIndex];
id cellData = row[rowIndex];
NSFormatter *formatter = [self tableGrid:aTableGrid formatterForColumn:columnIndex];
if (formatter) {
cellData = [formatter stringForObjectValue:cellData];
}
[colData addObject:cellData];
}];
NSString *rowString = [colData componentsJoinedByString:@"\t"];
[rowData addObject:rowString];
}];
NSString *tsvString = [rowData componentsJoinedByString:@"\n"];
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
[pasteboard declareTypes:@[NSPasteboardTypeTabularText, NSPasteboardTypeString, PasteboardTypeColumnClass] owner:nil];
[pasteboard setString:tsvString forType:NSPasteboardTypeTabularText];
[pasteboard setString:tsvString forType:NSPasteboardTypeString];
[pasteboard setPropertyList:colClasses forType:PasteboardTypeColumnClass];
}
- (void)tableGrid:(MBTableGrid *)aTableGrid pasteCellsAtColumns:(NSIndexSet *)columnIndexes rows:(NSIndexSet *)rowIndexes
{
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
BOOL isSingleSelection = columnIndexes.count == 1 && rowIndexes.count == 1;
NSString *tavString = [pasteboard stringForType:NSPasteboardTypeTabularText];
if (!tavString.length) {
tavString = [pasteboard stringForType:NSPasteboardTypeString];
}
if (!tavString.length) {
return;
}
// Extract the rows and columns to a more convenient form
NSMutableArray *rowArray = [NSMutableArray array];
for (NSString *rowString in [tavString componentsSeparatedByString:@"\n"]) {
NSMutableArray *columnArray = [NSMutableArray array];
for (NSString *columnString in [rowString componentsSeparatedByString:@"\t"]) {
[columnArray addObject:columnString];
}
[rowArray addObject:columnArray];
}
NSUInteger firstSelectedColumn = [columnIndexes firstIndex];
NSUInteger firstSelectedRow = [rowIndexes firstIndex];
NSUInteger numberOfExistingColumns = [columns count];
NSUInteger numberOfExistingRows = [[columns firstObject] count];
NSUInteger numberOfPastingColumns = [[rowArray firstObject] count];
NSUInteger numberOfPastingRows = [rowArray count];
// If pasting to a single cell, we want to paste all of the values, so add rows and columns if needed
if (isSingleSelection) {
NSInteger extraColumns = firstSelectedColumn + numberOfPastingColumns - numberOfExistingColumns;
NSInteger extraRows = firstSelectedRow + numberOfPastingRows - numberOfExistingRows;
if (extraColumns > 0) {
// Add extra columns; a real controller could use the PasteboardTypeColumnClass values to add appropriate column types to the database
[self tableGrid:aTableGrid addColumns:extraColumns shouldReload:NO];
}
if (extraRows > 0) {
[self tableGrid:aTableGrid addRows:extraRows shouldReload:NO];
}
} else {
numberOfPastingColumns = columnIndexes.count;
numberOfPastingRows = rowIndexes.count;
}
// Insert the values
[rowArray enumerateObjectsUsingBlock:^(NSArray *columnArray, NSUInteger rowOffset, BOOL *stopRows) {
[columnArray enumerateObjectsUsingBlock:^(NSString *value, NSUInteger columnOffset, BOOL *stopColumns) {
NSUInteger column = firstSelectedColumn + columnOffset;
NSUInteger row = firstSelectedRow + rowOffset;
NSFormatter *formatter = [self tableGrid:aTableGrid formatterForColumn:column];
id obj = value;
if (!formatter || [formatter getObjectValue:&obj forString:value errorDescription:nil]) {
[self tableGrid:aTableGrid setObjectValue:obj forColumn:column row:row];
}
if (columnOffset == numberOfPastingColumns - 1) {
*stopColumns = YES;
}
}];
if (rowOffset == numberOfPastingRows - 1) {
*stopRows = YES;
}
}];
}
#pragma mark Adding and Removing Columns & Rows
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid addColumns:(NSUInteger)numberOfColumns shouldReload:(BOOL)shouldReload;
{
// Default number of rows
NSUInteger numberOfRows = 0;
// If there are already other columns, get the number of rows from one of them
if ([columns count] > 0) {
numberOfRows = [columns[0] count];
}
for (NSUInteger column = 0; column < numberOfColumns; column++) {
NSMutableArray *newColumn = [NSMutableArray array];
for (NSUInteger row = 0; row < numberOfRows; row++) {
// Insert blank items for each row
[newColumn addObject:@""];
}
[columns addObject:newColumn];
if (columns.count > self.columnIdentifiers.count) {
[self.columnIdentifiers addObject:[NSString stringWithFormat:@"extra%@", @(columns.count)]];
}
}
if (shouldReload) {
[tableGrid reloadData];
}
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid addRows:(NSUInteger)numberOfRows;
{
return [self tableGrid:aTableGrid addRows:numberOfRows shouldReload:YES];
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid addRows:(NSUInteger)numberOfRows shouldReload:(BOOL)shouldReload;
{
for (NSUInteger row = 0; row < numberOfRows; row++) {
for (NSMutableArray *column in columns) {
// Add a blank item to each row
[column addObject:@""];
}
}
[aTableGrid.columnRects removeAllObjects];
if (shouldReload) {
[aTableGrid reloadData];
}
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid removeRows:(NSIndexSet *)rowIndexes;
{
for (NSMutableArray *column in columns) {
[column removeObjectsAtIndexes:rowIndexes];
}
[aTableGrid reloadData];
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid changeFrozenColumns:(NSUInteger)numberOfColumns shouldReload:(BOOL)shouldReload;
{
aTableGrid.numberOfFrozenColumns = numberOfColumns;
if (shouldReload) {
[aTableGrid reloadData];
}
return YES;
}
- (BOOL)tableGrid:(MBTableGrid *)aTableGrid freezeColumns:(BOOL)freezeColumns shouldReload:(BOOL)shouldReload;
{
aTableGrid.freezeColumns = freezeColumns;
if (shouldReload) {
[aTableGrid reloadData];
}
return YES;
}
- (void)tableGrid:(MBTableGrid *)aTableGrid includeGroupSummaryRows:(BOOL)includeGroupSummaryRows shouldReload:(BOOL)shouldReload;
{
aTableGrid.includeGroupSummaryRows = includeGroupSummaryRows;
if (shouldReload) {
[aTableGrid reloadData];
}
}
#pragma mark MBTableGridDelegate
- (void)tableGridDidMoveRows:(NSNotification *)aNotification
{
NSLog(@"moved");
}
- (void)tableGrid:(MBTableGrid *)aTableGrid userDidEnterInvalidStringInColumn:(NSUInteger)columnIndex row:(NSUInteger)rowIndex errorDescription:(NSString *)errorDescription {
NSLog(@"Invalid input at %lu,%lu: %@", (unsigned long)columnIndex, (unsigned long)rowIndex, errorDescription);
}
- (void)tableGrid:(MBTableGrid *)aTableGrid accessoryButtonClicked:(NSUInteger)columnIndex row:(NSUInteger)rowIndex {
NSString *columnIdentifier = self.columnIdentifiers[columnIndex];
if (columnIdentifier == ColumnImage) {
[self quickLookAction:nil];
}
}
- (void)tableGrid:(MBTableGrid *)aTableGrid didAddRows:(NSIndexSet *)rowIndexes;
{
// Add the rows to the database, or whatever is needed
}
- (NSDictionary *)tableGridAutosavedColumnProperties:(MBTableGrid *)aTableGrid;
{
return [[NSUserDefaults standardUserDefaults] objectForKey:aTableGrid.autosaveName];
}
- (void)tableGrid:(MBTableGrid *)aTableGrid didAutosaveColumnProperties:(NSDictionary *)columnProperties;
{
[[NSUserDefaults standardUserDefaults] setObject:columnProperties forKey:aTableGrid.autosaveName];
}
#pragma mark - QuickLook
-(void)quickLookAction:(id)sender {
// [[NSApp mainWindow] makeFirstResponder:self];
if ([QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]) {
[[QLPreviewPanel sharedPreviewPanel] orderOut:nil];
} else {
QLPreviewPanel *previewPanel = [QLPreviewPanel sharedPreviewPanel];
previewPanel.dataSource = self;
previewPanel.delegate = self;
[previewPanel makeKeyAndOrderFront:sender];
}
}
// Quick Look panel support
- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel; {
return YES;
}
- (void)beginPreviewPanelControl:(QLPreviewPanel *)panel {
// This document is now responsible of the preview panel
// It is allowed to set the delegate, data source and refresh panel.
panel.delegate = self;
panel.dataSource = self;
}
- (void)endPreviewPanelControl:(QLPreviewPanel *)panel {
panel.delegate = nil;
panel.dataSource = nil;
}
// Quick Look panel data source
- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel {
return 1;
}
- (id <QLPreviewItem>)previewPanel:(QLPreviewPanel *)panel previewItemAtIndex:(NSInteger)index {
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
NSURL *fileURL = nil;
__block NSURL *returnURL = nil;
NSError *error = nil;
fileURL = [[NSBundle mainBundle] URLForImageResource:@"rose"];
[coordinator coordinateReadingItemAtURL:fileURL
options:NSFileCoordinatorReadingWithoutChanges
error:&error
byAccessor:^(NSURL *newURL) {
returnURL = newURL;
}];
return returnURL;
}
// This delegate method provides the rect on screen from which the panel will zoom.
- (NSRect)previewPanel:(QLPreviewPanel *)panel sourceFrameOnScreenForPreviewItem:(id <QLPreviewItem>)item {
// convert selected cell rect to screen coordinates
NSInteger selectedColumn = [tableGrid.selectedColumnIndexes firstIndex];
NSInteger selectedRow = [tableGrid.selectedRowIndexes firstIndex];
NSCell *selectedCell = [tableGrid selectedCell];
NSRect photoPreviewFrame = [tableGrid frameOfCellAtColumn:selectedColumn row:selectedRow];
NSRect rectInWinCoords = [selectedCell.controlView convertRect:photoPreviewFrame toView:nil];
NSRect rectInScreenCoords = [[NSApp mainWindow] convertRectToScreen:rectInWinCoords];
return rectInScreenCoords;
}
#pragma mark -
#pragma mark Subclass Methods
- (IBAction)addColumn:(id)sender {
[self tableGrid:tableGrid addColumns:1 shouldReload:YES];
}
- (IBAction)addRow:(id)sender {
[self tableGrid:tableGrid addRows:1 shouldReload:YES];
}