Skip to content

Commit

Permalink
fix: Potential TransformGroup memory leak (#13529)
Browse files Browse the repository at this point in the history
* fix: Potential TransformGroup memoey leak

* fix: Address review

* fix: Address review

* fix: review
  • Loading branch information
workgroupengineering authored and maxkatz6 committed Dec 5, 2023
1 parent 6794148 commit 40d50b1
Showing 1 changed file with 31 additions and 13 deletions.
44 changes: 31 additions & 13 deletions src/Avalonia.Base/Media/TransformGroup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using Avalonia.Collections;
using Avalonia.Metadata;

Expand All @@ -11,25 +12,17 @@ public sealed class TransformGroup : Transform
public static readonly StyledProperty<Transforms> ChildrenProperty =
AvaloniaProperty.Register<TransformGroup, Transforms>(nameof(Children));

[System.Diagnostics.CodeAnalysis.SuppressMessage("AvaloniaProperty", "AVP1012",
private IDisposable? _childrenNotificationSubscription;
private readonly EventHandler _childTransformChangedHandler;

[System.Diagnostics.CodeAnalysis.SuppressMessage("AvaloniaProperty", "AVP1012",
Justification = "Collection properties shouldn't be set with SetCurrentValue.")]
public TransformGroup()
{
_childTransformChangedHandler = (_, _) => RaiseChanged();
Children = new Transforms();
Children.ResetBehavior = ResetBehavior.Remove;
Children.CollectionChanged += delegate
{
Children.ForEachItem(
(tr) => tr.Changed += ChildTransform_Changed,
(tr) => tr.Changed -= ChildTransform_Changed,
() => { });
};
}

private void ChildTransform_Changed(object? sender, System.EventArgs e)
{
this.RaiseChanged();
}

/// <summary>
/// Gets or sets the children.
Expand Down Expand Up @@ -61,6 +54,31 @@ public override Matrix Value
return result;
}
}

protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == ChildrenProperty)
{
_childrenNotificationSubscription?.Dispose();
if (change.OldValue is Transforms oldTransforms)
{
foreach (var item in oldTransforms)
{
item.Changed -= _childTransformChangedHandler;
}
}
if (change.NewValue is Transforms newTransforms)
{
// Ensure reset behavior is Remove
newTransforms.ResetBehavior = ResetBehavior.Remove;
_childrenNotificationSubscription = newTransforms.ForEachItem(
(tr) => tr.Changed += _childTransformChangedHandler,
(tr) => tr.Changed -= _childTransformChangedHandler,
() => { });
}
}
}
}

public sealed class Transforms : AvaloniaList<Transform>
Expand Down

0 comments on commit 40d50b1

Please sign in to comment.