XAML-Map-Control/MapControl/Shared/TileImageLoader.cs

235 lines
9.6 KiB
C#
Raw Normal View History

2025-02-27 18:46:32 +01:00
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
2025-03-31 21:33:52 +02:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2017-08-04 21:38:58 +02:00
using System;
using System.Collections.Concurrent;
2019-06-10 17:20:21 +02:00
using System.Collections.Generic;
2024-08-30 16:37:40 +02:00
using System.IO;
using System.Linq;
2025-08-20 19:50:22 +02:00
using System.Security.Policy;
2025-08-19 23:20:11 +02:00
using System.Threading;
using System.Threading.Tasks;
2025-05-08 19:51:31 +02:00
#if WPF
using System.Windows.Media;
#elif UWP
using Windows.UI.Xaml.Media;
#elif WINUI
using Microsoft.UI.Xaml.Media;
#endif
2017-08-04 21:38:58 +02:00
namespace MapControl
{
/// <summary>
/// Loads and optionally caches map tile images for a MapTileLayer.
/// </summary>
public interface ITileImageLoader
{
2025-08-20 00:29:56 +02:00
Task LoadTilesAsync(IEnumerable<Tile> tiles, TileSource tileSource, string cacheName, IProgress<double> progress, CancellationToken cancellationToken);
}
2017-08-04 21:38:58 +02:00
public partial class TileImageLoader : ITileImageLoader
{
2024-08-15 19:46:14 +02:00
/// <summary>
/// Default folder path where a persistent cache implementation may save data, i.e. "C:\ProgramData\MapControl\TileCache".
/// </summary>
public static string DefaultCacheFolder =>
2025-02-20 11:45:45 +01:00
#if UWP
Path.Combine(Windows.Storage.ApplicationData.Current.LocalCacheFolder.Path, "TileCache");
#else
2024-08-30 16:37:40 +02:00
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MapControl", "TileCache");
2025-02-20 11:45:45 +01:00
#endif
2017-08-04 21:38:58 +02:00
/// <summary>
2024-02-03 20:53:32 +01:00
/// An IDistributedCache implementation used to cache tile images.
/// The default value is a MemoryDistributedCache instance.
2017-08-04 21:38:58 +02:00
/// </summary>
public static IDistributedCache Cache { get; set; } = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
2017-08-04 21:38:58 +02:00
/// <summary>
/// Default expiration time for cached tile images. Used when no expiration time
/// was transmitted on download. The default value is one day.
2017-08-04 21:38:58 +02:00
/// </summary>
public static TimeSpan DefaultCacheExpiration { get; set; } = TimeSpan.FromDays(1);
2017-08-04 21:38:58 +02:00
2025-02-18 17:22:14 +01:00
/// <summary>
/// Minimum expiration time for cached tile images. A transmitted expiration time
/// that falls below this value is ignored. The default value is TimeSpan.Zero.
/// </summary>
public static TimeSpan MinCacheExpiration { get; set; } = TimeSpan.Zero;
2017-08-04 21:38:58 +02:00
/// <summary>
2021-01-07 22:52:41 +01:00
/// Maximum expiration time for cached tile images. A transmitted expiration time
/// that exceeds this value is ignored. The default value is ten days.
2017-08-04 21:38:58 +02:00
/// </summary>
2021-01-07 22:52:41 +01:00
public static TimeSpan MaxCacheExpiration { get; set; } = TimeSpan.FromDays(10);
2024-02-03 20:53:32 +01:00
/// <summary>
/// Maximum number of parallel tile loading tasks. The default value is 4.
/// </summary>
public static int MaxLoadTasks { get; set; } = 4;
/// <summary>
/// Indicates whether HTTP requests are cancelled when the LoadTilesAsync method is cancelled.
/// If the property value is false, cancellation only stops dequeuing entries from the tile queue,
/// but lets currently running requests run to completion.
/// </summary>
public static bool RequestCancellationEnabled { get; set; }
2025-03-31 21:33:52 +02:00
private static ILogger logger;
private static ILogger Logger => logger ?? (logger = ImageLoader.LoggerFactory?.CreateLogger<TileImageLoader>());
/// <summary>
/// Loads all pending tiles from the tiles collection. Tile image caching is enabled when the Cache
2025-08-19 23:20:11 +02:00
/// property is not null and tileSource.UriFormat starts with "http" and cacheName is a non-empty string.
/// </summary>
2025-08-20 00:29:56 +02:00
public async Task LoadTilesAsync(IEnumerable<Tile> tiles, TileSource tileSource, string cacheName, IProgress<double> progress, CancellationToken cancellationToken)
2017-08-04 21:38:58 +02:00
{
2025-08-20 00:29:56 +02:00
var pendingTiles = new ConcurrentStack<Tile>(tiles.Where(tile => tile.IsPending).Reverse());
var tileCount = pendingTiles.Count;
var taskCount = Math.Min(tileCount, MaxLoadTasks);
2021-11-22 23:07:07 +01:00
2025-08-20 00:29:56 +02:00
if (taskCount > 0)
2021-11-22 23:07:07 +01:00
{
2025-08-20 00:29:56 +02:00
if (Cache == null || tileSource.UriTemplate == null || !tileSource.UriTemplate.StartsWith("http"))
{
cacheName = null; // disable tile image caching
}
2021-07-05 14:51:28 +02:00
2025-08-20 00:29:56 +02:00
async Task LoadTilesFromQueueAsync()
2021-11-28 23:50:22 +01:00
{
2025-08-20 00:29:56 +02:00
while (!cancellationToken.IsCancellationRequested && pendingTiles.TryPop(out var tile))
2021-11-28 23:50:22 +01:00
{
2025-08-20 00:29:56 +02:00
tile.IsPending = false;
2023-08-16 22:20:04 +02:00
progress?.Report((double)(tileCount - pendingTiles.Count) / tileCount);
2025-08-19 23:20:11 +02:00
2025-08-20 19:50:22 +02:00
Logger?.LogTrace("[{thread}] Loading tile image {zoom}/{column}/{row}", Environment.CurrentManagedThreadId, tile.ZoomLevel, tile.Column, tile.Row);
2025-08-20 17:12:09 +02:00
2025-08-20 00:29:56 +02:00
try
{
2025-08-20 19:50:22 +02:00
var requestCancellationToken = RequestCancellationEnabled ? cancellationToken : CancellationToken.None;
await LoadTileImage(tile, tileSource, cacheName, requestCancellationToken).ConfigureAwait(false);
2025-08-20 00:29:56 +02:00
}
catch (Exception ex)
2023-08-12 17:36:37 +02:00
{
2025-08-20 00:29:56 +02:00
Logger?.LogError(ex, "Failed loading tile image {zoom}/{column}/{row}", tile.ZoomLevel, tile.Column, tile.Row);
2023-08-12 17:36:37 +02:00
}
}
2025-08-20 00:29:56 +02:00
}
try
{
var tasks = new Task[taskCount];
for (int i = 0; i < taskCount; i++)
{
tasks[i] = Task.Run(LoadTilesFromQueueAsync, cancellationToken);
}
2025-08-20 17:12:09 +02:00
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
2025-08-20 00:29:56 +02:00
{
// no action
}
2025-08-20 00:29:56 +02:00
if (cancellationToken.IsCancellationRequested)
{
2025-08-20 17:12:09 +02:00
Logger?.LogTrace("Cancelled LoadTilesAsync with {count} pending tiles", pendingTiles.Count);
}
2017-08-04 21:38:58 +02:00
}
}
2025-08-19 23:20:11 +02:00
private static async Task LoadTileImage(Tile tile, TileSource tileSource, string cacheName, CancellationToken cancellationToken)
{
2025-01-20 19:28:59 +01:00
// Pass tileSource.LoadImageAsync calls to platform-specific method
2025-01-26 22:40:33 +01:00
// LoadTileImage(Tile, Func<Task<ImageSource>>) for execution on the UI thread in WinUI and UWP.
2024-08-31 11:55:59 +02:00
2025-01-20 19:28:59 +01:00
if (string.IsNullOrEmpty(cacheName))
{
2025-08-19 23:20:11 +02:00
Task<ImageSource> LoadImage() => tileSource.LoadImageAsync(tile.Column, tile.Row, tile.ZoomLevel, cancellationToken);
2025-05-08 19:51:31 +02:00
await LoadTileImage(tile, LoadImage, cancellationToken).ConfigureAwait(false);
2025-01-20 19:28:59 +01:00
}
else
{
var uri = tileSource.GetUri(tile.Column, tile.Row, tile.ZoomLevel);
if (uri != null)
2025-01-17 17:21:05 +01:00
{
2025-08-19 23:20:11 +02:00
var buffer = await LoadCachedBuffer(tile, uri, cacheName, cancellationToken).ConfigureAwait(false);
2025-01-20 19:28:59 +01:00
if (buffer != null && buffer.Length > 0)
2025-01-17 17:21:05 +01:00
{
2025-05-08 19:51:31 +02:00
Task<ImageSource> LoadImage() => tileSource.LoadImageAsync(buffer);
await LoadTileImage(tile, LoadImage, cancellationToken).ConfigureAwait(false);
2025-01-17 17:21:05 +01:00
}
}
}
2017-08-04 21:38:58 +02:00
}
2025-08-19 23:20:11 +02:00
private static async Task<byte[]> LoadCachedBuffer(Tile tile, Uri uri, string cacheName, CancellationToken cancellationToken)
2017-08-04 21:38:58 +02:00
{
byte[] buffer = null;
2024-08-30 16:37:40 +02:00
var extension = Path.GetExtension(uri.LocalPath);
2024-02-03 20:53:32 +01:00
2024-02-07 19:18:16 +01:00
if (string.IsNullOrEmpty(extension) || extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
2021-01-07 22:52:41 +01:00
{
2024-02-03 20:53:32 +01:00
extension = ".jpg";
2021-01-07 22:52:41 +01:00
}
2024-02-03 20:53:32 +01:00
2024-04-16 19:55:59 +02:00
var cacheKey = $"{cacheName}/{tile.ZoomLevel}/{tile.Column}/{tile.Row}{extension}";
2024-02-03 20:53:32 +01:00
try
{
2025-08-19 23:20:11 +02:00
buffer = await Cache.GetAsync(cacheKey, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Logger?.LogTrace("Cancelled Cache.GetAsync({cacheKey})", cacheKey);
}
catch (Exception ex)
{
Logger?.LogError(ex, "Cache.GetAsync({cacheKey})", cacheKey);
}
2024-02-03 20:53:32 +01:00
if (buffer == null)
2021-01-07 22:52:41 +01:00
{
2025-08-19 23:20:11 +02:00
var response = await ImageLoader.GetHttpResponseAsync(uri, null, cancellationToken).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
2024-02-05 14:10:10 +01:00
if (response != null)
2024-02-03 20:53:32 +01:00
{
2025-05-08 19:51:31 +02:00
buffer = response.Buffer ?? Array.Empty<byte>(); // cache even if null, when no tile available
2024-02-03 20:53:32 +01:00
try
{
2025-05-08 19:51:31 +02:00
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
!response.MaxAge.HasValue ? DefaultCacheExpiration
: response.MaxAge.Value < MinCacheExpiration ? MinCacheExpiration
: response.MaxAge.Value > MaxCacheExpiration ? MaxCacheExpiration
: response.MaxAge.Value
};
2025-08-19 23:20:11 +02:00
await Cache.SetAsync(cacheKey, buffer, options, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Logger?.LogTrace("Cancelled Cache.SetAsync({cacheKey})", cacheKey);
}
catch (Exception ex)
{
Logger?.LogError(ex, "Cache.SetAsync({cacheKey})", cacheKey);
}
}
2024-02-09 16:10:55 +01:00
}
return buffer;
2024-02-09 16:10:55 +01:00
}
2017-08-04 21:38:58 +02:00
}
}