상속: IDisposable
        public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            StorageFile file = null;

            try
            {
                var filePath = Path.GetDirectoryName(identifier);

                if (!string.IsNullOrWhiteSpace(filePath))
                {
                    file = await StorageFile.GetFileFromPathAsync(identifier);
                }
            }
            catch (Exception)
            {
            }

            if (file != null)
            {
                var imageInformation = new ImageInformation();
                imageInformation.SetPath(identifier);
                imageInformation.SetFilePath(identifier);

                token.ThrowIfCancellationRequested();
                var stream = await file.OpenStreamForReadAsync();

                return new Tuple<Stream, LoadingResult, ImageInformation>(stream, LoadingResult.Disk, imageInformation);
            }

            throw new FileNotFoundException(identifier);
        }
        public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            // Resource name is always without extension
            string resourceName = Path.GetFileNameWithoutExtension(identifier);

            int resourceId = 0;
            if (!_resourceIdentifiersCache.TryGetValue(resourceName, out resourceId))
            {
                token.ThrowIfCancellationRequested();
                resourceId = Context.Resources.GetIdentifier(resourceName.ToLower(), "drawable", Context.PackageName);
                _resourceIdentifiersCache.TryAdd(resourceName.ToLower(), resourceId);
            }

            if (resourceId == 0)
                throw new FileNotFoundException(identifier);

            token.ThrowIfCancellationRequested();
            Stream stream  = Context.Resources.OpenRawResource(resourceId);

            if (stream == null)
                throw new FileNotFoundException(identifier);

            var imageInformation = new ImageInformation();
            imageInformation.SetPath(identifier);
            imageInformation.SetFilePath(identifier);

            return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>(
                stream, LoadingResult.CompiledResource, imageInformation));
        }
        protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, bool clearCacheOnOutOfMemory, bool verboseLoadingCancelledLogging)
        {
            _verboseLoadingCancelledLogging = verboseLoadingCancelledLogging;
            _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory;
            CancellationToken = new CancellationTokenSource();
            Parameters = parameters;
            NumberOfRetryNeeded = parameters.RetryCount;
            MainThreadDispatcher = mainThreadDispatcher;
            Logger = miniLogger;
            ConfigureParameters();

            _hasCustomCacheKey = !string.IsNullOrWhiteSpace(Parameters.CustomCacheKey);
            _keys = new ConcurrentDictionary<string, string>();

            _transformationsKey = new Lazy<string>(() =>
            {
                if (Parameters.Transformations == null || Parameters.Transformations.Count == 0)
                    return string.Empty;

                return ";" + string.Join(";", Parameters.Transformations.Select(t => t.Key));
            });

            _downsamplingKey = new Lazy<string>(() =>
            {
                if (Parameters.DownSampleSize == null)
                    return string.Empty;

                return string.Concat(";", Parameters.DownSampleSize.Item1, "x", Parameters.DownSampleSize.Item2);
            });

            _rawKey = new Lazy<string>(() => GetKeyInternal(null, true));

            _streamKey = new Lazy<string>(() => "Stream" + GetNextStreamIndex());
        }
        public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            var imageInformation = new ImageInformation();
            var stream = await parameters.Stream?.Invoke(token);

            return new Tuple<Stream, LoadingResult, ImageInformation>(stream, LoadingResult.Stream, imageInformation);
        }
예제 #5
0
		public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func<UIView> getNativeControl, Action<UIImage, bool> doWithImage, nfloat imageScale)
			: base(mainThreadDispatcher, miniLogger, parameters)
		{
			_getNativeControl = getNativeControl;
			_doWithImage = doWithImage;
			_imageScale = imageScale;
			DownloadCache = downloadCache;
		}
예제 #6
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func<Image> getNativeControl, Action<WriteableBitmap, bool> doWithImage)
            : base(mainThreadDispatcher, miniLogger, parameters)
        {
            _getNativeControl = getNativeControl;
            _doWithImage = doWithImage;

            DownloadCache = downloadCache;
        }
		/// <summary>
		/// Constructsa new TaskParameter to load an image from a file from application bundle.
		/// </summary>
		/// <param name="filepath">Path to the file.</param>
		/// <returns>The new TaskParameter.</returns>
		public static TaskParameter FromApplicationBundle(string filepath)
		{
			var taskParameter = new TaskParameter() { Source = ImageSource.ApplicationBundle, Path = filepath };

            if (!taskParameter.Priority.HasValue)
                taskParameter.Priority = (int)LoadingPriority.Normal + 1;

            return taskParameter;
		}
		/// <summary>
		/// Constructs a new TaskParameter to load an image from a compiled drawable resource.
		/// </summary>
		/// <returns>The new TaskParameter.</returns>
		/// <param name="resourceName">Name of the resource in drawable folder without extension</param>
		public static TaskParameter FromCompiledResource(string resourceName)
		{
			var taskParameter = new TaskParameter() { Source = ImageSource.CompiledResource, Path = resourceName };

            if (!taskParameter.Priority.HasValue)
                taskParameter.Priority = (int)LoadingPriority.Normal + 1;

            return taskParameter;
		}
