HasImageComponent+Kingfisher.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 KingfisherImageSettable: KingfisherCompatible {
  27. @MainActor func setImage(
  28. _ image: KFCrossPlatformImage?,
  29. options: KingfisherParsedOptionsInfo
  30. )
  31. @MainActor func getImage() -> KFCrossPlatformImage?
  32. }
  33. public protocol KingfisherHasImageComponent: KingfisherImageSettable {
  34. @MainActor var image: KFCrossPlatformImage? { set get }
  35. }
  36. extension KingfisherHasImageComponent {
  37. @MainActor
  38. public func setImage(_ image: KFCrossPlatformImage?, options: KingfisherParsedOptionsInfo) {
  39. self.image = image
  40. }
  41. @MainActor
  42. public func getImage() -> KFCrossPlatformImage? {
  43. image
  44. }
  45. }
  46. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  47. import AppKit
  48. @available(macOS 13.0, *)
  49. extension NSComboButton: KingfisherHasImageComponent {}
  50. @available(macOS 13.0, *)
  51. extension NSColorWell: KingfisherHasImageComponent {}
  52. extension NSTableViewRowAction: KingfisherHasImageComponent {}
  53. extension NSMenuItem: KingfisherHasImageComponent {}
  54. extension NSPathControlItem: KingfisherHasImageComponent {}
  55. extension NSToolbarItem: KingfisherHasImageComponent {}
  56. extension NSTabViewItem: KingfisherHasImageComponent {}
  57. extension NSStatusItem: KingfisherHasImageComponent {}
  58. extension NSCell: KingfisherHasImageComponent {}
  59. #endif
  60. #if canImport(UIKit) && !os(watchOS)
  61. import UIKit
  62. @available(iOS 13.0, tvOS 13.0, *)
  63. extension UIAction: KingfisherHasImageComponent {}
  64. @available(iOS 13.0, tvOS 13.0, *)
  65. extension UICommand: KingfisherHasImageComponent {}
  66. extension UIBarItem: KingfisherHasImageComponent {}
  67. #endif
  68. #if canImport(WatchKit)
  69. import WatchKit
  70. extension WKInterfaceImage: KingfisherHasImageComponent {
  71. @MainActor public var image: KFCrossPlatformImage? {
  72. get { nil }
  73. set { setImage(newValue) }
  74. }
  75. }
  76. #endif
  77. #if canImport(TVUIKit)
  78. import TVUIKit
  79. extension TVMonogramView: KingfisherHasImageComponent {}
  80. #endif
  81. struct ImagePropertyAccessor<ImageType>: Sendable {
  82. let setImage: @Sendable @MainActor (ImageType?, KingfisherParsedOptionsInfo) -> Void
  83. let getImage: @Sendable @MainActor () -> ImageType?
  84. }
  85. struct TaskPropertyAccessor: Sendable {
  86. let setTaskIdentifier: @Sendable @MainActor (Source.Identifier.Value?) -> Void
  87. let getTaskIdentifier: @Sendable @MainActor () -> Source.Identifier.Value?
  88. let setTask: @Sendable @MainActor (DownloadTask?) -> Void
  89. }
  90. @MainActor
  91. extension KingfisherWrapper where Base: KingfisherImageSettable {
  92. // MARK: Setting Image
  93. /// Sets an image to the image view with a ``Source``.
  94. ///
  95. /// - Parameters:
  96. /// - source: The ``Source`` object that defines data information from the network or a data provider.
  97. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  98. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  99. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  100. /// `expectedContentLength`, this block will not be called.
  101. /// - completionHandler: Called when the image retrieval and setting are finished.
  102. /// - Returns: A task that represents the image downloading.
  103. ///
  104. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  105. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  106. ///
  107. /// ```swift
  108. /// // Set image from a network source.
  109. /// let url = URL(string: "https://example.com/image.png")!
  110. /// imageView.kf.setImage(with: .network(url))
  111. ///
  112. /// // Or set image from a data provider.
  113. /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
  114. /// imageView.kf.setImage(with: .provider(provider))
  115. /// ```
  116. ///
  117. /// For both ``Source/network(_:)`` and ``Source/provider(_:)`` sources, there are corresponding view extension
  118. /// methods. So the code above is equivalent to:
  119. ///
  120. /// ```swift
  121. /// imageView.kf.setImage(with: url)
  122. /// imageView.kf.setImage(with: provider)
  123. /// ```
  124. ///
  125. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  126. /// changes, it is your responsibility to call it from the main thread.
  127. ///
  128. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  129. @discardableResult
  130. public func setImage(
  131. with source: Source?,
  132. placeholder: KFCrossPlatformImage? = nil,
  133. options: KingfisherOptionsInfo? = nil,
  134. progressBlock: DownloadProgressBlock? = nil,
  135. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  136. ) -> DownloadTask?
  137. {
  138. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  139. return setImage(
  140. with: source,
  141. placeholder: placeholder,
  142. parsedOptions: options,
  143. progressBlock: progressBlock,
  144. completionHandler: completionHandler
  145. )
  146. }
  147. /// Sets an image to the image view with a ``Source``.
  148. ///
  149. /// - Parameters:
  150. /// - source: The ``Source`` object that defines data information from the network or a data provider.
  151. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  152. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  153. /// - completionHandler: Called when the image retrieval and setting are finished.
  154. /// - Returns: A task that represents the image downloading.
  155. ///
  156. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  157. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  158. ///
  159. /// ```swift
  160. /// // Set image from a network source.
  161. /// let url = URL(string: "https://example.com/image.png")!
  162. /// imageView.kf.setImage(with: .network(url))
  163. ///
  164. /// // Or set image from a data provider.
  165. /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
  166. /// imageView.kf.setImage(with: .provider(provider))
  167. /// ```
  168. ///
  169. /// For both ``Source/network(_:)`` and ``Source/provider(_:)`` sources, there are corresponding view extension
  170. /// methods. So the code above is equivalent to:
  171. ///
  172. /// ```swift
  173. /// imageView.kf.setImage(with: url)
  174. /// imageView.kf.setImage(with: provider)
  175. /// ```
  176. ///
  177. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  178. /// changes, it is your responsibility to call it from the main thread.
  179. ///
  180. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  181. @discardableResult
  182. public func setImage(
  183. with source: Source?,
  184. placeholder: KFCrossPlatformImage? = nil,
  185. options: KingfisherOptionsInfo? = nil,
  186. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  187. ) -> DownloadTask?
  188. {
  189. return setImage(
  190. with: source,
  191. placeholder: placeholder,
  192. options: options,
  193. progressBlock: nil,
  194. completionHandler: completionHandler
  195. )
  196. }
  197. /// Sets an image to the image view with a requested ``Resource``.
  198. ///
  199. /// - Parameters:
  200. /// - resource: The ``Resource`` object contains information about the resource.
  201. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  202. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  203. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  204. /// `expectedContentLength`, this block will not be called.
  205. /// - completionHandler: Called when the image retrieval and setting are finished.
  206. /// - Returns: A task that represents the image downloading.
  207. ///
  208. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  209. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  210. ///
  211. /// ```swift
  212. /// // Set image from a URL resource.
  213. /// let url = URL(string: "https://example.com/image.png")!
  214. /// imageView.kf.setImage(with: url)
  215. /// ```
  216. ///
  217. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  218. /// changes, it is your responsibility to call it from the main thread.
  219. ///
  220. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  221. @discardableResult
  222. public func setImage(
  223. with resource: (any Resource)?,
  224. placeholder: KFCrossPlatformImage? = nil,
  225. options: KingfisherOptionsInfo? = nil,
  226. progressBlock: DownloadProgressBlock? = nil,
  227. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  228. ) -> DownloadTask?
  229. {
  230. return setImage(
  231. with: resource?.convertToSource(),
  232. placeholder: placeholder,
  233. options: options,
  234. progressBlock: progressBlock,
  235. completionHandler: completionHandler
  236. )
  237. }
  238. /// Sets an image to the image view with a requested ``Resource``.
  239. ///
  240. /// - Parameters:
  241. /// - resource: The ``Resource`` object contains information about the resource.
  242. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  243. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  244. /// - completionHandler: Called when the image retrieval and setting are finished.
  245. /// - Returns: A task that represents the image downloading.
  246. ///
  247. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  248. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  249. ///
  250. /// ```swift
  251. /// // Set image from a URL resource.
  252. /// let url = URL(string: "https://example.com/image.png")!
  253. /// imageView.kf.setImage(with: url)
  254. /// ```
  255. ///
  256. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  257. /// changes, it is your responsibility to call it from the main thread.
  258. ///
  259. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  260. @discardableResult
  261. public func setImage(
  262. with resource: (any Resource)?,
  263. placeholder: KFCrossPlatformImage? = nil,
  264. options: KingfisherOptionsInfo? = nil,
  265. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  266. ) -> DownloadTask?
  267. {
  268. return setImage(
  269. with: resource,
  270. placeholder: placeholder,
  271. options: options,
  272. progressBlock: nil,
  273. completionHandler: completionHandler
  274. )
  275. }
  276. /// Sets an image to the image view with a ``ImageDataProvider``.
  277. ///
  278. /// - Parameters:
  279. /// - provider: The ``ImageDataProvider`` object that defines data information from the data provider.
  280. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  281. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  282. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  283. /// `expectedContentLength`, this block will not be called.
  284. /// - completionHandler: Called when the image retrieval and setting are finished.
  285. /// - Returns: A task that represents the image downloading.
  286. ///
  287. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  288. /// changes, it is your responsibility to call it from the main thread.
  289. ///
  290. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  291. @discardableResult
  292. public func setImage(
  293. with provider: (any ImageDataProvider)?,
  294. placeholder: KFCrossPlatformImage? = nil,
  295. options: KingfisherOptionsInfo? = nil,
  296. progressBlock: DownloadProgressBlock? = nil,
  297. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  298. ) -> DownloadTask?
  299. {
  300. return setImage(
  301. with: provider.map { .provider($0) },
  302. placeholder: placeholder,
  303. options: options,
  304. progressBlock: progressBlock,
  305. completionHandler: completionHandler
  306. )
  307. }
  308. /// Sets an image to the image view with a ``ImageDataProvider``.
  309. ///
  310. /// - Parameters:
  311. /// - provider: The ``ImageDataProvider`` object that defines data information from the data provider.
  312. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  313. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  314. /// - completionHandler: Called when the image retrieval and setting are finished.
  315. /// - Returns: A task that represents the image downloading.
  316. ///
  317. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  318. /// changes, it is your responsibility to call it from the main thread.
  319. ///
  320. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  321. @discardableResult
  322. public func setImage(
  323. with provider: (any ImageDataProvider)?,
  324. placeholder: KFCrossPlatformImage? = nil,
  325. options: KingfisherOptionsInfo? = nil,
  326. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  327. ) -> DownloadTask?
  328. {
  329. return setImage(
  330. with: provider,
  331. placeholder: placeholder,
  332. options: options,
  333. progressBlock: nil,
  334. completionHandler: completionHandler
  335. )
  336. }
  337. func setImage(
  338. with source: Source?,
  339. placeholder: KFCrossPlatformImage? = nil,
  340. parsedOptions: KingfisherParsedOptionsInfo,
  341. progressBlock: DownloadProgressBlock? = nil,
  342. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  343. ) -> DownloadTask? {
  344. return setImage(
  345. with: source,
  346. imageAccessor: ImagePropertyAccessor(
  347. setImage: { base.setImage($0, options: $1) },
  348. getImage: { base.getImage() }
  349. ),
  350. taskAccessor: TaskPropertyAccessor(
  351. setTaskIdentifier: {
  352. var mutatingSelf = self
  353. mutatingSelf.taskIdentifier = $0
  354. },
  355. getTaskIdentifier: { self.taskIdentifier },
  356. setTask: { task in
  357. var mutatingSelf = self
  358. mutatingSelf.imageTask = task
  359. }
  360. ),
  361. placeholder: placeholder,
  362. parsedOptions: parsedOptions,
  363. progressBlock: progressBlock,
  364. completionHandler: completionHandler
  365. )
  366. }
  367. }
  368. @MainActor
  369. extension KingfisherWrapper {
  370. func setImage(
  371. with source: Source?,
  372. imageAccessor: ImagePropertyAccessor<KFCrossPlatformImage>,
  373. taskAccessor: TaskPropertyAccessor,
  374. placeholder: KFCrossPlatformImage? = nil,
  375. parsedOptions: KingfisherParsedOptionsInfo,
  376. progressBlock: DownloadProgressBlock? = nil,
  377. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  378. ) -> DownloadTask?
  379. {
  380. guard let source = source else {
  381. imageAccessor.setImage(placeholder, parsedOptions)
  382. taskAccessor.setTaskIdentifier(nil)
  383. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  384. return nil
  385. }
  386. var options = parsedOptions
  387. // Always set placeholder while there is no image/placeholder yet.
  388. #if os(watchOS)
  389. let usePlaceholderDuringLoading = !options.keepCurrentImageWhileLoading
  390. #else
  391. let usePlaceholderDuringLoading = !options.keepCurrentImageWhileLoading || imageAccessor.getImage() == nil
  392. #endif
  393. if usePlaceholderDuringLoading {
  394. imageAccessor.setImage(placeholder, options)
  395. }
  396. let issuedIdentifier = Source.Identifier.next()
  397. taskAccessor.setTaskIdentifier(issuedIdentifier)
  398. if let block = progressBlock {
  399. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  400. }
  401. let task = KingfisherManager.shared.retrieveImage(
  402. with: source,
  403. options: options,
  404. downloadTaskUpdated: { task in
  405. Task { @MainActor in taskAccessor.setTask(task) }
  406. },
  407. progressiveImageSetter: { imageAccessor.setImage($0, options) },
  408. referenceTaskIdentifierChecker: { issuedIdentifier == taskAccessor.getTaskIdentifier() },
  409. completionHandler: { result in
  410. CallbackQueueMain.currentOrAsync {
  411. guard issuedIdentifier == taskAccessor.getTaskIdentifier() else {
  412. let reason: KingfisherError.ImageSettingErrorReason
  413. do {
  414. let value = try result.get()
  415. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  416. } catch {
  417. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  418. }
  419. let error = KingfisherError.imageSettingError(reason: reason)
  420. completionHandler?(.failure(error))
  421. return
  422. }
  423. taskAccessor.setTask(nil)
  424. taskAccessor.setTaskIdentifier(nil)
  425. switch result {
  426. case .success(let value):
  427. imageAccessor.setImage(value.image, options)
  428. case .failure:
  429. if let image = options.onFailureImage {
  430. imageAccessor.setImage(image, options)
  431. }
  432. }
  433. completionHandler?(result)
  434. }
  435. }
  436. )
  437. taskAccessor.setTask(task)
  438. return task
  439. }
  440. }
  441. // MARK: - Associated Object
  442. @MainActor private var taskIdentifierKey: Void?
  443. @MainActor private var imageTaskKey: Void?
  444. @MainActor
  445. extension KingfisherWrapper where Base: KingfisherImageSettable {
  446. // MARK: Properties
  447. public private(set) var taskIdentifier: Source.Identifier.Value? {
  448. get {
  449. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  450. return box?.value
  451. }
  452. set {
  453. let box = newValue.map { Box($0) }
  454. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  455. }
  456. }
  457. private var imageTask: DownloadTask? {
  458. get { return getAssociatedObject(base, &imageTaskKey) }
  459. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  460. }
  461. /// Cancels the image download task of the image view if it is running.
  462. ///
  463. /// Nothing will happen if the downloading has already finished.
  464. public func cancelDownloadTask() {
  465. imageTask?.cancel()
  466. }
  467. }