NSButton+Kingfisher.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. //
  2. // NSButton+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Jie Zhang on 14/04/2016.
  6. //
  7. // Copyright (c) 2019 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. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  27. import AppKit
  28. extension KingfisherWrapper where Base: NSButton {
  29. // MARK: Setting Image
  30. /// Sets an image to the button with a source.
  31. ///
  32. /// - Parameters:
  33. /// - source: The `Source` object contains information about how to get the image.
  34. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  35. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  36. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  37. /// `expectedContentLength`, this block will not be called.
  38. /// - completionHandler: Called when the image retrieved and set finished.
  39. /// - Returns: A task represents the image downloading.
  40. ///
  41. /// - Note:
  42. /// Internally, this method will use `KingfisherManager` to get the requested source.
  43. /// Since this method will perform UI changes, you must call it from the main thread.
  44. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  45. ///
  46. @discardableResult
  47. public func setImage(
  48. with source: Source?,
  49. placeholder: KFCrossPlatformImage? = nil,
  50. options: KingfisherOptionsInfo? = nil,
  51. progressBlock: DownloadProgressBlock? = nil,
  52. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  53. {
  54. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  55. return setImage(
  56. with: source,
  57. placeholder: placeholder,
  58. parsedOptions: options,
  59. progressBlock: progressBlock,
  60. completionHandler: completionHandler
  61. )
  62. }
  63. /// Sets an image to the button with a requested resource.
  64. ///
  65. /// - Parameters:
  66. /// - resource: The `Resource` object contains information about the resource.
  67. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  68. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  69. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  70. /// `expectedContentLength`, this block will not be called.
  71. /// - completionHandler: Called when the image retrieved and set finished.
  72. /// - Returns: A task represents the image downloading.
  73. ///
  74. /// - Note:
  75. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  76. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  77. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  78. ///
  79. @discardableResult
  80. public func setImage(
  81. with resource: Resource?,
  82. placeholder: KFCrossPlatformImage? = nil,
  83. options: KingfisherOptionsInfo? = nil,
  84. progressBlock: DownloadProgressBlock? = nil,
  85. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  86. {
  87. return setImage(
  88. with: resource?.convertToSource(),
  89. placeholder: placeholder,
  90. options: options,
  91. progressBlock: progressBlock,
  92. completionHandler: completionHandler)
  93. }
  94. func setImage(
  95. with source: Source?,
  96. placeholder: KFCrossPlatformImage? = nil,
  97. parsedOptions: KingfisherParsedOptionsInfo,
  98. progressBlock: DownloadProgressBlock? = nil,
  99. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  100. {
  101. var mutatingSelf = self
  102. guard let source = source else {
  103. base.image = placeholder
  104. mutatingSelf.taskIdentifier = nil
  105. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  106. return nil
  107. }
  108. var options = parsedOptions
  109. if !options.keepCurrentImageWhileLoading {
  110. base.image = placeholder
  111. }
  112. let issuedIdentifier = Source.Identifier.next()
  113. mutatingSelf.taskIdentifier = issuedIdentifier
  114. if let block = progressBlock {
  115. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  116. }
  117. if let provider = ImageProgressiveProvider(options, refresh: { image in
  118. self.base.image = image
  119. }) {
  120. options.onDataReceived = (options.onDataReceived ?? []) + [provider]
  121. }
  122. options.onDataReceived?.forEach {
  123. $0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
  124. }
  125. let task = KingfisherManager.shared.retrieveImage(
  126. with: source,
  127. options: options,
  128. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  129. completionHandler: { result in
  130. CallbackQueue.mainCurrentOrAsync.execute {
  131. guard issuedIdentifier == self.taskIdentifier else {
  132. let reason: KingfisherError.ImageSettingErrorReason
  133. do {
  134. let value = try result.get()
  135. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  136. } catch {
  137. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  138. }
  139. let error = KingfisherError.imageSettingError(reason: reason)
  140. completionHandler?(.failure(error))
  141. return
  142. }
  143. mutatingSelf.imageTask = nil
  144. mutatingSelf.taskIdentifier = nil
  145. switch result {
  146. case .success(let value):
  147. self.base.image = value.image
  148. completionHandler?(result)
  149. case .failure:
  150. if let image = options.onFailureImage {
  151. self.base.image = image
  152. }
  153. completionHandler?(result)
  154. }
  155. }
  156. }
  157. )
  158. mutatingSelf.imageTask = task
  159. return task
  160. }
  161. // MARK: Cancelling Downloading Task
  162. /// Cancels the image download task of the button if it is running.
  163. /// Nothing will happen if the downloading has already finished.
  164. public func cancelImageDownloadTask() {
  165. imageTask?.cancel()
  166. }
  167. // MARK: Setting Alternate Image
  168. @discardableResult
  169. public func setAlternateImage(
  170. with source: Source?,
  171. placeholder: KFCrossPlatformImage? = nil,
  172. options: KingfisherOptionsInfo? = nil,
  173. progressBlock: DownloadProgressBlock? = nil,
  174. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  175. {
  176. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  177. return setAlternateImage(
  178. with: source,
  179. placeholder: placeholder,
  180. parsedOptions: options,
  181. progressBlock: progressBlock,
  182. completionHandler: completionHandler
  183. )
  184. }
  185. /// Sets an alternate image to the button with a requested resource.
  186. ///
  187. /// - Parameters:
  188. /// - resource: The `Resource` object contains information about the resource.
  189. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  190. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  191. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  192. /// `expectedContentLength`, this block will not be called.
  193. /// - completionHandler: Called when the image retrieved and set finished.
  194. /// - Returns: A task represents the image downloading.
  195. ///
  196. /// - Note:
  197. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  198. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  199. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  200. ///
  201. @discardableResult
  202. public func setAlternateImage(
  203. with resource: Resource?,
  204. placeholder: KFCrossPlatformImage? = nil,
  205. options: KingfisherOptionsInfo? = nil,
  206. progressBlock: DownloadProgressBlock? = nil,
  207. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  208. {
  209. return setAlternateImage(
  210. with: resource?.convertToSource(),
  211. placeholder: placeholder,
  212. options: options,
  213. progressBlock: progressBlock,
  214. completionHandler: completionHandler)
  215. }
  216. func setAlternateImage(
  217. with source: Source?,
  218. placeholder: KFCrossPlatformImage? = nil,
  219. parsedOptions: KingfisherParsedOptionsInfo,
  220. progressBlock: DownloadProgressBlock? = nil,
  221. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  222. {
  223. var mutatingSelf = self
  224. guard let source = source else {
  225. base.alternateImage = placeholder
  226. mutatingSelf.alternateTaskIdentifier = nil
  227. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  228. return nil
  229. }
  230. var options = parsedOptions
  231. if !options.keepCurrentImageWhileLoading {
  232. base.alternateImage = placeholder
  233. }
  234. let issuedIdentifier = Source.Identifier.next()
  235. mutatingSelf.alternateTaskIdentifier = issuedIdentifier
  236. if let block = progressBlock {
  237. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  238. }
  239. if let provider = ImageProgressiveProvider(options, refresh: { image in
  240. self.base.alternateImage = image
  241. }) {
  242. options.onDataReceived = (options.onDataReceived ?? []) + [provider]
  243. }
  244. options.onDataReceived?.forEach {
  245. $0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier }
  246. }
  247. let task = KingfisherManager.shared.retrieveImage(
  248. with: source,
  249. options: options,
  250. downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 },
  251. completionHandler: { result in
  252. CallbackQueue.mainCurrentOrAsync.execute {
  253. guard issuedIdentifier == self.alternateTaskIdentifier else {
  254. let reason: KingfisherError.ImageSettingErrorReason
  255. do {
  256. let value = try result.get()
  257. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  258. } catch {
  259. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  260. }
  261. let error = KingfisherError.imageSettingError(reason: reason)
  262. completionHandler?(.failure(error))
  263. return
  264. }
  265. mutatingSelf.alternateImageTask = nil
  266. mutatingSelf.alternateTaskIdentifier = nil
  267. switch result {
  268. case .success(let value):
  269. self.base.alternateImage = value.image
  270. completionHandler?(result)
  271. case .failure:
  272. if let image = options.onFailureImage {
  273. self.base.alternateImage = image
  274. }
  275. completionHandler?(result)
  276. }
  277. }
  278. }
  279. )
  280. mutatingSelf.alternateImageTask = task
  281. return task
  282. }
  283. // MARK: Cancelling Alternate Image Downloading Task
  284. /// Cancels the alternate image download task of the button if it is running.
  285. /// Nothing will happen if the downloading has already finished.
  286. public func cancelAlternateImageDownloadTask() {
  287. alternateImageTask?.cancel()
  288. }
  289. }
  290. // MARK: - Associated Object
  291. private var taskIdentifierKey: Void?
  292. private var imageTaskKey: Void?
  293. private var alternateTaskIdentifierKey: Void?
  294. private var alternateImageTaskKey: Void?
  295. extension KingfisherWrapper where Base: NSButton {
  296. // MARK: Properties
  297. public private(set) var taskIdentifier: Source.Identifier.Value? {
  298. get {
  299. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  300. return box?.value
  301. }
  302. set {
  303. let box = newValue.map { Box($0) }
  304. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  305. }
  306. }
  307. private var imageTask: DownloadTask? {
  308. get { return getAssociatedObject(base, &imageTaskKey) }
  309. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  310. }
  311. public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
  312. get {
  313. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
  314. return box?.value
  315. }
  316. set {
  317. let box = newValue.map { Box($0) }
  318. setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
  319. }
  320. }
  321. private var alternateImageTask: DownloadTask? {
  322. get { return getAssociatedObject(base, &alternateImageTaskKey) }
  323. set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
  324. }
  325. }
  326. #endif