예제 #9
0
		public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, nfloat imageScale, ITarget<UIImage, ImageLoaderTask> target, bool clearCacheOnOutOfMemory)
			: base(mainThreadDispatcher, miniLogger, parameters, true, clearCacheOnOutOfMemory)
		{
			if (target == null)
				throw new ArgumentNullException(nameof(target));
			
			_target = target;
			DownloadCache = downloadCache;
		}
		protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters)
		{
			CancellationToken = new CancellationTokenSource();
			Parameters = parameters;
			NumberOfRetryNeeded = parameters.RetryCount;
			MainThreadDispatcher = mainThreadDispatcher;
			Logger = miniLogger;
			ConfigureParameters();
		}
예제 #11
0
		public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ImageView imageView)
			: base(mainThreadDispatcher, miniLogger, parameters, true)
		{
			DownloadCache = downloadCache;

			if (imageView != null)
			{
				_imageWeakReference = new WeakReference<ImageView>(imageView);
			}
		}
예제 #12
0
		public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ImageView imageView)
			: base(mainThreadDispatcher, miniLogger, parameters)
		{
			CancellationToken = new CancellationTokenSource();
			Context = Android.App.Application.Context.ApplicationContext;
			DownloadCache = downloadCache;
			_imageWeakReference = new WeakReference<ImageView>(imageView);

			UseFadeInBitmap = true;
		}
        public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            string file = null;

            int scale = (int)ScaleHelper.Scale;
            if (scale > 1)
            {
                var filename = Path.GetFileNameWithoutExtension(identifier);
                var extension = Path.GetExtension(identifier);
                const string pattern = "{0}@{1}x{2}";

                while (scale > 1)
                {
                    token.ThrowIfCancellationRequested();

                    var tmpFile = string.Format(pattern, filename, scale, extension);
                    if (FileStore.Exists(tmpFile))
                    {
                        file = tmpFile;
                        break;
                    }
                    scale--;
                }
            }

            if (string.IsNullOrEmpty(file) && FileStore.Exists(identifier))
            {
                file = identifier;
            }

            token.ThrowIfCancellationRequested();

            if (!string.IsNullOrEmpty(file))
            {
                var stream = FileStore.GetInputStream(file, true);
                var imageInformation = new ImageInformation();
                imageInformation.SetPath(identifier);
                imageInformation.SetFilePath(file);

                var result = (LoadingResult)(int)parameters.Source;

                if (parameters.LoadingPlaceholderPath == identifier)
                    result = (LoadingResult)(int)parameters.LoadingPlaceholderSource;
                else if (parameters.ErrorPlaceholderPath == identifier)
                    result = (LoadingResult)(int)parameters.ErrorPlaceholderSource;

                return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>(
                    stream, result, imageInformation));
            }

            throw new FileNotFoundException(identifier);
        }
예제 #14
0
 public static IDataResolver GetResolver(ImageSource source, TaskParameter parameter, IDownloadCache downloadCache)
 {
     switch (source)
     {
         case ImageSource.ApplicationBundle:
         case ImageSource.CompiledResource:
         case ImageSource.Filepath:
             return new FilePathDataResolver(source);
         case ImageSource.Url:
             return new UrlDataResolver(parameter, downloadCache);
         default:
             throw new ArgumentException("Unknown type of ImageSource");
     }
 }
        public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();
            var stream = Context.Assets.Open(identifier, Access.Streaming);

            if (stream == null)
                throw new FileNotFoundException(identifier);

            var imageInformation = new ImageInformation();
            imageInformation.SetPath(identifier);
            imageInformation.SetFilePath(null);

            return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>(
                stream, LoadingResult.ApplicationBundle, imageInformation));
        }
