forked from overtake/telegram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
POPAnimator.mm
executable file
·794 lines (639 loc) · 19.5 KB
/
POPAnimator.mm
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
/**
Copyright (c) 2014-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#import "POPAnimator.h"
#import "POPAnimatorPrivate.h"
#import <list>
#import <objc/objc-auto.h>
#import <vector>
#import <QuartzCore/QuartzCore.h>
#import "POPAnimation.h"
#import "POPAnimationExtras.h"
#import "POPBasicAnimationInternal.h"
#import "POPDecayAnimation.h"
using namespace std;
using namespace POP;
#define ENABLE_LOGGING_DEBUG 0
#define ENABLE_LOGGING_INFO 0
#if ENABLE_LOGGING_DEBUG
#define FBLogAnimDebug NSLog
#else
#define FBLogAnimDebug(...)
#endif
#if ENABLE_LOGGING_INFO
#define FBLogAnimInfo NSLog
#else
#define FBLogAnimInfo(...)
#endif
class POPAnimatorItem
{
public:
id __weak object;
NSString *key;
POPAnimation *animation;
NSInteger refCount;
id __unsafe_unretained unretainedObject;
POPAnimatorItem(id o, NSString *k, POPAnimation *a) POP_NOTHROW
{
object = o;
key = [k copy];
animation = a;
refCount = 1;
unretainedObject = o;
}
~POPAnimatorItem()
{
}
bool operator==(const POPAnimatorItem& o) const {
return unretainedObject == o.unretainedObject && animation == o.animation && [key isEqualToString:o.key];
}
};
typedef std::shared_ptr<POPAnimatorItem> POPAnimatorItemRef;
typedef std::shared_ptr<const POPAnimatorItem> POPAnimatorItemConstRef;
typedef std::list<POPAnimatorItemRef> POPAnimatorItemList;
typedef POPAnimatorItemList::iterator POPAnimatorItemListIterator;
typedef POPAnimatorItemList::const_iterator POPAnimatorItemListConstIterator;
static BOOL _disableBackgroundThread = YES;
@interface POPAnimator ()
{
#if TARGET_OS_IPHONE
CADisplayLink *_displayLink;
#else
CVDisplayLinkRef _displayLink;
#endif
POPAnimatorItemList _list;
CFMutableDictionaryRef _dict;
NSMutableArray *_observers;
POPAnimatorItemList _pendingList;
CFRunLoopObserverRef _pendingListObserver;
CFTimeInterval _slowMotionStartTime;
CFTimeInterval _slowMotionLastTime;
CFTimeInterval _slowMotionAccumulator;
CFTimeInterval _beginTime;
OSSpinLock _lock;
BOOL _disableDisplayLink;
}
@end
@implementation POPAnimator
@synthesize delegate = _delegate;
@synthesize disableDisplayLink = _disableDisplayLink;
@synthesize beginTime = _beginTime;
#if !TARGET_OS_IPHONE
static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *context)
{
if (_disableBackgroundThread) {
dispatch_async(dispatch_get_main_queue(), ^{
[(__bridge POPAnimator*)context render];
});
} else {
[(__bridge POPAnimator*)context render];
}
return kCVReturnSuccess;
}
#endif
// call while holding lock
static void updateDisplayLink(POPAnimator *self)
{
BOOL paused = (0 == self->_observers.count && self->_list.empty()) || self->_disableDisplayLink;
#if TARGET_OS_IPHONE
if (paused != self->_displayLink.paused) {
FBLogAnimInfo(paused ? @"pausing display link" : @"unpausing display link");
self->_displayLink.paused = paused;
}
#else
if (paused == CVDisplayLinkIsRunning(self->_displayLink)) {
FBLogAnimInfo(paused ? @"pausing display link" : @"unpausing display link");
if (paused) {
CVDisplayLinkStop(self->_displayLink);
} else {
CVDisplayLinkStart(self->_displayLink);
}
}
#endif
}
static void updateAnimatable(id obj, POPPropertyAnimationState *anim, bool shouldAvoidExtraneousWrite = false)
{
// handle user-initiated stop or pause; hault animation
if (!anim->active || anim->paused)
return;
if (anim->hasValue()) {
pop_animatable_write_block write = anim->property.writeBlock;
if (NULL == write)
return;
// current animation value
VectorRef currentVec = anim->currentValue();
if (!anim->additive) {
// if avoiding extraneous writes and we have a read block defined
if (shouldAvoidExtraneousWrite) {
pop_animatable_read_block read = anim->property.readBlock;
if (read) {
// compare current animation value with object value
Vector4r currentValue = currentVec->vector4r();
Vector4r objectValue = read_values(read, obj, anim->valueCount);
if (objectValue == currentValue) {
return;
}
}
}
// update previous values; support animation convergence
anim->previous2Vec = anim->previousVec;
anim->previousVec = currentVec;
// write value
write(obj, currentVec->data());
if (anim->tracing) {
[anim->tracer writePropertyValue:POPBox(currentVec, anim->valueType, true)];
}
} else {
pop_animatable_read_block read = anim->property.readBlock;
NSCAssert(read, @"additive requires an animatable property readBlock");
if (NULL == read) {
return;
}
// object value
Vector4r objectValue = read_values(read, obj, anim->valueCount);
// current value
Vector4r currentValue = currentVec->vector4r();
// determine animation change
if (anim->previousVec) {
Vector4r previousValue = anim->previousVec->vector4r();
currentValue -= previousValue;
}
// avoid writing no change
if (shouldAvoidExtraneousWrite && currentValue == Vector4r::Zero()) {
return;
}
// add to object value
currentValue += objectValue;
// update previous values; support animation convergence
anim->previous2Vec = anim->previousVec;
anim->previousVec = currentVec;
// write value
write(obj, currentValue.data());
if (anim->tracing) {
[anim->tracer writePropertyValue:POPBox(currentVec, anim->valueType, true)];
}
}
}
}
static void applyAnimationTime(id obj, POPAnimationState *state, CFTimeInterval time)
{
if (!state->advanceTime(time, obj)) {
return;
}
POPPropertyAnimationState *ps = dynamic_cast<POPPropertyAnimationState*>(state);
if (NULL != ps) {
updateAnimatable(obj, ps);
}
state->delegateApply();
}
static void applyAnimationToValue(id obj, POPAnimationState *state)
{
POPPropertyAnimationState *ps = dynamic_cast<POPPropertyAnimationState*>(state);
if (NULL != ps) {
// finalize progress
ps->finalizeProgress();
// write to value, updating only if needed
updateAnimatable(obj, ps, true);
}
state->delegateApply();
}
static POPAnimation *deleteDictEntry(POPAnimator *self, id __unsafe_unretained obj, NSString *key, BOOL cleanup = YES)
{
POPAnimation *anim = nil;
// lock
OSSpinLockLock(&self->_lock);
NSMutableDictionary *keyAnimationsDict = (__bridge id)CFDictionaryGetValue(self->_dict, (__bridge void *)obj);
if (keyAnimationsDict) {
anim = keyAnimationsDict[key];
if (anim) {
// remove key
[keyAnimationsDict removeObjectForKey:key];
// cleanup empty dictionaries
if (cleanup && 0 == keyAnimationsDict.count) {
CFDictionaryRemoveValue(self->_dict, (__bridge void *)obj);
}
}
}
// unlock
OSSpinLockUnlock(&self->_lock);
return anim;
}
static void stopAndCleanup(POPAnimator *self, POPAnimatorItemRef item, bool shouldRemove, bool finished)
{
// remove
if (shouldRemove) {
deleteDictEntry(self, item->unretainedObject, item->key);
}
// stop
POPAnimationState *state = POPAnimationGetState(item->animation);
state->stop(shouldRemove, finished);
if (shouldRemove) {
// lock
OSSpinLockLock(&self->_lock);
// find item in list
// may have already been removed on animationDidStop:
POPAnimatorItemListIterator find_iter = find(self->_list.begin(), self->_list.end(), item);
BOOL found = find_iter != self->_list.end();
if (found) {
self->_list.erase(find_iter);
}
// unlock
OSSpinLockUnlock(&self->_lock);
}
}
+ (id)sharedAnimator
{
static POPAnimator* _animator = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_animator = [[POPAnimator alloc] init];
});
return _animator;
}
+ (BOOL)disableBackgroundThread
{
return _disableBackgroundThread;
}
+ (void)setDisableBackgroundThread:(BOOL)flag
{
_disableBackgroundThread = flag;
}
#pragma mark - Lifecycle
- (id)init
{
self = [super init];
if (nil == self) return nil;
#if TARGET_OS_IPHONE
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(render)];
_displayLink.paused = YES;
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
#else
CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink);
CVDisplayLinkSetOutputCallback(_displayLink, displayLinkCallback, (__bridge void *)self);
#endif
_dict = POPDictionaryCreateMutableWeakPointerToStrongObject(5);
_lock = OS_SPINLOCK_INIT;
return self;
}
- (void)dealloc
{
#if TARGET_OS_IPHONE
[_displayLink invalidate];
#else
CVDisplayLinkStop(_displayLink);
CVDisplayLinkRelease(_displayLink);
#endif
[self _clearPendingListObserver];
}
#pragma mark - Utility
- (void)_processPendingList
{
// rendering pending animations
CFTimeInterval time = [self _currentRenderTime];
[self _renderTime:(0 != _beginTime) ? _beginTime : time items:_pendingList];
// lock
OSSpinLockLock(&_lock);
// clear list and observer
_pendingList.clear();
[self _clearPendingListObserver];
// unlock
OSSpinLockUnlock(&_lock);
}
- (void)_clearPendingListObserver
{
if (_pendingListObserver) {
CFRunLoopRemoveObserver(CFRunLoopGetMain(), _pendingListObserver, kCFRunLoopCommonModes);
CFRelease(_pendingListObserver);
_pendingListObserver = NULL;
}
}
- (void)_scheduleProcessPendingList
{
// see WebKit for magic numbers, eg http://trac.webkit.org/changeset/166540
static const CFIndex CATransactionCommitRunLoopOrder = 2000000;
static const CFIndex POPAnimationApplyRunLoopOrder = CATransactionCommitRunLoopOrder - 1;
// lock
OSSpinLockLock(&_lock);
if (!_pendingListObserver) {
__weak POPAnimator *weakSelf = self;
_pendingListObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopBeforeWaiting | kCFRunLoopExit, false, POPAnimationApplyRunLoopOrder, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
[weakSelf _processPendingList];
});
if (_pendingListObserver) {
CFRunLoopAddObserver(CFRunLoopGetMain(), _pendingListObserver, kCFRunLoopCommonModes);
}
}
// unlock
OSSpinLockUnlock(&_lock);
}
- (void)_renderTime:(CFTimeInterval)time items:(std::list<POPAnimatorItemRef>)items
{
// begin transaction with actions disabled
[CATransaction begin];
[CATransaction setDisableActions:YES];
// notify delegate
__strong __typeof__(_delegate) delegate = _delegate;
[delegate animatorWillAnimate:self];
// lock
OSSpinLockLock(&_lock);
// count active animations
const NSUInteger count = items.size();
if (0 == count) {
// unlock
OSSpinLockUnlock(&_lock);
} else {
// copy list into vectory
std::vector<POPAnimatorItemRef> vector{ std::begin(items), std::end(items) };
// unlock
OSSpinLockUnlock(&_lock);
for (auto item : vector) {
[self _renderTime:time item:item];
}
}
// notify observers
for (id observer in self.observers) {
[observer animatorDidAnimate:(id)self];
}
// lock
OSSpinLockLock(&_lock);
// update display link
updateDisplayLink(self);
// unlock
OSSpinLockUnlock(&_lock);
// notify delegate and commit
[delegate animatorDidAnimate:self];
[CATransaction commit];
}
- (void)_renderTime:(CFTimeInterval)time item:(POPAnimatorItemRef)item
{
id obj = item->object;
POPAnimation *anim = item->animation;
POPAnimationState *state = POPAnimationGetState(anim);
if (nil == obj) {
// object exists not; stop animating
NSAssert(item->unretainedObject, @"object should exist");
stopAndCleanup(self, item, true, false);
} else {
// start if needed
state->startIfNeeded(obj, time, _slowMotionAccumulator);
// only run active, not paused animations
if (state->active && !state->paused) {
// object exists; animate
applyAnimationTime(obj, state, time);
FBLogAnimDebug(@"time:%f running:%@", time, item->animation);
if (state->isDone()) {
// set end value
applyAnimationToValue(obj, state);
state->repeatCount--;
if (state->repeatForever || state->repeatCount > 0) {
if ([anim isKindOfClass:[POPPropertyAnimation class]]) {
POPPropertyAnimation *propAnim = (POPPropertyAnimation *)anim;
id oldFromValue = propAnim.fromValue;
propAnim.fromValue = propAnim.toValue;
if (state->autoreverses) {
if (state->tracing) {
[state->tracer autoreversed];
}
if (state->type == kPOPAnimationDecay) {
POPDecayAnimation *decayAnimation = (POPDecayAnimation *)propAnim;
decayAnimation.velocity = [decayAnimation reversedVelocity];
} else {
propAnim.toValue = oldFromValue;
}
} else {
if (state->type == kPOPAnimationDecay) {
POPDecayAnimation *decayAnimation = (POPDecayAnimation *)propAnim;
id originalVelocity = decayAnimation.originalVelocity;
decayAnimation.velocity = originalVelocity;
} else {
propAnim.fromValue = oldFromValue;
}
}
}
state->stop(NO, NO);
state->reset(true);
state->startIfNeeded(obj, time, _slowMotionAccumulator);
} else {
stopAndCleanup(self, item, state->removedOnCompletion, YES);
}
}
}
}
}
#pragma mark - API
- (NSArray *)observers
{
// lock
OSSpinLockLock(&_lock);
// get observers
NSArray *observers = 0 != _observers.count ? [_observers copy] : nil;
// unlock
OSSpinLockUnlock(&_lock);
return observers;
}
- (void)addAnimation:(POPAnimation *)anim forObject:(id)obj key:(NSString *)key
{
if (!anim || !obj) {
return;
}
// support arbitrarily many nil keys
if (!key) {
key = [[NSUUID UUID] UUIDString];
}
// lock
OSSpinLockLock(&_lock);
// get key, animation dict associated with object
NSMutableDictionary *keyAnimationDict = (__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj);
// update associated animation state
if (nil == keyAnimationDict) {
keyAnimationDict = [NSMutableDictionary dictionary];
CFDictionarySetValue(_dict, (__bridge void *)obj, (__bridge void *)keyAnimationDict);
} else {
// if the animation instance already exists, avoid cancelling only to restart
POPAnimation *existingAnim = keyAnimationDict[key];
if (existingAnim) {
// unlock
OSSpinLockUnlock(&_lock);
if (existingAnim == anim) {
return;
}
[self removeAnimationForObject:obj key:key cleanupDict:NO];
// lock
OSSpinLockLock(&_lock);
}
}
keyAnimationDict[key] = anim;
// create entry after potential removal
POPAnimatorItemRef item(new POPAnimatorItem(obj, key, anim));
// add to list and pending list
_list.push_back(item);
_pendingList.push_back(item);
// support animation re-use, reset all animation state
POPAnimationGetState(anim)->reset(true);
// update display link
updateDisplayLink(self);
// unlock
OSSpinLockUnlock(&_lock);
// schedule runloop processing of pending animations
[self _scheduleProcessPendingList];
}
- (void)removeAllAnimationsForObject:(id)obj
{
// lock
OSSpinLockLock(&_lock);
NSArray *animations = [(__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj) allValues];
CFDictionaryRemoveValue(_dict, (__bridge void *)obj);
// unlock
OSSpinLockUnlock(&_lock);
if (0 == animations.count) {
return;
}
NSHashTable *animationSet = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality capacity:animations.count];
for (id animation in animations) {
[animationSet addObject:animation];
}
// lock
OSSpinLockLock(&_lock);
POPAnimatorItemRef item;
for (auto iter = _list.begin(); iter != _list.end();) {
item = *iter;
if(![animationSet containsObject:item->animation]) {
iter++;
} else {
iter = _list.erase(iter);
}
}
// unlock
OSSpinLockUnlock(&_lock);
for (POPAnimation *anim in animations) {
POPAnimationState *state = POPAnimationGetState(anim);
state->stop(true, !state->active);
}
}
- (void)removeAnimationForObject:(id)obj key:(NSString *)key cleanupDict:(BOOL)cleanupDict
{
POPAnimation *anim = deleteDictEntry(self, obj, key, cleanupDict);
if (nil == anim) {
return;
}
// lock
OSSpinLockLock(&_lock);
// remove from list
POPAnimatorItemRef item;
for (auto iter = _list.begin(); iter != _list.end();) {
item = *iter;
if(anim == item->animation) {
_list.erase(iter);
break;
} else {
iter++;
}
}
// remove from pending list
for (auto iter = _pendingList.begin(); iter != _pendingList.end();) {
item = *iter;
if(anim == item->animation) {
_pendingList.erase(iter);
break;
} else {
iter++;
}
}
// unlock
OSSpinLockUnlock(&_lock);
// stop animation and callout
POPAnimationState *state = POPAnimationGetState(anim);
state->stop(true, (!state->active && !state->paused));
}
- (void)removeAnimationForObject:(id)obj key:(NSString *)key
{
[self removeAnimationForObject:obj key:key cleanupDict:YES];
}
- (NSArray *)animationKeysForObject:(id)obj
{
// lock
OSSpinLockLock(&_lock);
// get keys
NSArray *keys = [(__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj) allKeys];
// unlock
OSSpinLockUnlock(&_lock);
return keys;
}
- (id)animationForObject:(id)obj key:(NSString *)key
{
// lock
OSSpinLockLock(&_lock);
// lookup animation
NSDictionary *keyAnimationsDict = (__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj);
POPAnimation *animation = keyAnimationsDict[key];
// unlock
OSSpinLockUnlock(&_lock);
return animation;
}
- (CFTimeInterval)_currentRenderTime
{
CFTimeInterval time = CACurrentMediaTime();
#if TARGET_IPHONE_SIMULATOR
// support slow-motion animations
time += _slowMotionAccumulator;
float f = POPAnimationDragCoefficient();
if (f > 1.0) {
if (!_slowMotionStartTime) {
_slowMotionStartTime = time;
} else {
time = (time - _slowMotionStartTime) / f + _slowMotionStartTime;
_slowMotionLastTime = time;
}
} else if (_slowMotionStartTime) {
CFTimeInterval dt = (_slowMotionLastTime - time);
time += dt;
_slowMotionAccumulator += dt;
_slowMotionStartTime = 0;
}
#endif
return time;
}
- (void)render
{
CFTimeInterval time = [self _currentRenderTime];
[self renderTime:time];
}
- (void)renderTime:(CFTimeInterval)time
{
[self _renderTime:time items:_list];
}
- (void)addObserver:(id<POPAnimatorObserving>)observer
{
NSAssert(nil != observer, @"attempting to add nil %@ observer", self);
if (nil == observer) {
return;
}
// lock
OSSpinLockLock(&_lock);
if (!_observers) {
// use ordered collection for deterministic callout
_observers = [[NSMutableArray alloc] initWithCapacity:1];
}
[_observers addObject:observer];
updateDisplayLink(self);
// unlock
OSSpinLockUnlock(&_lock);
}
- (void)removeObserver:(id<POPAnimatorObserving>)observer
{
NSAssert(nil != observer, @"attempting to remove nil %@ observer", self);
if (nil == observer) {
return;
}
// lock
OSSpinLockLock(&_lock);
[_observers removeObject:observer];
updateDisplayLink(self);
// unlock
OSSpinLockUnlock(&_lock);
}
@end