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
92 changes: 69 additions & 23 deletions src/Controls/tests/Core.UnitTests/MapTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1442,37 +1442,37 @@ public void ClusterInfoConstructorThrowsOnNullArguments()
}

[Fact]
public void GetClusterIconCacheKeyForFileImageSourceIsStableAcrossInstances()
public void GetIconCacheKeyForFileImageSourceIsStableAcrossInstances()
{
var first = new FileImageSource { File = "icon.png" };
var second = new FileImageSource { File = "icon.png" };

var firstKey = MapHandler.GetClusterIconCacheKey(first);
var secondKey = MapHandler.GetClusterIconCacheKey(second);
var firstKey = MapHandler.GetIconCacheKey(first);
var secondKey = MapHandler.GetIconCacheKey(second);

Assert.NotNull(firstKey);
Assert.StartsWith("file:", firstKey, StringComparison.Ordinal);
Assert.Equal(firstKey, secondKey);
}

[Fact]
public void GetClusterIconCacheKeyForUriImageSourceDependsOnCachingEnabled()
public void GetIconCacheKeyForUriImageSourceDependsOnCachingEnabled()
{
var uri = new Uri("https://example.com/icon.png");

var cachingEnabled = new UriImageSource { Uri = uri, CachingEnabled = true };
var cachingDisabled = new UriImageSource { Uri = uri, CachingEnabled = false };

var enabledKey = MapHandler.GetClusterIconCacheKey(cachingEnabled);
var disabledKey = MapHandler.GetClusterIconCacheKey(cachingDisabled);
var enabledKey = MapHandler.GetIconCacheKey(cachingEnabled);
var disabledKey = MapHandler.GetIconCacheKey(cachingDisabled);

Assert.NotNull(enabledKey);
Assert.StartsWith("uri:", enabledKey, StringComparison.Ordinal);
Assert.Null(disabledKey);
}

[Fact]
public void GetClusterIconCacheKeyForUriImageSourceRequiresPositiveValidity()
public void GetIconCacheKeyForUriImageSourceRequiresPositiveValidity()
{
var source = new UriImageSource
{
Expand All @@ -1481,22 +1481,22 @@ public void GetClusterIconCacheKeyForUriImageSourceRequiresPositiveValidity()
CacheValidity = TimeSpan.Zero
};

Assert.Null(MapHandler.GetClusterIconCacheKey(source));
Assert.Null(MapHandler.GetIconCacheKey(source));
}

[Fact]
public void GetClusterIconCacheKeyForFontImageSourceContainsGlyph()
public void GetIconCacheKeyForFontImageSourceContainsGlyph()
{
var font = new FontImageSource { Glyph = "A", FontFamily = "F", Size = 24, Color = Colors.White };

var key = MapHandler.GetClusterIconCacheKey(font);
var key = MapHandler.GetIconCacheKey(font);

Assert.NotNull(key);
Assert.Contains("A", key, StringComparison.Ordinal);
}

[Fact]
public void GetClusterIconCacheKeyForFontImageSourceDistinguishesWeight()
public void GetIconCacheKeyForFontImageSourceDistinguishesWeight()
{
var regular = new FakeFontImageSource
{
Expand All @@ -1511,16 +1511,16 @@ public void GetClusterIconCacheKeyForFontImageSourceDistinguishesWeight()
Font = Font.OfSize("F", 24).WithWeight(FontWeight.Bold)
};

var regularKey = MapHandler.GetClusterIconCacheKey(regular);
var boldKey = MapHandler.GetClusterIconCacheKey(bold);
var regularKey = MapHandler.GetIconCacheKey(regular);
var boldKey = MapHandler.GetIconCacheKey(bold);

Assert.NotNull(regularKey);
Assert.NotNull(boldKey);
Assert.NotEqual(regularKey, boldKey);
}