예제 #16
0
        public virtual async Task<CacheStream> DownloadAndCacheIfNeededAsync(string url, TaskParameter parameters, Configuration configuration, CancellationToken token)
        {
            var allowCustomKey = !string.IsNullOrWhiteSpace(parameters.CustomCacheKey)
                                       && (string.IsNullOrWhiteSpace(parameters.LoadingPlaceholderPath) || parameters.LoadingPlaceholderPath != url)
                                       && (string.IsNullOrWhiteSpace(parameters.ErrorPlaceholderPath) || parameters.ErrorPlaceholderPath != url);

            string filename = (allowCustomKey ? MD5Helper.MD5(parameters.CustomCacheKey) : MD5Helper.MD5(url))?.ToSanitizedKey();
            var allowDiskCaching = AllowDiskCaching(parameters.CacheType);
            var duration = parameters.CacheDuration.HasValue ? parameters.CacheDuration.Value : configuration.DiskCacheDuration;
            string filePath = null;

            if (allowDiskCaching)
            {
                var diskStream = await configuration.DiskCache.TryGetStreamAsync(filename).ConfigureAwait(false);
                if (diskStream != null)
                {
                    token.ThrowIfCancellationRequested();
                    filePath = await configuration.DiskCache.GetFilePathAsync(filename).ConfigureAwait(false);
                    return new CacheStream(diskStream, true, filePath);
                }
            }

            token.ThrowIfCancellationRequested();

            var downloadInfo = new DownloadInformation(url, parameters.CustomCacheKey, filename, allowDiskCaching, duration);
            parameters.OnDownloadStarted?.Invoke(downloadInfo);

            var responseBytes = await Retry.DoAsync(
                async () => await DownloadAsync(url, token, configuration.HttpClient).ConfigureAwait(false),
                DelayBetweenRetry,
                parameters.RetryCount,
                () => configuration.Logger.Debug(string.Format("Retry download: {0}", url)));

            if (responseBytes == null)
                throw new HttpRequestException("No Content");

            if (allowDiskCaching)
            {
                await configuration.DiskCache.AddToSavingQueueIfNotExistsAsync(filename, responseBytes, duration).ConfigureAwait(false);
            }

            token.ThrowIfCancellationRequested();
            filePath = await configuration.DiskCache.GetFilePathAsync(filename).ConfigureAwait(false);
            token.ThrowIfCancellationRequested();
            var memoryStream = new MemoryStream(responseBytes, false);
            return new CacheStream(memoryStream, false, filePath);
        }
        public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            var downloadedData = await DownloadCache.DownloadAndCacheIfNeededAsync(identifier, parameters, Configuration, token).ConfigureAwait(false);

            if (token.IsCancellationRequested)
            {
                downloadedData?.ImageStream?.Dispose();
                token.ThrowIfCancellationRequested();
            }

            var imageInformation = new ImageInformation();
            imageInformation.SetPath(identifier);
            imageInformation.SetFilePath(downloadedData?.FilePath);

            return new Tuple<Stream, LoadingResult, ImageInformation>(
                downloadedData?.ImageStream, downloadedData.RetrievedFromDiskCache ? LoadingResult.DiskCache : LoadingResult.Internet, imageInformation);
        }
 public virtual IDataResolver GetResolver(string identifier, ImageSource source, TaskParameter parameters, Configuration configuration)
 {
     switch (source)
     {
         case ImageSource.ApplicationBundle:
         case ImageSource.CompiledResource:
             return new ResourceDataResolver();
         case ImageSource.Filepath:
             return new FileDataResolver();
         case ImageSource.Url:
             return new UrlDataResolver(configuration);
         case ImageSource.Stream:
             return new StreamDataResolver();
         default:
             throw new ArgumentException("Unknown type of ImageSource");
     }
 }
        public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            if (!FileStore.Exists(identifier))
            {
                throw new FileNotFoundException(identifier);
            }

            token.ThrowIfCancellationRequested();

            var stream = FileStore.GetInputStream(identifier, true);

            var imageInformation = new ImageInformation();
            imageInformation.SetPath(identifier);
            imageInformation.SetFilePath(identifier);

            return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>(
                stream, LoadingResult.Disk, imageInformation));          
        }
        public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            StorageFile file = null;

            try
            {
                string resPath = identifier.TrimStart('\\', '/');

                if (!resPath.StartsWith(@"Assets\") && !resPath.StartsWith("Assets/"))
                {
                    resPath = @"Assets\" + resPath;
                }

                var imgUri = new Uri("ms-appx:///" + resPath);
                file = await StorageFile.GetFileFromApplicationUriAsync(imgUri);
            }
            catch (Exception)
            {
                try
                {
                    var imgUri = new Uri("ms-appx:///" + identifier);
                    file = await StorageFile.GetFileFromApplicationUriAsync(imgUri);
                }
                catch (Exception)
                {
                }
            }


            if (file != null)
            {
                var imageInformation = new ImageInformation();
                imageInformation.SetPath(identifier);
                imageInformation.SetFilePath(file.Path);

                token.ThrowIfCancellationRequested();
                var stream = await file.OpenStreamForReadAsync();

                return new Tuple<Stream, LoadingResult, ImageInformation>(stream, LoadingResult.CompiledResource, imageInformation);
            }

            throw new FileNotFoundException(identifier);
        }
		public async Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
		{
			ImageSource source = parameters.Source;

			if (parameters.LoadingPlaceholderPath == identifier)
				source = parameters.LoadingPlaceholderSource;
			else if (parameters.ErrorPlaceholderPath == identifier)
				source = parameters.ErrorPlaceholderSource;

			var resolvedData = await Configuration.DataResolverFactory
			                                .GetResolver(identifier, source, parameters, Configuration)
			                                .Resolve(identifier, parameters, token);

			if (resolvedData?.Item1 == null)
				throw new FileNotFoundException(identifier);

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

			using (var svgStream = resolvedData.Item1)
			{
				picture = svg.Load(resolvedData?.Item1);
			}

			using (var bitmap = new SKBitmap(200, 200, true))
			using (var canvas = new SKCanvas(bitmap))
			{
				float canvasMin = Math.Min(200, 200);
				float svgMax = Math.Max(svg.Picture.Bounds.Width, svg.Picture.Bounds.Height);
				float scale = canvasMin / svgMax;
				var matrix = SKMatrix.MakeScale(scale, scale);
				canvas.DrawPicture(picture, ref matrix);

				using (var image = SKImage.FromBitmap(bitmap))
				{
					var stream = image.Encode()?.AsStream();
					return new Tuple<Stream, LoadingResult, ImageInformation>(stream, resolvedData.Item2, resolvedData.Item3);
				}
			}
		}
        public virtual async Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            NSBundle bundle = null;
            string file = null;
            var filename = Path.GetFileNameWithoutExtension(identifier);
            var extension = Path.GetExtension(identifier);
            const string pattern = "{0}@{1}x{2}";

            foreach (var fileType in fileTypes)
            {
                token.ThrowIfCancellationRequested();

                int scale = (int)ScaleHelper.Scale;
                if (scale > 1)
                {
                    while (scale > 1)
                    {
                        token.ThrowIfCancellationRequested();

                        var tmpFile = string.Format(pattern, filename, scale, extension);
                        bundle = NSBundle._AllBundles.FirstOrDefault(bu =>
                        {
                            var path = bu.PathForResource(tmpFile, fileType);
                            return !string.IsNullOrWhiteSpace(path);
                        });

                        if (bundle != null)
                        {
                            file = tmpFile;
                            break;
                        }
                        scale--;
                    }
                }

                token.ThrowIfCancellationRequested();

                if (file == null)
                {
                    file = identifier;
                    bundle = NSBundle._AllBundles.FirstOrDefault(bu =>
                    {
                        var path = bu.PathForResource(file, fileType);
                        return !string.IsNullOrWhiteSpace(path);
                    });
                }

                token.ThrowIfCancellationRequested();

                if (bundle != null)
                {
                    var path = bundle.PathForResource(file, fileType);

                    var stream = FileStore.GetInputStream(path, true);
                    var imageInformation = new ImageInformation();
                    imageInformation.SetPath(identifier);
                    imageInformation.SetFilePath(path);

                    return new Tuple<Stream, LoadingResult, ImageInformation>(
                        stream, LoadingResult.CompiledResource, imageInformation);
                }
            }

            //Asset catalog
            token.ThrowIfCancellationRequested();

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                NSDataAsset asset = null;

                try
                {
                    await MainThreadDispatcher.Instance.PostAsync(() => asset = new NSDataAsset(filename)).ConfigureAwait(false);
                }
                catch (Exception) { }

                if (asset != null)
                {
                    token.ThrowIfCancellationRequested();
                    var stream = asset.Data?.AsStream();
                    var imageInformation = new ImageInformation();
                    imageInformation.SetPath(identifier);
                    imageInformation.SetFilePath(null);

                    return new Tuple<Stream, LoadingResult, ImageInformation>(
                        stream, LoadingResult.CompiledResource, imageInformation);
                }
            }
            else if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
            {
                UIImage image = null;

                try
                {
                    await MainThreadDispatcher.Instance.PostAsync(() => image = UIImage.FromBundle(filename)).ConfigureAwait(false);
                }
                catch (Exception) { }

                if (image != null)
                {
                    token.ThrowIfCancellationRequested();
                    var stream = image.AsPNG()?.AsStream();
                    var imageInformation = new ImageInformation();
                    imageInformation.SetPath(identifier);
                    imageInformation.SetFilePath(null);

                    return new Tuple<Stream, LoadingResult, ImageInformation>(
                        stream, LoadingResult.CompiledResource, imageInformation);
                }
            }

            throw new FileNotFoundException(identifier);
        }
 public PlatformImageLoaderTask(ITarget <SharedEvasImage, TImageView> target, TaskParameter parameters, IImageService imageService) : base(EvasImageCache.Instance, target, parameters, imageService)
 {
 }
