Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SVG SKPicture cache #1279

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions source/FFImageLoading.Common/Cache/SimpleLRUCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;

namespace FFImageLoading.Cache
{
public class SimpleLRUCache<TKey, TValue>
{
private readonly object _lock = new object();
private readonly int _capacity;
private readonly LinkedList<CacheItem<TKey, TValue>> _lru = new LinkedList<CacheItem<TKey, TValue>>();
private readonly Dictionary<TKey, LinkedListNode<CacheItem<TKey, TValue>>> _cache = new Dictionary<TKey, LinkedListNode<CacheItem<TKey, TValue>>>();

public SimpleLRUCache(int capacity)
{
if (capacity < 1)
throw new ArgumentException("Capacity must be greater than zero.");

_capacity = capacity;
}

public void AddOrReplace(TKey key, TValue value)
{
lock(_lock)
{
if (_cache.TryGetValue(key, out var node))
{
node.Value.Value = value;
_lru.Remove(node);
}
else
{
if (_capacity == _lru.Count)
{
var lastNode = _lru.First;
_cache.Remove(lastNode.Value.Key);
_lru.RemoveFirst();
}

node = new LinkedListNode<CacheItem<TKey, TValue>>(new CacheItem<TKey, TValue>(key, value));
_cache.Add(key, node);
}

_lru.AddLast(node);
}
}

public bool TryGetValue(TKey key, out TValue value)
{
lock (_lock)
{
if (_cache.TryGetValue(key, out var node))
{
_lru.Remove(node);
_lru.AddLast(node);

value = node.Value.Value;
return true;
}

value = default;
return false;
}
}

private class CacheItem<K, V>
{
public K Key { get; }
public V Value { get; set; }

public CacheItem(K key, V value)
{
this.Key = key;
this.Value = value;
}
}
}
}
4 changes: 3 additions & 1 deletion source/FFImageLoading.Svg.Shared/SkSvg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ public SKSvg(float pixelsPerInch, SKSize canvasSize)
ThrowOnUnsupportedElement = DefaultThrowOnUnsupportedElement;
}

public bool HasRasterImage { get; private set; }

public float PixelsPerInch { get; set; }

public bool ThrowOnUnsupportedElement { get; set; }
Expand Down Expand Up @@ -207,7 +209,6 @@ private SKPicture Load(XDocument xdoc, CancellationToken token = default)

// read elements
LoadElements(svg.Elements(), canvas, stroke, fill, token);

Picture = recorder.EndRecording();
}

