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

187 lines
6.5 KiB
C#
Raw Normal View History

2017-08-04 21:38:58 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2024-02-03 21:01:53 +01:00
// Copyright © 2024 Clemens Fischer
2017-08-04 21:38:58 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
2024-02-03 20:53:32 +01:00
using Microsoft.Extensions.Caching.Distributed;
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;
2019-06-10 22:18:02 +02:00
using System.Diagnostics;
2021-07-05 00:03:44 +02:00
using System.Globalization;
2017-08-04 21:38:58 +02:00
using System.IO;
using System.Linq;
2017-08-04 21:38:58 +02:00
using System.Threading.Tasks;
namespace MapControl
{
/// <summary>
/// Loads and optionally caches map tile images for a MapTileLayer.
/// </summary>
public partial class TileImageLoader : ITileImageLoader
{
private class TileQueue : ConcurrentStack<Tile>
{
public TileQueue(IEnumerable<Tile> tiles)
2023-08-12 17:36:37 +02:00
: base(tiles.Where(tile => tile.IsPending).Reverse())
{
}
public bool TryDequeue(out Tile tile)
{
2023-08-15 07:27:50 +02:00
if (TryPop(out tile))
{
2023-08-15 07:27:50 +02:00
tile.IsPending = false;
return true;
}
2023-08-15 07:27:50 +02:00
tile = null;
return false;
}
}
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.
2017-08-04 21:38:58 +02:00
/// </summary>
2024-02-03 20:53:32 +01:00
public static IDistributedCache Cache { get; set; }
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
/// <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;
2023-08-12 17:36:37 +02:00
private TileQueue pendingTiles;
2017-08-04 21:38:58 +02:00
/// <summary>
2023-08-16 22:20:04 +02:00
/// Loads all pending tiles from the tiles collection.
2021-07-06 01:01:22 +02:00
/// If tileSource.UriFormat starts with "http" and cacheName is a non-empty string,
/// tile images will be cached in the TileImageLoader's Cache - if that is not null.
/// </summary>
public Task LoadTilesAsync(IEnumerable<Tile> tiles, TileSource tileSource, string cacheName, IProgress<double> progress)
2017-08-04 21:38:58 +02:00
{
2023-08-15 07:27:50 +02:00
pendingTiles?.Clear();
2021-11-22 23:07:07 +01:00
2023-08-12 17:36:37 +02:00
if (tiles != null && tileSource != null)
2021-11-22 23:07:07 +01:00
{
2023-08-12 17:36:37 +02:00
pendingTiles = new TileQueue(tiles);
2021-07-05 14:51:28 +02:00
2023-08-15 07:27:50 +02:00
var tileCount = pendingTiles.Count;
var taskCount = Math.Min(tileCount, MaxLoadTasks);
2021-07-05 14:51:28 +02:00
2023-08-15 07:27:50 +02:00
if (taskCount > 0)
2021-11-28 23:50:22 +01:00
{
if (Cache == null || tileSource.UriTemplate == null || !tileSource.UriTemplate.StartsWith("http"))
2021-11-28 23:50:22 +01:00
{
cacheName = null; // no tile caching
}
2019-06-10 22:18:02 +02:00
2023-08-15 17:37:25 +02:00
progress?.Report(0d);
2023-08-16 22:20:04 +02:00
var tileQueue = pendingTiles; // pendingTiles may change while tasks are running
var tasks = new Task[taskCount];
async Task LoadTilesFromQueueAsync()
2023-08-12 17:36:37 +02:00
{
2023-08-15 07:27:50 +02:00
while (tileQueue.TryDequeue(out var tile))
2023-08-12 17:36:37 +02:00
{
2023-08-15 17:37:25 +02:00
progress?.Report((double)(tileCount - tileQueue.Count) / tileCount);
2023-08-12 17:36:37 +02:00
try
{
await LoadTileAsync(tile, tileSource, cacheName).ConfigureAwait(false);
2023-08-12 17:36:37 +02:00
}
catch (Exception ex)
{
Debug.WriteLine($"TileImageLoader: {tile.ZoomLevel}/{tile.Column}/{tile.Row}: {ex.Message}");
}
}
}
2023-08-16 22:20:04 +02:00
for (int i = 0; i < taskCount; i++)
{
tasks[i] = Task.Run(LoadTilesFromQueueAsync);
2023-08-16 22:20:04 +02:00
}
return Task.WhenAll(tasks);
}
2017-08-04 21:38:58 +02:00
}
2023-08-12 17:36:37 +02:00
return Task.CompletedTask;
2017-08-04 21:38:58 +02:00
}
private static Task LoadTileAsync(Tile tile, TileSource tileSource, string cacheName)
{
2021-07-06 22:58:03 +02:00
if (string.IsNullOrEmpty(cacheName))
{
return LoadTileAsync(tile, () => tileSource.LoadImageAsync(tile.Column, tile.Row, tile.ZoomLevel));
2021-01-23 17:41:52 +01:00
}
2022-11-22 19:15:34 +01:00
var uri = tileSource.GetUri(tile.Column, tile.Row, tile.ZoomLevel);
2021-11-28 23:50:22 +01:00
if (uri != null)
{
2024-02-03 20:53:32 +01:00
return LoadCachedTileAsync(tile, uri, cacheName);
}
2021-11-28 23:50:22 +01:00
return Task.CompletedTask;
2017-08-04 21:38:58 +02:00
}
2024-02-03 20:53:32 +01:00
private static async Task LoadCachedTileAsync(Tile tile, Uri uri, string cacheName)
2017-08-04 21:38:58 +02:00
{
2024-02-03 20:53:32 +01:00
var extension = Path.GetExtension(uri.LocalPath);
if (string.IsNullOrEmpty(extension) || extension == ".jpeg")
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
var cacheKey = string.Format(CultureInfo.InvariantCulture,
"{0}/{1}/{2}/{3}{4}", cacheName, tile.ZoomLevel, tile.Column, tile.Row, extension);
var buffer = await Cache.GetAsync(cacheKey).ConfigureAwait(false);
if (buffer == null)
2021-01-07 22:52:41 +01:00
{
2024-02-03 20:53:32 +01:00
var response = await ImageLoader.GetHttpResponseAsync(uri).ConfigureAwait(false);
if (response != null) // download succeeded
{
buffer = response.Buffer ?? Array.Empty<byte>(); // may be empty when no tile available, but still be cached
var maxAge = response.MaxAge ?? DefaultCacheExpiration;
if (maxAge > MaxCacheExpiration)
{
maxAge = MaxCacheExpiration;
}
var cacheOptions = new DistributedCacheEntryOptions
{
AbsoluteExpiration = DateTimeOffset.UtcNow.Add(maxAge)
};
await Cache.SetAsync(cacheKey, buffer, cacheOptions).ConfigureAwait(false);
}
2021-01-07 22:52:41 +01:00
}
2024-02-03 20:53:32 +01:00
//else System.Diagnostics.Debug.WriteLine($"Cached: {cacheKey}");
2021-01-07 22:52:41 +01:00
2024-02-03 20:53:32 +01:00
if (buffer != null && buffer.Length > 0)
{
await LoadTileAsync(tile, () => ImageLoader.LoadImageAsync(buffer)).ConfigureAwait(false);
}
2017-08-04 21:38:58 +02:00
}
}
}