added iOS source code
[wl-app.git] / iOS / Pods / Kingfisher / Sources / ImagePrefetcher.swift
1 //
2 //  ImagePrefetcher.swift
3 //  Kingfisher
4 //
5 //  Created by Claire Knight <claire.knight@moggytech.co.uk> on 24/02/2016
6 //
7 //  Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
8 //
9 //  Permission is hereby granted, free of charge, to any person obtaining a copy
10 //  of this software and associated documentation files (the "Software"), to deal
11 //  in the Software without restriction, including without limitation the rights
12 //  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 //  copies of the Software, and to permit persons to whom the Software is
14 //  furnished to do so, subject to the following conditions:
15 //
16 //  The above copyright notice and this permission notice shall be included in
17 //  all copies or substantial portions of the Software.
18 //
19 //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 //  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 //  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 //  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 //  THE SOFTWARE.
26
27
28 #if os(macOS)
29     import AppKit
30 #else
31     import UIKit
32 #endif
33
34
35 /// Progress update block of prefetcher. 
36 ///
37 /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
38 /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
39 /// - `completedResources`: An array of resources that are downloaded and cached successfully.
40 public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
41
42 /// Completion block of prefetcher.
43 ///
44 /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
45 /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
46 /// - `completedResources`: An array of resources that are downloaded and cached successfully.
47 public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
48
49 /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
50 /// This is useful when you know a list of image resources and want to download them before showing.
51 public class ImagePrefetcher {
52     
53     /// The maximum concurrent downloads to use when prefetching images. Default is 5.
54     public var maxConcurrentDownloads = 5
55     
56     private let prefetchResources: [Resource]
57     private let optionsInfo: KingfisherOptionsInfo
58     private var progressBlock: PrefetcherProgressBlock?
59     private var completionHandler: PrefetcherCompletionHandler?
60     
61     private var tasks = [URL: RetrieveImageDownloadTask]()
62     
63     private var pendingResources: ArraySlice<Resource>
64     private var skippedResources = [Resource]()
65     private var completedResources = [Resource]()
66     private var failedResources = [Resource]()
67     
68     private var stopped = false
69     
70     // The created manager used for prefetch. We will use the helper method in manager.
71     private let manager: KingfisherManager
72     
73     private var finished: Bool {
74         return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty
75     }
76     
77     /**
78      Init an image prefetcher with an array of URLs.
79      
80      The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. 
81      After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
82      The images already cached will be skipped without downloading again.
83      
84      - parameter urls:              The URLs which should be prefetched.
85      - parameter options:           A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
86      - parameter progressBlock:     Called every time an resource is downloaded, skipped or cancelled.
87      - parameter completionHandler: Called when the whole prefetching process finished.
88      
89      - returns: An `ImagePrefetcher` object.
90      
91      - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as 
92      the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
93      Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
94      */
95     public convenience init(urls: [URL],
96                          options: KingfisherOptionsInfo? = nil,
97                    progressBlock: PrefetcherProgressBlock? = nil,
98                completionHandler: PrefetcherCompletionHandler? = nil)
99     {
100         let resources: [Resource] = urls.map { $0 }
101         self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
102     }
103     
104     /**
105      Init an image prefetcher with an array of resources.
106      
107      The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
108      After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
109      The images already cached will be skipped without downloading again.
110      
111      - parameter resources:         The resources which should be prefetched. See `Resource` type for more.
112      - parameter options:           A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
113      - parameter progressBlock:     Called every time an resource is downloaded, skipped or cancelled.
114      - parameter completionHandler: Called when the whole prefetching process finished.
115      
116      - returns: An `ImagePrefetcher` object.
117      
118      - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
119      the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
120      Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
121      */
122     public init(resources: [Resource],
123                   options: KingfisherOptionsInfo? = nil,
124             progressBlock: PrefetcherProgressBlock? = nil,
125         completionHandler: PrefetcherCompletionHandler? = nil)
126     {
127         prefetchResources = resources
128         pendingResources = ArraySlice(resources)
129         
130         // We want all callbacks from main queue, so we ignore the call back queue in options
131         let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
132         self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
133         
134         let cache = self.optionsInfo.targetCache
135         let downloader = self.optionsInfo.downloader
136         manager = KingfisherManager(downloader: downloader, cache: cache)
137         
138         self.progressBlock = progressBlock
139         self.completionHandler = completionHandler
140     }
141     
142     /**
143      Start to download the resources and cache them. This can be useful for background downloading
144      of assets that are required for later use in an app. This code will not try and update any UI
145      with the results of the process.
146      */
147     public func start()
148     {
149         // Since we want to handle the resources cancellation in main thread only.
150         DispatchQueue.main.safeAsync {
151             
152             guard !self.stopped else {
153                 assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
154                 self.handleComplete()
155                 return
156             }
157             
158             guard self.maxConcurrentDownloads > 0 else {
159                 assertionFailure("There should be concurrent downloads value should be at least 1.")
160                 self.handleComplete()
161                 return
162             }
163             
164             guard self.prefetchResources.count > 0 else {
165                 self.handleComplete()
166                 return
167             }
168             
169             let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
170             for _ in 0 ..< initialConcurentDownloads {
171                 if let resource = self.pendingResources.popFirst() {
172                     self.startPrefetching(resource)
173                 }
174             }
175         }
176     }
177
178    
179     /**
180      Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
181      */
182     public func stop() {
183         DispatchQueue.main.safeAsync {
184             if self.finished { return }
185             self.stopped = true
186             self.tasks.values.forEach { $0.cancel() }
187         }
188     }
189     
190     func downloadAndCache(_ resource: Resource) {
191
192         let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> Void in
193             self.tasks.removeValue(forKey: resource.downloadURL)
194             if let _ = error {
195                 self.failedResources.append(resource)
196             } else {
197                 self.completedResources.append(resource)
198             }
199             
200             self.reportProgress()
201             if self.stopped {
202                 if self.tasks.isEmpty {
203                     self.failedResources.append(contentsOf: self.pendingResources)
204                     self.handleComplete()
205                 }
206             } else {
207                 self.reportCompletionOrStartNext()
208             }
209         }
210         
211         let downloadTask = manager.downloadAndCacheImage(
212             with: resource.downloadURL,
213             forKey: resource.cacheKey,
214             retrieveImageTask: RetrieveImageTask(),
215             progressBlock: nil,
216             completionHandler: downloadTaskCompletionHandler,
217             options: optionsInfo)
218         
219         if let downloadTask = downloadTask {
220             tasks[resource.downloadURL] = downloadTask
221         }
222     }
223     
224     func append(cached resource: Resource) {
225         skippedResources.append(resource)
226  
227         reportProgress()
228         reportCompletionOrStartNext()
229     }
230     
231     func startPrefetching(_ resource: Resource)
232     {
233         if optionsInfo.forceRefresh {
234             downloadAndCache(resource)
235         } else {
236             let alreadyInCache = manager.cache.imageCachedType(forKey: resource.cacheKey,
237                                                              processorIdentifier: optionsInfo.processor.identifier).cached
238             if alreadyInCache {
239                 append(cached: resource)
240             } else {
241                 downloadAndCache(resource)
242             }
243         }
244     }
245     
246     func reportProgress() {
247         progressBlock?(skippedResources, failedResources, completedResources)
248     }
249     
250     func reportCompletionOrStartNext() {
251         DispatchQueue.main.async {
252             if let resource = self.pendingResources.popFirst() {
253                 self.startPrefetching(resource)
254             } else {
255                 guard self.tasks.isEmpty else { return }
256                 self.handleComplete()
257             }
258         }
259     }
260     
261     func handleComplete() {
262         completionHandler?(skippedResources, failedResources, completedResources)
263         completionHandler = nil
264         progressBlock = nil
265     }
266 }