VLCFolderCollectionViewFlowLayout.m 18.6 KB
Newer Older
Carola's avatar
Carola committed
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
/*****************************************************************************
 * VLCFolderCollectionViewFlowLayout.m
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2014 VideoLAN. All rights reserved.
 * $Id$
 *
 * Authors: Carola Nitz <nitz.carola # googlemail.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

#import "VLCFolderCollectionViewFlowLayout.h"
#import <objc/runtime.h>
#import "VLCPlaylistViewController.h"

//framrate were motion appears fluent
#define LX_FRAMES_PER_SECOND 60.0

#ifndef CGGEOMETRY_LXSUPPORT_H_
CG_INLINE CGPoint
LXS_CGPointAdd(CGPoint point1, CGPoint point2) {
    return CGPointMake(point1.x + point2.x, point1.y + point2.y);
}
#endif

typedef NS_ENUM(NSInteger, LXScrollingDirection) {
    LXScrollingDirectionUnknown = 0,
    LXScrollingDirectionUp,
    LXScrollingDirectionDown,
    LXScrollingDirectionLeft,
    LXScrollingDirectionRight
};

static NSString * const kLXScrollingDirectionKey = @"LXScrollingDirection";
static NSString * const kLXCollectionViewKeyPath = @"collectionView";

@interface CADisplayLink (LX_userInfo)
@property (nonatomic, copy) NSDictionary *LX_userInfo;
@end

@implementation CADisplayLink (LX_userInfo)
- (void) setLX_userInfo:(NSDictionary *) LX_userInfo {
    objc_setAssociatedObject(self, "LX_userInfo", LX_userInfo, OBJC_ASSOCIATION_COPY);
}

- (NSDictionary *) LX_userInfo {
    return objc_getAssociatedObject(self, "LX_userInfo");
}
@end

@interface UICollectionViewCell (VLCFolderCollectionViewLayout)

- (UIImage *)LX_rasterizedImage;

@end

@implementation UICollectionViewCell (VLCFolderCollectionViewLayout)

- (UIImage *)LX_rasterizedImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0f);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

@interface VLCFolderCollectionViewFlowLayout ()
{
    NSIndexPath *_selectedItemIndexPath;
    UIView *_currentView;
    CGPoint _currentViewCenter;
    CGPoint _panTranslationInCollectionView;
    CADisplayLink *_displayLink;
    UIView *_folderView;
78
    BOOL _didPan;
Carola's avatar
Carola committed
79
80
81
82
83
84
85
86
87
88
89
90
}

@end

@implementation VLCFolderCollectionViewFlowLayout

- (void)setDefaults {
    _scrollingSpeed = 300.0f;
    _scrollingTriggerEdgeInsets = UIEdgeInsetsMake(50.0f, 50.0f, 50.0f, 50.0f);
}

- (void)setupCollectionView {
91
92
93
    _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(handleLongPressGesture:)];
    _longPressGestureRecognizer.delegate = self;
Carola's avatar
Carola committed
94

95
96
    // Links the default long press gesture recognizer to the custom long press gesture recognizer we are creating now
    // by enforcing failure dependency so that they doesn't clash.
Carola's avatar
Carola committed
97
    for (UIGestureRecognizer *gestureRecognizer in self.collectionView.gestureRecognizers) {
98
99
100
        if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {
            [gestureRecognizer requireGestureRecognizerToFail:_longPressGestureRecognizer];
        }
Carola's avatar
Carola committed
101
102
    }

103
104
105
106
107
    [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];

    _panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                    action:@selector(handlePanGesture:)];
    _panGestureRecognizer.delegate = self;
Carola's avatar
Carola committed
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
    [self.collectionView addGestureRecognizer:_panGestureRecognizer];

    // Useful in multiple scenarios: one common scenario being when the Notification Center drawer is pulled down
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleApplicationWillResignActive:) name: UIApplicationWillResignActiveNotification object:nil];
}

- (id)init {
    self = [super init];
    if (self) {
        [self setDefaults];
        [self addObserver:self forKeyPath:kLXCollectionViewKeyPath options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setDefaults];
        [self addObserver:self forKeyPath:kLXCollectionViewKeyPath options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)dealloc {
    [self invalidatesScrollTimer];
    [self removeObserver:self forKeyPath:kLXCollectionViewKeyPath];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    if ([layoutAttributes.indexPath isEqual:_selectedItemIndexPath])
        layoutAttributes.hidden = YES;
}

- (id<VLCFolderCollectionViewDelegateFlowLayout>)delegate {
    return (id<VLCFolderCollectionViewDelegateFlowLayout>)self.collectionView.delegate;
}

- (void)invalidateLayoutIfNecessary {
    NSIndexPath *newIndexPath = [self.collectionView indexPathForItemAtPoint:_currentView.center];
    NSIndexPath *previousIndexPath = _selectedItemIndexPath;
150

Carola's avatar
Carola committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
    if ((newIndexPath == nil) || [newIndexPath isEqual:previousIndexPath]) {
        _currentView.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
        [_folderView removeFromSuperview];
        return;
    }

    UICollectionViewCell *cell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:newIndexPath];
    if (!_folderView) {
        _folderView = [[UIView alloc] initWithFrame:cell.frame];
        _folderView.backgroundColor = [UIColor colorWithRed:(236.0f/255.0f) green:(111.0f/255.0f) blue:0.0f alpha:1.f];
        _folderView.layer.cornerRadius = 8;
    }
    [self.collectionView insertSubview:_folderView atIndex:0];

165
    if (!CGPointEqualToPoint(_folderView.center,cell.center))
Carola's avatar
Carola committed
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
        _folderView.frame = cell.frame;

    [UIView
     animateWithDuration:0.3
     delay:0.0
     options:UIViewAnimationOptionBeginFromCurrentState
     animations:^{
         _currentView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
     }
     completion:nil];
}

- (void)invalidatesScrollTimer {
    if (!_displayLink.paused)
        [_displayLink invalidate];
    _displayLink = nil;
}

- (void)setupScrollTimerInDirection:(LXScrollingDirection)direction {
    if (!_displayLink.paused) {
        LXScrollingDirection oldDirection = [_displayLink.LX_userInfo[kLXScrollingDirectionKey] integerValue];

        if (direction == oldDirection)
            return;
    }
191

Carola's avatar
Carola committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    [self invalidatesScrollTimer];

    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleScroll:)];
    _displayLink.LX_userInfo = @{ kLXScrollingDirectionKey : @(direction) };

    [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

#pragma mark - Target/Action methods
// Tight loop, allocate memory sparely, even if they are stack allocation.
- (void)handleScroll:(CADisplayLink *)displayLink {
    LXScrollingDirection direction = (LXScrollingDirection)[displayLink.LX_userInfo[kLXScrollingDirectionKey] integerValue];
    if (direction == LXScrollingDirectionUnknown)
        return;
206

Carola's avatar
Carola committed
207
208
209
210
211
212
213
    CGSize frameSize = self.collectionView.bounds.size;
    CGSize contentSize = self.collectionView.contentSize;
    CGPoint contentOffset = self.collectionView.contentOffset;
    // Important to have an integer `distance` as the `contentOffset` property automatically gets rounded
    // and it would diverge from the view's center resulting in a "cell is slipping away under finger"-bug.
    CGFloat distance = rint(self.scrollingSpeed / LX_FRAMES_PER_SECOND);
    CGPoint translation = CGPointZero;
214

Carola's avatar
Carola committed
215
216
217
218
    switch(direction) {
        case LXScrollingDirectionUp: {
            distance = -distance;
            CGFloat minY = 0.0f;
219

Carola's avatar
Carola committed
220
221
            if ((contentOffset.y + distance) <= minY)
                distance = -contentOffset.y;
222

Carola's avatar
Carola committed
223
224
225
226
            translation = CGPointMake(0.0f, distance);
        } break;
        case LXScrollingDirectionDown: {
            CGFloat maxY = MAX(contentSize.height, frameSize.height) - frameSize.height;
227

Carola's avatar
Carola committed
228
229
            if ((contentOffset.y + distance) >= maxY)
                distance = maxY - contentOffset.y;
230

Carola's avatar
Carola committed
231
232
233
234
235
236
            translation = CGPointMake(0.0f, distance);
        } break;
        case LXScrollingDirectionLeft: {

            distance = -distance;
            CGFloat minX = 0.0f;
237

Carola's avatar
Carola committed
238
239
            if ((contentOffset.x + distance) <= minX)
                distance = -contentOffset.x;
240

Carola's avatar
Carola committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
            translation = CGPointMake(distance, 0.0f);
        } break;
        case LXScrollingDirectionRight: {
            CGFloat maxX = MAX(contentSize.width, frameSize.width) - frameSize.width;

            if ((contentOffset.x + distance) >= maxX)
                distance = maxX - contentOffset.x;

            translation = CGPointMake(distance, 0.0f);
        } break;
        default: {
            // Do nothing...
        } break;
    }
    _currentViewCenter = LXS_CGPointAdd(_currentViewCenter, translation);
    _currentView.center = LXS_CGPointAdd(_currentViewCenter, _panTranslationInCollectionView);
    self.collectionView.contentOffset = LXS_CGPointAdd(contentOffset, translation);
}

260
- (void)handleLongPressGesture:(UILongPressGestureRecognizer *)gestureRecognizer {
Carola's avatar
Carola committed
261
262
263
    //keeps the controller from dragging while not in editmode
    if (!((VLCPlaylistViewController *)self.delegate).isEditing) return;

264
    switch(gestureRecognizer.state) {
Carola's avatar
Carola committed
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
        case UIGestureRecognizerStateBegan: {
            NSIndexPath *currentIndexPath = [self.collectionView indexPathForItemAtPoint:[gestureRecognizer locationInView:self.collectionView]];
            _selectedItemIndexPath = currentIndexPath;

            UICollectionViewCell *collectionViewCell = [self.collectionView cellForItemAtIndexPath:_selectedItemIndexPath];

            _currentView = [[UIView alloc] initWithFrame:collectionViewCell.frame];

            collectionViewCell.highlighted = YES;
            UIImageView *highlightedImageView = [[UIImageView alloc] initWithImage:[collectionViewCell LX_rasterizedImage]];
            highlightedImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            highlightedImageView.alpha = 1.0f;

            collectionViewCell.highlighted = NO;
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[collectionViewCell LX_rasterizedImage]];
            imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            imageView.alpha = 0.0f;

            [_currentView addSubview:imageView];
            [_currentView addSubview:highlightedImageView];
            [self.collectionView addSubview:_currentView];

            _currentViewCenter = _currentView.center;

            [UIView
             animateWithDuration:0.3
             delay:0.0
             options:UIViewAnimationOptionBeginFromCurrentState
             animations:^{
294
295
296
                 _currentView.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
                 highlightedImageView.alpha = 0.0f;
                 imageView.alpha = 1.0f;
Carola's avatar
Carola committed
297
298
             }
             completion:^(BOOL finished) {
299
                [highlightedImageView removeFromSuperview];
Carola's avatar
Carola committed
300
301
302
             }];

            [self invalidateLayout];
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
        } break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded: {
            if (_didPan) return;

            NSIndexPath *currentIndexPath = _selectedItemIndexPath;

            if (currentIndexPath) {
                _selectedItemIndexPath = nil;
                _currentViewCenter = CGPointZero;

                UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForItemAtIndexPath:currentIndexPath];

                [UIView
                 animateWithDuration:0.3
                 delay:0.0
                 options:UIViewAnimationOptionBeginFromCurrentState
                 animations:^{
                     _currentView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                     _currentView.center = layoutAttributes.center;
                 }
                 completion:^(BOOL finished) {

                     [_currentView removeFromSuperview];
                     _currentView = nil;
                     [self invalidateLayout];

                 }];
            }
        } break;

        default: break;
    }
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer {

    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            _didPan = YES;
Carola's avatar
Carola committed
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
        case UIGestureRecognizerStateChanged: {
            _panTranslationInCollectionView = [gestureRecognizer translationInView:self.collectionView];
            CGPoint viewCenter = _currentView.center = LXS_CGPointAdd(_currentViewCenter, _panTranslationInCollectionView);
            [self invalidateLayoutIfNecessary];

            switch (self.scrollDirection) {
                case UICollectionViewScrollDirectionVertical: {
                    if (viewCenter.y < (CGRectGetMinY(self.collectionView.bounds) + self.scrollingTriggerEdgeInsets.top)) {
                        [self setupScrollTimerInDirection:LXScrollingDirectionUp];
                    } else {
                        if (viewCenter.y > (CGRectGetMaxY(self.collectionView.bounds) - self.scrollingTriggerEdgeInsets.bottom)) {
                            [self setupScrollTimerInDirection:LXScrollingDirectionDown];
                        } else {
                            [self invalidatesScrollTimer];
                        }
                    }
                } break;
                case UICollectionViewScrollDirectionHorizontal: {
                    if (viewCenter.x < (CGRectGetMinX(self.collectionView.bounds) + self.scrollingTriggerEdgeInsets.left)) {
                        [self setupScrollTimerInDirection:LXScrollingDirectionLeft];
                    } else {
                        if (viewCenter.x > (CGRectGetMaxX(self.collectionView.bounds) - self.scrollingTriggerEdgeInsets.right)) {
                            [self setupScrollTimerInDirection:LXScrollingDirectionRight];
                        } else {
                            [self invalidatesScrollTimer];
                        }
                    }
                } break;
            }
        } break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded: {
375
            _didPan = NO;
Carola's avatar
Carola committed
376
377
378
379
380
            [_folderView removeFromSuperview];
            _folderView = nil;
            NSIndexPath *newIndexPath = [self.collectionView indexPathForItemAtPoint:_currentView.center];
            NSIndexPath *currentIndexPath = _selectedItemIndexPath;

381
            if (newIndexPath != nil && ![currentIndexPath isEqual:newIndexPath] && ((VLCPlaylistViewController *)self.delegate).isEditing) {
Carola's avatar
Carola committed
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
                [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                    _currentView.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
                    _currentView.center = [self layoutAttributesForItemAtIndexPath:newIndexPath].center;
                } completion:^(BOOL finished) {
                    [self.delegate collectionView:self.collectionView requestToMoveItemAtIndexPath:currentIndexPath intoFolderAtIndexPath:newIndexPath];
                    _selectedItemIndexPath = nil;
                    _currentViewCenter = CGPointZero;
                    [_currentView removeFromSuperview];
                    _currentView = nil;
                }];
            } else if (currentIndexPath) {
                [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                    _currentView.center = [self layoutAttributesForItemAtIndexPath:currentIndexPath].center;
                } completion:^(BOOL finished) {
                    _selectedItemIndexPath = nil;
                    _currentViewCenter = CGPointZero;
                    [_currentView removeFromSuperview];
                    _currentView = nil;
                    [self invalidateLayout];
                }];
            }
            [self invalidatesScrollTimer];
        } break;
        default: {
            // Do nothing...
        } break;
    }
}

#pragma mark - UICollectionViewLayout overridden methods

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *layoutAttributesForElementsInRect = [super layoutAttributesForElementsInRect:rect];
415

Carola's avatar
Carola committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    for (UICollectionViewLayoutAttributes *layoutAttributes in layoutAttributesForElementsInRect) {
        switch (layoutAttributes.representedElementCategory) {
            case UICollectionElementCategoryCell: {
                [self applyLayoutAttributes:layoutAttributes];
            } break;
            default: {
                // Do nothing...
            } break;
        }
    }
    return layoutAttributesForElementsInRect;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *layoutAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
431

Carola's avatar
Carola committed
432
433
434
435
436
437
438
439
    switch (layoutAttributes.representedElementCategory) {
        case UICollectionElementCategoryCell: {
            [self applyLayoutAttributes:layoutAttributes];
        } break;
        default: {
            // Do nothing...
        } break;
    }
440

Carola's avatar
Carola committed
441
442
    return layoutAttributes;
}
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#pragma mark - UIGestureRecognizerDelegate methods

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([self.panGestureRecognizer isEqual:gestureRecognizer]) {
        return (_selectedItemIndexPath != nil);
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if ([self.longPressGestureRecognizer isEqual:gestureRecognizer]) {
        return [self.panGestureRecognizer isEqual:otherGestureRecognizer];
    }

    if ([self.panGestureRecognizer isEqual:gestureRecognizer]) {
        return [self.longPressGestureRecognizer isEqual:otherGestureRecognizer];
    }
    return NO;
}
Carola's avatar
Carola committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481

#pragma mark - Key-Value Observing methods

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:kLXCollectionViewKeyPath]) {
        if (self.collectionView != nil) {
            [self setupCollectionView];
        } else {
            [self invalidatesScrollTimer];
        }
    }
}
#pragma mark - Notifications

- (void)handleApplicationWillResignActive:(NSNotification *)notification {
    self.panGestureRecognizer.enabled = NO;
    self.panGestureRecognizer.enabled = YES;
}

@end