NSButton+Kingfisher.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. @MainActor
  29. extension KingfisherWrapper where Base: NSButton {
  30. // MARK: Setting Image
  31. /// Sets an image to the button with a ``Source``.
  32. ///
  33. /// - Parameters:
  34. /// - source: The ``Source`` object that defines data information from the network or a data provider.
  35. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  36. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  37. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  38. /// `expectedContentLength`, this block will not be called.
  39. /// - completionHandler: Called when the image retrieval and setting are finished.
  40. /// - Returns: A task that represents the image downloading.
  41. ///
  42. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  43. /// changes, it is your responsibility to call it from the main thread.
  44. ///
  45. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  46. @discardableResult
  47. public func setImage(
  48. with source: Source?,
  49. placeholder: KFCrossPlatformImage? = nil,
  50. options: KingfisherOptionsInfo? = nil,
  51. progressBlock: DownloadProgressBlock? = nil,
  52. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  53. ) -> DownloadTask?
  54. {
  55. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  56. return setImage(
  57. with: source,
  58. placeholder: placeholder,
  59. parsedOptions: options,
  60. progressBlock: progressBlock,
  61. completionHandler: completionHandler
  62. )
  63. }
  64. /// Sets an image to the button with a ``Resource``.
  65. ///
  66. /// - Parameters:
  67. /// - resource: The ``Resource`` object that defines data information from the network or a data provider.
  68. /// - placeholder: A placeholder to show while retrieving the image from the given `source`.
  69. /// - options: A set of options to define image setting behaviors. See ``KingfisherOptionsInfo`` for more.
  70. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  71. /// `expectedContentLength`, this block will not be called.
  72. /// - completionHandler: Called when the image retrieval and setting are finished.
  73. /// - Returns: A task that represents the image downloading.
  74. ///
  75. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  76. /// changes, it is your responsibility to call it from the main thread.
  77. ///
  78. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  79. @discardableResult
  80. public func setImage(
  81. with resource: (any Resource)?,
  82. placeholder: KFCrossPlatformImage? = nil,
  83. options: KingfisherOptionsInfo? = nil,
  84. progressBlock: DownloadProgressBlock? = nil,
  85. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  86. ) -> DownloadTask?
  87. {
  88. return setImage(
  89. with: resource?.convertToSource(),
  90. placeholder: placeholder,
  91. options: options,
  92. progressBlock: progressBlock,
  93. completionHandler: completionHandler)
  94. }
  95. func setImage(
  96. with source: Source?,
  97. placeholder: KFCrossPlatformImage? = nil,
  98. parsedOptions: KingfisherParsedOptionsInfo,
  99. progressBlock: DownloadProgressBlock? = nil,
  100. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  101. ) -> DownloadTask?
  102. {
  103. var mutatingSelf = self
  104. return setImage(
  105. with: source,
  106. imageAccessor: ImagePropertyAccessor(
  107. setImage: { image, _ in
  108. base.image = image
  109. }, getImage: {
  110. base.image
  111. }),
  112. taskAccessor: TaskPropertyAccessor(
  113. setTaskIdentifier: { mutatingSelf.taskIdentifier = $0 },
  114. getTaskIdentifier: { mutatingSelf.taskIdentifier },
  115. setTask: { mutatingSelf.imageTask = $0 }),
  116. placeholder: placeholder,
  117. parsedOptions: parsedOptions,
  118. progressBlock: progressBlock,
  119. completionHandler: completionHandler
  120. )
  121. }
  122. // MARK: Cancelling Downloading Task
  123. /// Cancels the image download task of the button if it is running.
  124. /// Nothing will happen if the downloading has already finished.
  125. public func cancelImageDownloadTask() {
  126. imageTask?.cancel()
  127. }
  128. // MARK: Setting Alternate Image
  129. @discardableResult
  130. public func setAlternateImage(
  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 setAlternateImage(
  140. with: source,
  141. placeholder: placeholder,
  142. parsedOptions: options,
  143. progressBlock: progressBlock,
  144. completionHandler: completionHandler
  145. )
  146. }
  147. /// Sets an alternate image to the button with a ``Resource``.
  148. ///
  149. /// - Parameters:
  150. /// - resource: The ``Resource`` 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. /// - progressBlock: Called when the image downloading progress is updated. If the response does not contain an
  154. /// `expectedContentLength`, this block will not be called.
  155. /// - completionHandler: Called when the image retrieval and setting are finished.
  156. /// - Returns: A task that represents the image downloading.
  157. ///
  158. /// Internally, this method will use ``KingfisherManager`` to get the source. Since this method will perform UI
  159. /// changes, it is your responsibility to call it from the main thread.
  160. ///
  161. /// > Both `progressBlock` and `completionHandler` will also be executed in the main thread.
  162. @discardableResult
  163. public func setAlternateImage(
  164. with resource: (any Resource)?,
  165. placeholder: KFCrossPlatformImage? = nil,
  166. options: KingfisherOptionsInfo? = nil,
  167. progressBlock: DownloadProgressBlock? = nil,
  168. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  169. ) -> DownloadTask?
  170. {
  171. return setAlternateImage(
  172. with: resource?.convertToSource(),
  173. placeholder: placeholder,
  174. options: options,
  175. progressBlock: progressBlock,
  176. completionHandler: completionHandler)
  177. }
  178. func setAlternateImage(
  179. with source: Source?,
  180. placeholder: KFCrossPlatformImage? = nil,
  181. parsedOptions: KingfisherParsedOptionsInfo,
  182. progressBlock: DownloadProgressBlock? = nil,
  183. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
  184. ) -> DownloadTask?
  185. {
  186. var mutatingSelf = self
  187. return setImage(
  188. with: source,
  189. imageAccessor: ImagePropertyAccessor(
  190. setImage: { image, _ in
  191. base.alternateImage = image
  192. }, getImage: {
  193. base.alternateImage
  194. }),
  195. taskAccessor: TaskPropertyAccessor(
  196. setTaskIdentifier: { mutatingSelf.alternateTaskIdentifier = $0 },
  197. getTaskIdentifier: { mutatingSelf.alternateTaskIdentifier },
  198. setTask: { mutatingSelf.alternateImageTask = $0 }
  199. ),
  200. placeholder: placeholder,
  201. parsedOptions: parsedOptions,
  202. progressBlock: progressBlock,
  203. completionHandler: completionHandler
  204. )
  205. }
  206. // MARK: Cancelling Alternate Image Downloading Task
  207. /// Cancels the image download task of the image view if it is running.
  208. ///
  209. /// Nothing will happen if the downloading has already finished.
  210. public func cancelAlternateImageDownloadTask() {
  211. alternateImageTask?.cancel()
  212. }
  213. }
  214. // MARK: - Associated Object
  215. @MainActor private var taskIdentifierKey: Void?
  216. @MainActor private var imageTaskKey: Void?
  217. @MainActor private var alternateTaskIdentifierKey: Void?
  218. @MainActor private var alternateImageTaskKey: Void?
  219. @MainActor
  220. extension KingfisherWrapper where Base: NSButton {
  221. // MARK: Properties
  222. public private(set) var taskIdentifier: Source.Identifier.Value? {
  223. get {
  224. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  225. return box?.value
  226. }
  227. set {
  228. let box = newValue.map { Box($0) }
  229. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  230. }
  231. }
  232. private var imageTask: DownloadTask? {
  233. get { return getAssociatedObject(base, &imageTaskKey) }
  234. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  235. }
  236. public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
  237. get {
  238. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
  239. return box?.value
  240. }
  241. set {
  242. let box = newValue.map { Box($0) }
  243. setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
  244. }
  245. }
  246. private var alternateImageTask: DownloadTask? {
  247. get { return getAssociatedObject(base, &alternateImageTaskKey) }
  248. set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
  249. }
  250. }
  251. #endif