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

274 lines
9.5 KiB
C#
Raw Normal View History

// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// © 2017 Clemens Fischer
2012-05-04 12:52:20 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Collections.Concurrent;
2012-04-25 22:02:53 +02:00
using System.Collections.Generic;
using System.Diagnostics;
2012-04-25 22:02:53 +02:00
using System.IO;
using System.Linq;
using System.Net;
2012-06-24 23:42:11 +02:00
using System.Runtime.Caching;
using System.Text;
2012-04-25 22:02:53 +02:00
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
2012-04-25 22:02:53 +02:00
namespace MapControl
{
2012-05-04 12:52:20 +02:00
/// <summary>
/// Loads map tile images and optionally caches them in a System.Runtime.Caching.ObjectCache.
2012-05-04 12:52:20 +02:00
/// </summary>
public class TileImageLoader : ITileImageLoader
2012-04-25 22:02:53 +02:00
{
/// <summary>
/// Default name of an ObjectCache instance that is assigned to the Cache property.
/// </summary>
public const string DefaultCacheName = "TileCache";
/// <summary>
/// Default folder path where an ObjectCache instance may save cached data.
/// </summary>
public static readonly string DefaultCacheFolder =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MapControl");
/// <summary>
/// Default expiration time for cached tile images. Used when no expiration time
/// was transmitted on download. The default value is one day.
/// </summary>
public static TimeSpan DefaultCacheExpiration { get; set; }
/// <summary>
/// Minimum expiration time for cached tile images. Used when an unnecessarily small expiration time
/// was transmitted on download (e.g. Cache-Control: max-age=0). The default value is one hour.
/// </summary>
public static TimeSpan MinimumCacheExpiration { get; set; }
/// <summary>
/// The ObjectCache used to cache tile images. The default is MemoryCache.Default.
/// </summary>
public static ObjectCache Cache { get; set; }
/// <summary>
/// Optional value to be used for the HttpWebRequest.UserAgent property. The default is null.
/// </summary>
public static string HttpUserAgent { get; set; }
static TileImageLoader()
{
DefaultCacheExpiration = TimeSpan.FromDays(1);
MinimumCacheExpiration = TimeSpan.FromHours(1);
Cache = MemoryCache.Default;
}
2017-07-17 21:31:09 +02:00
private readonly ConcurrentStack<Tile> pendingTiles = new ConcurrentStack<Tile>();
private int taskCount;
2012-04-25 22:02:53 +02:00
2017-07-17 21:31:09 +02:00
public void LoadTiles(MapTileLayer tileLayer)
2012-04-25 22:02:53 +02:00
{
2017-07-17 21:31:09 +02:00
pendingTiles.Clear();
var tileStack = tileLayer.Tiles.Where(t => t.Pending).Reverse().ToArray();
if (tileStack.Length > 0)
{
2017-07-17 21:31:09 +02:00
pendingTiles.PushRange(tileStack);
var tileSource = tileLayer.TileSource;
2017-07-17 21:31:09 +02:00
var sourceName = tileLayer.SourceName;
var maxDownloads = tileLayer.MaxParallelDownloads;
2017-07-17 21:31:09 +02:00
while (taskCount < Math.Min(pendingTiles.Count, maxDownloads))
{
2017-07-17 21:31:09 +02:00
Interlocked.Increment(ref taskCount);
Task.Run(() =>
{
2017-07-17 21:31:09 +02:00
LoadPendingTiles(tileSource, sourceName);
2017-07-17 21:31:09 +02:00
Interlocked.Decrement(ref taskCount);
});
}
}
2012-04-25 22:02:53 +02:00
}
2017-07-17 21:31:09 +02:00
private void LoadPendingTiles(TileSource tileSource, string sourceName)
{
2017-07-17 21:31:09 +02:00
var imageTileSource = tileSource as ImageTileSource;
Tile tile;
2015-01-20 17:52:02 +01:00
2017-07-17 21:31:09 +02:00
while (pendingTiles.TryPop(out tile))
{
2017-07-17 21:31:09 +02:00
tile.Pending = false;
2017-07-17 21:31:09 +02:00
try
2015-01-20 17:52:02 +01:00
{
2017-07-17 21:31:09 +02:00
ImageSource image = null;
Uri uri;
if (imageTileSource != null)
{
image = imageTileSource.LoadImage(tile.XIndex, tile.Y, tile.ZoomLevel);
}
else if ((uri = tileSource.GetUri(tile.XIndex, tile.Y, tile.ZoomLevel)) != null)
{
image = LoadImage(uri, sourceName, tile.XIndex, tile.Y, tile.ZoomLevel);
}
if (image != null)
{
tile.SetImage(image);
}
}
2017-07-17 21:31:09 +02:00
catch (Exception ex)
{
2017-07-17 21:31:09 +02:00
Debug.WriteLine("{0}/{1}/{2}: {3}", tile.ZoomLevel, tile.XIndex, tile.Y, ex.Message);
}
}
2012-04-25 22:02:53 +02:00
}
2017-07-17 21:31:09 +02:00
private ImageSource LoadImage(Uri uri, string sourceName, int x, int y, int zoomLevel)
2012-04-25 22:02:53 +02:00
{
2017-07-17 21:31:09 +02:00
ImageSource image = null;
2017-07-17 21:31:09 +02:00
try
2012-04-25 22:02:53 +02:00
{
2017-07-17 21:31:09 +02:00
if (!uri.IsAbsoluteUri)
{
image = BitmapSourceHelper.FromFile(uri.OriginalString);
}
else if (uri.Scheme == "file")
{
image = BitmapSourceHelper.FromFile(uri.LocalPath);
}
else if (Cache == null || string.IsNullOrEmpty(sourceName))
{
2017-07-17 21:31:09 +02:00
image = DownloadImage(uri, null);
}
else
{
2017-07-17 21:31:09 +02:00
var cacheKey = string.Format("{0}/{1}/{2}/{3}", sourceName, zoomLevel, x, y);
2017-07-17 21:31:09 +02:00
if (!GetCachedImage(cacheKey, ref image))
{
2017-07-17 21:31:09 +02:00
// Either no cached image was found or expiration time has expired.
// If download fails use possibly cached but expired image anyway.
image = DownloadImage(uri, cacheKey);
}
}
2012-04-25 22:02:53 +02:00
}
2017-07-17 21:31:09 +02:00
catch (WebException ex)
{
2017-07-17 21:31:09 +02:00
Debug.WriteLine("{0}: {1}: {2}", uri, ex.Status, ex.Message);
}
catch (Exception ex)
{
2017-07-17 21:31:09 +02:00
Debug.WriteLine("{0}: {1}", uri, ex.Message);
}
return image;
2012-04-25 22:02:53 +02:00
}
2017-07-17 21:31:09 +02:00
private static ImageSource DownloadImage(Uri uri, string cacheKey)
{
ImageSource image = null;
2017-07-17 21:31:09 +02:00
var request = WebRequest.CreateHttp(uri);
2017-07-17 21:31:09 +02:00
if (HttpUserAgent != null)
{
2017-07-17 21:31:09 +02:00
request.UserAgent = HttpUserAgent;
}
2017-07-17 21:31:09 +02:00
using (var response = (HttpWebResponse)request.GetResponse())
{
2017-07-17 21:31:09 +02:00
if (response.Headers["X-VE-Tile-Info"] != "no-tile") // set by Bing Maps
{
2017-07-17 21:31:09 +02:00
using (var responseStream = response.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
2017-07-17 21:31:09 +02:00
responseStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
image = BitmapSourceHelper.FromStream(memoryStream);
if (cacheKey != null)
{
2017-07-17 21:31:09 +02:00
SetCachedImage(cacheKey, memoryStream, GetExpiration(response.Headers));
}
}
2012-04-25 22:02:53 +02:00
}
}
return image;
}
2017-07-17 21:31:09 +02:00
private static bool GetCachedImage(string cacheKey, ref ImageSource image)
2015-01-20 17:52:02 +01:00
{
2017-07-17 21:31:09 +02:00
var result = false;
var buffer = Cache.Get(cacheKey) as byte[];
if (buffer != null)
{
try
{
using (var memoryStream = new MemoryStream(buffer))
{
image = BitmapSourceHelper.FromStream(memoryStream);
}
DateTime expiration = DateTime.MinValue;
if (buffer.Length >= 16 && Encoding.ASCII.GetString(buffer, buffer.Length - 16, 8) == "EXPIRES:")
{
expiration = new DateTime(BitConverter.ToInt64(buffer, buffer.Length - 8), DateTimeKind.Utc);
}
2017-07-17 21:31:09 +02:00
result = expiration > DateTime.UtcNow;
}
catch (Exception ex)
{
Debug.WriteLine("{0}: {1}", cacheKey, ex.Message);
}
}
2017-07-17 21:31:09 +02:00
return result;
}
private static void SetCachedImage(string cacheKey, MemoryStream memoryStream, DateTime expiration)
{
memoryStream.Seek(0, SeekOrigin.End);
memoryStream.Write(Encoding.ASCII.GetBytes("EXPIRES:"), 0, 8);
memoryStream.Write(BitConverter.GetBytes(expiration.Ticks), 0, 8);
Cache.Set(cacheKey, memoryStream.ToArray(), new CacheItemPolicy { AbsoluteExpiration = expiration });
}
private static DateTime GetExpiration(WebHeaderCollection headers)
{
var expiration = DefaultCacheExpiration;
var cacheControl = headers["Cache-Control"];
if (cacheControl != null)
{
int maxAgeValue;
var maxAgeDirective = cacheControl
.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault(s => s.StartsWith("max-age="));
if (maxAgeDirective != null &&
int.TryParse(maxAgeDirective.Substring(8), out maxAgeValue))
{
expiration = TimeSpan.FromSeconds(maxAgeValue);
if (expiration < MinimumCacheExpiration)
{
expiration = MinimumCacheExpiration;
}
}
}
return DateTime.UtcNow.Add(expiration);
}
2012-04-25 22:02:53 +02:00
}
}