[Fact]
public void GetClusterIconCacheKeyForFontImageSourceDistinguishesAutoScaling()
public void GetIconCacheKeyForFontImageSourceDistinguishesAutoScaling()
{
var scalingEnabled = new FakeFontImageSource
{
Expand All @@ -1535,27 +1535,27 @@ public void GetClusterIconCacheKeyForFontImageSourceDistinguishesAutoScaling()
Font = Font.OfSize("F", 24, enableScaling: false)
};

var enabledKey = MapHandler.GetClusterIconCacheKey(scalingEnabled);
var disabledKey = MapHandler.GetClusterIconCacheKey(scalingDisabled);
var enabledKey = MapHandler.GetIconCacheKey(scalingEnabled);
var disabledKey = MapHandler.GetIconCacheKey(scalingDisabled);

Assert.NotNull(enabledKey);
Assert.NotNull(disabledKey);
Assert.NotEqual(enabledKey, disabledKey);
}

[Fact]
public void GetClusterIconCacheKeyIsNullForStreamOrMissingSource()
public void GetIconCacheKeyIsNullForStreamOrMissingSource()
{
var stream = new StreamImageSource();

Assert.Null(MapHandler.GetClusterIconCacheKey(stream));
Assert.Null(MapHandler.GetClusterIconCacheKey(null));
Assert.Null(MapHandler.GetIconCacheKey(stream));
Assert.Null(MapHandler.GetIconCacheKey(null));
}

[Fact]
public async Task ClusterIconCacheCoalescesConcurrentLoads()
public async Task IconCacheCoalescesConcurrentLoads()
{
var cache = new ClusterIconCache<object>(2);
var cache = new IconCache<object>(2);
var release = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var loadCount = 0;

Expand All @@ -1576,9 +1576,9 @@ Task<object> Load()
}

[Fact]
public async Task ClusterIconCacheEvictsLeastRecentlyUsedEntry()
public async Task IconCacheEvictsLeastRecentlyUsedEntry()
{
var cache = new ClusterIconCache<object>(2);
var cache = new IconCache<object>(2);
var first = new object();
var second = new object();
var third = new object();
Expand All @@ -1595,6 +1595,52 @@ public async Task ClusterIconCacheEvictsLeastRecentlyUsedEntry()
Assert.Same(third, cachedThird);
}

// The recluster path re-runs AddPins on every zoom step, so this is what stops a pin's icon
// being decoded and rescaled again on each pass.
[Fact]
public async Task IconCacheDoesNotReloadAKeyedSourceOnALaterPass()

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.

🔍 AI-Generated Review (multi-model)

[moderate] Regression Prevention and Test Coverage — The two added tests exercise only the IconCache<T> primitive (keyed reuse, null-key bypass), which already existed and is not where the reported bug lives. None of the actual behavior changes in this PR are covered: the reused MarkerOptions being cleared when ImageSource becomes null, UpdatePinImageSourceAsync writing back to the handler's MarkerOptions so a later cluster pass does not restore the previous icon, and the post-await stale-source guard in AddPinAsync. Those are the changes that could regress #37773, and they only fail-without-fix here because of the type rename, not because of behavior. A device/UI test on Android that sets a pin ImageSource, forces a zoom-driven recluster, and asserts the icon survives (and that clearing ImageSource reverts to the default marker) would give this fix real regression protection.

{
var cache = new IconCache<object>(2);
var icon = new object();
var loadCount = 0;

Task<object> Load()
{
loadCount++;
return Task.FromResult(icon);
}

var first = await cache.GetOrCreateAsync("file:pin.png", Load, () => DateTime.MaxValue);
var second = await cache.GetOrCreateAsync("file:pin.png", Load, () => DateTime.MaxValue);

Assert.Equal(1, loadCount);
Assert.Same(icon, first);
Assert.Same(second, first);
}

// GetIconCacheKey returns null for a source that can't be keyed stably, or that opted out of
// caching (see GetIconCacheKeyForUriImageSourceDependsOnCachingEnabled). Those must never be
// frozen by the handler-level cache - they reload on every pass instead.
[Fact]
public async Task IconCacheAlwaysReloadsWhenTheKeyIsNull()
{
var cache = new IconCache<object>(2);
var loadCount = 0;

Task<object> Load()
{
loadCount++;
return Task.FromResult(new object());
}

var first = await cache.GetOrCreateAsync(null, Load, () => DateTime.MaxValue);
var second = await cache.GetOrCreateAsync(null, Load, () => DateTime.MaxValue);

Assert.Equal(2, loadCount);
Assert.NotSame(first, second);
Assert.Equal(0, cache.Count);
}