Expand Down Expand Up @@ -315,6 +316,7 @@ private void ReadElement(XElement e, SKCanvas canvas, SKPaint stroke, SKPaint fi
{
if (bitmap != null)
{
HasRasterImage = true;
canvas.DrawBitmap(bitmap, image.Rect);
}
}
Expand Down
119 changes: 71 additions & 48 deletions source/FFImageLoading.Svg.Shared/SvgDataResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Linq;
using System.Text.RegularExpressions;
using FFImageLoading.Helpers;
using FFImageLoading.Cache;

#if __IOS__
using Foundation;
Expand Down Expand Up @@ -43,6 +44,7 @@ public class SvgDataResolver : IVectorDataResolver
{
#pragma warning disable RECS0108 // Warns about static fields in generic types
private static readonly object _encodingLock = new object();
private static readonly SimpleLRUCache<string, SKPicture> _cache = new SimpleLRUCache<string, SKPicture>(50);
#pragma warning restore RECS0108 // Warns about static fields in generic types

#if __IOS__
Expand Down Expand Up @@ -205,62 +207,81 @@ private async Task<DataResolverResult> Decode(SKPicture picture, SKBitmap bitmap

public async Task<DataResolverResult> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
{
var source = parameters.Source;
var replaceStringMapKey = (ReplaceStringMap == null || ReplaceStringMap.Count == 0)
? null : string.Join(",", ReplaceStringMap.Select(x => string.Format("{0}/{1}", x.Key, x.Value)).OrderBy(v => v));
var key = replaceStringMapKey == null ? identifier : $"{identifier};{replaceStringMapKey}";

if (!string.IsNullOrWhiteSpace(parameters.LoadingPlaceholderPath) && parameters.LoadingPlaceholderPath == identifier)
source = parameters.LoadingPlaceholderSource;
else if (!string.IsNullOrWhiteSpace(parameters.ErrorPlaceholderPath) && parameters.ErrorPlaceholderPath == identifier)
source = parameters.ErrorPlaceholderSource;
DataResolverResult resolvedData;

var resolvedData = await (Configuration.DataResolverFactory ?? new DataResolverFactory())
.GetResolver(identifier, source, parameters, Configuration)
.Resolve(identifier, parameters, token).ConfigureAwait(false);
if (_cache.TryGetValue(key, out var picture))
{
resolvedData = new DataResolverResult()
{
LoadingResult = LoadingResult.MemoryCache,
ImageInformation = new ImageInformation()
};
}
else
{
var source = parameters.Source;

if (resolvedData?.Stream == null)
throw new FileNotFoundException(identifier);
if (!string.IsNullOrWhiteSpace(parameters.LoadingPlaceholderPath) && parameters.LoadingPlaceholderPath == identifier)
source = parameters.LoadingPlaceholderSource;
else if (!string.IsNullOrWhiteSpace(parameters.ErrorPlaceholderPath) && parameters.ErrorPlaceholderPath == identifier)
source = parameters.ErrorPlaceholderSource;

var svg = new SKSvg()
{
ThrowOnUnsupportedElement = false,
};
SKPicture picture;
resolvedData = await (Configuration.DataResolverFactory ?? new DataResolverFactory())
.GetResolver(identifier, source, parameters, Configuration)
.Resolve(identifier, parameters, token).ConfigureAwait(false);

if (ReplaceStringMap == null || ReplaceStringMap.Count == 0)
{
using (var svgStream = resolvedData.Stream)
{
picture = svg.Load(svgStream, token);
}
}
else
{
using (var svgStream = resolvedData.Stream)
using (var reader = new StreamReader(svgStream))
{
var inputString = await reader.ReadToEndAsync().ConfigureAwait(false);
if (resolvedData?.Stream == null)
throw new FileNotFoundException(identifier);

var svg = new SKSvg()
{
ThrowOnUnsupportedElement = false,
};

if (ReplaceStringMap == null || ReplaceStringMap.Count == 0)
{
using (var svgStream = resolvedData.Stream)
{
picture = svg.Load(svgStream, token);
}
}
else
{
using (var svgStream = resolvedData.Stream)
using (var reader = new StreamReader(svgStream))
{
var inputString = await reader.ReadToEndAsync().ConfigureAwait(false);

foreach (var map in ReplaceStringMap
.Where(v => v.Key.StartsWith("regex:", StringComparison.OrdinalIgnoreCase)))
{
inputString = Regex.Replace(inputString, map.Key.Substring(6), map.Value);
}
foreach (var map in ReplaceStringMap
.Where(v => v.Key.StartsWith("regex:", StringComparison.OrdinalIgnoreCase)))
{
inputString = Regex.Replace(inputString, map.Key.Substring(6), map.Value);
}

var builder = new StringBuilder(inputString);
var builder = new StringBuilder(inputString);

foreach (var map in ReplaceStringMap
.Where(v => !v.Key.StartsWith("regex:", StringComparison.OrdinalIgnoreCase)))
{
builder.Replace(map.Key, map.Value);
}
foreach (var map in ReplaceStringMap
.Where(v => !v.Key.StartsWith("regex:", StringComparison.OrdinalIgnoreCase)))
{
builder.Replace(map.Key, map.Value);
}

token.ThrowIfCancellationRequested();
token.ThrowIfCancellationRequested();

using (var svgFinalStream = new MemoryStream(Encoding.UTF8.GetBytes(builder.ToString())))
{
picture = svg.Load(svgFinalStream);
}
}
}
using (var svgFinalStream = new MemoryStream(Encoding.UTF8.GetBytes(builder.ToString())))
{
picture = svg.Load(svgFinalStream);
}
}
}

if (!svg.HasRasterImage)
_cache.AddOrReplace(key, picture);
}

token.ThrowIfCancellationRequested();

Expand Down Expand Up @@ -294,8 +315,6 @@ public async Task<DataResolverResult> Resolve(string identifier, TaskParameter p
sizeX = (int)(sizeY / picture.CullRect.Height * picture.CullRect.Width);
}

resolvedData.ImageInformation.SetType(ImageInformation.ImageType.SVG);

using (var bitmap = new SKBitmap(new SKImageInfo((int)sizeX, (int)sizeY)))
using (var canvas = new SKCanvas(bitmap))
using (var paint = new SKPaint())
Expand All @@ -309,6 +328,10 @@ public async Task<DataResolverResult> Resolve(string identifier, TaskParameter p

token.ThrowIfCancellationRequested();

resolvedData.ImageInformation.SetType(ImageInformation.ImageType.SVG);
resolvedData.ImageInformation.SetCurrentSize((int)sizeX, (int)sizeY);
resolvedData.ImageInformation.SetOriginalSize((int)picture.CullRect.Width, (int)picture.CullRect.Height);

return await Decode(picture, bitmap, resolvedData).ConfigureAwait(false);
}
}
Expand Down