예제 #24
0
 public PlatformImageLoaderTask(ITarget <WriteableBitmap, TImageView> target, TaskParameter parameters, IImageService imageService, Configuration configuration, IMainThreadDispatcher mainThreadDispatcher)
     : base(ImageCache.Instance, configuration.DataResolverFactory ?? DataResolvers.DataResolverFactory.Instance, target, parameters, imageService, configuration, mainThreadDispatcher, false)
 {
 }
예제 #25
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func <Image> getNativeControl, Action <WriteableBitmap, bool, bool> doWithImage)
            : base(mainThreadDispatcher, miniLogger, parameters, false)
        {
            _getNativeControl = getNativeControl;
            _doWithImage      = doWithImage;

            DownloadCache = downloadCache;
        }
예제 #26
0
 /// <summary>
 /// This constructor is useful for child classes only. It can help when having a totally different loading logic.
 /// </summary>
 /// <param name="miniLogger">Logger</param>
 /// <param name="key">Key.</param>
 /// <param name="imageView">Image view.</param>
 protected ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, string key, ImageView imageView)
     : this(downloadCache, mainThreadDispatcher, miniLogger, TaskParameter.FromFile(key), imageView)
 {
 }
예제 #27
0
 public ImageLoaderTask(IMemoryCache <TImageContainer> memoryCache, IDataResolverFactory dataResolverFactory, ITarget <TImageContainer, TImageView> target, TaskParameter parameters, IImageService imageService, Configuration configuration, IMainThreadDispatcher mainThreadDispatcher, bool clearCacheOnOutOfMemory)
 {
     _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory;
     MemoryCache             = memoryCache;
     DataResolverFactory     = dataResolverFactory;
     PlatformTarget          = target;
     ImageService            = imageService;
     Configuration           = configuration;
     MainThreadDispatcher    = mainThreadDispatcher;
     Parameters              = parameters;
     CancellationTokenSource = new CancellationTokenSource();
     ImageInformation        = new ImageInformation();
     CanUseMemoryCache       = true;
     SetKeys();
     Target?.SetImageLoadingTask(this);
 }