class FakeFontImageSource : IFontImageSource
{
public Color Color { get; set; }
Expand Down
67 changes: 51 additions & 16 deletions src/Core/maps/src/Handlers/Map/MapHandler.Android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ public partial class MapHandler : ViewHandler<IMap, MapView>
bool _isClusteringEnabled;
List<MapCluster>? _clusters;
Dictionary<string, MapCluster>? _clusterMarkers;
const int MaxClusterIconCacheSize = 64;
readonly ClusterIconCache<BitmapDescriptor> _clusterIconCache = new(MaxClusterIconCacheSize);
const int MaxIconCacheSize = 64;
readonly IconCache<BitmapDescriptor> _iconCache = new(MaxIconCacheSize);

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.

🔍 AI-Generated Review (multi-model)

[moderate] Performance-Critical Path — The 64-entry LRU is now shared between cluster icons and every un-clustered pin icon, but the capacity was not revisited. On a map with more than 64 distinct pin ImageSources (a common clustering scenario), a single AddPins pass touches more distinct keys than the cache can hold, so entries are evicted in the same pass that inserted them: pin icons still decode every recluster, and the cluster icons that the cache originally existed to protect are now evicted by pin traffic on each zoom step. That is a regression of the pre-existing cluster-icon caching in exactly the workload this PR targets. Either size the cache relative to the pin count or keep cluster icons in a separate partition/reserved segment.

WeakReference<IMap>? _clusterImageOwner;
int _clusterImageVersion = int.MinValue;

Expand Down Expand Up @@ -135,7 +135,7 @@ protected override void DisconnectHandler(MapView platformView)
_circles = null;
_clusters?.Clear();
_clusterMarkers?.Clear();
_clusterIconCache.Clear();
_iconCache.Clear();
_clusterImageOwner = null;
_clusterImageVersion = int.MinValue;
_init = true;
Expand Down Expand Up @@ -414,7 +414,7 @@ void UpdateClusterImageVersion(IMap map)

_clusterImageOwner = new WeakReference<IMap>(map);
_clusterImageVersion = version;
_clusterIconCache.Clear();
_iconCache.Clear();

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.

🔍 AI-Generated Review (multi-model)

[minor] Performance-Critical Path — This Clear() fires whenever the cluster image version changes, and it now discards all cached pin icons as well, not just cluster icons. An app that recomputes its cluster image (bumping the version) while zooming forces every pin icon to be decoded and rescaled again on the next pass — the exact cost this PR set out to remove. Scoping the invalidation to cluster-image keys (e.g. a key prefix or a separate cache instance for cluster images) would keep the pin entries alive.

}

/// <summary>
Expand Down Expand Up @@ -907,11 +907,27 @@ async Task AddPinAsync(IMapPin pin, CancellationToken ct)

var markerOptions = iMapPinHandler.PlatformView;

// Load custom image if specified
if (pin.ImageSource != null)
// Captured before the await: if ImageSource changes while the load is running, the write
// below has to be dropped rather than publish a marker with the older icon.
var requestedSource = pin.ImageSource;

