-
Notifications
You must be signed in to change notification settings - Fork 436
/
Copy pathCompositeDrawable.cs
2036 lines (1643 loc) · 81.6 KB
/
CompositeDrawable.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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Lists;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Colour;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Transforms;
using osu.Framework.Timing;
using osu.Framework.Threading;
using osu.Framework.Statistics;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Caching;
using osu.Framework.Development;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Extensions.ExceptionExtensions;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Layout;
using osu.Framework.Logging;
using osu.Framework.Utils;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A drawable consisting of a composite of child drawables which are
/// managed by the composite object itself. Transformations applied to
/// a <see cref="CompositeDrawable"/> are also applied to its children.
/// Additionally, <see cref="CompositeDrawable"/>s support various effects, such as masking, edge effect,
/// padding, and automatic sizing depending on their children.
/// </summary>
public abstract partial class CompositeDrawable : Drawable
{
#region Construction and disposal
/// <summary>
/// Constructs a <see cref="CompositeDrawable"/> that stores children.
/// </summary>
protected CompositeDrawable()
{
var childComparer = new ChildComparer(this);
internalChildren = new SortedList<Drawable>(childComparer);
aliveInternalChildren = new SortedList<Drawable>(childComparer);
// Validate initially. Done before the layout is added below to prevent a callback to this composite.
childrenSizeDependencies.Validate();
AddLayout(childrenSizeDependencies);
AddLayout(childMaskingBoundsBacking);
}
/// <summary>
/// Create a local dependency container which will be used by our nested children.
/// If not overridden, the load-time parent's dependency tree will be used.
/// </summary>
/// <param name="parent">The parent <see cref="IReadOnlyDependencyContainer"/> which should be passed through if we want fallback lookups to work.</param>
/// <returns>A new dependency container to be stored for this Drawable.</returns>
protected virtual IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => DependencyActivator.MergeDependencies(this, parent);
/// <summary>
/// Contains all dependencies that can be injected into this CompositeDrawable's children using <see cref="BackgroundDependencyLoaderAttribute"/>.
/// Add or override dependencies by calling <see cref="DependencyContainer.Cache(object)"/>.
/// </summary>
public IReadOnlyDependencyContainer Dependencies { get; private set; }
protected sealed override void InjectDependencies(IReadOnlyDependencyContainer dependencies)
{
// get our dependencies from our parent, but allow local overriding of our inherited dependency container
Dependencies = CreateChildDependencies(dependencies);
base.InjectDependencies(dependencies);
}
private CancellationTokenSource disposalCancellationSource;
private WeakList<Drawable> loadingComponents;
internal static readonly ThreadedTaskScheduler SCHEDULER_STANDARD = new ThreadedTaskScheduler(4, $"{nameof(LoadComponentsAsync)} (standard)");
internal static readonly ThreadedTaskScheduler SCHEDULER_LONG_LOAD = new ThreadedTaskScheduler(4, $"{nameof(LoadComponentsAsync)} (long load)");
/// <summary>
/// Loads a future child or grand-child of this <see cref="CompositeDrawable"/> asynchronously. <see cref="Dependencies"/>
/// and <see cref="Drawable.Clock"/> are inherited from this <see cref="CompositeDrawable"/>.
///
/// Note that this will always use the dependencies and clock from this instance. If you must load to a nested container level,
/// consider using <see cref="DelayedLoadWrapper"/>
/// </summary>
/// <typeparam name="TLoadable">The type of the future future child or grand-child to be loaded.</typeparam>
/// <param name="component">The child or grand-child to be loaded.</param>
/// <param name="onLoaded">Callback to be invoked on the update thread after loading is complete.</param>
/// <param name="cancellation">An optional cancellation token.</param>
/// <param name="scheduler">The scheduler for <paramref name="onLoaded"/> to be invoked on. If null, the local scheduler will be used.</param>
/// <returns>The task which is used for loading and callbacks.</returns>
protected internal Task LoadComponentAsync<TLoadable>([NotNull] TLoadable component, Action<TLoadable> onLoaded = null, CancellationToken cancellation = default, Scheduler scheduler = null)
where TLoadable : Drawable
{
ArgumentNullException.ThrowIfNull(component);
return LoadComponentsAsync(component.Yield(), l => onLoaded?.Invoke(l.Single()), cancellation, scheduler);
}
/// <summary>
/// Loads a future child or grand-child of this <see cref="CompositeDrawable"/> synchronously and immediately. <see cref="Dependencies"/>
/// and <see cref="Drawable.Clock"/> are inherited from this <see cref="CompositeDrawable"/>.
/// <remarks>
/// This is generally useful if already in an asynchronous context and requiring forcefully (pre)loading content without adding it to the hierarchy.
/// </remarks>
/// </summary>
/// <typeparam name="TLoadable">The type of the future future child or grand-child to be loaded.</typeparam>
/// <param name="component">The child or grand-child to be loaded.</param>
protected void LoadComponent<TLoadable>(TLoadable component) where TLoadable : Drawable
=> LoadComponents(component.Yield());
/// <summary>
/// Loads several future child or grand-child of this <see cref="CompositeDrawable"/> asynchronously. <see cref="Dependencies"/>
/// and <see cref="Drawable.Clock"/> are inherited from this <see cref="CompositeDrawable"/>.
///
/// Note that this will always use the dependencies and clock from this instance. If you must load to a nested container level,
/// consider using <see cref="DelayedLoadWrapper"/>
/// </summary>
/// <typeparam name="TLoadable">The type of the future future child or grand-child to be loaded.</typeparam>
/// <param name="components">The children or grand-children to be loaded.</param>
/// <param name="onLoaded">Callback to be invoked on the update thread after loading is complete.</param>
/// <param name="cancellation">An optional cancellation token.</param>
/// <param name="scheduler">The scheduler for <paramref name="onLoaded"/> to be invoked on. If null, the local scheduler will be used.</param>
/// <returns>The task which is used for loading and callbacks.</returns>
protected internal Task LoadComponentsAsync<TLoadable>(IEnumerable<TLoadable> components, Action<IEnumerable<TLoadable>> onLoaded = null, CancellationToken cancellation = default,
Scheduler scheduler = null)
where TLoadable : Drawable
{
if (LoadState < LoadState.Loading)
throw new InvalidOperationException($"May not invoke {nameof(LoadComponentAsync)} prior to this {nameof(CompositeDrawable)} being loaded.");
EnsureMutationAllowed($"load components via {nameof(LoadComponentsAsync)}");
ObjectDisposedException.ThrowIf(IsDisposed, this);
disposalCancellationSource ??= new CancellationTokenSource();
var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(disposalCancellationSource.Token, cancellation);
var deps = new DependencyContainer(Dependencies);
deps.CacheValueAs(linkedSource.Token);
loadingComponents ??= new WeakList<Drawable>();
var loadables = components.ToList();
foreach (var d in loadables)
{
loadingComponents.Add(d);
LoadingComponentsLogger.Add(d);
d.OnLoadComplete += _ =>
{
loadingComponents.Remove(d);
LoadingComponentsLogger.Remove(d);
};
}
var taskScheduler = loadables.Any(c => c.IsLongRunning) ? SCHEDULER_LONG_LOAD : SCHEDULER_STANDARD;
return Task.Factory.StartNew(() => loadComponents(loadables, deps, true, linkedSource.Token), linkedSource.Token, TaskCreationOptions.HideScheduler, taskScheduler).ContinueWith(loaded =>
{
var exception = loaded.Exception?.AsSingular();
if (loadables.Count == 0)
return;
if (linkedSource.Token.IsCancellationRequested)
{
// In the case of cancellation the final load state will not be reached, so cleanup here is required.
foreach (var d in loadables)
LoadingComponentsLogger.Remove(d);
linkedSource.Dispose();
return;
}
(scheduler ?? Scheduler).Add(() =>
{
try
{
if (exception != null)
ExceptionDispatchInfo.Capture(exception).Throw();
if (!linkedSource.Token.IsCancellationRequested)
onLoaded?.Invoke(loadables);
}
finally
{
linkedSource.Dispose();
}
});
}, TaskContinuationOptions.ExecuteSynchronously);
}
/// <summary>
/// Loads several future child or grand-child of this <see cref="CompositeDrawable"/> synchronously and immediately. <see cref="Dependencies"/>
/// and <see cref="Drawable.Clock"/> are inherited from this <see cref="CompositeDrawable"/>.
/// <remarks>
/// This is generally useful if already in an asynchronous context and requiring forcefully (pre)loading content without adding it to the hierarchy.
/// </remarks>
/// </summary>
/// <typeparam name="TLoadable">The type of the future future child or grand-child to be loaded.</typeparam>
/// <param name="components">The children or grand-children to be loaded.</param>
protected void LoadComponents<TLoadable>(IEnumerable<TLoadable> components) where TLoadable : Drawable
{
if (LoadState < LoadState.Loading)
throw new InvalidOperationException($"May not invoke {nameof(LoadComponent)} prior to this {nameof(CompositeDrawable)} being loaded.");
ObjectDisposedException.ThrowIf(IsDisposed, this);
loadComponents(components.ToList(), Dependencies, false);
}
/// <summary>
/// Load the provided components. Any components which could not be loaded will be removed from the provided list.
/// </summary>
private void loadComponents<TLoadable>(List<TLoadable> components, IReadOnlyDependencyContainer dependencies, bool isDirectAsyncContext, CancellationToken cancellation = default)
where TLoadable : Drawable
{
for (int i = 0; i < components.Count; i++)
{
if (cancellation.IsCancellationRequested)
break;
if (!components[i].LoadFromAsync(Clock, dependencies, isDirectAsyncContext))
{
LoadingComponentsLogger.Remove(components[i]);
components.Remove(components[i--]);
}
}
}
[BackgroundDependencyLoader(true)]
private void load(ShaderManager shaders, CancellationToken? cancellation)
{
hasCustomDrawNode = GetType().GetMethod(nameof(CreateDrawNode))?.DeclaringType != typeof(CompositeDrawable);
Shader ??= shaders?.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE);
// We are in a potentially async context, so let's aggressively load all our children
// regardless of their alive state. this also gives children a clock so they can be checked
// for their correct alive state in the case LifetimeStart is set to a definite value.
foreach (var c in internalChildren)
{
cancellation?.ThrowIfCancellationRequested();
loadChild(c);
}
}
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
// At this point we can assume that we are loaded although we're not in the "ready" state, because we'll be given
// a "ready" state soon after this method terminates. Therefore we can perform an early check to add any alive children
// while we're still in an asynchronous context and avoid putting pressure on the main thread during UpdateSubTree.
CheckChildrenLife();
}
/// <summary>
/// Loads a <see cref="Drawable"/> child. This will not throw in the event of the load being cancelled.
/// </summary>
/// <param name="child">The <see cref="Drawable"/> child to load.</param>
private void loadChild(Drawable child)
{
try
{
if (IsDisposed)
return;
child.Load(Clock, Dependencies, false);
child.Parent = this;
}
catch (OperationCanceledException)
{
}
catch (AggregateException ae)
{
foreach (var e in ae.Flatten().InnerExceptions)
{
if (e is OperationCanceledException)
continue;
ExceptionDispatchInfo.Capture(e).Throw();
}
}
}
protected override void Dispose(bool isDisposing)
{
if (IsDisposed)
return;
disposalCancellationSource?.Cancel();
disposalCancellationSource?.Dispose();
InternalChildren?.ForEach(c => c.Dispose());
if (loadingComponents != null)
{
foreach (var d in loadingComponents)
{
d.Dispose();
LoadingComponentsLogger.Remove(d);
}
}
OnAutoSize = null;
Dependencies = null;
schedulerAfterChildren = null;
base.Dispose(isDisposing);
}
#endregion
#region Children management
/// <summary>
/// Invoked when a child has entered <see cref="AliveInternalChildren"/>.
/// </summary>
internal event Action<Drawable> ChildBecameAlive;
/// <summary>
/// Invoked when a child has left <see cref="AliveInternalChildren"/>.
/// </summary>
internal event Action<Drawable> ChildDied;
/// <summary>
/// Fired after a child's <see cref="Drawable.Depth"/> is changed.
/// </summary>
internal event Action<Drawable> ChildDepthChanged;
/// <summary>
/// Gets or sets the only child in <see cref="InternalChildren"/>.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected internal Drawable InternalChild
{
get
{
if (InternalChildren.Count != 1)
{
throw new InvalidOperationException(
$"Cannot call {nameof(InternalChild)} unless there's exactly one {nameof(Drawable)} in {nameof(InternalChildren)} (currently {InternalChildren.Count})!");
}
return InternalChildren[0];
}
set
{
if (IsDisposed)
return;
ClearInternal();
AddInternal(value);
}
}
protected class ChildComparer : IComparer<Drawable>
{
private readonly CompositeDrawable owner;
public ChildComparer(CompositeDrawable owner)
{
this.owner = owner;
}
public int Compare(Drawable x, Drawable y) => owner.Compare(x, y);
}
/// <summary>
/// Compares two <see cref="InternalChildren"/> to determine their sorting.
/// </summary>
/// <param name="x">The first child to compare.</param>
/// <param name="y">The second child to compare.</param>
/// <returns>-1 if <paramref name="x"/> comes before <paramref name="y"/>, and 1 otherwise.</returns>
protected virtual int Compare(Drawable x, Drawable y)
{
ArgumentNullException.ThrowIfNull(x);
ArgumentNullException.ThrowIfNull(y);
int i = y.Depth.CompareTo(x.Depth);
if (i != 0) return i;
return x.ChildID.CompareTo(y.ChildID);
}
/// <summary>
/// Helper method comparing children by their depth first, and then by their reversed child ID.
/// </summary>
/// <param name="x">The first child to compare.</param>
/// <param name="y">The second child to compare.</param>
/// <returns>-1 if <paramref name="x"/> comes before <paramref name="y"/>, and 1 otherwise.</returns>
protected int CompareReverseChildID(Drawable x, Drawable y)
{
ArgumentNullException.ThrowIfNull(x);
ArgumentNullException.ThrowIfNull(y);
int i = y.Depth.CompareTo(x.Depth);
if (i != 0) return i;
return y.ChildID.CompareTo(x.ChildID);
}
private readonly SortedList<Drawable> internalChildren;
/// <summary>
/// This <see cref="CompositeDrawable"/> list of children. Assigning to this property will dispose all existing children of this <see cref="CompositeDrawable"/>.
/// </summary>
protected internal IReadOnlyList<Drawable> InternalChildren
{
get => internalChildren;
set => InternalChildrenEnumerable = value;
}
/// <summary>
/// Replaces all internal children of this <see cref="CompositeDrawable"/> with the elements contained in the enumerable.
/// </summary>
protected internal IEnumerable<Drawable> InternalChildrenEnumerable
{
set
{
if (IsDisposed)
return;
ClearInternal();
AddRangeInternal(value);
}
}
private readonly SortedList<Drawable> aliveInternalChildren;
protected internal IReadOnlyList<Drawable> AliveInternalChildren => aliveInternalChildren;
/// <summary>
/// The index of a given child within <see cref="InternalChildren"/>.
/// </summary>
/// <returns>
/// If the child is found, its index. Otherwise, the negated index it would obtain
/// if it were added to <see cref="InternalChildren"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <list type="bullet">
/// <item>If the supplied <paramref name="drawable"/> is already attached to another <see cref="Drawable.Parent"/>.</item>
/// <item>If a child drawable was matched using <see cref="Compare"/>, but that child drawable was not the supplied <paramref name="drawable"/>.</item>
/// </list>
/// </exception>
protected internal int IndexOfInternal(Drawable drawable)
{
if (drawable.Parent != null && drawable.Parent != this)
throw new InvalidOperationException($@"Cannot call {nameof(IndexOfInternal)} for a drawable that already is a child of a different parent.");
int index = internalChildren.IndexOf(drawable);
if (index >= 0 && internalChildren[index].ChildID != drawable.ChildID)
throw new InvalidOperationException($@"A non-matching {nameof(Drawable)} was returned. Please ensure {GetType()}'s {nameof(Compare)} override implements a stable sort algorithm.");
return index;
}
/// <summary>
/// Checks whether a given child is contained within <see cref="InternalChildren"/>.
/// </summary>
protected internal bool ContainsInternal(Drawable drawable) => IndexOfInternal(drawable) >= 0;
/// <summary>
/// Removes a given child from this <see cref="InternalChildren"/>.
/// </summary>
/// <param name="drawable">The <see cref="Drawable"/> to be removed.</param>
/// <param name="disposeImmediately">Whether removed item should be immediately disposed.</param>
/// <returns>False if <paramref name="drawable"/> was not a child of this <see cref="CompositeDrawable"/> and true otherwise.</returns>
protected internal virtual bool RemoveInternal(Drawable drawable, bool disposeImmediately)
{
try
{
EnsureChildMutationAllowed();
ArgumentNullException.ThrowIfNull(drawable);
int index = IndexOfInternal(drawable);
if (index < 0)
return false;
internalChildren.RemoveAt(index);
if (drawable.IsAlive)
{
aliveInternalChildren.Remove(drawable);
ChildDied?.Invoke(drawable);
}
if (drawable.LoadState >= LoadState.Ready && drawable.Parent != this)
throw new InvalidOperationException($@"Removed a drawable ({drawable}) whose parent was not this ({this}), but {drawable.Parent}.");
drawable.Parent = null;
drawable.IsAlive = false;
if (AutoSizeAxes != Axes.None)
Invalidate(Invalidation.RequiredParentSizeToFit, InvalidationSource.Child);
return true;
}
finally
{
if (disposeImmediately)
drawable?.Dispose();
}
}
/// <summary>
/// Clear all of <see cref="InternalChildren"/>.
/// </summary>
/// <param name="disposeChildren">
/// Whether removed children should also get disposed.
/// Disposal will be recursive.
/// </param>
protected internal virtual void ClearInternal(bool disposeChildren = true)
{
EnsureChildMutationAllowed();
if (IsDisposed)
return;
if (internalChildren.Count == 0) return;
foreach (Drawable t in internalChildren)
{
if (t.IsAlive)
ChildDied?.Invoke(t);
t.IsAlive = false;
t.Parent = null;
if (disposeChildren)
DisposeChildAsync(t);
Trace.Assert(t.Parent == null);
}
internalChildren.Clear();
aliveInternalChildren.Clear();
RequestsNonPositionalInputSubTree = RequestsNonPositionalInput;
RequestsPositionalInputSubTree = RequestsPositionalInput;
if (AutoSizeAxes != Axes.None)
Invalidate(Invalidation.RequiredParentSizeToFit, InvalidationSource.Child);
}
/// <summary>
/// Used to assign a monotonically increasing ID to children as they are added. This member is
/// incremented whenever a child is added.
/// </summary>
private ulong currentChildID;
/// <summary>
/// Adds a child to <see cref="InternalChildren"/>.
/// </summary>
protected virtual void AddInternal(Drawable drawable)
{
EnsureChildMutationAllowed();
if (IsDisposed)
return;
if (drawable == null)
throw new ArgumentNullException(nameof(drawable), $"null {nameof(Drawable)}s may not be added to {nameof(CompositeDrawable)}.");
if (drawable == this)
throw new InvalidOperationException($"{nameof(CompositeDrawable)} may not be added to itself.");
// If the drawable's ChildId is not zero, then it was added to another parent even if it wasn't loaded
if (drawable.ChildID != 0)
throw new InvalidOperationException("May not add a drawable to multiple containers.");
drawable.ChildID = ++currentChildID;
drawable.RemoveCompletedTransforms = RemoveCompletedTransforms;
if (LoadState >= LoadState.Loading)
{
// If we're already loaded, we can eagerly allow children to be loaded
if (drawable.LoadState >= LoadState.Ready)
drawable.Parent = this;
else
loadChild(drawable);
}
internalChildren.Add(drawable);
if (AutoSizeAxes != Axes.None)
Invalidate(Invalidation.RequiredParentSizeToFit, InvalidationSource.Child);
}
/// <summary>
/// Adds a range of children to <see cref="InternalChildren"/>. This is equivalent to calling
/// <see cref="AddInternal(Drawable)"/> on each element of the range in order.
/// </summary>
protected internal void AddRangeInternal(IEnumerable<Drawable> range)
{
if (range is IContainerEnumerable<Drawable>)
{
throw new InvalidOperationException($"Attempting to add a {nameof(IContainer)} as a range of children to {this}."
+ $"If intentional, consider using the {nameof(IContainerEnumerable<Drawable>.Children)} property instead.");
}
foreach (Drawable d in range)
AddInternal(d);
}
/// <summary>
/// Changes the depth of an internal child. This affects ordering of <see cref="InternalChildren"/>.
/// </summary>
/// <param name="child">The child whose depth is to be changed.</param>
/// <param name="newDepth">The new depth value to be set.</param>
protected internal void ChangeInternalChildDepth(Drawable child, float newDepth)
{
EnsureChildMutationAllowed();
if (child.Depth == newDepth) return;
int index = IndexOfInternal(child);
if (index < 0)
throw new InvalidOperationException($"Can not change depth of drawable which is not contained within this {nameof(CompositeDrawable)}.");
internalChildren.RemoveAt(index);
int aliveIndex = aliveInternalChildren.IndexOf(child);
if (aliveIndex >= 0) // remove if found
aliveInternalChildren.RemoveAt(aliveIndex);
ulong chId = child.ChildID;
child.ChildID = 0; // ensure Depth-change does not throw an exception
child.Depth = newDepth;
child.ChildID = chId;
internalChildren.Add(child);
if (aliveIndex >= 0) // re-add if it used to be in aliveInternalChildren
aliveInternalChildren.Add(child);
ChildDepthChanged?.Invoke(child);
}
/// <summary>
/// Sorts all children of this <see cref="CompositeDrawable"/>.
/// </summary>
/// <remarks>
/// This can be used to re-sort the children if the result of <see cref="Compare"/> has changed.
/// </remarks>
protected internal void SortInternal()
{
EnsureChildMutationAllowed();
internalChildren.Sort();
aliveInternalChildren.Sort();
}
#endregion
#region Updating (per-frame periodic)
private Scheduler schedulerAfterChildren;
/// <summary>
/// A lazily-initialized scheduler used to schedule tasks to be invoked in future <see cref="UpdateAfterChildren"/>s calls.
/// The tasks are invoked at the beginning of the <see cref="UpdateAfterChildren"/> method before anything else.
/// </summary>
protected internal Scheduler SchedulerAfterChildren
{
get
{
if (schedulerAfterChildren != null)
return schedulerAfterChildren;
lock (LoadLock)
return schedulerAfterChildren ??= new Scheduler(() => ThreadSafety.IsUpdateThread, Clock);
}
}
/// <summary>
/// Updates the life status of <see cref="InternalChildren"/> according to their
/// <see cref="Drawable.ShouldBeAlive"/> property.
/// </summary>
/// <returns>True iff the life status of at least one child changed.</returns>
protected virtual bool UpdateChildrenLife()
{
// Can not have alive children if we are not loaded.
if (LoadState < LoadState.Ready)
return false;
if (!CheckChildrenLife())
return false;
return true;
}
/// <summary>
/// Checks whether the alive state of any child has changed and processes it. This will add or remove
/// children from <see cref="aliveInternalChildren"/> depending on their alive states.
/// <para>Note that this does NOT check the load state of this <see cref="CompositeDrawable"/> to check if it can hold any alive children.</para>
/// </summary>
/// <returns>Whether any child's alive state has changed.</returns>
protected virtual bool CheckChildrenLife()
{
bool anyAliveChanged = false;
for (int i = 0; i < internalChildren.Count; i++)
{
var state = checkChildLife(internalChildren[i]);
anyAliveChanged |= state.HasFlagFast(ChildLifeStateChange.MadeAlive) || state.HasFlagFast(ChildLifeStateChange.MadeDead);
if (state.HasFlagFast(ChildLifeStateChange.Removed))
i--;
}
FrameStatistics.Add(StatisticsCounterType.CCL, internalChildren.Count);
return anyAliveChanged;
}
/// <summary>
/// Checks whether the alive state of a child has changed and processes it. This will add or remove
/// the child from <see cref="aliveInternalChildren"/> depending on its alive state.
///
/// This should only ever be called on a <see cref="CompositeDrawable"/>'s own <see cref="internalChildren"/>.
///
/// <para>Note that this does NOT check the load state of this <see cref="CompositeDrawable"/> to check if it can hold any alive children.</para>
/// </summary>
/// <param name="child">The child to check.</param>
/// <returns>Whether the child's alive state has changed.</returns>
private ChildLifeStateChange checkChildLife(Drawable child)
{
ChildLifeStateChange state = ChildLifeStateChange.None;
if (child.ShouldBeAlive)
{
if (!child.IsAlive)
{
if (child.LoadState < LoadState.Ready)
{
// If we're already loaded, we can eagerly allow children to be loaded
loadChild(child);
if (child.LoadState < LoadState.Ready)
return ChildLifeStateChange.None;
}
MakeChildAlive(child);
state = ChildLifeStateChange.MadeAlive;
}
}
else
{
if (child.IsAlive || child.RemoveWhenNotAlive)
{
if (MakeChildDead(child))
state |= ChildLifeStateChange.Removed;
state |= ChildLifeStateChange.MadeDead;
}
}
return state;
}
[Flags]
private enum ChildLifeStateChange
{
None = 0,
MadeAlive = 1,
MadeDead = 1 << 1,
Removed = 1 << 2,
}
/// <summary>
/// Makes a child alive.
/// </summary>
/// <remarks>
/// Callers have to ensure that <paramref name="child"/> is of this <see cref="CompositeDrawable"/>'s non-alive <see cref="InternalChildren"/> and <see cref="LoadState"/> of the <paramref name="child"/> is at least <see cref="LoadState.Ready"/>.
/// </remarks>
/// <param name="child">The child of this <see cref="CompositeDrawable"/>> to make alive.</param>
protected void MakeChildAlive(Drawable child)
{
Debug.Assert(!child.IsAlive && child.LoadState >= LoadState.Ready);
// If the new child has the flag set, we should propagate the flag towards the root.
// We can stop at the ancestor which has the flag already set because further ancestors will also have the flag set.
if (child.RequestsNonPositionalInputSubTree)
{
for (var ancestor = this; ancestor != null && !ancestor.RequestsNonPositionalInputSubTree; ancestor = ancestor.Parent)
ancestor.RequestsNonPositionalInputSubTree = true;
}
if (child.RequestsPositionalInputSubTree)
{
for (var ancestor = this; ancestor != null && !ancestor.RequestsPositionalInputSubTree; ancestor = ancestor.Parent)
ancestor.RequestsPositionalInputSubTree = true;
}
aliveInternalChildren.Add(child);
child.IsAlive = true;
ChildBecameAlive?.Invoke(child);
// Layout invalidations on non-alive children are blocked, so they must be invalidated once when they become alive.
child.Invalidate(Invalidation.Layout, InvalidationSource.Parent);
// Notify ourselves that a child has become alive.
Invalidate(Invalidation.Presence, InvalidationSource.Child);
}
/// <summary>
/// Makes a child dead (not alive) and removes it if <see cref="Drawable.RemoveWhenNotAlive"/> of the <paramref name="child"/> is set.
/// </summary>
/// <remarks>
/// Callers have to ensure that <paramref name="child"/> is of this <see cref="CompositeDrawable"/>'s <see cref="AliveInternalChildren"/>.
/// </remarks>
/// <param name="child">The child of this <see cref="CompositeDrawable"/>> to make dead.</param>
/// <returns>Whether <paramref name="child"/> has been removed by death.</returns>
protected bool MakeChildDead(Drawable child)
{
if (child.IsAlive)
{
aliveInternalChildren.Remove(child);
child.IsAlive = false;
ChildDied?.Invoke(child);
}
bool removed = false;
if (child.RemoveWhenNotAlive)
{
RemoveInternal(child, false);
if (child.DisposeOnDeathRemoval)
DisposeChildAsync(child);
removed = true;
}
// Notify ourselves that a child has died.
Invalidate(Invalidation.Presence, InvalidationSource.Child);
return removed;
}
internal override void UnbindAllBindablesSubTree()
{
base.UnbindAllBindablesSubTree();
// TODO: this code can potentially be run from an update thread while a drawable is still loading (see ScreenStack as an example).
// while this is quite a bad issue, it is rare and generally happens in tests which have frame perfect behaviours.
// as such, for loop is used here intentionally to avoid collection modified exceptions for this (usually) non-critical failure.
// see https://github.com/ppy/osu-framework/issues/4054.
for (int i = 0; i < internalChildren.Count; i++)
{
Drawable child = internalChildren[i];
child.UnbindAllBindablesSubTree();
}
}
/// <summary>
/// Unbinds a child's bindings synchronously and queues an asynchronous disposal of the child.
/// </summary>
/// <param name="drawable">The child to dispose.</param>
internal void DisposeChildAsync(Drawable drawable)
{
drawable.UnbindAllBindablesSubTree();
AsyncDisposalQueue.Enqueue(drawable);
}
internal override void UpdateClock(IFrameBasedClock clock)
{
if (Clock == clock)
return;
base.UpdateClock(clock);
foreach (Drawable child in internalChildren)
child.UpdateClock(Clock);
schedulerAfterChildren?.UpdateClock(Clock);
}
/// <summary>
/// Specifies whether this <see cref="CompositeDrawable"/> requires an update of its children.
/// If the return value is false, then children are not updated and
/// <see cref="UpdateAfterChildren"/> is not called.
/// </summary>
protected virtual bool RequiresChildrenUpdate => !IsMaskedAway || !childrenSizeDependencies.IsValid;
public override bool UpdateSubTree()
{
if (!base.UpdateSubTree()) return false;
// We update our children's life even if we are invisible.
// Note, that this does not propagate down and may need
// generalization in the future.
UpdateChildrenLife();
// If we are not present then there is never a reason to check
// for children, as they should never affect our present status.
if (!IsPresent || !RequiresChildrenUpdate) return false;
UpdateAfterChildrenLife();
if (TypePerformanceMonitor.Active)
{
for (int i = 0; i < aliveInternalChildren.Count; ++i)
{
Drawable c = aliveInternalChildren[i];
TypePerformanceMonitor.BeginCollecting(c);
updateChild(c);
TypePerformanceMonitor.EndCollecting(c);
}
}
else
{
for (int i = 0; i < aliveInternalChildren.Count; ++i)
updateChild(aliveInternalChildren[i]);
}
if (schedulerAfterChildren != null)
{
int amountScheduledTasks = schedulerAfterChildren.Update();
FrameStatistics.Add(StatisticsCounterType.ScheduleInvk, amountScheduledTasks);
}
UpdateAfterChildren();
updateChildrenSizeDependencies();
applyAutoSize();
UpdateAfterAutoSize();
return true;
}
private void updateChild(Drawable c)
{
Debug.Assert(c.LoadState >= LoadState.Ready);
c.UpdateSubTree();
}
/// <summary>
/// Updates all masking calculations for this <see cref="CompositeDrawable"/> and its <see cref="AliveInternalChildren"/>.
/// This occurs post-<see cref="UpdateSubTree"/> to ensure that all <see cref="Drawable"/> updates have taken place.
/// </summary>
/// <returns>Whether masking calculations have taken place.</returns>
public override bool UpdateSubTreeMasking()
{
if (!base.UpdateSubTreeMasking())
return false;
if (IsMaskedAway)
return true;
if (aliveInternalChildren.Count == 0)
return true;
if (RequiresChildrenUpdate)
{
for (int i = 0; i < aliveInternalChildren.Count; i++)
aliveInternalChildren[i].UpdateSubTreeMasking();
}
return true;
}
protected override bool ComputeIsMaskedAway(RectangleF maskingBounds)
{
if (!CanBeFlattened)
return base.ComputeIsMaskedAway(maskingBounds);
// The masking check is overly expensive (requires creation of ScreenSpaceDrawQuad)
// when only few children exist.
return aliveInternalChildren.Count >= amount_children_required_for_masking_check && base.ComputeIsMaskedAway(maskingBounds);
}
/// <summary>
/// Computes the <see cref="RectangleF"/> to be used as the masking bounds for all <see cref="AliveInternalChildren"/>.
/// </summary>
/// <returns>The <see cref="RectangleF"/> to be used as the masking bounds for <see cref="AliveInternalChildren"/>.</returns>
protected virtual RectangleF ComputeChildMaskingBounds() => Masking ? RectangleF.Intersect(ComputeMaskingBounds(), ScreenSpaceDrawQuad.AABBFloat) : ComputeMaskingBounds();