예제 #28
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ITarget <BitmapDrawable, ImageLoaderTask> target)
            : base(mainThreadDispatcher, miniLogger, parameters, true)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            _target       = target;
            DownloadCache = downloadCache;
        }
예제 #29
0
        protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, IDownloadCache downloadCache, bool clearCacheOnOutOfMemory, bool verboseLoadingCancelledLogging)
        {
            _verboseLoadingCancelledLogging = verboseLoadingCancelledLogging;
            _clearCacheOnOutOfMemory        = clearCacheOnOutOfMemory;
            CancellationToken    = new CancellationTokenSource();
            DownloadCache        = downloadCache;
            Parameters           = parameters;
            NumberOfRetryNeeded  = parameters.RetryCount;
            MainThreadDispatcher = mainThreadDispatcher;
            Logger = miniLogger;
            ConfigureParameters();

            _hasCustomCacheKey = !string.IsNullOrWhiteSpace(Parameters.CustomCacheKey);
            _keys = new ConcurrentDictionary <string, string>();

            _transformationsKey = new Lazy <string>(() =>
            {
                if (Parameters.Transformations == null || Parameters.Transformations.Count == 0)
                {
                    return(string.Empty);
                }

                return(";" + string.Join(";", Parameters.Transformations.Select(t => t.Key)));
            });

            _downsamplingKey = new Lazy <string>(() =>
            {
                if (Parameters.DownSampleSize == null)
                {
                    return(string.Empty);
                }

                return(string.Concat(";", Parameters.DownSampleSize.Item1, "x", Parameters.DownSampleSize.Item2));
            });

            _rawKey = new Lazy <string>(() => GetKeyInternal(null, true));

            _streamKey = new Lazy <string>(() => "Stream" + GetNextStreamIndex());
        }