if (requestedSource is null)
{
// The MarkerOptions are reused, so a cleared ImageSource has to take the previous
// icon off them - null is Android's "use the default marker".
markerOptions.SetIcon(null);
}
else
{
var icon = await LoadPinIconAsync(pin.ImageSource, MauiContext, ct);
if (icon != null)
// Clustering re-runs AddPins on every zoom change, so without the cache the icon of
// every un-clustered pin is decoded and rescaled again on each pass.
var icon = await GetIconAsync(requestedSource, MauiContext, ct);

// Re-checked after the await: UpdatePinImageSourceAsync can have applied a newer
// source in the meantime, and it guards its own write the same way. Without this
// the two writers race and the marker can be published with the older icon while
// the change notification that would fix it has already been consumed.
if (icon != null && ReferenceEquals(pin.ImageSource, requestedSource))

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.

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — The post-await guard drops the icon write, but the comment's assumption that UpdatePinImageSourceAsync will supply the newer icon does not hold during a recluster pass. ReclusterPins removes every marker and sets _markers = null before calling AddPins, while pin.MarkerId still names the removed marker. If pin.ImageSource changes from A to B while this await GetIconAsync(...) is in flight, PinOnPropertyChanged runs, fails to find a matching entry in the freshly rebuilt _markers list, and returns without scheduling UpdatePinImageSourceAsync. This method then resumes, ReferenceEquals(pin.ImageSource, requestedSource) is false, so nothing is written — and the reused MarkerOptions still carries icon A from the previous pass. Map.AddMarker(markerOptions) publishes the marker with the stale icon A and no further notification arrives to correct it. Consider re-reading pin.ImageSource and loading/clearing the current source instead of silently skipping the write.

markerOptions.SetIcon(icon);
}

Expand Down Expand Up @@ -955,9 +971,35 @@ async Task UpdatePinImageSourceAsync(IMapPin pin, Marker marker, CancellationTok
if (!ct.IsCancellationRequested && ReferenceEquals(pin.ImageSource, requestedSource) && (pin.MarkerId as string) == marker.Id)
{
marker.SetIcon(icon);

// The MarkerOptions are reused the next time this pin is added, so update them too -
// otherwise the next cluster pass would restore the previous icon. Reached through
// the non-throwing accessor: this resumes after an await, and the typed PlatformView
// throws once the handler has been disconnected.
if (pin.Handler is MapPinHandler mapPinHandler &&
((IElementHandler)mapPinHandler).PlatformView is MarkerOptions handlerOptions)
{
handlerOptions.SetIcon(icon);

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.

🔍 AI-Generated Review (multi-model)

[minor] Complexity Reduction — This new write pushes the descriptor produced by the direct LoadPinIconAsync call in this method onto the handler's reused MarkerOptions, bypassing GetIconAsync/_iconCache. Consequences: (1) setting a pin's ImageSource to an image already in the cache still triggers a full decode/rescale, and (2) the descriptor stored on MarkerOptions is a different instance from the one AddPinAsync will hand the same key on the next pass, so the two paths do not actually converge on one decoded bitmap. Routing this method's load through GetIconAsync as well would make the caching invariant stated in the IconCache comment true for both writers.

}
}
}

// Shared by pin and cluster markers: one decoded descriptor backs every marker naming the same
// image, so a recluster pass reuses it instead of decoding per marker. GetIconCacheKey returns
// null for a source that can't be keyed stably, or that opted out of caching - those load fresh
// every time, which is also why they keep this caller's ct: nobody else is waiting on them.
// A keyable load is shared, so it must not be cancelled by whichever caller happened to start it.
Task<BitmapDescriptor?> GetIconAsync(IImageSource imageSource, IMauiContext mauiContext, CancellationToken ct)

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.

🔍 AI-Generated Review (multi-model)

[minor] Async and Threading Safety — For any keyable source the load is started with CancellationToken.None, so LoadPinIconAsync -> imageSource.GetPlatformImageAsync(mauiContext) can no longer be aborted. Previously only cluster images had this property; it now applies to every pin icon. A slow or hanging IUriImageSource load started just before DisconnectHandler/AddPins cancellation keeps running with the captured IMauiContext until it completes, and the result is stored in the handler cache afterwards. The callers still re-check ct after the await, so there is no incorrect write — but the underlying work and the context capture outlive the cancellation. A linked token that is cancelled only when all awaiters have gone away would preserve both sharing and cancellability.

