-
Notifications
You must be signed in to change notification settings - Fork 2
/
AnimationSet.cs
642 lines (550 loc) · 22.5 KB
/
AnimationSet.cs
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
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Xaml.Media.Animation;
namespace Microsoft.Toolkit.Uwp.UI.Animations
{
/// <summary>
/// Defines an object for storing and managing CompositionAnimations for an element
/// </summary>
public class AnimationSet : IDisposable
{
private List<AnimationSet> _animationSets;
private Compositor _compositor;
private CompositionScopedBatch _batch;
private Dictionary<string, CompositionAnimation> _compositionAnimations;
private List<EffectAnimationDefinition> _compositionEffectAnimations;
private Dictionary<string, object> _directCompositionPropertyChanges;
private List<EffectDirectPropertyChangeDefinition> _directCompositionEffectPropertyChanges;
private Storyboard _storyboard;
private Dictionary<string, Timeline> _storyboardAnimations;
private List<AnimationTask> _animationTasks;
private TaskCompletionSource<bool> _animationTCS;
private bool _storyboardCompleted;
private bool _compositionCompleted;
/// <summary>
/// Gets or sets a value indicating whether composition must be use even on SDK > 10586
/// </summary>
public static bool UseComposition { get; set; }
/// <summary>
/// Gets the <see cref="Visual"/> object that backs the XAML element
/// </summary>
public Visual Visual { get; private set; }
/// <summary>
/// Gets the <see cref="UIElement"/>
/// </summary>
public UIElement Element { get; private set; }
/// <summary>
/// Gets the current state of the AnimationSet
/// </summary>
public AnimationSetState State { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="AnimationSet"/> class.
/// </summary>
/// <param name="element">The associated element</param>
public AnimationSet(UIElement element)
{
if (element == null)
{
throw new NullReferenceException("Element must not be null");
}
var visual = ElementCompositionPreview.GetElementVisual(element);
if (visual == null)
{
throw new NullReferenceException("Visual must not be null");
}
Visual = visual;
if (Visual.Compositor == null)
{
throw new NullReferenceException("Visual must have a compositor");
}
Element = element;
State = AnimationSetState.NotStarted;
_compositor = Visual.Compositor;
_compositionAnimations = new Dictionary<string, CompositionAnimation>();
_compositionEffectAnimations = new List<EffectAnimationDefinition>();
_directCompositionPropertyChanges = new Dictionary<string, object>();
_directCompositionEffectPropertyChanges = new List<EffectDirectPropertyChangeDefinition>();
_animationSets = new List<AnimationSet>();
_storyboard = new Storyboard();
_storyboardAnimations = new Dictionary<string, Timeline>();
_animationTasks = new List<AnimationTask>();
}
/// <summary>
/// Occurs when all animations have completed
/// </summary>
public event EventHandler<AnimationSetCompletedEventArgs> Completed;
/// <summary>
/// Stats all animations. This method is not awaitable.
/// </summary>
public async void Start()
{
await StartAsync();
}
/// <summary>
/// Starts all animations and returns an awaitable task.
/// </summary>
/// <returns>A <see cref="Task"/> that can be awaited until all animations have completed</returns>
public async Task<bool> StartAsync()
{
if (_animationTCS == null || _animationTCS.Task.IsCompleted)
{
if (_animationTCS != null && _animationTCS.Task.IsCompleted)
{
foreach (var set in _animationSets)
{
set.State = AnimationSetState.NotStarted;
set._animationTCS = null;
}
}
State = AnimationSetState.Running;
_animationTCS = new TaskCompletionSource<bool>();
}
else
{
return await _animationTCS.Task;
}
foreach (var set in _animationSets)
{
if (set.State != AnimationSetState.Completed)
{
var completed = await set.StartAsync();
if (!completed)
{
// the animation was stopped
return await _animationTCS.Task;
}
}
}
foreach (var task in _animationTasks)
{
if (task.Task != null && !task.Task.IsCompleted)
{
await task.Task;
}
// if _animationSet is stopped while task was running
if (State == AnimationSetState.Stopped)
{
return await _animationTCS.Task;
}
}
_animationTasks.Clear();
foreach (var property in _directCompositionPropertyChanges)
{
typeof(Visual).GetProperty(property.Key).SetValue(Visual, property.Value);
}
foreach (var definition in _directCompositionEffectPropertyChanges)
{
definition.EffectBrush.Properties.InsertScalar(definition.PropertyName, definition.Value);
}
if (_compositionAnimations.Count > 0 || _compositionEffectAnimations.Count > 0)
{
if (_batch != null)
{
if (!_batch.IsEnded)
{
_batch.End();
}
_batch.Completed -= Batch_Completed;
}
_batch = _compositor.CreateScopedBatch(CompositionBatchTypes.Animation);
_batch.Completed += Batch_Completed;
foreach (var anim in _compositionAnimations)
{
Visual.StartAnimation(anim.Key, anim.Value);
}
foreach (var effect in _compositionEffectAnimations)
{
effect.EffectBrush.StartAnimation(effect.PropertyName, effect.Animation);
}
_compositionCompleted = false;
_batch.End();
}
else
{
_compositionCompleted = true;
}
if (_storyboardAnimations.Count > 0)
{
_storyboardCompleted = false;
_storyboard.Completed -= Storyboard_Completed;
_storyboard.Completed += Storyboard_Completed;
_storyboard.Begin();
}
else
{
_storyboardCompleted = true;
}
HandleCompleted();
return await _animationTCS.Task;
}
/// <summary>
/// Stops all animations.
/// </summary>
public void Stop()
{
foreach (var set in _animationSets)
{
if (set.State != AnimationSetState.Completed)
{
set.Stop();
}
}
if (_batch != null)
{
if (!_batch.IsEnded)
{
_batch.End();
}
_batch.Completed -= Batch_Completed;
}
foreach (var anim in _compositionAnimations)
{
Visual.StopAnimation(anim.Key);
}
foreach (var effect in _compositionEffectAnimations)
{
effect.EffectBrush.StopAnimation(effect.PropertyName);
}
_storyboard.Pause();
HandleCompleted(true);
_animationTCS = null;
}
/// <summary>
/// Wait for existing animations to complete before running new animations
/// </summary>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet Then()
{
var savedAnimationSet = new AnimationSet(Element);
savedAnimationSet._compositionAnimations = _compositionAnimations;
savedAnimationSet._compositionEffectAnimations = _compositionEffectAnimations;
savedAnimationSet._directCompositionPropertyChanges = _directCompositionPropertyChanges;
savedAnimationSet._directCompositionEffectPropertyChanges = _directCompositionEffectPropertyChanges;
savedAnimationSet._storyboard = _storyboard;
savedAnimationSet._storyboardAnimations = _storyboardAnimations;
_animationTasks.ForEach(t => t.AnimationSet = savedAnimationSet);
savedAnimationSet._animationTasks = _animationTasks;
_animationSets.Add(savedAnimationSet);
_compositionAnimations = new Dictionary<string, CompositionAnimation>();
_compositionEffectAnimations = new List<EffectAnimationDefinition>();
_directCompositionPropertyChanges = new Dictionary<string, object>();
_directCompositionEffectPropertyChanges = new List<EffectDirectPropertyChangeDefinition>();
_storyboard = new Storyboard();
_storyboardAnimations = new Dictionary<string, Timeline>();
_animationTasks = new List<AnimationTask>();
return this;
}
/// <summary>
/// Ovewrites the duration on all animations after last Then()
/// to the specified value
/// </summary>
/// <param name="duration">The duration in milliseconds</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDuration(double duration)
{
if (duration <= 0)
{
duration = 1;
}
return SetDuration(TimeSpan.FromMilliseconds(duration));
}
/// <summary>
/// Ovewrites the duration on all animations after last Then()
/// to the specified value
/// </summary>
/// <param name="duration"><see cref="TimeSpan"/> for the duration</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDuration(TimeSpan duration)
{
foreach (var task in _animationTasks)
{
task.Duration = duration;
}
foreach (var anim in _compositionAnimations)
{
var animation = anim.Value as KeyFrameAnimation;
if (animation != null)
{
animation.Duration = duration;
}
}
foreach (var effect in _compositionEffectAnimations)
{
var animation = effect.Animation as KeyFrameAnimation;
if (animation != null)
{
animation.Duration = duration;
}
}
foreach (var timeline in _storyboardAnimations)
{
var animation = timeline.Value as DoubleAnimation;
if (animation != null)
{
animation.Duration = duration;
}
}
return this;
}
/// <summary>
/// Ovewrites the duration on all animations to the specified value
/// </summary>
/// <param name="duration">The duration in milliseconds</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDurationForAll(double duration)
{
foreach (var set in _animationSets)
{
set.SetDuration(duration);
}
return SetDuration(duration);
}
/// <summary>
/// Ovewrites the duration on all animations to the specified value
/// </summary>
/// <param name="duration"><see cref="TimeSpan"/> for the duration</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDurationForAll(TimeSpan duration)
{
foreach (var set in _animationSets)
{
set.SetDuration(duration);
}
return SetDuration(duration);
}
/// <summary>
/// Ovewrites the delay time on all animations after last Then()
/// to the specified value
/// </summary>
/// <param name="delayTime">The delay time in milliseconds</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDelay(double delayTime)
{
if (delayTime < 0)
{
delayTime = 0;
}
return SetDelay(TimeSpan.FromMilliseconds(delayTime));
}
/// <summary>
/// Ovewrites the delay time on all animations after last Then()
/// to the specified value
/// </summary>
/// <param name="delayTime"><see cref="TimeSpan"/> for how much to delay</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDelay(TimeSpan delayTime)
{
foreach (var task in _animationTasks)
{
task.Delay = delayTime;
}
foreach (var anim in _compositionAnimations)
{
var animation = anim.Value as KeyFrameAnimation;
if (animation != null)
{
animation.DelayTime = delayTime;
}
}
foreach (var effect in _compositionEffectAnimations)
{
var animation = effect.Animation as KeyFrameAnimation;
if (animation != null)
{
animation.DelayTime = delayTime;
}
}
foreach (var timeline in _storyboardAnimations)
{
var animation = timeline.Value as DoubleAnimation;
if (animation != null)
{
animation.BeginTime = delayTime;
}
}
return this;
}
/// <summary>
/// Ovewrites the delay time on all animations to the specified value
/// </summary>
/// <param name="delayTime">The delay time in milliseconds</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDelayForAll(double delayTime)
{
foreach (var set in _animationSets)
{
set.SetDelay(delayTime);
}
return SetDelay(delayTime);
}
/// <summary>
/// Ovewrites the delay time on all animations to the specified value
/// </summary>
/// <param name="delayTime"><see cref="TimeSpan"/> for how much to delay</param>
/// <returns>AnimationSet to allow chaining</returns>
public AnimationSet SetDelayForAll(TimeSpan delayTime)
{
foreach (var set in _animationSets)
{
set.SetDelay(delayTime);
}
return SetDelay(delayTime);
}
/// <summary>
/// Adds a composition animation to be run on <see cref="StartAsync"/>
/// </summary>
/// <param name="propertyName">The property to be animated on the backing Visual</param>
/// <param name="animation">The <see cref="CompositionAnimation"/> to be applied</param>
public void AddCompositionAnimation(string propertyName, CompositionAnimation animation)
{
_compositionAnimations[propertyName] = animation;
}
/// <summary>
/// Removes a composition animation from being run on <see cref="Visual"/> property
/// </summary>
/// <param name="propertyName">The property that no longer needs to be animated</param>
public void RemoveCompositionAnimation(string propertyName)
{
if (_compositionAnimations.ContainsKey(propertyName))
{
_compositionAnimations.Remove(propertyName);
}
}
/// <summary>
/// Adds a composition effect animation to be run on backing <see cref="Visual"/>
/// </summary>
/// <param name="effectBrush">The <see cref="CompositionEffectBrush"/> that will have a property animated</param>
/// <param name="animation">The animation to be applied</param>
/// <param name="propertyName">The property of the effect to be animated</param>
public void AddCompositionEffectAnimation(CompositionObject effectBrush, CompositionAnimation animation, string propertyName)
{
var effect = new EffectAnimationDefinition()
{
EffectBrush = effectBrush,
Animation = animation,
PropertyName = propertyName
};
_compositionEffectAnimations.Add(effect);
}
/// <summary>
/// Adds a composition property that will change instantaneously
/// </summary>
/// <param name="propertyName">The property to be animated on the backing Visual</param>
/// <param name="value">The value to be applied</param>
public void AddCompositionDirectPropertyChange(string propertyName, object value)
{
_directCompositionPropertyChanges[propertyName] = value;
}
/// <summary>
/// Removes a composition property change
/// </summary>
/// <param name="propertyName">The property that no longer needs to be changed</param>
public void RemoveCompositionDirectPropertyChange(string propertyName)
{
if (_directCompositionPropertyChanges.ContainsKey(propertyName))
{
_directCompositionPropertyChanges.Remove(propertyName);
}
}
/// <summary>
/// Adds a storyboard animation to be run
/// </summary>
/// <param name="propertyPath">The property to be animated with Storyboards</param>
/// <param name="timeline">The timeline object to be added to storyboard</param>
public void AddStoryboardAnimation(string propertyPath, Timeline timeline)
{
if (_storyboardAnimations.ContainsKey(propertyPath))
{
var previousAnimation = _storyboardAnimations[propertyPath];
_storyboard.Children.Remove(previousAnimation);
_storyboardAnimations.Remove(propertyPath);
}
_storyboardAnimations.Add(propertyPath, timeline);
_storyboard.Children.Add(timeline);
Storyboard.SetTarget(timeline, Element);
Storyboard.SetTargetProperty(timeline, propertyPath);
}
/// <summary>
/// Dispose resources.
/// </summary>
public void Dispose()
{
_animationTCS = null;
}
/// <summary>
/// Adds a <see cref="AnimationTask"/> to the AnimationSet that
/// will run add an animation once completed. Usefull when an animation
/// needs to do asyncronous initialization before running
/// </summary>
/// <param name="animationTask">The <see cref="AnimationTask"/> to be added</param>
internal void AddAnimationThroughTask(AnimationTask animationTask)
{
_animationTasks.Add(animationTask);
}
/// <summary>
/// Adds an effect propety change to be run on <see cref="StartAsync"/>
/// </summary>
/// <param name="effectBrush">The <see cref="CompositionObject"/> that will have a property changed</param>
/// <param name="value">The value to be applied</param>
/// <param name="propertyName">The property of the effect to be animated</param>
internal void AddEffectDirectPropertyChange(CompositionObject effectBrush, float value, string propertyName)
{
var definition = new EffectDirectPropertyChangeDefinition()
{
EffectBrush = effectBrush,
Value = value,
PropertyName = propertyName
};
_directCompositionEffectPropertyChanges.Add(definition);
}
private void Storyboard_Completed(object sender, object e)
{
_storyboardCompleted = true;
_storyboard.Completed -= Storyboard_Completed;
HandleCompleted();
}
private void Batch_Completed(object sender, CompositionBatchCompletedEventArgs args)
{
_compositionCompleted = true;
_batch.Completed -= Batch_Completed;
HandleCompleted();
}
private void HandleCompleted(bool stopped = false)
{
var completed = _storyboardCompleted && _compositionCompleted;
if (!completed && !stopped)
{
return;
}
if (_storyboardCompleted && _compositionCompleted)
{
State = AnimationSetState.Completed;
}
else
{
State = AnimationSetState.Stopped;
}
if (_animationTCS != null && !_animationTCS.Task.IsCompleted)
{
Completed?.Invoke(this, new AnimationSetCompletedEventArgs() { Completed = _storyboardCompleted && _compositionCompleted });
_animationTCS.SetResult(State == AnimationSetState.Completed);
}
}
}
}