예제 #30
0
        public ImageLoaderTask(IMemoryCache <TImageContainer> memoryCache, IDataResolverFactory dataResolverFactory, ITarget <TImageContainer, TImageView> target, TaskParameter parameters, IImageService imageService, Configuration configuration, IMainThreadDispatcher mainThreadDispatcher, bool clearCacheOnOutOfMemory)
        {
            _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory;
            MemoryCache             = memoryCache;
            DataResolverFactory     = dataResolverFactory;
            PlatformTarget          = target;
            ImageService            = imageService;
            Configuration           = configuration;
            MainThreadDispatcher    = mainThreadDispatcher;
            Parameters              = parameters;
            CancellationTokenSource = new CancellationTokenSource();
            ImageInformation        = new ImageInformation();
            CanUseMemoryCache       = true;

            KeyRaw = Parameters.Path;
            if (Parameters.Source == ImageSource.Stream)
            {
                CanUseMemoryCache = false;
                KeyRaw            = string.Concat("Stream_", GetNextStreamIndex());
            }

            if (!string.IsNullOrWhiteSpace(Parameters.CustomCacheKey))
            {
                CanUseMemoryCache = true;
                KeyRaw            = Parameters.CustomCacheKey;
            }

            if (Parameters.CacheType == CacheType.Disk)
            {
                CanUseMemoryCache = false;
            }

            if (string.IsNullOrWhiteSpace(KeyRaw))
            {
                KeyRaw = Guid.NewGuid().ToString("N");
            }

            var vect = Parameters.CustomDataResolver as IVectorDataResolver;

            if (vect != null)
            {
                KeyRaw = string.Format("{0};(size={1}x{2},dip={3})", KeyRaw, vect.VectorWidth, vect.VectorHeight, vect.UseDipUnits);
            }

            KeyDownsamplingOnly = string.Empty;
            if (Parameters.DownSampleSize != null && (Parameters.DownSampleSize.Item1 > 0 || Parameters.DownSampleSize.Item2 > 0))
            {
                if (Parameters.DownSampleUseDipUnits)
                {
                    KeyDownsamplingOnly = string.Concat(";", DpiToPixels(Parameters.DownSampleSize.Item1), "x", DpiToPixels(Parameters.DownSampleSize.Item2));
                }
                else
                {
                    KeyDownsamplingOnly = string.Concat(";", Parameters.DownSampleSize.Item1, "x", Parameters.DownSampleSize.Item2);
                }
            }

            KeyTransformationsOnly = string.Empty;
            if (Parameters.Transformations != null && Parameters.Transformations.Count > 0)
            {
                KeyTransformationsOnly = string.Concat(string.Join(";", Parameters.Transformations.Select(t => t.Key)));
            }

            Key = string.Concat(KeyRaw, KeyDownsamplingOnly, KeyTransformationsOnly);
            KeyWithoutTransformations = string.Concat(KeyRaw, KeyDownsamplingOnly);

            if (!string.IsNullOrWhiteSpace(Parameters.LoadingPlaceholderPath))
            {
                if (TransformPlaceholders)
                {
                    KeyForLoadingPlaceholder = string.Concat(Parameters.LoadingPlaceholderPath, KeyDownsamplingOnly, KeyTransformationsOnly);
                }
                else
                {
                    KeyForLoadingPlaceholder = string.Concat(Parameters.LoadingPlaceholderPath, KeyDownsamplingOnly);
                }

                var vectLo = Parameters.CustomLoadingPlaceholderDataResolver as IVectorDataResolver;
                if (vectLo != null)
                {
                    KeyForLoadingPlaceholder = string.Format("{0};(size={1}x{2},dip={3})", KeyForLoadingPlaceholder, vectLo.VectorWidth, vectLo.VectorHeight, vectLo.UseDipUnits);
                }
            }

            if (!string.IsNullOrWhiteSpace(Parameters.ErrorPlaceholderPath))
            {
                if (TransformPlaceholders)
                {
                    KeyForErrorPlaceholder = string.Concat(Parameters.ErrorPlaceholderPath, KeyDownsamplingOnly, KeyTransformationsOnly);
                }
                else
                {
                    KeyForErrorPlaceholder = string.Concat(Parameters.ErrorPlaceholderPath, KeyDownsamplingOnly);
                }

                var vectEr = Parameters.CustomLoadingPlaceholderDataResolver as IVectorDataResolver;
                if (vectEr != null)
                {
                    KeyForErrorPlaceholder = string.Format("{0};(size={1}x{2},dip={3})", KeyForErrorPlaceholder, vectEr.VectorWidth, vectEr.VectorHeight, vectEr.UseDipUnits);
                }
            }

            ImageInformation.SetKey(Key, Parameters.CustomCacheKey);
            ImageInformation.SetPath(Parameters.Path);

            Target?.SetImageLoadingTask(this);
        }
