UWP ImageFileCache and Package References

This commit is contained in:
ClemensFischer 2024-08-14 17:27:14 +02:00
parent be48c45e91
commit 0d242e556c
21 changed files with 301 additions and 33 deletions

View file

@ -15,7 +15,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.1.1" />
<PackageReference Include="Avalonia" Version="11.1.3" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118" />
</ItemGroup>
</Project>

View file

@ -11,7 +11,7 @@
<AssemblyName>MBTiles.UWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22000.0</TargetPlatformVersion>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22621.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>

View file

@ -18,7 +18,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240627000" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240802000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118" />
</ItemGroup>

View file

@ -16,7 +16,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.1.1" />
<PackageReference Include="Avalonia" Version="11.1.3" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
</ItemGroup>

View file

@ -15,7 +15,6 @@ namespace MapControl
public static string DefaultCacheFolder =>
System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MapControl", "TileCache");
private static async Task LoadTileAsync(Tile tile, Func<Task<IImage>> loadImageFunc)
{
var image = await loadImageFunc().ConfigureAwait(false);

View file

@ -8,11 +8,11 @@ using Microsoft.Extensions.Options;
using System;
using System.Diagnostics;
using System.IO;
using Path = System.IO.Path;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Path = System.IO.Path;
namespace MapControl.Caching
{
@ -269,11 +269,13 @@ namespace MapControl.Caching
try
{
var hasExpired = false;
var buffer = new byte[16];
using (var stream = file.OpenRead())
{
stream.Seek(-16, SeekOrigin.End);
var buffer = new byte[16];
hasExpired = stream.Read(buffer, 0, 16) == 16
&& GetExpirationTicks(buffer, out long expiration)
&& expiration <= DateTimeOffset.UtcNow.Ticks;
@ -377,10 +379,11 @@ namespace MapControl.Caching
private static Task WriteAsync(Stream stream, byte[] bytes) => stream.WriteAsync(bytes, 0, bytes.Length);
static partial void SetAccessControl(string path);
#if !UWP && !AVALONIA
static partial void SetAccessControl(string path)
private static void SetAccessControl(string path)
{
#if AVALONIA
if (!OperatingSystem.IsWindows()) return;
#endif
var fileInfo = new FileInfo(path);
var fileSecurity = fileInfo.GetAccessControl();
var fullControlRule = new System.Security.AccessControl.FileSystemAccessRule(
@ -392,6 +395,5 @@ namespace MapControl.Caching
fileSecurity.AddAccessRule(fullControlRule);
fileInfo.SetAccessControl(fileSecurity);
}
#endif
}
}

View file

@ -0,0 +1,272 @@
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// Copyright © 2024 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using Buffer = Windows.Storage.Streams.Buffer;
namespace MapControl.Caching
{
/// <summary>
/// IDistributedCache implementation based on local image files.
/// </summary>
public partial class ImageFileCache : IDistributedCache
{
private static readonly byte[] expirationTag = Encoding.ASCII.GetBytes("EXPIRES:");
private readonly MemoryDistributedCache memoryCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
private readonly StorageFolder rootFolder;
public ImageFileCache(StorageFolder folder)
{
rootFolder = folder ?? throw new ArgumentException($"The {nameof(folder)} argument must not be null or empty.", nameof(folder));
Debug.WriteLine($"ImageFileCache: {rootFolder}");
_ = Task.Factory.StartNew(CleanAsync, TaskCreationOptions.LongRunning);
}
public byte[] Get(string key)
{
throw new NotSupportedException();
}
public void Set(string key, byte[] buffer, DistributedCacheEntryOptions options)
{
throw new NotSupportedException();
}
public void Remove(string key)
{
throw new NotSupportedException();
}
public Task RemoveAsync(string key, CancellationToken token = default)
{
throw new NotSupportedException();
}
public void Refresh(string key)
{
throw new NotSupportedException();
}
public Task RefreshAsync(string key, CancellationToken token = default)
{
throw new NotSupportedException();
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
{
var buffer = await memoryCache.GetAsync(key, token).ConfigureAwait(false);
if (buffer == null)
{
try
{
var item = await rootFolder.TryGetItemAsync(key.Replace('/', '\\'));
if (item is StorageFile file)
{
buffer = (await FileIO.ReadBufferAsync(file)).ToArray();
if (CheckExpiration(ref buffer, out DistributedCacheEntryOptions options))
{
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed reading {key}: {ex.Message}");
}
}
return buffer;
}
public async Task SetAsync(string key, byte[] buffer, DistributedCacheEntryOptions options, CancellationToken token = default)
{
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
if (buffer?.Length > 0)
{
try
{
var keyComponents = key.Split('/');
var folder = rootFolder;
for (int i = 0; i < keyComponents.Length - 1; i++)
{
folder = await folder.CreateFolderAsync(keyComponents[i], CreationCollisionOption.OpenIfExists);
}
var file = await folder.CreateFileAsync(keyComponents[keyComponents.Length - 1], CreationCollisionOption.OpenIfExists);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await stream.WriteAsync(buffer.AsBuffer());
if (GetExpirationBytes(options, out byte[] expiration))
{
await stream.WriteAsync(expiration.AsBuffer());
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed writing {key}: {ex.Message}");
}
}
}
public async Task CleanAsync()
{
var deletedFileCount = await CleanFolder(rootFolder);
if (deletedFileCount > 0)
{
Debug.WriteLine($"ImageFileCache: Deleted {deletedFileCount} expired files.");
}
}
private static async Task<int> CleanFolder(StorageFolder folder)
{
var deletedFileCount = 0;
try
{
foreach (var f in await folder.GetFoldersAsync())
{
deletedFileCount += await CleanFolder(f);
}
foreach (var f in await folder.GetFilesAsync())
{
deletedFileCount += await CleanFile(f);
}
if ((await folder.GetItemsAsync()).Count == 0)
{
await folder.DeleteAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed cleaning {folder.Path}: {ex.Message}");
}
return deletedFileCount;
}
private static async Task<int> CleanFile(StorageFile file)
{
var deletedFileCount = 0;
var size = (await file.GetBasicPropertiesAsync()).Size;
if (size > 16)
{
try
{
var hasExpired = false;
using (var stream = await file.OpenReadAsync())
{
stream.Seek(size - 16);
var buffer = await stream.ReadAsync(new Buffer(16), 16, InputStreamOptions.None);
hasExpired = buffer.Length == 16
&& GetExpirationTicks(buffer.ToArray(), out long expiration)
&& expiration <= DateTimeOffset.UtcNow.Ticks;
}
if (hasExpired)
{
await file.DeleteAsync();
deletedFileCount = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed cleaning {file.Path}: {ex.Message}");
}
}
return deletedFileCount;
}
private static bool CheckExpiration(ref byte[] buffer, out DistributedCacheEntryOptions options)
{
if (GetExpirationTicks(buffer, out long expiration))
{
if (expiration > DateTimeOffset.UtcNow.Ticks)
{
Array.Resize(ref buffer, buffer.Length - 16);
options = new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(expiration, TimeSpan.Zero)
};
return true;
}
buffer = null; // buffer has expired
}
options = null;
return false;
}
private static bool GetExpirationTicks(byte[] buffer, out long expirationTicks)
{
if (buffer.Length >= 16 &&
expirationTag.SequenceEqual(buffer.Skip(buffer.Length - 16).Take(8)))
{
expirationTicks = BitConverter.ToInt64(buffer, buffer.Length - 8);
return true;
}
expirationTicks = 0;
return false;
}
private static bool GetExpirationBytes(DistributedCacheEntryOptions options, out byte[] expirationBytes)
{
long expirationTicks;
if (options.AbsoluteExpiration.HasValue)
{
expirationTicks = options.AbsoluteExpiration.Value.Ticks;
}
else if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
expirationTicks = DateTimeOffset.UtcNow.Add(options.AbsoluteExpirationRelativeToNow.Value).Ticks;
}
else if (options.SlidingExpiration.HasValue)
{
expirationTicks = DateTimeOffset.UtcNow.Add(options.SlidingExpiration.Value).Ticks;
}
else
{
expirationBytes = null;
return false;
}
expirationBytes = expirationTag.Concat(BitConverter.GetBytes(expirationTicks)).ToArray();
return true;
}
}
}

View file

@ -11,7 +11,7 @@
<AssemblyName>MapControl.UWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22000.0</TargetPlatformVersion>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22621.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>
@ -83,9 +83,6 @@
<Compile Include="..\Shared\GroundOverlay.cs">
<Link>GroundOverlay.cs</Link>
</Compile>
<Compile Include="..\Shared\ImageFileCache.cs">
<Link>ImageFileCache.cs</Link>
</Compile>
<Compile Include="..\Shared\ImageLoader.cs">
<Link>ImageLoader.cs</Link>
</Compile>
@ -275,6 +272,7 @@
<Compile Include="..\WinUI\Tile.WinUI.cs">
<Link>Tile.WinUI.cs</Link>
</Compile>
<Compile Include="ImageFileCache.UWP.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TileImageLoader.UWP.cs" />
<EmbeddedResource Include="Properties\MapControl.UWP.rd.xml" />

View file

@ -15,8 +15,7 @@ namespace MapControl
/// <summary>
/// Default folder where the Cache instance may save data.
/// </summary>
public static string DefaultCacheFolder => ApplicationData.Current.TemporaryFolder.Path;
public static StorageFolder DefaultCacheFolder => ApplicationData.Current.LocalCacheFolder;
private static async Task LoadTileAsync(Tile tile, Func<Task<ImageSource>> loadImageFunc)
{

View file

@ -17,7 +17,6 @@ namespace MapControl
public static string DefaultCacheFolder =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MapControl", "TileCache");
private static async Task LoadTileAsync(Tile tile, Func<Task<ImageSource>> loadImageFunc)
{
var image = await loadImageFunc().ConfigureAwait(false);

View file

@ -21,7 +21,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240627000" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240802000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />

View file

@ -18,7 +18,6 @@ namespace MapControl
public static string DefaultCacheFolder =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MapControl", "TileCache");
private static Task LoadTileAsync(Tile tile, Func<Task<ImageSource>> loadImageFunc)
{
var tcs = new TaskCompletionSource();

View file

@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.1.1" />
<PackageReference Include="Avalonia" Version="11.1.3" />
<PackageReference Include="ProjNET4GeoAPI" Version="1.4.1" />
</ItemGroup>
</Project>

View file

@ -11,7 +11,7 @@
<AssemblyName>MapProjections.UWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22000.0</TargetPlatformVersion>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22621.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>

View file

@ -22,7 +22,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240627000" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240802000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
<PackageReference Include="ProjNET4GeoAPI" Version="1.4.1" />
</ItemGroup>

View file

@ -15,6 +15,6 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.1.1" />
<PackageReference Include="Avalonia" Version="11.1.3" />
</ItemGroup>
</Project>

View file

@ -11,7 +11,7 @@
<AssemblyName>MapUiTools.UWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22000.0</TargetPlatformVersion>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.22621.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>

View file

@ -18,7 +18,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240627000" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240802000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
</ItemGroup>
</Project>

View file

@ -32,11 +32,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.1.1" />
<PackageReference Include="Avalonia.Desktop" Version="11.1.1" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.1.1" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.1.1" />
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.1.1" />
<PackageReference Include="Avalonia" Version="11.1.3" />
<PackageReference Include="Avalonia.Desktop" Version="11.1.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.1.3" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.1.3" />
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.1.3" />
<PackageReference Include="Markdown.Avalonia.Tight" Version="11.0.2" />
</ItemGroup>
</Project>

View file

@ -11,7 +11,7 @@
<AssemblyName>UniversalApp</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.22000.0</TargetPlatformVersion>
<TargetPlatformVersion>10.0.22621.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>

View file

@ -37,7 +37,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240627000" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240802000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
<Manifest Include="$(ApplicationManifest)" />
</ItemGroup>