Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/Controls/src/Core/Internals/WeakEventProxy.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using Microsoft.Maui.Controls.Shapes;

// NOTE: warning disabled for netstandard projects
#pragma warning disable 0436
Expand Down Expand Up @@ -152,4 +153,62 @@ public override void Unsubscribe()
base.Unsubscribe();
}
}

/// <summary>
/// A "proxy" class for subscribing Geometry and PathGeometry invalidation via WeakReference.
/// General usage is to store this in a member variable and call Subscribe()/Unsubscribe() appropriately.
/// Your class should have a finalizer that calls Unsubscribe() to prevent WeakGeometryChangedProxy objects from leaking.
/// </summary>
class WeakGeometryChangedProxy : WeakEventProxy<Geometry, EventHandler>
{
public WeakGeometryChangedProxy() { }

public WeakGeometryChangedProxy(Geometry source, EventHandler handler)
{
Subscribe(source, handler);
}

void OnGeometryChanged(object? sender, EventArgs e)
{
if (TryGetHandler(out var handler))
{
handler(sender, e);
}
else
{
Unsubscribe();
}
}

public override void Subscribe(Geometry source, EventHandler handler)
{
if (TryGetSource(out var s))
{
s.PropertyChanged -= OnGeometryChanged;

if (s is PathGeometry oldPathGeometry)
oldPathGeometry.InvalidatePathGeometryRequested -= OnGeometryChanged;
}

source.PropertyChanged += OnGeometryChanged;

if (source is PathGeometry pathGeometry)
pathGeometry.InvalidatePathGeometryRequested += OnGeometryChanged;

base.Subscribe(source, handler);
}

public override void Unsubscribe()
{
if (TryGetSource(out var s))
{
s.PropertyChanged -= OnGeometryChanged;

if (s is PathGeometry pathGeometry)
pathGeometry.InvalidatePathGeometryRequested -= OnGeometryChanged;
}

base.Unsubscribe();
}
}
}
79 changes: 50 additions & 29 deletions src/Controls/src/Core/Shapes/Path.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,24 @@ namespace Microsoft.Maui.Controls.Shapes
/// </summary>
public sealed partial class Path : Shape, IShape
{
WeakGeometryChangedProxy _dataProxy;
EventHandler _dataChanged;
WeakNotifyPropertyChangedProxy _transformProxy;
PropertyChangedEventHandler _transformChanged;

/// <summary>
/// Initializes a new instance of the <see cref="Path"/> class.
/// </summary>
public Path() : base()
{
}

~Path()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[major] Public API Surface / Build — Adding a destructor to public Path introduces a new finalizer API entry, but the PR does not update the Controls PublicAPI.Unshipped.txt baselines. The shipped API files already track destructors for Shape, Border, and other public types, so API validation is likely to fail for Microsoft.Maui.Controls.Shapes.Path.~Path() -> void on each target. Either add the new destructor entries to the appropriate src/Controls/src/Core/PublicAPI/*/PublicAPI.Unshipped.txt files, or avoid introducing a Path finalizer by moving the cleanup to an already-finalized base/type-level cleanup pattern.

{
_dataProxy?.Unsubscribe();
_transformProxy?.Unsubscribe();
}

public Path(Geometry data) : this()
{
Data = data;
Expand All @@ -26,12 +37,30 @@ public Path(Geometry data) : this()
/// <summary>Bindable property for <see cref="Data"/>.</summary>
public static readonly BindableProperty DataProperty =
BindableProperty.Create(nameof(Data), typeof(Geometry), typeof(Path), null,
propertyChanged: OnGeometryPropertyChanged);
propertyChanging: (bindable, oldValue, newValue) =>
{
if (oldValue != null)
(bindable as Path)?.StopNotifyingDataChanges();
},
propertyChanged: (bindable, oldValue, newValue) =>
{
if (newValue != null)
(bindable as Path)?.NotifyDataChanges();
});

/// <summary>Bindable property for <see cref="RenderTransform"/>.</summary>
public static readonly BindableProperty RenderTransformProperty =
BindableProperty.Create(nameof(RenderTransform), typeof(Transform), typeof(Path), null,
propertyChanged: OnTransformPropertyChanged);
propertyChanging: (bindable, oldValue, newValue) =>
{
if (oldValue != null)
(bindable as Path)?.StopNotifyingTransformChanges();
},
propertyChanged: (bindable, oldValue, newValue) =>
{
if (newValue != null)
(bindable as Path)?.NotifyTransformChanges();
});

/// <summary>
/// Gets or sets the <see cref="Geometry"/> that specifies the shape to be drawn. This is a bindable property.
Expand All @@ -52,46 +81,38 @@ public Transform RenderTransform
get { return (Transform)GetValue(RenderTransformProperty); }
}

static void OnGeometryPropertyChanged(BindableObject bindable, object oldValue, object newValue)
void NotifyDataChanges()
{
if (oldValue != null)
{
(oldValue as Geometry).PropertyChanged -= (bindable as Path).OnGeometryPropertyChanged;

if (oldValue is PathGeometry pathGeometry)
pathGeometry.InvalidatePathGeometryRequested -= (bindable as Path).OnInvalidatePathGeometryRequested;
}
var data = Data;

if (newValue != null)
if (data != null)
{
(newValue as Geometry).PropertyChanged += (bindable as Path).OnGeometryPropertyChanged;

if (newValue is PathGeometry pathGeometry)
pathGeometry.InvalidatePathGeometryRequested += (bindable as Path).OnInvalidatePathGeometryRequested;
_dataChanged ??= (sender, e) => OnPropertyChanged(nameof(Data));
_dataProxy ??= new WeakGeometryChangedProxy();
_dataProxy.Subscribe(data, _dataChanged);
}
}

static void OnTransformPropertyChanged(BindableObject bindable, object oldValue, object newValue)
void StopNotifyingDataChanges()
{
if (oldValue != null)
{
(oldValue as Transform).PropertyChanged -= (bindable as Path).OnTransformPropertyChanged;
}

if (newValue != null)
{
(newValue as Transform).PropertyChanged += (bindable as Path).OnTransformPropertyChanged;
}
_dataProxy?.Unsubscribe();
}

void OnGeometryPropertyChanged(object sender, PropertyChangedEventArgs args)
void NotifyTransformChanges()
{
OnPropertyChanged(nameof(Data));
var renderTransform = RenderTransform;

if (renderTransform != null)
{
_transformChanged ??= OnTransformPropertyChanged;
_transformProxy ??= new WeakNotifyPropertyChangedProxy();
_transformProxy.Subscribe(renderTransform, _transformChanged);
}
}

void OnInvalidatePathGeometryRequested(object sender, EventArgs e)
void StopNotifyingTransformChanges()
{
OnPropertyChanged(nameof(Data));
_transformProxy?.Unsubscribe();
}

void OnTransformPropertyChanged(object sender, PropertyChangedEventArgs args)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using System;
using Microsoft.Maui.Controls.Shapes;
using Microsoft.Maui.Graphics;
using Xunit;

namespace Microsoft.Maui.Controls.Core.UnitTests.Shapes;

public class PathSharedResourcesMemoryLeakTests : BaseTestFixture
{
// NOTE: Path creation MUST be in a separate method.
// If created inline in the test method, the JIT keeps local variables alive for the
// entire method scope in debug mode — making the path uncollectable regardless of the fix.
// This is the standard .NET pattern for writing reliable GC/leak unit tests.

static WeakReference CreatePathWithGeometry(PathGeometry geometry)
{
var path = new Path { Data = geometry };
return new WeakReference(path);
}

static WeakReference CreatePathWithTransform(ScaleTransform transform)
{
var path = new Path { RenderTransform = transform };
return new WeakReference(path);
}

static WeakReference CreatePathWithBoth(PathGeometry geometry, ScaleTransform transform)
{
var path = new Path { Data = geometry, RenderTransform = transform };
return new WeakReference(path);
}

[Fact]
public void SharedPathGeometry_DoesNotKeepPathAlive()
{
var sharedGeometry = new PathGeometry
{
Figures = new PathFigureCollection
{
new PathFigure
{
StartPoint = new Point(0, 0),
Segments = new PathSegmentCollection
{
new LineSegment { Point = new Point(100, 100) }
}
}
}
};

var pathRef = CreatePathWithGeometry(sharedGeometry);

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Assert.False(pathRef.IsAlive,
"Path was not collected. The shared PathGeometry is holding a strong reference to " +
"Path via its PropertyChanged event handler. Use WeakGeometryChangedProxy to fix.");

// Ensures sharedGeometry is a live GC root during the Collect calls above.
GC.KeepAlive(sharedGeometry);
}

[Fact]
public void SharedRenderTransform_DoesNotKeepPathAlive()
{
var sharedTransform = new ScaleTransform(1.5, 1.5) { CenterX = 50, CenterY = 50 };

var pathRef = CreatePathWithTransform(sharedTransform);

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Assert.False(pathRef.IsAlive,
"Path was not collected. The shared ScaleTransform is holding a strong reference to " +
"Path via its PropertyChanged event handler. Use WeakNotifyPropertyChangedProxy to fix.");

GC.KeepAlive(sharedTransform);
}

[Fact]
public void SharedGeometryAndTransform_DoNotKeepPathAlive()
{
var sharedGeometry = new PathGeometry
{
Figures = new PathFigureCollection
{
new PathFigure
{
StartPoint = new Point(0, 0),
Segments = new PathSegmentCollection
{
new LineSegment { Point = new Point(50, 50) }
}
}
}
};
var sharedTransform = new ScaleTransform(2.0, 2.0) { CenterX = 25, CenterY = 25 };

var pathRef = CreatePathWithBoth(sharedGeometry, sharedTransform);

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Assert.False(pathRef.IsAlive,
"Path was not collected. Shared PathGeometry and/or ScaleTransform are holding " +
"strong references to Path via event subscriptions. Use weak proxies to fix.");

GC.KeepAlive(sharedGeometry);
GC.KeepAlive(sharedTransform);
}
}
Loading