예제 #31
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, nfloat imageScale, ITarget <UIImage, ImageLoaderTask> target, bool clearCacheOnOutOfMemory)
            : base(mainThreadDispatcher, miniLogger, parameters, true, clearCacheOnOutOfMemory)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            _target       = target;
            _imageScale   = imageScale;
            DownloadCache = downloadCache;
        }
 public PlatformImageLoaderTask(ITarget <PImage, TImageView> target, TaskParameter parameters, IImageService imageService, Configuration configuration, IMainThreadDispatcher mainThreadDispatcher)
     : base(ImageCache.Instance, configuration.DataResolverFactory ?? DataResolvers.DataResolverFactory.Instance, target, parameters, imageService, configuration, mainThreadDispatcher, true)
 {
     // do not remove! Kicks scale retrieval so it's available for all, without deadlocks due to accessing MainThread
     ScaleHelper.Init();
 }
 public PlatformImageLoaderTask(ITarget <PImage, TImageView> target, TaskParameter parameters, IImageService imageService) : base(ImageCache.Instance, target, parameters, imageService)
 {
     // do not remove! Kicks scale retrieval so it's available for all, without deadlocks due to accessing MainThread
     ScaleHelper.Init();
 }
		private void CleanParameters()
		{
			if (_parameters != null)
			{
				_parameters.Dispose();
				_parameters = null;
			}
			OnSuccess = null;
			OnError = null;
			OnFinish = null;
		}
예제 #35
0
 public ImageLoaderTask(IMemoryCache <TImageContainer> memoryCache, ITarget <TImageContainer, TImageView> target, TaskParameter parameters, IImageService imageService)
 {
     MemoryCache             = memoryCache;
     DataResolverFactory     = imageService.Config.DataResolverFactory;
     PlatformTarget          = target;
     ImageService            = imageService;
     Configuration           = imageService.Config;
     Parameters              = parameters;
     CancellationTokenSource = new CancellationTokenSource();
     ImageInformation        = new ImageInformation();
     CanUseMemoryCache       = true;
     SetKeys();
 }
예제 #36
0
 protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, bool clearCacheOnOutOfMemory)
 {
     _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory;
     CancellationToken        = new CancellationTokenSource();
     Parameters           = parameters;
     NumberOfRetryNeeded  = parameters.RetryCount;
     MainThreadDispatcher = mainThreadDispatcher;
     Logger = miniLogger;
     ConfigureParameters();
 }
예제 #37
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ITarget <BitmapDrawable, ImageLoaderTask> target)
            : base(mainThreadDispatcher, miniLogger, parameters, true, ImageService.Instance.Config.VerboseLoadingCancelledLogging)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            _target       = target;
            DownloadCache = downloadCache;
        }
예제 #38
0
 /// <summary>
 /// This constructor is useful for child classes only. It can help when having a totally different loading logic.
 /// </summary>
 /// <param name="miniLogger">Logger</param>
 /// <param name="key">Key.</param>
 /// <param name="imageView">Image view.</param>
 protected ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, string key, ITarget <BitmapDrawable, ImageLoaderTask> target)
     : this(downloadCache, mainThreadDispatcher, miniLogger, TaskParameter.FromFile(key), target)
 {
 }
예제 #39
0
 public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func <UIView> getNativeControl, Action <UIImage> doWithImage, nfloat imageScale)
     : base(mainThreadDispatcher, miniLogger, parameters)
 {
     CancellationToken = new CancellationTokenSource();
     _getNativeControl = getNativeControl;
     _doWithImage      = doWithImage;
     _imageScale       = imageScale;
     DownloadCache     = downloadCache;
 }
