-
Notifications
You must be signed in to change notification settings - Fork 944
/
MDCActivityIndicator.m
1011 lines (834 loc) · 32 KB
/
MDCActivityIndicator.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 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "MDCActivityIndicator.h"
#import <QuartzCore/QuartzCore.h>
#import <MDFInternationalization/MDFInternationalization.h>
#import <MotionAnimator/MotionAnimator.h>
#import "MaterialApplication.h"
#import "MaterialPalettes.h"
#import "private/MDCActivityIndicatorMotionSpec.h"
#import "private/MDCActivityIndicator+Private.h"
#import "private/MaterialActivityIndicatorStrings.h"
#import "private/MaterialActivityIndicatorStrings_table.h"
static const NSInteger kTotalDetentCount = 5;
static const NSTimeInterval kAnimateOutDuration = 0.1f;
static const CGFloat kCycleRotation = 3.0f / 2.0f;
static const CGFloat kOuterRotationIncrement =
(1.0f / kTotalDetentCount) * (CGFloat)M_PI;
static const CGFloat kSpinnerRadius = 12.f;
static const CGFloat kStrokeLength = 0.75f;
#ifndef CGFLOAT_EPSILON
#if CGFLOAT_IS_DOUBLE
#define CGFLOAT_EPSILON DBL_EPSILON
#else
#define CGFLOAT_EPSILON FLT_EPSILON
#endif
#endif
// The Bundle for string resources.
static NSString *const kBundle = @"MaterialActivityIndicator.bundle";
/**
Total rotation (outer rotation + stroke rotation) per _cycleCount. One turn is 2.0f.
*/
static const CGFloat kSingleCycleRotation =
2 * kStrokeLength + kCycleRotation + 1.0f / kTotalDetentCount;
@interface MDCActivityIndicator ()
/**
The minimum stroke difference to use when collapsing the stroke to a dot. Based on current
radius and stroke width.
*/
@property(nonatomic, assign, readonly) CGFloat minStrokeDifference;
/**
The index of the current stroke color in the @c cycleColors array.
@note Subclasses can change this value to start the spinner at a different color.
*/
@property(nonatomic, assign) NSUInteger cycleColorsIndex;
/**
The current cycle count.
*/
@property(nonatomic, assign, readonly) NSInteger cycleCount;
/**
The cycle index at which to start the activity spinner animation. Default is 0, which corresponds
to the top of the spinner (12 o'clock position). Spinner cycle indices are based on a 5-point
star.
*/
@property(nonatomic, assign) NSInteger cycleStartIndex;
/**
The outer layer that handles cycle rotations and houses the stroke layer.
*/
@property(nonatomic, strong, readonly, nullable) CALayer *outerRotationLayer;
/**
The shape layer that handles the animating stroke.
*/
@property(nonatomic, strong, readonly, nullable) CAShapeLayer *strokeLayer;
/**
The shape layer that shows a faint, circular track along the path of the stroke layer. Enabled
via the trackEnabled property.
*/
@property(nonatomic, strong, readonly, nullable) CAShapeLayer *trackLayer;
/**
The currently queued stop transition, which will be run as soon as the current animation cycle
completes. At all other times should be nil.
*/
@property(nonatomic, strong, nullable) MDCActivityIndicatorTransition *stopTransition;
@end
@implementation MDCActivityIndicator {
BOOL _animatingOut;
BOOL _animationsAdded;
BOOL _animationInProgress;
BOOL _backgrounded;
BOOL _cycleInProgress;
CGFloat _currentProgress;
CGFloat _lastProgress;
MDMMotionAnimator *_animator;
}
#pragma mark - Init
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commonMDCActivityIndicatorInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self commonMDCActivityIndicatorInit];
// TODO: Overwrite cycleColors if the value is present in the coder
// https://github.com/material-components/material-components-ios/issues/1530
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self applyPropertiesWithoutAnimation:^{
// Resize and recenter rotation layer.
_outerRotationLayer.bounds = self.bounds;
_outerRotationLayer.position =
CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_strokeLayer.bounds = _outerRotationLayer.bounds;
_strokeLayer.position = _outerRotationLayer.position;
[self updateStrokePath];
}];
}
- (void)commonMDCActivityIndicatorInit {
// Register notifications for foreground and background if needed.
[self registerForegroundAndBackgroundNotificationObserversIfNeeded];
// The activity indicator reflects the passage of time (a spatial semantic context) and so
// will not be mirrored in RTL languages.
self.mdf_semanticContentAttribute = UISemanticContentAttributeSpatial;
_animator = [[MDMMotionAnimator alloc] init];
_animator.additive = NO;
_cycleStartIndex = 0;
_indicatorMode = MDCActivityIndicatorModeIndeterminate;
// Property defaults.
_radius = kSpinnerRadius;
_strokeWidth = 2.0f;
// Colors.
_cycleColorsIndex = 0;
_cycleColors = [MDCActivityIndicator defaultCycleColors];
// Track layer.
_trackLayer = [CAShapeLayer layer];
_trackLayer.lineWidth = _strokeWidth;
_trackLayer.fillColor = [UIColor clearColor].CGColor;
[self.layer addSublayer:_trackLayer];
_trackLayer.hidden = YES;
// Rotation layer.
_outerRotationLayer = [CALayer layer];
[self.layer addSublayer:_outerRotationLayer];
// Stroke layer.
_strokeLayer = [CAShapeLayer layer];
_strokeLayer.lineWidth = _strokeWidth;
_strokeLayer.fillColor = [UIColor clearColor].CGColor;
_strokeLayer.strokeStart = 0;
_strokeLayer.strokeEnd = 0;
[_outerRotationLayer addSublayer:_strokeLayer];
}
#pragma mark - UIView
- (void)willMoveToWindow:(UIWindow *)newWindow {
// If the activity indicator is removed from the window, we should
// immediately stop animating, otherwise it will start chewing up CPU.
if (!newWindow) {
[self actuallyStopAnimating];
} else if (_animating && !_backgrounded) {
[self actuallyStartAnimating];
}
}
- (CGSize)intrinsicContentSize {
CGFloat edge = 2 * _radius + _strokeWidth;
return CGSizeMake(edge, edge);
}
- (CGSize)sizeThatFits:(__unused CGSize)size {
CGFloat edge = 2 * _radius + _strokeWidth;
return CGSizeMake(edge, edge);
}
#pragma mark - Public methods
- (void)startAnimating {
if (_animatingOut) {
if ([_delegate respondsToSelector:@selector(activityIndicatorAnimationDidFinish:)]) {
[_delegate activityIndicatorAnimationDidFinish:self];
}
[self removeAnimations];
}
if (_animating) {
return;
}
_animating = YES;
if (!self.window || _backgrounded) {
return;
}
[self actuallyStartAnimating];
}
- (void)startAnimatingWithTransition:(nonnull MDCActivityIndicatorTransition *)startTransition
cycleStartIndex:(NSInteger)cycleStartIndex {
if (_animating) {
return;
}
BOOL indeterminate = self.indicatorMode == MDCActivityIndicatorModeIndeterminate;
NSAssert(indeterminate, @"startAnimatingWithStartAnimation requires an indeterminate mode.");
if (!indeterminate) {
return;
}
if (_animatingOut) {
if ([_delegate respondsToSelector:@selector(activityIndicatorAnimationDidFinish:)]) {
[_delegate activityIndicatorAnimationDidFinish:self];
}
[self removeAnimations];
}
_animating = YES;
if (!self.window || _backgrounded) {
return;
}
_cycleStartIndex = cycleStartIndex;
_cycleCount = _cycleStartIndex;
_animationInProgress = YES;
[CATransaction begin];
{
[CATransaction setCompletionBlock:^{
_animationInProgress = NO;
[self actuallyStartAnimating];
_cycleColorsIndex = self.cycleColors.count > 0 ? cycleStartIndex % self.cycleColors.count : 0;
[self applyPropertiesWithoutAnimation:^{
[self updateStrokeColor];
}];
if (startTransition.completion) {
startTransition.completion();
}
}];
[CATransaction setAnimationDuration:startTransition.duration];
[CATransaction setDisableActions:YES];
CGFloat outerRotation = kOuterRotationIncrement * _cycleStartIndex;
CGFloat innerRotation = _cycleStartIndex * (CGFloat)M_PI;
CGFloat strokeStart =
(CGFloat)fmod(innerRotation + outerRotation, 2 * M_PI) / (CGFloat)(2 * M_PI);
CGFloat strokeEnd = _minStrokeDifference + strokeStart;
strokeEnd = strokeEnd > 1 ? strokeEnd - 1 : strokeEnd;
startTransition.animation(strokeStart, strokeEnd);
}
[CATransaction commit];
}
- (void)stopAnimating {
if (!_animating) {
return;
}
_animating = NO;
[self animateOut];
}
- (void)stopAnimatingWithTransition:(MDCActivityIndicatorTransition *)stopTransition {
if (!_animating) {
return;
}
BOOL indeterminate = self.indicatorMode == MDCActivityIndicatorModeIndeterminate;
NSAssert(indeterminate, @"stopAnimationWithTransition requires an indeterminate mode.");
if (!indeterminate) {
return;
}
_animating = NO;
_animatingOut = YES;
self.stopTransition = stopTransition;
}
- (void)stopAnimatingImmediately {
if (!_animating) {
return;
}
_animating = NO;
[self actuallyStopAnimating];
if ([_delegate respondsToSelector:@selector(activityIndicatorAnimationDidFinish:)]) {
[_delegate activityIndicatorAnimationDidFinish:self];
}
}
- (void)resetStrokeColor {
_cycleColorsIndex = 0;
[self updateStrokeColor];
}
- (void)setStrokeColor:(UIColor *)strokeColor {
_strokeLayer.strokeColor = strokeColor.CGColor;
_trackLayer.strokeColor = [strokeColor colorWithAlphaComponent:0.3f].CGColor;
}
- (void)setIndicatorMode:(MDCActivityIndicatorMode)indicatorMode {
if (_indicatorMode == indicatorMode) {
return;
}
_indicatorMode = indicatorMode;
if (_animating && !_animationInProgress) {
switch (indicatorMode) {
case MDCActivityIndicatorModeDeterminate:
[self addTransitionToDeterminateCycle];
break;
case MDCActivityIndicatorModeIndeterminate:
[self addTransitionToIndeterminateCycle];
break;
}
} else if (!_animating) {
if ([_delegate respondsToSelector:@selector(activityIndicatorModeTransitionDidFinish:)]) {
[_delegate activityIndicatorModeTransitionDidFinish:self];
}
}
}
- (void)setIndicatorMode:(MDCActivityIndicatorMode)mode animated:(__unused BOOL)animated {
[self setIndicatorMode:mode];
}
- (void)setProgress:(float)progress {
_progress = MAX(0.0f, MIN(progress, 1.0f));
if (_progress == _currentProgress) {
return;
}
if (_animating && !_animationInProgress) {
switch (_indicatorMode) {
case MDCActivityIndicatorModeDeterminate:
// Currently animating the determinate mode but no animation queued.
[self addProgressAnimation];
break;
case MDCActivityIndicatorModeIndeterminate:
break;
}
}
}
#pragma mark - Properties
- (void)setStrokeWidth:(CGFloat)strokeWidth {
_strokeWidth = strokeWidth;
_strokeLayer.lineWidth = _strokeWidth;
_trackLayer.lineWidth = _strokeWidth;
[self updateStrokePath];
}
- (void)setRadius:(CGFloat)radius {
_radius = MIN(MAX(radius, 5.0f), 72.0f);
[self updateStrokePath];
}
- (void)setTrackEnabled:(BOOL)trackEnabled {
_trackEnabled = trackEnabled;
_trackLayer.hidden = !_trackEnabled;
}
#pragma mark - Private methods
/**
If this class is not being run in an extension, register for foreground changes and initialize
the app background state in case UI is created when the app is backgrounded. (Extensions always
return UIApplicationStateBackground for |[UIApplication sharedApplication].applicationState|.)
*/
- (void)registerForegroundAndBackgroundNotificationObserversIfNeeded {
if ([UIApplication mdc_isAppExtension]) {
return;
}
_backgrounded =
[UIApplication mdc_safeSharedApplication].applicationState == UIApplicationStateBackground;
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(controlAnimatingOnForegroundChange:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[notificationCenter addObserver:self
selector:@selector(controlAnimatingOnForegroundChange:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
- (void)controlAnimatingOnForegroundChange:(NSNotification *)notification {
// Stop or restart animating if the app has a foreground change.
_backgrounded = [notification.name isEqualToString:UIApplicationDidEnterBackgroundNotification];
if (_animating) {
if (_backgrounded) {
[self actuallyStopAnimating];
} else if (self.window) {
[self actuallyStartAnimating];
}
}
}
- (void)actuallyStartAnimating {
if (_animationsAdded) {
return;
}
_animationsAdded = YES;
_cycleCount = _cycleStartIndex;
[self applyPropertiesWithoutAnimation:^{
_strokeLayer.strokeStart = 0.0f;
_strokeLayer.strokeEnd = 0.001f;
_strokeLayer.lineWidth = _strokeWidth;
_trackLayer.lineWidth = _strokeWidth;
[self resetStrokeColor];
[self updateStrokePath];
}];
switch (_indicatorMode) {
case MDCActivityIndicatorModeIndeterminate:
[self addStrokeRotationCycle];
break;
case MDCActivityIndicatorModeDeterminate:
[self addProgressAnimation];
break;
}
}
- (void)actuallyStopAnimating {
if (!_animationsAdded) {
return;
}
[self removeAnimations];
[self applyPropertiesWithoutAnimation:^{
_strokeLayer.strokeStart = 0.0f;
_strokeLayer.strokeEnd = 0.0f;
}];
}
- (void)setCycleColors:(NSArray<UIColor *> *)cycleColors {
if (cycleColors.count) {
_cycleColors = [cycleColors copy];
} else {
_cycleColors = [MDCActivityIndicator defaultCycleColors];
}
if (self.cycleColors.count) {
[self setStrokeColor:self.cycleColors[0]];
}
}
- (void)addStopAnimation {
MDCActivityIndicatorTransition *stopTransition = self.stopTransition;
CGFloat innerRotation =
[[_strokeLayer valueForKeyPath:MDMKeyPathRotation] floatValue];
CGFloat outerRotation =
[[_outerRotationLayer valueForKeyPath:MDMKeyPathRotation] floatValue];
CGFloat totalRotation =
(CGFloat)fmod(innerRotation + outerRotation, 2 * M_PI) / (CGFloat)(2 * M_PI);
CGFloat strokeStart = _strokeLayer.strokeStart + totalRotation;
strokeStart = strokeStart > 1 ? strokeStart - 1 : strokeStart;
CGFloat strokeEnd = _strokeLayer.strokeEnd + totalRotation;
strokeEnd = strokeEnd > 1 ? strokeEnd - 1 : strokeEnd;
[self applyPropertiesWithoutAnimation:^{
_strokeLayer.strokeStart = 0.0f;
_strokeLayer.strokeEnd = 0.0f;
}];
[CATransaction begin];
{
[CATransaction setCompletionBlock:^{
if (stopTransition.completion) {
stopTransition.completion();
}
if (stopTransition == self.stopTransition) {
if ([_delegate respondsToSelector:@selector(activityIndicatorAnimationDidFinish:)]) {
[_delegate activityIndicatorAnimationDidFinish:self];
}
[self removeAnimations];
}
}];
[CATransaction setAnimationDuration:stopTransition.duration];
[CATransaction setDisableActions:YES];
stopTransition.animation(strokeStart, strokeEnd);
}
[CATransaction commit];
}
- (void)updateStrokePath {
CGFloat offsetRadius = _radius - _strokeLayer.lineWidth / 2.0f;
UIBezierPath *strokePath = [UIBezierPath bezierPathWithArcCenter:_strokeLayer.position
radius:offsetRadius
startAngle:-1.0f * (CGFloat)M_PI_2
endAngle:3.0f * (CGFloat)M_PI_2
clockwise:YES];
_strokeLayer.path = strokePath.CGPath;
_trackLayer.path = strokePath.CGPath;
_minStrokeDifference = _strokeLayer.lineWidth / ((CGFloat)M_PI * 2 * _radius);
}
- (void)updateStrokeColor {
if (self.cycleColors.count > 0 && self.cycleColors.count > self.cycleColorsIndex) {
[self setStrokeColor:self.cycleColors[self.cycleColorsIndex]];
} else {
NSAssert(NO, @"cycleColorsIndex is outside the bounds of cycleColors.");
[self setStrokeColor:[[MDCActivityIndicator defaultCycleColors] firstObject]];
}
}
- (void)addStrokeRotationCycle {
if (_animationInProgress) {
return;
}
[CATransaction begin];
[CATransaction setCompletionBlock:^{
[self strokeRotationCycleFinishedFromState:MDCActivityIndicatorStateIndeterminate];
}];
MDCActivityIndicatorMotionSpecIndeterminate timing =
MDCActivityIndicatorMotionSpec.loopIndeterminate;
// These values may be equal if we've never received a progress. In this case we don't want our
// duration to become zero.
if (fabs(_lastProgress - _currentProgress) > CGFLOAT_EPSILON) {
timing.strokeEnd.duration *= ABS(_lastProgress - _currentProgress);
}
[_animator animateWithTiming:timing.outerRotation
toLayer:_outerRotationLayer
withValues:@[@(kOuterRotationIncrement * _cycleCount),
@(kOuterRotationIncrement * (_cycleCount + 1))]
keyPath:MDMKeyPathRotation];
CGFloat startRotation = _cycleCount * (CGFloat)M_PI;
CGFloat endRotation = startRotation + kCycleRotation * (CGFloat)M_PI;
[_animator animateWithTiming:timing.innerRotation
toLayer:_strokeLayer
withValues:@[@(startRotation), @(endRotation)]
keyPath:MDMKeyPathRotation];
[_animator animateWithTiming:timing.strokeStart
toLayer:_strokeLayer
withValues:@[@0, @(kStrokeLength)]
keyPath:MDMKeyPathStrokeStart];
// Ensure the stroke never completely disappears on start by animating from non-zero start and
// to a value slightly larger than the strokeStart's final value.
[_animator animateWithTiming:timing.strokeEnd
toLayer:_strokeLayer
withValues:@[@(_minStrokeDifference), @(kStrokeLength + _minStrokeDifference)]
keyPath:MDMKeyPathStrokeEnd];
[CATransaction commit];
_animationInProgress = YES;
}
- (void)addTransitionToIndeterminateCycle {
if (_animationInProgress) {
return;
}
// Find the nearest cycle to transition through.
NSInteger nearestCycle = 0;
CGFloat nearestDistance = CGFLOAT_MAX;
const CGFloat normalizedProgress = MAX(_lastProgress - _minStrokeDifference, 0.0f);
for (NSInteger cycle = 0; cycle < kTotalDetentCount; cycle++) {
const CGFloat currentRotation = [self normalizedRotationForCycle:cycle];
if (currentRotation >= normalizedProgress) {
if (nearestDistance >= (currentRotation - normalizedProgress)) {
nearestDistance = currentRotation - normalizedProgress;
nearestCycle = cycle;
}
}
}
if (nearestCycle == 0 && _lastProgress <= _minStrokeDifference) {
// Special case for 0% progress.
_cycleCount = nearestCycle;
[self strokeRotationCycleFinishedFromState:MDCActivityIndicatorStateTransitionToIndeterminate];
if ([_delegate respondsToSelector:@selector(activityIndicatorModeTransitionDidFinish:)]) {
[_delegate activityIndicatorModeTransitionDidFinish:self];
}
return;
}
_cycleCount = nearestCycle;
CGFloat targetRotation = [self normalizedRotationForCycle:nearestCycle];
if (targetRotation <= 0.001f) {
targetRotation = 1.0f;
}
CGFloat pointCycleDuration = (CGFloat)MDCActivityIndicatorMotionSpec.pointCycleDuration;
CGFloat pointCycleMinimumVariableDuration =
(CGFloat)MDCActivityIndicatorMotionSpec.pointCycleMinimumVariableDuration;
CGFloat normalizedDuration = 2 * (targetRotation + _currentProgress) / kSingleCycleRotation *
pointCycleDuration;
CGFloat strokeEndTravelDistance = targetRotation - _currentProgress + _minStrokeDifference;
CGFloat totalDistance = targetRotation + strokeEndTravelDistance;
CGFloat strokeStartDuration =
MAX(normalizedDuration * targetRotation / totalDistance, pointCycleMinimumVariableDuration);
CGFloat strokeEndDuration = MAX(normalizedDuration * strokeEndTravelDistance / totalDistance,
pointCycleMinimumVariableDuration);
[CATransaction begin];
{
[CATransaction setCompletionBlock:^{
[self
strokeRotationCycleFinishedFromState:MDCActivityIndicatorStateTransitionToIndeterminate];
if ([_delegate respondsToSelector:@selector(activityIndicatorModeTransitionDidFinish:)]) {
[_delegate activityIndicatorModeTransitionDidFinish:self];
}
}];
[CATransaction setDisableActions:YES];
MDCActivityIndicatorMotionSpecTransitionToIndeterminate timing =
MDCActivityIndicatorMotionSpec.willChangeToIndeterminate;
_outerRotationLayer.transform = CATransform3DIdentity;
_strokeLayer.transform = CATransform3DIdentity;
timing.strokeStart.duration = strokeStartDuration;
timing.strokeStart.delay = strokeEndDuration;
[_animator animateWithTiming:timing.strokeStart
toLayer:_strokeLayer
withValues:@[@0, @(targetRotation)]
keyPath:MDMKeyPathStrokeStart];
timing.strokeEnd.duration = strokeEndDuration;
timing.strokeEnd.delay = 0;
[_animator animateWithTiming:timing.strokeEnd
toLayer:_strokeLayer
withValues:@[@(_currentProgress), @(targetRotation + _minStrokeDifference)]
keyPath:MDMKeyPathStrokeEnd];
}
[CATransaction commit];
_animationInProgress = YES;
}
- (void)addTransitionToDeterminateCycle {
if (_animationInProgress) {
return;
}
if (!_cycleCount) {
// The animation period is complete: no need for transition.
[_strokeLayer removeAllAnimations];
[_outerRotationLayer removeAllAnimations];
// Necessary for transition from indeterminate to determinate when cycle == 0.
_currentProgress = 0.0f;
_lastProgress = _currentProgress;
[self strokeRotationCycleFinishedFromState:MDCActivityIndicatorStateTransitionToDeterminate];
if ([_delegate respondsToSelector:@selector(activityIndicatorModeTransitionDidFinish:)]) {
[_delegate activityIndicatorModeTransitionDidFinish:self];
}
} else {
_currentProgress = MAX(_progress, _minStrokeDifference);
CGFloat rotationDelta = 1.0f - [self normalizedRotationForCycle:_cycleCount];
// Change the duration relative to the distance in order to keep same relative speed.
CGFloat pointCycleDuration = (CGFloat)MDCActivityIndicatorMotionSpec.pointCycleDuration;
CGFloat pointCycleMinimumVariableDuration =
(CGFloat)MDCActivityIndicatorMotionSpec.pointCycleMinimumVariableDuration;
CGFloat duration = 2.0f * (rotationDelta + _currentProgress) / kSingleCycleRotation *
pointCycleDuration;
duration = MAX(duration, pointCycleMinimumVariableDuration);
[CATransaction begin];
{
[CATransaction setCompletionBlock:^{
[self
strokeRotationCycleFinishedFromState:MDCActivityIndicatorStateTransitionToDeterminate];
if ([_delegate respondsToSelector:@selector(activityIndicatorModeTransitionDidFinish:)]) {
[_delegate activityIndicatorModeTransitionDidFinish:self];
}
}];
[CATransaction setDisableActions:YES];
[CATransaction mdm_setTimeScaleFactor:@(duration)];
MDCActivityIndicatorMotionSpecTransitionToDeterminate spec =
MDCActivityIndicatorMotionSpec.willChangeToDeterminate;
_outerRotationLayer.transform =
CATransform3DMakeRotation(kOuterRotationIncrement * _cycleCount, 0, 0, 1);
CGFloat startRotation = _cycleCount * (CGFloat)M_PI;
CGFloat endRotation = startRotation + rotationDelta * 2.0f * (CGFloat)M_PI;
[_animator animateWithTiming:spec.innerRotation
toLayer:_strokeLayer
withValues:@[@(startRotation), @(endRotation)]
keyPath:MDMKeyPathRotation];
_strokeLayer.strokeStart = 0;
[_animator animateWithTiming:spec.strokeEnd
toLayer:_strokeLayer
withValues:@[@(_minStrokeDifference), @(_currentProgress)]
keyPath:MDMKeyPathStrokeEnd];
}
[CATransaction commit];
_animationInProgress = YES;
_lastProgress = _currentProgress;
}
}
- (void)addProgressAnimation {
if (_animationInProgress) {
return;
}
_currentProgress = MAX(_progress, _minStrokeDifference);
[CATransaction begin];
{
[CATransaction setCompletionBlock:^{
[self strokeRotationCycleFinishedFromState:MDCActivityIndicatorStateDeterminate];
}];
[CATransaction setDisableActions:YES];
_outerRotationLayer.transform = CATransform3DIdentity;
_strokeLayer.transform = CATransform3DIdentity;
_strokeLayer.strokeStart = 0;
[_animator animateWithTiming:MDCActivityIndicatorMotionSpec.willChangeProgress.strokeEnd
toLayer:_strokeLayer
withValues:@[@(_lastProgress), @(_currentProgress)]
keyPath:MDMKeyPathStrokeEnd];
}
[CATransaction commit];
_lastProgress = _currentProgress;
_animationInProgress = YES;
}
- (void)strokeRotationCycleFinishedFromState:(MDCActivityIndicatorState)state {
_animationInProgress = NO;
if (!_animationsAdded) {
return;
}
if (self.stopTransition) {
[self addStopAnimation];
return;
}
if (state == MDCActivityIndicatorStateIndeterminate) {
if (self.cycleColors.count > 0) {
self.cycleColorsIndex = (self.cycleColorsIndex + 1) % self.cycleColors.count;
[self updateStrokeColor];
}
_cycleCount = (_cycleCount + 1) % kTotalDetentCount;
}
switch (_indicatorMode) {
case MDCActivityIndicatorModeDeterminate:
switch (state) {
case MDCActivityIndicatorStateDeterminate:
case MDCActivityIndicatorStateTransitionToDeterminate:
[self addProgressAnimationIfRequired];
break;
case MDCActivityIndicatorStateIndeterminate:
case MDCActivityIndicatorStateTransitionToIndeterminate:
[self addTransitionToDeterminateCycle];
break;
}
break;
case MDCActivityIndicatorModeIndeterminate:
switch (state) {
case MDCActivityIndicatorStateDeterminate:
case MDCActivityIndicatorStateTransitionToDeterminate:
[self addTransitionToIndeterminateCycle];
break;
case MDCActivityIndicatorStateIndeterminate:
case MDCActivityIndicatorStateTransitionToIndeterminate:
[self addStrokeRotationCycle];
break;
}
break;
}
}
- (void)addProgressAnimationIfRequired {
if (_indicatorMode == MDCActivityIndicatorModeDeterminate) {
if (MAX(_progress, _minStrokeDifference) != _currentProgress) {
// The values were changes in the while animating or animation is starting.
[self addProgressAnimation];
}
}
}
/**
Rotation that a given cycle has. Represented between 0.0f (cycle has no rotation) and 1.0f.
*/
- (CGFloat)normalizedRotationForCycle:(NSInteger)cycle {
CGFloat cycleRotation = cycle * kSingleCycleRotation / 2.0f;
return cycleRotation - ((NSInteger)cycleRotation);
}
- (void)animateOut {
_animatingOut = YES;
[CATransaction begin];
[CATransaction setCompletionBlock:^{
if (_animatingOut) {
[self removeAnimations];
if ([_delegate respondsToSelector:@selector(activityIndicatorAnimationDidFinish:)]) {
[_delegate activityIndicatorAnimationDidFinish:self];
}
}
}];
[CATransaction setAnimationDuration:kAnimateOutDuration];
_strokeLayer.lineWidth = 0;
_trackLayer.lineWidth = 0;
[CATransaction commit];
}
- (void)removeAnimations {
_animationsAdded = NO;
_animatingOut = NO;
self.stopTransition = nil;
[_strokeLayer removeAllAnimations];
[_outerRotationLayer removeAllAnimations];
// Reset current and latest progress, to ensure addProgressAnimationIfRequired adds a progress animation
// when returning from hidden.
_currentProgress = 0;
_lastProgress = 0;
// Reset cycle count to 0 rather than cycleStart to reflect default starting position (top).
_cycleCount = 0;
// However _animationInProgress represents the CATransaction that hasn't finished, so we leave it
// alone here.
}
+ (CGFloat)defaultHeight {
return kSpinnerRadius * 2.f;
}
+ (NSArray<UIColor *> *)defaultCycleColors {
static NSArray<UIColor *> *s_defaultCycleColors;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
s_defaultCycleColors =
@[ MDCPalette.bluePalette.tint500,
MDCPalette.redPalette.tint500,
MDCPalette.yellowPalette.tint500,
MDCPalette.greenPalette.tint500 ];
});
return s_defaultCycleColors;
}
- (void)applyPropertiesWithoutAnimation:(void (^)(void))setPropBlock {
[CATransaction begin];
// Disable implicit CALayer animations
[CATransaction setDisableActions:YES];
setPropBlock();
[CATransaction commit];
}
#pragma mark - Resource Bundle
+ (NSBundle *)bundle {
static NSBundle *bundle = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
bundle = [NSBundle bundleWithPath:[self bundlePathWithName:kBundle]];
});
return bundle;
}
+ (NSString *)bundlePathWithName:(NSString *)bundleName {
// In iOS 8+, we could be included by way of a dynamic framework, and our resource bundles may
// not be in the main .app bundle, but rather in a nested framework, so figure out where we live
// and use that as the search location.
NSBundle *bundle = [NSBundle bundleForClass:[MDCActivityIndicator class]];
NSString *resourcePath = [(nil == bundle ? [NSBundle mainBundle] : bundle)resourcePath];
return [resourcePath stringByAppendingPathComponent:bundleName];
}
#pragma mark - Accessibility
- (BOOL)isAccessibilityElement {
return YES;
}
- (NSString *)accessibilityLabel {
if (self.isAnimating) {
if (self.indicatorMode == MDCActivityIndicatorModeIndeterminate) {
NSString *key =
kMaterialActivityIndicatorStringTable[kStr_MaterialActivityIndicatorInProgressAccessibilityLabel];
return NSLocalizedStringFromTableInBundle(key,
kMaterialActivityIndicatorStringsTableName,
[[self class] bundle],
@"In Progress");
} else {
NSUInteger percentage = (int)(self.progress * 100);
NSString *key =
kMaterialActivityIndicatorStringTable[kStr_MaterialActivityIndicatorProgressCompletedAccessibilityLabel];
NSString *localizedString = NSLocalizedStringFromTableInBundle(key,
kMaterialActivityIndicatorStringsTableName,
[[self class] bundle],
@"{percentage} Percent Complete");
return [NSString localizedStringWithFormat:localizedString, percentage];
}
} else {
NSString *key =
kMaterialActivityIndicatorStringTable[kStr_MaterialActivityIndicatorProgressHaltedAccessibilityLabel];
return NSLocalizedStringFromTableInBundle(key,
kMaterialActivityIndicatorStringsTableName,
[[self class] bundle],
@"Progress Halted");
}
}
- (UIAccessibilityTraits)accessibilityTraits {
return UIAccessibilityTraitUpdatesFrequently;
}
- (NSString *)accessibilityValue {
if (self.isAnimating) {
return [NSNumberFormatter localizedStringFromNumber:@1 numberStyle:NSNumberFormatterNoStyle];
} else {
return [NSNumberFormatter localizedStringFromNumber:@0 numberStyle:NSNumberFormatterNoStyle];
}
}