{
var cacheKey = GetIconCacheKey(imageSource);
var loadToken = cacheKey is null ? ct : CancellationToken.None;

return _iconCache.GetOrCreateAsync(
cacheKey,
() => LoadPinIconAsync(imageSource, mauiContext, loadToken),
() => GetIconCacheExpiry(imageSource));
}

// Loads imageSource into a BitmapDescriptor
// Returns null on cancel/failure/no drawable.
static async Task<BitmapDescriptor?> LoadPinIconAsync(IImageSource imageSource, IMauiContext mauiContext, CancellationToken ct)
Expand Down Expand Up @@ -1009,14 +1051,7 @@ async Task AddClusterMarkerAsync(MapCluster cluster, CancellationToken ct)

BitmapDescriptor? icon = null;
if (image != null)
{
var cacheKey = GetClusterIconCacheKey(image);
var loadToken = cacheKey is null ? ct : CancellationToken.None;
icon = await _clusterIconCache.GetOrCreateAsync(
cacheKey,
() => LoadPinIconAsync(image, mauiContext, loadToken),
() => GetClusterIconCacheExpiry(image));
}
icon = await GetIconAsync(image, mauiContext, ct);

if (ct.IsCancellationRequested || !ReferenceEquals(Map, map))
return;
Expand Down
19 changes: 11 additions & 8 deletions src/Core/maps/src/Handlers/Map/MapHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,13 @@ public static void MapHideInfoWindow(IMapHandler handler, IMap map, object? arg)
mapHandler.HideInfoWindow(pin);
}

// Builds a stable cache key for a cluster icon so logically identical images (same file, URI,
// or font glyph) share one decoded/rasterized bitmap even when the provider hands back a fresh
// ImageSource instance on every recluster. Returns null for sources that can't be keyed stably
// (e.g. streams), so those are simply loaded fresh instead of being cached forever.
// Builds a stable cache key for a marker icon - cluster or pin - so logically identical images
// (same file, URI, or font glyph) share one decoded/rasterized bitmap even when the caller hands
// back a fresh ImageSource instance on every recluster. Returns null for sources that can't be
// keyed stably (e.g. streams), so those are simply loaded fresh instead of being cached forever.
// A URI source with CachingEnabled == false has explicitly opted out of caching, so it must not
// be frozen by this handler-level cache either.
internal static string? GetClusterIconCacheKey(IImageSource? source) =>
internal static string? GetIconCacheKey(IImageSource? source) =>
source switch
{
IFileImageSource file when !string.IsNullOrEmpty(file.File) => $"file:{file.File}",
Expand All @@ -124,7 +124,7 @@ public static void MapHideInfoWindow(IMapHandler handler, IMap map, object? arg)
// URI sources carry an explicit CacheValidity; other stable sources never expire on their own
// (the cache is bounded and cleared during handler cleanup). Clamped so a large
// validity like TimeSpan.MaxValue ("cache forever") can't overflow DateTime arithmetic.
internal static DateTime GetClusterIconCacheExpiry(IImageSource? source)
internal static DateTime GetIconCacheExpiry(IImageSource? source)
{
if (source is not IUriImageSource uri)
return DateTime.MaxValue;
Expand All @@ -134,7 +134,10 @@ internal static DateTime GetClusterIconCacheExpiry(IImageSource? source)
}
}

internal sealed class ClusterIconCache<T>
// Bounded LRU of decoded marker icons, shared by cluster and pin markers so one decode serves
// every marker naming the same image. Keys come from MapHandler.GetIconCacheKey; a null key
// bypasses the cache entirely rather than being stored under a fabricated one.
internal sealed class IconCache<T>
where T : class
{
readonly Dictionary<string, (T Value, DateTime ExpiresAtUtc, long AccessTick)> _entries = new();
Expand All @@ -145,7 +148,7 @@ internal sealed class ClusterIconCache<T>
long _accessCounter;
int _generation;

internal ClusterIconCache(int capacity, Action<T>? disposeValue = null)
internal IconCache(int capacity, Action<T>? disposeValue = null)
{
if (capacity <= 0)
throw new ArgumentOutOfRangeException(nameof(capacity));
Expand Down
Loading
Loading