예제 #40
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ITarget <WriteableBitmap, ImageLoaderTask> target, bool clearCacheOnOutOfMemory)
            : base(mainThreadDispatcher, miniLogger, parameters, false, clearCacheOnOutOfMemory)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            _target = target;

            DownloadCache = downloadCache;
        }
예제 #41
0
        public ImageLoaderTask(IMemoryCache <TImageContainer> memoryCache, IDataResolverFactory dataResolverFactory, ITarget <TImageContainer, TImageView> target, TaskParameter parameters, IImageService imageService, Configuration configuration, IMainThreadDispatcher mainThreadDispatcher, bool clearCacheOnOutOfMemory)
        {
            _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory;
            MemoryCache             = memoryCache;
            DataResolverFactory     = dataResolverFactory;
            PlatformTarget          = target;
            ImageService            = imageService;
            Configuration           = configuration;
            MainThreadDispatcher    = mainThreadDispatcher;
            Parameters              = parameters;
            CancellationTokenSource = new CancellationTokenSource();
            ImageInformation        = new ImageInformation();
            CanUseMemoryCache       = true;

            KeyRaw = Parameters.Path;
            if (Parameters.Source == ImageSource.Stream)
            {
                CanUseMemoryCache = false;
                KeyRaw            = string.Concat("Stream_", GetNextStreamIndex());
            }

            if (!string.IsNullOrWhiteSpace(Parameters.CustomCacheKey))
            {
                CanUseMemoryCache = true;
                KeyRaw            = Parameters.CustomCacheKey;
            }

            KeyDownsamplingOnly = string.Empty;
            if (Parameters.DownSampleSize != null)
            {
                KeyDownsamplingOnly = string.Concat(";", Parameters.DownSampleSize.Item1, "x", Parameters.DownSampleSize.Item2);
            }

            KeyTransformationsOnly = string.Empty;
            if (Parameters.Transformations != null && Parameters.Transformations.Count > 0)
            {
                KeyTransformationsOnly = string.Concat(string.Join(";", Parameters.Transformations.Select(t => t.Key)));
            }

            Key = string.Concat(KeyRaw, KeyDownsamplingOnly, KeyTransformationsOnly);
            KeyWithoutTransformations = string.Concat(KeyRaw, KeyDownsamplingOnly);

            if (!string.IsNullOrWhiteSpace(Parameters.LoadingPlaceholderPath))
            {
                if (TransformPlaceholders)
                {
                    KeyForLoadingPlaceholder = string.Concat(Parameters.LoadingPlaceholderPath, KeyDownsamplingOnly, KeyTransformationsOnly);
                }
                else
                {
                    KeyForLoadingPlaceholder = string.Concat(Parameters.LoadingPlaceholderPath, KeyDownsamplingOnly);
                }
            }

            if (!string.IsNullOrWhiteSpace(Parameters.ErrorPlaceholderPath))
            {
                if (TransformPlaceholders)
                {
                    KeyForErrorPlaceholder = string.Concat(Parameters.ErrorPlaceholderPath, KeyDownsamplingOnly, KeyTransformationsOnly);
                }
                else
                {
                    KeyForErrorPlaceholder = string.Concat(Parameters.ErrorPlaceholderPath, KeyDownsamplingOnly);
                }
            }

            ImageInformation.SetKey(Key, Parameters.CustomCacheKey);
            ImageInformation.SetPath(Parameters.Path);

            Target?.SetImageLoadingTask(this);
        }
		public Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
		{
			throw new NotImplementedException();
		}
예제 #43
0
 public PlatformImageLoaderTask(ITarget <BitmapSource, TImageView> target, TaskParameter parameters, IImageService imageService) : base(ImageCache.Instance, target, parameters, imageService)
 {
 }
예제 #44
0
        public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ImageView imageView)
            : base(mainThreadDispatcher, miniLogger, parameters, true)
        {
            DownloadCache = downloadCache;

            if (imageView != null)
            {
                _imageWeakReference = new WeakReference <ImageView>(imageView);
            }
        }
예제 #45
0
		public UrlStreamResolver(TaskParameter parameter, IDownloadCache downloadCache) {
			Parameters = parameter;
			DownloadCache = downloadCache;
		}
예제 #46
0
 public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func <UIView> getNativeControl, Action <UIImage, bool, bool> doWithImage, nfloat imageScale)
     : base(mainThreadDispatcher, miniLogger, parameters, true)
 {
     _getNativeControl = getNativeControl;
     _doWithImage      = doWithImage;
     _imageScale       = imageScale;
     DownloadCache     = downloadCache;
 }