forked from indragiek/OEGridView
-
Notifications
You must be signed in to change notification settings - Fork 4
/
OEGridView.m
1640 lines (1352 loc) · 63.4 KB
/
OEGridView.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) 2012, OpenEmu Team
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the OpenEmu Team nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "OEGridView.h"
#import "OEGridViewCell+OEGridView.h"
#import "NSColor+OEAdditions.h"
#import <Carbon/Carbon.h>
#define OERunningMountainLion (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7)
const NSTimeInterval OEInitialPeriodicDelay = 0.4; // Initial delay of a periodic events
const NSTimeInterval OEPeriodicInterval = 0.075; // Subsequent interval of periodic events
@interface OEGridView ()
- (void)OE_commonGridViewInit;
- (void)OE_updateSelectedCellsActiveSelectorWithFocus:(BOOL)focus;
- (void)OE_windowChangedKey:(NSNotification *)notification;
- (void)OE_clipViewFrameChanged:(NSNotification *)notification;
- (void)OE_clipViewBoundsChanged:(NSNotification *)notification;
- (void)OE_moveKeyboardSelectionToIndex:(NSUInteger)index;
- (void)OE_setNeedsLayoutGridView;
- (void)OE_layoutGridViewIfNeeded;
- (void)OE_layoutGridView;
- (void)OE_enqueueCellsAtIndexes:(NSIndexSet *)indexes;
- (void)OE_calculateCachedValuesAndQueryForDataChanges:(BOOL)queryForDataChanges;
- (void)OE_checkForDataReload;
- (void)OE_setNeedsReloadData;
- (void)OE_reloadDataIfNeeded;
- (void)OE_centerNoItemsView;
- (void)OE_reorderSublayers;
- (void)OE_updateDecorativeLayers;
- (NSPoint)OE_pointInViewFromEvent:(NSEvent *)theEvent;
- (OEGridLayer *)OE_gridLayerForPoint:(const NSPoint)point;
- (NSDragOperation)OE_dragOperationForDestinationLayer:(id<NSDraggingInfo>)sender;
- (void)OE_setupFieldEditorForCell:(OEGridViewCell *)cell titleLayer:(CATextLayer *)textLayer;
- (void)OE_cancelFieldEditor;
@end
@implementation OEGridView {
NSTrackingArea *_trackingArea;
OEGridLayer *_rootLayer; // Root layer, where all other layers are inserted into
CALayer *_selectionLayer; // Selection box that appears when selecting multiple cells
OEGridLayer *_dragIndicationLayer; // A visual indication that a file is being dragged onto the grid view
NSView *_noItemsView; // A decorative view when there are no items to show, e.g. blank slate
NSScrollElasticity _previousElasticity; // Caches the original elasticity of the scroller eview before the blank slate is added
NSMutableIndexSet *_originalSelectionIndexes; // Original set of indexes selected before an inverted (cmd key) selection operation
NSMutableIndexSet *_selectionIndexes; // Index or indexes that are currently selected
NSUInteger _indexOfKeyboardSelection; // Last index of the selected cell using the keyboard
NSMutableDictionary *_visibleCellByIndex; // Cached visible cells
NSMutableIndexSet *_visibleCellsIndexes; // Cached indexes of the visible cells
NSMutableSet *_reuseableCells; // Cached cells that are no longer in view
NSDraggingSession *_draggingSession; // Drag session used during a drag operation
OEGridLayer *_prevDragDestinationLayer; // Previous destination cell of a drag operation, used to prevent multiple messages to same cell
OEGridLayer *_dragDestinationLayer; // Destination cell of a drag operation
NSDragOperation _lastDragOperation; // Last drag operation generated by -draggingEntered:
OEGridLayer *_trackingLayer; // The layer receiving all the drag operations (can be root layer)
NSPoint _initialPoint; // Initial position of the mouse of a drag operation
OEGridLayer *_hoveringLayer;
BOOL _needsReloadData; // Determines if the data should be reloaded
BOOL _abortReloadCells;
BOOL _needsLayoutGridView; // Determines if the cells should really be laid out
NSUInteger _cachedNumberOfVisibleColumns; // Cached number of visible columns
NSUInteger _cachedNumberOfVisibleRows; // Cached number of visiabl rows (include partially visible rows)
NSUInteger _cachedNumberOfItems; // Cached number of items in the data source
NSUInteger _cachedNumberOfRows; // Cached number of rows (including hidden ones)
NSPoint _cachedContentOffset; // Last known content offset
NSSize _cachedViewSize; // Last known view size
NSSize _cachedItemSize; // Cached cell size that includes row spacing and cached column spacing
CGFloat _cachedColumnSpacing; // Cached column spacing is the dynamic spacing between columns, no less than minimumColumnSpacing
NSUInteger _supressFrameResize;
OEGridViewFieldEditor *_fieldEditor; // Text field editor of a CATextLayer
struct
{
unsigned int selectionChanged : 1;
unsigned int doubleClickedCellForItemAtIndex : 1;
unsigned int validateDrop : 1;
unsigned int draggingUpdated : 1;
unsigned int acceptDrop : 1;
unsigned int magnifiedWithEvent : 1;
unsigned int magnifyEndedWithEvent : 1;
} _delegateHas; // Cached methods that the delegate implements
struct
{
unsigned int viewForNoItemsInGridView : 1;
unsigned int willBeginEditingCellForItemAtIndex : 1;
unsigned int didEndEditingCellForItemAtIndex : 1;
unsigned int pasteboardWriterForIndex : 1;
unsigned int menuForItemsAtIndexes : 1;
} _dataSourceHas; // Cached methods that the dataSource implements
}
@synthesize foregroundLayer=_foregroundLayer;
@synthesize backgroundLayer=_backgroundLayer;
@synthesize minimumColumnSpacing=_minimumColumnSpacing;
@synthesize rowSpacing=_rowSpacing;
@synthesize itemSize=_itemSize;
@synthesize delegate = _delegate, dataSource = _dataSource;
- (id)initWithFrame:(NSRect)frame
{
if((self = [super initWithFrame:frame]))
{
[self OE_commonGridViewInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if((self = [super initWithCoder:aDecoder]))
{
[self OE_commonGridViewInit];
}
return self;
}
- (void)OE_commonGridViewInit
{
// Set default values
_minimumColumnSpacing = 24.0;
_rowSpacing = 20.0;
_itemSize = CGSizeMake(250.0, 250.0);
// Allocate memory for objects
_selectionIndexes = [[NSMutableIndexSet alloc] init];
_visibleCellByIndex = [[NSMutableDictionary alloc] init];
_visibleCellsIndexes = [[NSMutableIndexSet alloc] init];
_reuseableCells = [[NSMutableSet alloc] init];
[self setWantsLayer:YES];
}
- (CALayer *)makeBackingLayer
{
CALayer *layer = [[CALayer alloc] init];
[layer setFrame:[self bounds]];
if (!_rootLayer)
{
_rootLayer = [[OEGridLayer alloc] init];
[_rootLayer setInteractive:YES];
[_rootLayer setLayoutManager:[OEGridViewLayoutManager layoutManager]];
[_rootLayer setDelegate:self];
[_rootLayer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[_rootLayer setFrame:[self bounds]];
CGFloat scaleFactor = [[self window] backingScaleFactor];
if (!OERunningMountainLion) {
[_rootLayer setGeometryFlipped:YES];
}
[_rootLayer setContentsScale:scaleFactor];
_dragIndicationLayer = [[OEGridLayer alloc] init];
[_dragIndicationLayer setInteractive:NO];
[_dragIndicationLayer setBorderColor:[[NSColor colorWithDeviceRed:0.03 green:0.41 blue:0.85 alpha:1.0] CGColor]];
[_dragIndicationLayer setBorderWidth:2.0];
[_dragIndicationLayer setCornerRadius:8.0];
[_dragIndicationLayer setHidden:YES];
[_dragIndicationLayer setContentsScale:scaleFactor];
[_rootLayer addSublayer:_dragIndicationLayer];
_fieldEditor = [[OEGridViewFieldEditor alloc] initWithFrame:NSMakeRect(50, 50, 50, 50)];
[self addSubview:_fieldEditor];
[self OE_reorderSublayers];
[self OE_setNeedsReloadData];
}
[layer addSublayer:_rootLayer];
return layer;
}
#pragma mark - CALayer delegate
- (BOOL)layer:(CALayer *)layer shouldInheritContentsScale:(CGFloat)newScale
fromWindow:(NSWindow *)window
{
return YES;
}
#pragma mark -
#pragma mark Query Data Sources
- (id)dequeueReusableCell
{
if([_reuseableCells count] == 0) return nil;
OEGridViewCell *cell = [_reuseableCells anyObject];
[_reuseableCells removeObject:cell];
[cell prepareForReuse];
return cell;
}
- (NSUInteger)numberOfItems
{
return _cachedNumberOfItems;
}
- (OEGridViewCell *)cellForItemAtIndex:(NSUInteger)index makeIfNecessary:(BOOL)necessary
{
OEGridViewCell *result = [_visibleCellByIndex objectForKey:[NSNumber numberWithUnsignedInt:index]];
if(result == nil && necessary)
{
result = [_dataSource gridView:self cellForItemAtIndex:index];
[result OE_setIndex:index];
[result setSelected:[_selectionIndexes containsIndex:index] animated:NO];
[result setFrame:[self rectForCellAtIndex:index]];
}
return result;
}
#pragma mark -
#pragma mark Query Cells
- (NSUInteger)indexForCell:(OEGridViewCell *)cell
{
return [cell OE_index];
}
- (NSUInteger)indexForCellAtPoint:(NSPoint)point
{
return [[self indexesForCellsInRect:NSMakeRect(point.x, point.y, 1.0, 1.0)] firstIndex];
}
- (NSIndexSet *)indexesForCellsInRect:(NSRect)rect
{
// This needs to return both on and off screen cells, make sure that the rect requested is even within the bounds
if(NSIsEmptyRect(rect) || _cachedNumberOfItems == 0) return [NSIndexSet indexSet];
// Figure out the first row and column, and the number of cells and rows within the rect.
NSMutableIndexSet *result = [NSMutableIndexSet indexSet];
const NSUInteger firstCol = (NSUInteger)floor(NSMinX(rect) / _cachedItemSize.width);
const NSUInteger firstRow = (NSUInteger)floor(NSMinY(rect) / _cachedItemSize.height);
const NSUInteger numCols = (NSUInteger)ceil(NSMaxX(rect) / _cachedItemSize.width) - firstCol;
const NSUInteger numRows = (NSUInteger)ceil(NSMaxY(rect) / _cachedItemSize.height) - firstRow;
// Calculate the starting index
NSUInteger startIndex = firstCol + (firstRow * _cachedNumberOfVisibleColumns);
NSUInteger index;
// As long as the start index is within the number of known items, then we can return some cells
if(startIndex < _cachedNumberOfItems)
{
// Iterate through each row and column, as a row is iterated move the start index by the number of visible columns.
OEGridViewCell *cell;
NSRect hitRect, frame;
for(NSUInteger row = 0; row < numRows; row++)
{
index = startIndex;
for(NSUInteger col = 0; col < numCols; col++, index++)
{
if(index >= _cachedNumberOfItems) break;
cell = [self cellForItemAtIndex:index makeIfNecessary:YES];
frame = [cell frame];
hitRect = NSOffsetRect([cell hitRect], NSMinX(frame), NSMinY(frame));
if(NSIntersectsRect(rect, hitRect)) [result addIndex:index];
}
if(index >= _cachedNumberOfItems) break;
startIndex += _cachedNumberOfVisibleColumns;
}
}
else
{
result = [NSIndexSet indexSet];
}
// Return an immutable copy
return [result copy];
}
- (NSArray *)visibleCells
{
return [_visibleCellByIndex allValues];
}
- (NSIndexSet *)indexesForVisibleCells
{
// Return an immutable copy
return [_visibleCellsIndexes copy];
}
- (NSRect)rectForCellAtIndex:(NSUInteger)index
{
if(index >= _cachedNumberOfItems) return NSZeroRect;
const NSUInteger col = index % _cachedNumberOfVisibleColumns;
const NSUInteger row = index / _cachedNumberOfVisibleColumns;
return NSMakeRect(floor(col * _cachedItemSize.width + _cachedColumnSpacing), floor(row * _cachedItemSize.height + (_rowSpacing / 2.f)), _itemSize.width, _itemSize.height);
}
#pragma mark -
#pragma mark Selection
- (NSUInteger)indexForSelectedCell
{
return [_selectionIndexes firstIndex];
}
- (NSIndexSet *)indexesForSelectedCells
{
// Return an immutable copy
return [_selectionIndexes copy];
}
- (void)selectCellAtIndex:(NSUInteger)index
{
if(index == NSNotFound) return;
OEGridViewCell *item = [self cellForItemAtIndex:index makeIfNecessary:NO];
[item setSelected:YES animated:![CATransaction disableActions]];
[_selectionIndexes addIndex:index];
if(_delegateHas.selectionChanged) [_delegate selectionChangedInGridView:self];
}
- (void)deselectCellAtIndex:(NSUInteger)index
{
if(index == NSNotFound) return;
OEGridViewCell *item = [self cellForItemAtIndex:index makeIfNecessary:NO];
[item setSelected:NO animated:![CATransaction disableActions]];
[_selectionIndexes removeIndex:index];
if(_delegateHas.selectionChanged) [_delegate selectionChangedInGridView:self];
}
- (void)selectAll:(id)sender
{
// We add all the indexes immediately in case the visible cells shift while we are performing this operaiton
[_selectionIndexes addIndexesInRange:NSMakeRange(0, _cachedNumberOfItems)];
[_visibleCellByIndex enumerateKeysAndObjectsUsingBlock:
^ (NSNumber *key, OEGridViewCell *obj, BOOL *stop)
{
[obj setSelected:YES animated:YES];
}];
if(_delegateHas.selectionChanged) [_delegate selectionChangedInGridView:self];
}
- (void)deselectAll:(id)sender
{
_indexOfKeyboardSelection = NSNotFound;
if([_selectionIndexes count] == 0) return;
// We remove all the indexes immediately in case the visible cells shift while we are performing this operaiton
[_selectionIndexes removeAllIndexes];
[_visibleCellByIndex enumerateKeysAndObjectsUsingBlock:
^ (NSNumber *key, OEGridViewCell *obj, BOOL *stop)
{
[obj setSelected:NO animated:YES];
}];
if(_delegateHas.selectionChanged) [_delegate selectionChangedInGridView:self];
}
#pragma mark -
#pragma mark Data Reload
- (void)OE_enqueueCellsAtIndexes:(NSIndexSet *)indexes
{
if(!indexes || [indexes count] == 0) return;
[indexes enumerateIndexesUsingBlock:
^ (NSUInteger idx, BOOL *stop)
{
NSNumber *key = [NSNumber numberWithUnsignedInteger:idx];
OEGridViewCell *cell = [_visibleCellByIndex objectForKey:key];
if(cell)
{
if([_fieldEditor delegate] == cell) [self OE_cancelFieldEditor];
[_visibleCellByIndex removeObjectForKey:key];
[_reuseableCells addObject:cell];
[cell removeFromSuperlayer];
}
}];
}
- (void)OE_calculateCachedValuesAndQueryForDataChanges:(BOOL)shouldQueryForDataChanges
{
// Collect some basic information of the current environment
NSScrollView *enclosingScrollView = [self enclosingScrollView];
NSRect visibleRect = [enclosingScrollView documentVisibleRect];
NSPoint contentOffset = visibleRect.origin;
const NSSize cachedContentSize = [self bounds].size;
const NSSize viewSize = visibleRect.size;
// These variables help determine if the calculated values are different than their cached counter parts. These values
// are recalculated only if needed, so they are all initialized with their cached counter parts. If the recalculated
// values do not change from their cached counter parts, then there is nothing that we need to do.
NSUInteger numberOfVisibleColumns = _cachedNumberOfVisibleColumns; // Number of visible columns
NSUInteger numberOfVisibleRows = _cachedNumberOfVisibleRows; // Number of visible rows
NSUInteger numberOfItems = _cachedNumberOfItems; // Number of items in the data source
NSUInteger numberOfRows = _cachedNumberOfRows;
NSSize itemSize = NSMakeSize(_itemSize.width + _minimumColumnSpacing, _itemSize.height + _rowSpacing);
// Item Size (within minimumColumnSpacing and rowSpacing)
NSSize contentSize = cachedContentSize; // The scroll view's content size
BOOL checkForDataReload = FALSE; // Used to determine if we should consider reloading the data
// Query the data source for the number of items it has, this is only done if the caller explicitly sets shouldQueryForDataChanges.
if(shouldQueryForDataChanges && _dataSource) numberOfItems = [_dataSource numberOfItemsInGridView:self];
numberOfRows = ceil((CGFloat)numberOfItems / MAX((CGFloat)numberOfVisibleColumns, 1));
// Check to see if the frame's width has changed to update the number of visible columns and the cached cell size
if(itemSize.width == 0)
{
numberOfVisibleColumns = 1;
numberOfRows = ceil((CGFloat)numberOfItems / MAX((CGFloat)numberOfVisibleColumns, 1));
}
else if(_cachedViewSize.width != viewSize.width || !NSEqualSizes(_cachedItemSize, itemSize))
{
// Set the number of visible columns based on the view's width, there must be at least 1 visible column and no more than the total number
// of items within the data source. Just because a column is potentially visible doesn't mean that there is enough data to populate it.
numberOfVisibleColumns = MAX((NSUInteger)(floor(viewSize.width / itemSize.width)), 1);
numberOfRows = ceil((CGFloat)numberOfItems / MAX((CGFloat)numberOfVisibleColumns, 1));
// The cell's height include the original itemSize.height + rowSpacing. The cell's column spacing is based on the number of visible columns.
// The cell will be at least itemSize.width + minimumColumnSpacing, it could grow as larg as the width of the view
itemSize = NSMakeSize(MAX(itemSize.width, round(viewSize.width / numberOfVisibleColumns)), itemSize.height);
// Make sure that the scroll view's content width reflects the view's width. The scroll view's content height is be calculated later (if
// needed).
contentSize.width = viewSize.width;
}
// Check to see if the frame's height has changed to update the number of visible rows
if(itemSize.height == 0)
{
numberOfVisibleRows = 1;
}
else if(_cachedViewSize.height != viewSize.height || itemSize.height != _cachedItemSize.height)
{
numberOfVisibleRows = (NSUInteger)ceil(viewSize.height / itemSize.height);
}
// Check to see if the number of items, number of visible columns, or cached cell size has changed
if((_cachedNumberOfRows != numberOfRows) || (_cachedNumberOfItems != numberOfItems) || (_cachedNumberOfVisibleColumns != numberOfVisibleColumns) || !NSEqualSizes(_cachedItemSize, itemSize) || !NSEqualSizes(_cachedViewSize, viewSize))
{
// These three events may require a data reload but will most definitely cause the scroll view's content size to change
checkForDataReload = YES;
if(numberOfItems == 0)
{
contentSize.height = viewSize.height;
// If we previously had items and now we don't, then add the no items view
if(_cachedNumberOfItems > 0) [self OE_addNoItemsView];
}
else
{
contentSize.height = MAX(viewSize.height, ceil(numberOfRows * itemSize.height));
[self OE_removeNoItemsView];
}
++_supressFrameResize;
[super setFrameSize:contentSize];
[enclosingScrollView reflectScrolledClipView:(NSClipView *)[self superview]];
--_supressFrameResize;
// Changing the size of the frame may also change the contentOffset, recalculate that value
visibleRect = [enclosingScrollView documentVisibleRect];
contentOffset = visibleRect.origin;
// Check to see if the number visible columns or the cell size has changed as these vents will cause the layout to be recalculated
if(_cachedNumberOfVisibleColumns != numberOfVisibleColumns || !NSEqualSizes(_cachedItemSize, itemSize)) [self OE_setNeedsLayoutGridView];
}
// Check to see if the number of visible rows have changed
// Check to see if the scroll view's content offset or the view's height has changed
if((_cachedNumberOfVisibleRows != numberOfVisibleRows) || (_cachedContentOffset.y != contentOffset.y) || (_cachedViewSize.height != viewSize.height))
{
// This event may require a data reload
checkForDataReload = YES;
}
// Update the cached values
_cachedViewSize = viewSize;
_cachedItemSize = itemSize;
_cachedColumnSpacing = round((itemSize.width - _itemSize.width) / 2.0);
_cachedNumberOfVisibleColumns = numberOfVisibleColumns;
_cachedNumberOfVisibleRows = numberOfVisibleRows;
_cachedNumberOfItems = numberOfItems;
_cachedNumberOfRows = numberOfRows;
_cachedContentOffset = contentOffset;
// Reload data when appropriate
if(checkForDataReload) [self OE_checkForDataReload];
}
- (void)OE_checkForDataReload
{
if(_cachedNumberOfItems == 0) return;
// Check to see if the visible cells have changed
const CGFloat contentOffsetY = NSMinY([[self enclosingScrollView] documentVisibleRect]);
const NSUInteger firstVisibleIndex = MAX((NSInteger)floor(contentOffsetY / _cachedItemSize.height) - 1, 0) * _cachedNumberOfVisibleColumns;
const NSUInteger numberOfVisibleCells = _cachedNumberOfVisibleColumns * (_cachedNumberOfVisibleRows + 2);
NSIndexSet *visibleCellsIndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(firstVisibleIndex, MIN(numberOfVisibleCells, _cachedNumberOfItems - firstVisibleIndex))];
if ([_visibleCellsIndexes isEqualToIndexSet:visibleCellsIndexSet]) return;
// Calculate which cells to remove from view
if([_visibleCellsIndexes count] != 0)
{
NSMutableIndexSet *removeIndexSet = [_visibleCellsIndexes mutableCopy];
[removeIndexSet removeIndexes:visibleCellsIndexSet];
if([removeIndexSet count] != 0) [self OE_enqueueCellsAtIndexes:removeIndexSet];
}
// Calculate which cells to add to view
NSMutableIndexSet *addIndexSet = [visibleCellsIndexSet mutableCopy];
if([_visibleCellsIndexes count] != 0)
{
[addIndexSet removeIndexes:_visibleCellsIndexes];
[_visibleCellsIndexes removeAllIndexes];
}
// Update the visible cells index set
[_visibleCellsIndexes addIndexes:visibleCellsIndexSet];
if([addIndexSet count] != 0) [self reloadCellsAtIndexes:addIndexSet];
}
- (void)OE_setNeedsReloadData
{
_needsReloadData = YES;
[_rootLayer setNeedsLayout];
}
- (void)OE_reloadDataIfNeeded
{
if(_needsReloadData) [self reloadData];
}
- (void)noteNumberOfCellsChanged
{
[self OE_calculateCachedValuesAndQueryForDataChanges:YES];
}
- (void)OE_removeNoItemsView
{
if(_noItemsView != nil)
{
[_noItemsView removeFromSuperview];
_noItemsView = nil;
[[self enclosingScrollView] setVerticalScrollElasticity:_previousElasticity];
[self OE_setNeedsLayoutGridView];
}
}
- (void)OE_addNoItemsView
{
// Enqueue all the cells for later use and remove them from the view
[self OE_enqueueCellsAtIndexes:_visibleCellsIndexes];
[_visibleCellsIndexes removeAllIndexes];
// Check to see if the dataSource has a view to display when there is nothing to display
if(_dataSourceHas.viewForNoItemsInGridView)
{
_noItemsView = [_dataSource viewForNoItemsInGridView:self];
if(_noItemsView)
{
NSScrollView *enclosingScrollView = [self enclosingScrollView];
[self addSubview:_noItemsView];
[_noItemsView setHidden:NO];
[self OE_centerNoItemsView];
_previousElasticity = [enclosingScrollView verticalScrollElasticity];
[enclosingScrollView setVerticalScrollElasticity:NSScrollElasticityNone];
[self OE_setNeedsLayoutGridView];
}
}
}
- (void)reloadData
{
[_selectionIndexes removeAllIndexes];
_indexOfKeyboardSelection = NSNotFound;
[self OE_enqueueCellsAtIndexes:_visibleCellsIndexes];
[_visibleCellsIndexes removeAllIndexes];
[_reuseableCells removeAllObjects];
_cachedNumberOfVisibleColumns = 0;
_cachedNumberOfVisibleRows = 0;
_cachedNumberOfItems = 0;
_cachedContentOffset = NSZeroPoint;
_cachedViewSize = NSZeroSize;
_cachedItemSize = NSZeroSize;
_cachedColumnSpacing = 0.0;
[self OE_removeNoItemsView];
// Recalculate all of the required cached values
[self OE_calculateCachedValuesAndQueryForDataChanges:YES];
if(_cachedNumberOfItems == 0) [self OE_addNoItemsView];
_needsReloadData = NO;
}
- (void)reloadCellsAtIndexes:(NSIndexSet *)indexes
{
// If there is no index set or no items in the index set, then there is nothing to update
if([indexes count] == 0) return;
[indexes enumerateIndexesUsingBlock:
^ (NSUInteger idx, BOOL *stop)
{
// If the cell is not already visible, then there is nothing to reload
if([_visibleCellsIndexes containsIndex:idx])
{
OEGridViewCell *newCell = [_dataSource gridView:self cellForItemAtIndex:idx];
OEGridViewCell *oldCell = [self cellForItemAtIndex:idx makeIfNecessary:NO];
if(newCell != oldCell)
{
if(oldCell) [newCell setFrame:[oldCell frame]];
// Prepare the new cell for insertion
if (newCell)
{
[newCell OE_setIndex:idx];
[newCell setSelected:[_selectionIndexes containsIndex:idx] animated:NO];
// Replace the old cell with the new cell
if(oldCell)
{
[self OE_enqueueCellsAtIndexes:[NSIndexSet indexSetWithIndex:[oldCell OE_index]]];
}
[newCell setOpacity:1.0];
[newCell setHidden:NO];
if(!oldCell) [newCell setFrame:[self rectForCellAtIndex:idx]];
[_visibleCellByIndex setObject:newCell forKey:[NSNumber numberWithUnsignedInteger:idx]];
[_rootLayer addSublayer:newCell];
}
[self OE_setNeedsLayoutGridView];
}
}
}];
[self OE_reorderSublayers];
}
#pragma mark -
#pragma mark View Operations
- (BOOL)isFlipped
{
return YES;
}
- (void)updateTrackingAreas
{
[super updateTrackingAreas];
if (_trackingArea) { [self removeTrackingArea:_trackingArea]; }
NSTrackingAreaOptions options = (NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow);
_trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
[self addTrackingArea:_trackingArea];
}
- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSWindow *oldWindow = [self window];
if(oldWindow)
{
[notificationCenter removeObserver:self name:NSWindowDidBecomeKeyNotification object:oldWindow];
[notificationCenter removeObserver:self name:NSWindowDidResignKeyNotification object:oldWindow];
}
if(newWindow)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OE_windowChangedKey:) name:NSWindowDidBecomeKeyNotification object:[self window]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OE_windowChangedKey:) name:NSWindowDidResignKeyNotification object:[self window]];
}
[self updateTrackingAreas];
}
- (void)viewWillMoveToSuperview:(NSView *)newSuperview
{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSClipView *newClipView = ([newSuperview isKindOfClass:[NSClipView class]] ? (NSClipView *)newSuperview : nil);
NSClipView *oldClipView = [[self enclosingScrollView] contentView];
if(oldClipView)
{
[notificationCenter removeObserver:self name:NSViewBoundsDidChangeNotification object:oldClipView];
[notificationCenter removeObserver:self name:NSViewFrameDidChangeNotification object:oldClipView];
}
if(newClipView)
{
// TODO: I think there is some optimization we can do here
[self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[notificationCenter addObserver:self selector:@selector(OE_clipViewBoundsChanged:) name:NSViewBoundsDidChangeNotification object:newClipView];
[notificationCenter addObserver:self selector:@selector(OE_clipViewFrameChanged:) name:NSViewFrameDidChangeNotification object:newClipView];
[newClipView setPostsBoundsChangedNotifications:YES];
[newClipView setPostsFrameChangedNotifications:YES];
}
}
- (void)OE_updateSelectedCellsActiveSelectorWithFocus:(BOOL)focus
{
if(([_selectionIndexes count] == 0) || ([_selectionIndexes lastIndex] < [_visibleCellsIndexes firstIndex]) || ([_selectionIndexes firstIndex] > [_visibleCellsIndexes lastIndex])) return;
NSMutableIndexSet *visibleAndSelected = [_selectionIndexes mutableCopy];
[visibleAndSelected removeIndexesInRange:NSMakeRange([_selectionIndexes firstIndex], [_visibleCellsIndexes firstIndex] - [_selectionIndexes firstIndex])];
[visibleAndSelected removeIndexesInRange:NSMakeRange([_visibleCellsIndexes lastIndex] + 1, [_selectionIndexes lastIndex] - [_visibleCellsIndexes lastIndex])];
if([visibleAndSelected count] > 0)
{
[visibleAndSelected enumerateIndexesUsingBlock:
^ (NSUInteger idx, BOOL *stop)
{
OEGridViewCell *cell = [self cellForItemAtIndex:idx makeIfNecessary:NO];
if(cell)
{
if(focus) [cell didBecomeFocused];
else [cell willResignFocus];
}
}];
}
}
- (void)OE_windowChangedKey:(NSNotification *)notification
{
if([notification name] == NSWindowDidBecomeKeyNotification) [self OE_updateSelectedCellsActiveSelectorWithFocus:YES];
else if([notification name] == NSWindowDidResignKeyNotification) [self OE_updateSelectedCellsActiveSelectorWithFocus:NO];
}
- (void)OE_clipViewFrameChanged:(NSNotification *)notification
{
// Return immediately if this method is being surpressed.
if(_supressFrameResize > 0) return;
[self OE_updateDecorativeLayers];
if(_noItemsView)
{
[self setFrame:[[self enclosingScrollView] bounds]];
[self OE_centerNoItemsView];
}
const NSRect visibleRect = [[self enclosingScrollView] documentVisibleRect];
if(!NSEqualSizes(_cachedViewSize, visibleRect.size))
{
[self OE_cancelFieldEditor];
[self OE_calculateCachedValuesAndQueryForDataChanges:NO];
}
}
- (void)OE_clipViewBoundsChanged:(NSNotification *)notification
{
[self OE_updateDecorativeLayers];
const NSRect visibleRect = [[self enclosingScrollView] documentVisibleRect];
if(abs(_cachedContentOffset.y - visibleRect.origin.y) > _itemSize.height)
{
_cachedContentOffset = visibleRect.origin;
[self OE_checkForDataReload];
}
}
- (void)OE_centerNoItemsView
{
if(!_noItemsView) return;
const NSRect visibleRect = [[self enclosingScrollView] visibleRect];
const NSSize viewSize = [_noItemsView frame].size;
const NSRect viewFrame = NSMakeRect(ceil((NSWidth(visibleRect) - viewSize.width) / 2.0), ceil((NSHeight(visibleRect) - viewSize.height) / 2.0), viewSize.width, viewSize.height);
[_noItemsView setFrame:viewFrame];
}
#pragma mark -
#pragma mark Layer Operations
- (id)actionForLayer:(CALayer *)layer forKey:(NSString *)event
{
return [NSNull null];
}
- (void)OE_reorderSublayers
{
[_rootLayer insertSublayer:_backgroundLayer atIndex:0];
unsigned int index = (unsigned int)[[_rootLayer sublayers] count];
[_rootLayer insertSublayer:_foregroundLayer atIndex:index];
[_rootLayer insertSublayer:_selectionLayer atIndex:index];
[_rootLayer insertSublayer:_dragIndicationLayer atIndex:index];
}
- (void)OE_updateDecorativeLayers
{
if(!_dragIndicationLayer && !_backgroundLayer && !_foregroundLayer) return;
[CATransaction begin];
[CATransaction setDisableActions:YES];
const NSRect decorativeFrame = [[self enclosingScrollView] documentVisibleRect];
[_backgroundLayer setFrame:decorativeFrame];
[_foregroundLayer setFrame:decorativeFrame];
[_dragIndicationLayer setFrame:NSInsetRect(decorativeFrame, 1.0, 1.0)];
[CATransaction commit];
}
- (void)OE_setNeedsLayoutGridView
{
_needsLayoutGridView = YES;
[_rootLayer setNeedsLayout];
}
- (void)OE_layoutGridViewIfNeeded
{
// -layoutSublayers is called for every little thing, this checks to see if we really intended to adjust the location of the cells. This value can
// be set using OE_setNeedsLayoutGridView
if(_needsLayoutGridView) [self OE_layoutGridView];
}
- (void)OE_layoutGridView
{
if([_visibleCellByIndex count] == 0) return;
[_visibleCellByIndex enumerateKeysAndObjectsUsingBlock:
^ (NSNumber *key, OEGridViewCell *obj, BOOL *stop)
{
[obj setFrame:[self rectForCellAtIndex:[key unsignedIntegerValue]]];
}];
_needsLayoutGridView = NO;
}
- (void)layoutSublayers
{
[self OE_reloadDataIfNeeded];
[self OE_updateDecorativeLayers];
[self OE_layoutGridViewIfNeeded];
}
#pragma mark -
#pragma mark Responder Chain
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (BOOL)becomeFirstResponder
{
[self OE_updateSelectedCellsActiveSelectorWithFocus:YES];
return YES;
}
- (BOOL)resignFirstResponder
{
[self OE_updateSelectedCellsActiveSelectorWithFocus:NO];
return YES;
}
#pragma mark -
#pragma mark Mouse Handling Operations
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
return YES;
}
- (NSPoint)OE_pointInViewFromEvent:(NSEvent *)theEvent
{
return [self convertPoint:[theEvent locationInWindow] fromView:nil];
}
- (OEGridLayer *)OE_gridLayerForPoint:(const NSPoint)point
{
CALayer *hitLayer = [_rootLayer hitTest:[self convertPointToLayer:point]];
return ([hitLayer isKindOfClass:[OEGridLayer class]] ? (OEGridLayer *)hitLayer : nil);
}
- (void)mouseDown:(NSEvent *)theEvent
{
const NSPoint pointInView = [self OE_pointInViewFromEvent:theEvent];
_trackingLayer = [self OE_gridLayerForPoint:pointInView];
if(![_trackingLayer isInteractive]) _trackingLayer = _rootLayer;
OEGridViewCell *cell = nil;
if ([_trackingLayer isKindOfClass:[OEGridViewCell class]]) cell = (OEGridViewCell *)_trackingLayer;
if(cell == nil && _trackingLayer != nil && _trackingLayer != _rootLayer)
{
const NSPoint pointInLayer = [_rootLayer convertPoint:pointInView toLayer:_trackingLayer];
[_trackingLayer mouseDownAtPointInLayer:pointInLayer withEvent:theEvent];
if(![_trackingLayer isTracking]) _trackingLayer = nil;
}
const NSUInteger modifierFlags = [[NSApp currentEvent] modifierFlags];
const BOOL commandKeyDown = ((modifierFlags & NSCommandKeyMask) == NSCommandKeyMask);
const BOOL shiftKeyDown = ((modifierFlags & NSShiftKeyMask) == NSShiftKeyMask);
const BOOL invertSelection = commandKeyDown || shiftKeyDown;
// Figure out which cell was touched, inverse it's selection...
if(cell != nil)
{
if(!invertSelection && ![cell isSelected]) [self deselectAll:self];
NSUInteger idx = [cell OE_index];
if(![_selectionIndexes containsIndex:idx])
{
[self selectCellAtIndex:idx];
_indexOfKeyboardSelection = idx;
}
else if(invertSelection)
{
[self deselectCellAtIndex:idx];
_indexOfKeyboardSelection = [_selectionIndexes lastIndex];
}
}
else if(_trackingLayer == nil || _trackingLayer == _rootLayer)
{
_trackingLayer = _rootLayer;
if(!invertSelection) [self deselectAll:self];
// If the command key was pressed and there are already a list of selected indexes, then we may want to invert the items that are already selected
if(invertSelection && [_selectionIndexes count] > 0) _originalSelectionIndexes = [_selectionIndexes copy];
}
// Start tracking mouse
NSEvent *lastMouseDragEvent = nil;
const BOOL isTrackingRootLayer = (_trackingLayer == _rootLayer);
const NSUInteger eventMask = NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSKeyDownMask | (isTrackingRootLayer ? NSPeriodicMask : 0);
_initialPoint = pointInView;
// If we are tracking the root layer then we are dragging a selection box, fire off periodic events so that we can autoscroll the view
if(isTrackingRootLayer) [NSEvent startPeriodicEventsAfterDelay:OEInitialPeriodicDelay withPeriod:OEPeriodicInterval];
// Keep tracking as long as we are tracking a layer and there are events in the queue
while(_trackingLayer && (theEvent = [[self window] nextEventMatchingMask:eventMask]))
{
if(isTrackingRootLayer && [theEvent type] == NSPeriodic)
{
// Refire last mouse drag event when perioidc events are encountered
if(lastMouseDragEvent)
{