HasImageComponent+Kingfisher.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. //
  2. // KingfisherHasImageComponent+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by JH on 2023/12/5.
  6. //
  7. // Copyright (c) 2023 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. public protocol KingfisherHasImageComponent: KingfisherCompatible {
  27. var image: KFCrossPlatformImage? { set get }
  28. }
  29. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  30. import AppKit
  31. @available(macOS 13.0, *)
  32. extension NSComboButton: KingfisherHasImageComponent {}
  33. @available(macOS 13.0, *)
  34. extension NSColorWell: KingfisherHasImageComponent {}
  35. extension NSImageView: KingfisherHasImageComponent {}
  36. extension NSTableViewRowAction: KingfisherHasImageComponent {}
  37. extension NSMenuItem: KingfisherHasImageComponent {}
  38. extension NSPathControlItem: KingfisherHasImageComponent {}
  39. extension NSToolbarItem: KingfisherHasImageComponent {}
  40. extension NSTabViewItem: KingfisherHasImageComponent {}
  41. extension NSStatusItem: KingfisherHasImageComponent {}
  42. extension NSCell: KingfisherHasImageComponent {}
  43. #endif
  44. #if canImport(UIKit) && !os(watchOS)
  45. import UIKit
  46. @available(iOS 13.0, tvOS 13.0, *)
  47. extension UIAction: KingfisherHasImageComponent {}
  48. @available(iOS 13.0, tvOS 13.0, *)
  49. extension UICommand: KingfisherHasImageComponent {}
  50. extension UIBarItem: KingfisherHasImageComponent {}
  51. #endif
  52. extension KingfisherWrapper where Base: KingfisherHasImageComponent {
  53. // MARK: Setting Image
  54. /// Sets an image to the component with a source.
  55. ///
  56. /// - Parameters:
  57. /// - source: The `Source` object contains information about how to get the image.
  58. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  59. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  60. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  61. /// `expectedContentLength`, this block will not be called.
  62. /// - completionHandler: Called when the image retrieved and set finished.
  63. /// - Returns: A task represents the image downloading.
  64. ///
  65. /// - Note:
  66. /// Internally, this method will use `KingfisherManager` to get the requested source.
  67. /// Since this method will perform UI changes, you must call it from the main thread.
  68. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  69. ///
  70. @discardableResult
  71. public func setImage(
  72. with source: Source?,
  73. placeholder: KFCrossPlatformImage? = nil,
  74. options: KingfisherOptionsInfo? = nil,
  75. progressBlock: DownloadProgressBlock? = nil,
  76. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  77. ) -> DownloadTask? {
  78. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  79. return setImage(
  80. with: source,
  81. placeholder: placeholder,
  82. parsedOptions: options,
  83. progressBlock: progressBlock,
  84. completionHandler: completionHandler
  85. )
  86. }
  87. /// Sets an image to the component with a requested resource.
  88. ///
  89. /// - Parameters:
  90. /// - resource: The `Resource` object contains information about the resource.
  91. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  92. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  93. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  94. /// `expectedContentLength`, this block will not be called.
  95. /// - completionHandler: Called when the image retrieved and set finished.
  96. /// - Returns: A task represents the image downloading.
  97. ///
  98. /// - Note:
  99. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  100. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  101. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  102. ///
  103. @discardableResult
  104. public func setImage(
  105. with resource: Resource?,
  106. placeholder: KFCrossPlatformImage? = nil,
  107. options: KingfisherOptionsInfo? = nil,
  108. progressBlock: DownloadProgressBlock? = nil,
  109. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  110. ) -> DownloadTask? {
  111. return setImage(
  112. with: resource?.convertToSource(),
  113. placeholder: placeholder,
  114. options: options,
  115. progressBlock: progressBlock,
  116. completionHandler: completionHandler
  117. )
  118. }
  119. func setImage(
  120. with source: Source?,
  121. placeholder: KFCrossPlatformImage? = nil,
  122. parsedOptions: KingfisherParsedOptionsInfo,
  123. progressBlock: DownloadProgressBlock? = nil,
  124. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  125. ) -> DownloadTask? {
  126. var mutatingSelf = self
  127. guard let source else {
  128. base.image = placeholder
  129. mutatingSelf.taskIdentifier = nil
  130. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  131. return nil
  132. }
  133. var options = parsedOptions
  134. if !options.keepCurrentImageWhileLoading {
  135. base.image = placeholder
  136. }
  137. let issuedIdentifier = Source.Identifier.next()
  138. mutatingSelf.taskIdentifier = issuedIdentifier
  139. if let block = progressBlock {
  140. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  141. }
  142. let task = KingfisherManager.shared.retrieveImage(
  143. with: source,
  144. options: options,
  145. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  146. progressiveImageSetter: { self.base.image = $0 },
  147. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  148. completionHandler: { result in
  149. CallbackQueue.mainCurrentOrAsync.execute {
  150. guard issuedIdentifier == self.taskIdentifier else {
  151. let reason: KingfisherError.ImageSettingErrorReason
  152. do {
  153. let value = try result.get()
  154. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  155. } catch {
  156. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  157. }
  158. let error = KingfisherError.imageSettingError(reason: reason)
  159. completionHandler?(.failure(error))
  160. return
  161. }
  162. mutatingSelf.imageTask = nil
  163. mutatingSelf.taskIdentifier = nil
  164. switch result {
  165. case let .success(value):
  166. self.base.image = value.image
  167. completionHandler?(result)
  168. case .failure:
  169. if let image = options.onFailureImage {
  170. self.base.image = image
  171. }
  172. completionHandler?(result)
  173. }
  174. }
  175. }
  176. )
  177. mutatingSelf.imageTask = task
  178. return task
  179. }
  180. // MARK: Cancelling Downloading Task
  181. /// Cancels the image download task of the component if it is running.
  182. /// Nothing will happen if the downloading has already finished.
  183. public func cancelImageDownloadTask() {
  184. imageTask?.cancel()
  185. }
  186. }
  187. // MARK: - Associated Object
  188. private var taskIdentifierKey: Void?
  189. private var imageTaskKey: Void?
  190. private var alternateTaskIdentifierKey: Void?
  191. private var alternateImageTaskKey: Void?
  192. extension KingfisherWrapper where Base: KingfisherHasImageComponent {
  193. // MARK: Properties
  194. public private(set) var taskIdentifier: Source.Identifier.Value? {
  195. get {
  196. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  197. return box?.value
  198. }
  199. set {
  200. let box = newValue.map { Box($0) }
  201. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  202. }
  203. }
  204. private var imageTask: DownloadTask? {
  205. get { return getAssociatedObject(base, &imageTaskKey) }
  206. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue) }
  207. }
  208. }