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

143 lines
4.9 KiB
C#
Raw Normal View History

2017-08-04 21:38:58 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// © 2020 Clemens Fischer
2017-08-04 21:38:58 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
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;
2017-08-04 21:38:58 +02:00
using System.IO;
using System.Linq;
2019-06-10 22:18:02 +02:00
using System.Threading;
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
{
/// <summary>
2020-04-13 09:12:21 +02:00
/// Maximum number of parallel tile loading tasks. The default value is 4.
2017-08-04 21:38:58 +02:00
/// </summary>
2020-04-13 09:12:21 +02:00
public static int MaxLoadTasks { get; set; } = 4;
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>
/// Format string for creating cache keys from the sourceName argument passed to LoadTilesAsync,
/// the ZoomLevel, XIndex, and Y properties of a Tile, and the image file extension.
/// The default value is "{0}/{1}/{2}/{3}{4}".
2017-08-04 21:38:58 +02:00
/// </summary>
public static string CacheKeyFormat { get; set; } = "{0}/{1}/{2}/{3}{4}";
2017-08-04 21:38:58 +02:00
2020-09-24 23:33:23 +02:00
private class TileQueue : ConcurrentStack<Tile>
{
public void Enqueue(IEnumerable<Tile> tiles)
{
PushRange(tiles.Reverse().ToArray());
}
public bool TryDequeue(out Tile tile)
{
return TryPop(out tile);
}
}
2019-06-10 18:08:34 +02:00
private readonly TileQueue tileQueue = new TileQueue();
private Func<Tile, Task> loadTileImage;
2019-06-10 22:18:02 +02:00
private int taskCount;
2017-08-04 21:38:58 +02:00
/// <summary>
/// Loads all pending tiles from the tiles collection.
/// If tileSource.UriFormat starts with "http" and sourceName is a non-empty string,
/// tile images will be cached in the TileImageLoader's Cache (if it's not null).
2020-09-24 23:33:23 +02:00
/// The method is async void because it implements void ITileImageLoader.LoadTiles
/// and is not awaited when it is called in MapTileLayer.UpdateTiles().
/// </summary>
2020-09-24 23:33:23 +02:00
public async void LoadTiles(IEnumerable<Tile> tiles, TileSource tileSource, string sourceName)
2017-08-04 21:38:58 +02:00
{
2019-06-10 18:08:34 +02:00
tileQueue.Clear();
2019-06-10 22:18:02 +02:00
tiles = tiles.Where(tile => tile.Pending);
2019-06-10 22:18:02 +02:00
if (tiles.Any() && tileSource != null)
{
if (Cache != null &&
tileSource.UriFormat != null &&
tileSource.UriFormat.StartsWith("http") &&
!string.IsNullOrEmpty(sourceName))
{
loadTileImage = tile => LoadCachedTileImageAsync(tile, tileSource, sourceName);
}
else
{
loadTileImage = tile => LoadTileImageAsync(tile, tileSource);
}
tileQueue.Enqueue(tiles);
var newTasks = Math.Min(tileQueue.Count, MaxLoadTasks) - taskCount;
if (newTasks > 0)
{
Interlocked.Add(ref taskCount, newTasks);
2020-04-16 19:24:38 +02:00
var tasks = Enumerable.Range(0, newTasks).Select(n => LoadTilesFromQueueAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
2019-06-10 22:18:02 +02:00
}
}
private async Task LoadTilesFromQueueAsync()
2019-06-10 22:18:02 +02:00
{
2020-04-16 19:24:38 +02:00
while (tileQueue.TryDequeue(out Tile tile))
2019-06-10 22:18:02 +02:00
{
tile.Pending = false;
2019-06-10 22:18:02 +02:00
try
{
await loadTileImage(tile).ConfigureAwait(false);
2017-08-04 21:38:58 +02:00
}
2019-06-10 22:18:02 +02:00
catch (Exception ex)
2017-08-04 21:38:58 +02:00
{
2019-06-11 22:14:58 +02:00
Debug.WriteLine("TileImageLoader: {0}/{1}/{2}: {3}", tile.ZoomLevel, tile.XIndex, tile.Y, ex.Message);
2017-08-04 21:38:58 +02:00
}
}
2019-06-10 22:18:02 +02:00
Interlocked.Decrement(ref taskCount);
2017-08-04 21:38:58 +02:00
}
private static async Task LoadCachedTileImageAsync(Tile tile, TileSource tileSource, string sourceName)
{
var uri = tileSource.GetUri(tile.XIndex, tile.Y, tile.ZoomLevel);
if (uri != null)
{
var extension = Path.GetExtension(uri.LocalPath);
if (string.IsNullOrEmpty(extension) || extension == ".jpeg")
{
extension = ".jpg";
}
var cacheKey = string.Format(CacheKeyFormat, sourceName, tile.ZoomLevel, tile.XIndex, tile.Y, extension);
await LoadCachedTileImageAsync(tile, uri, cacheKey).ConfigureAwait(false);
}
2017-08-04 21:38:58 +02:00
}
private static DateTime GetExpiration(TimeSpan? maxAge)
2017-08-04 21:38:58 +02:00
{
2020-04-12 13:26:25 +02:00
return DateTime.UtcNow.Add(maxAge ?? DefaultCacheExpiration);
2017-08-04 21:38:58 +02:00
}
}
}