Browse Source

Fully adopt to namespacing

onevcat 9 years ago
parent
commit
95691f96a6

+ 2 - 2
Demo/Kingfisher-macOS-Demo/ViewController.swift

@@ -57,8 +57,8 @@ extension ViewController: NSCollectionViewDataSource {
         
         let url = URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.item + 1).jpg")!
         
-        item.imageView?.kf_indicatorType = .activity
-        item.imageView?.kf_setImage(with: url, placeholder: nil, options: nil,
+        item.imageView?.kf.indicatorType = .activity
+        item.imageView?.kf.setImage(with: url, placeholder: nil, options: nil,
                                                    progressBlock: { receivedSize, totalSize in
                                                     print("\(indexPath.item + 1): \(receivedSize)/\(totalSize)")
                                                     },

+ 6 - 1
Kingfisher.swift

@@ -7,6 +7,7 @@
 //
 
 import Foundation
+import ImageIO
 
 #if os(macOS)
     import AppKit
@@ -18,8 +19,10 @@ import Foundation
     import UIKit
     public typealias Image = UIImage
     public typealias Color = UIColor
+    #if !os(watchOS)
     public typealias ImageView = UIImageView
     typealias Button = UIButton
+    #endif
 #endif
 
 public struct Kingfisher<Base> {
@@ -44,6 +47,8 @@ public extension KingfisherCompatible {
     }
 }
 
-extension ImageView: KingfisherCompatible { }
 extension Image: KingfisherCompatible { }
+#if !os(watchOS)
+extension ImageView: KingfisherCompatible { }
 extension Button: KingfisherCompatible { }
+#endif

+ 5 - 4
Sources/AnimatedImageView.swift

@@ -258,7 +258,7 @@ class Animator {
             return AnimatedFrame.null
         }
         
-        let frameDuration = imageSource.kf_GIFProperties(at: index).flatMap {
+        let frameDuration = imageSource.kf.GIFProperties(at: index).flatMap {
             gifInfo -> Double? in
             
             let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
@@ -312,9 +312,10 @@ class Animator {
     }
 }
 
-extension CGImageSource {
-    func kf_GIFProperties(at index: Int) -> [String: Double]? {
-        let properties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary?
+extension CGImageSource: KingfisherCompatible { }
+extension Kingfisher where Base: CGImageSource {
+    func GIFProperties(at index: Int) -> [String: Double]? {
+        let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary?
         return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
     }
 }

+ 1 - 1
Sources/CacheSerializer.swift

@@ -63,7 +63,7 @@ public struct DefaultCacheSerializer: CacheSerializer {
     private init() {}
     
     public func data(with image: Image, original: Data?) -> Data? {
-        let imageFormat = original?.kf_imageFormat ?? .unknown
+        let imageFormat = original?.kf.imageFormat ?? .unknown
         
         let data: Data?
         switch imageFormat {

+ 4 - 1
Sources/Filter.swift

@@ -44,7 +44,7 @@ extension CIImageProcessor {
     public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
         switch item {
         case .image(let image):
-            return image.kf_apply(filter)
+            return image.kf.apply(filter)
         case .data(let data):
             return Kingfisher<Image>.image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData)
         }
@@ -136,6 +136,9 @@ public extension Image {
     /// - returns: A transformed image by input `Filter`.
     ///
     /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
+    @available(*, deprecated,
+    message: "Extensions directly on Image are deprecated. Use `kf.apply` instead.",
+    renamed: "kf.apply")
     public func kf_apply(_ filter: Filter) -> Image {
         return kf.apply(filter)
     }

+ 37 - 19
Sources/Image.swift

@@ -282,7 +282,7 @@ extension Kingfisher where Base: Image {
             return (images, gifDuration)
         }
         
-        // Start of kf_animatedImageWithGIFData
+        // Start of kf.animatedImageWithGIFData
         let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
         guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
             return nil
@@ -317,15 +317,16 @@ extension Kingfisher where Base: Image {
     
     static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
         var image: Image?
+        
         #if os(macOS)
-            switch data.kf_imageFormat {
+            switch data.kf.imageFormat {
             case .JPEG: image = Image(data: data)
             case .PNG: image = Image(data: data)
             case .GIF: image = Kingfisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
             case .unknown: image = Image(data: data)
             }
         #else
-            switch data.kf_imageFormat {
+            switch data.kf.imageFormat {
             case .JPEG: image = Image(data: data, scale: scale)
             case .PNG: image = Image(data: data, scale: scale)
             case .GIF: image = Kingfisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
@@ -380,10 +381,10 @@ extension Kingfisher where Base: Image {
     func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
         switch contentMode {
         case .scaleAspectFit:
-            let newSize = self.size.kf_constrained(size)
+            let newSize = self.size.kf.constrained(size)
             return resize(to: newSize)
         case .scaleAspectFill:
-            let newSize = self.size.kf_filling(size)
+            let newSize = self.size.kf.filling(size)
             return resize(to: newSize)
         default:
             return resize(to: size)
@@ -428,7 +429,7 @@ extension Kingfisher where Base: Image {
     /// - Note: This method only works for CG-based image.
     public func blurred(withRadius radius: CGFloat) -> Image {
         #if os(watchOS)
-            return self
+            return base
         #else
             guard let cgImage = cgImage else {
                 assertionFailure("[Kingfisher] Blur only works for CG-based image.")
@@ -570,7 +571,7 @@ extension Kingfisher where Base: Image {
     /// - returns: An image with a color tint applied.
     public func tinted(with color: Color) -> Image {
         #if os(watchOS)
-            return self
+            return base
         #else
             return apply(.tint(color))
         #endif
@@ -650,10 +651,20 @@ enum ImageFormat {
 
 
 // MARK: - Misc Helpers
-extension Data {
-    var kf_imageFormat: ImageFormat {
+protocol DataType {
+    func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int)
+}
+extension Data: DataType {
+    func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) {
+        (self as NSData).getBytes(buffer, length: length)
+    }
+}
+
+extension Data: KingfisherCompatible { }
+extension Kingfisher where Base: DataType {
+    var imageFormat: ImageFormat {
         var buffer = [UInt8](repeating: 0, count: 8)
-        (self as NSData).getBytes(&buffer, length: 8)
+        base.getBytes(&buffer, length: 8)
         if buffer == ImageHeaderData.PNG {
             return .PNG
         } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
@@ -672,23 +683,30 @@ extension Data {
     }
 }
 
-extension CGSize {
-    func kf_constrained(_ size: CGSize) -> CGSize {
-        let aspectWidth = round(kf_aspectRatio * size.height)
-        let aspectHeight = round(size.width / kf_aspectRatio)
+protocol SizeType {
+    var width: CGFloat { get }
+    var height: CGFloat { get }
+}
+extension CGSize: SizeType { }
+
+extension CGSize: KingfisherCompatible { }
+extension Kingfisher where Base: SizeType {
+    func constrained(_ size: CGSize) -> CGSize {
+        let aspectWidth = round(aspectRatio * size.height)
+        let aspectHeight = round(size.width / aspectRatio)
         
         return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
     }
     
-    func kf_filling(_ size: CGSize) -> CGSize {
-        let aspectWidth = round(kf_aspectRatio * size.height)
-        let aspectHeight = round(size.width / kf_aspectRatio)
+    func filling(_ size: CGSize) -> CGSize {
+        let aspectWidth = round(aspectRatio * size.height)
+        let aspectHeight = round(size.width / aspectRatio)
         
         return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
     }
     
-    private var kf_aspectRatio: CGFloat {
-        return height == 0.0 ? 1.0 : width / height
+    private var aspectRatio: CGFloat {
+        return base.height == 0.0 ? 1.0 : base.width / base.height
     }
 }
 

+ 7 - 6
Sources/ImageCache.swift

@@ -510,7 +510,7 @@ extension ImageCache {
     */
     @objc public func backgroundCleanExpiredDiskCache() {
         // if 'sharedApplication()' is unavailable, then return
-        guard let sharedApplication = UIApplication.kf_shared else { return }
+        guard let sharedApplication = Kingfisher<UIApplication>.shared else { return }
 
         func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
             sharedApplication.endBackgroundTask(task)
@@ -636,7 +636,7 @@ extension ImageCache {
     }
     
     func cacheFileName(forComputedKey key: String) -> String {
-        return key.kf_MD5
+        return key.kf.md5
     }
 }
 
@@ -656,11 +656,12 @@ extension Dictionary {
 
 #if !os(macOS) && !os(watchOS)
 // MARK: - For App Extensions
-extension UIApplication {
-    public static var kf_shared: UIApplication? {
+extension UIApplication: KingfisherCompatible { }
+extension Kingfisher where Base: UIApplication {
+    public static var shared: UIApplication? {
         let selector = NSSelectorFromString("sharedApplication")
-        guard responds(to: selector) else { return nil }
-        return perform(selector).takeUnretainedValue() as? UIApplication
+        guard Base.responds(to: selector) else { return nil }
+        return Base.perform(selector).takeUnretainedValue() as? UIApplication
     }
 }
 #endif

+ 1 - 1
Sources/ImagePrefetcher.swift

@@ -128,7 +128,7 @@ public class ImagePrefetcher {
         pendingResources = ArraySlice(resources)
         
         // We want all callbacks from main queue, so we ignore the call back queue in options
-        let optionsInfoWithoutQueue = options?.kf_removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
+        let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
         self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
         
         let cache = self.optionsInfo.targetCache

+ 3 - 5
Sources/ImageView+Kingfisher.swift

@@ -94,7 +94,7 @@ extension Kingfisher where Base: ImageView {
                         return
                     }
                     
-                    guard let transitionItem = options.kf_firstMatchIgnoringAssociatedValue(.transition(.none)),
+                    guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
                         case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
                     {
                         maybeIndicator?.stopAnimatingView()
@@ -182,7 +182,7 @@ extension Kingfisher where Base: ImageView {
     
     /// Holds any type that conforms to the protocol `Indicator`.
     /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
-    /// It will be `nil` if `kf_indicatorType` is `.none`.
+    /// It will be `nil` if `indicatorType` is `.none`.
     public fileprivate(set) var indicator: Indicator? {
         get {
             return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
@@ -252,9 +252,7 @@ extension ImageView {
      Nothing will happen if the downloading has already finished.
      */
     @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
-    public func kf_cancelDownloadTask() {
-        kf_imageTask?.downloadTask?.cancel()
-    }
+    public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
     
     /// Get the image URL binded to this image view.
     @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")

+ 11 - 11
Sources/KingfisherOptionsInfo.swift

@@ -138,18 +138,18 @@ func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Boo
 }
 
 extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
-    func kf_firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? {
+    func firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? {
         return index { $0 <== target }.flatMap { self[$0] }
     }
     
-    func kf_removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] {
+    func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] {
         return self.filter { !($0 <== target) }
     }
 }
 
 extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     var targetCache: ImageCache {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.targetCache(.default)),
+        if let item = firstMatchIgnoringAssociatedValue(.targetCache(.default)),
             case .targetCache(let cache) = item
         {
             return cache
@@ -158,7 +158,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var downloader: ImageDownloader {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.downloader(.default)),
+        if let item = firstMatchIgnoringAssociatedValue(.downloader(.default)),
             case .downloader(let downloader) = item
         {
             return downloader
@@ -167,7 +167,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var transition: ImageTransition {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.transition(.none)),
+        if let item = firstMatchIgnoringAssociatedValue(.transition(.none)),
             case .transition(let transition) = item
         {
             return transition
@@ -176,7 +176,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var downloadPriority: Float {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.downloadPriority(0)),
+        if let item = firstMatchIgnoringAssociatedValue(.downloadPriority(0)),
             case .downloadPriority(let priority) = item
         {
             return priority
@@ -209,7 +209,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var callbackDispatchQueue: DispatchQueue {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)),
+        if let item = firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)),
             case .callbackDispatchQueue(let queue) = item
         {
             return queue ?? DispatchQueue.main
@@ -218,7 +218,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var scaleFactor: CGFloat {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.scaleFactor(0)),
+        if let item = firstMatchIgnoringAssociatedValue(.scaleFactor(0)),
             case .scaleFactor(let scale) = item
         {
             return scale
@@ -227,7 +227,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var modifier: ImageDownloadRequestModifier {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)),
+        if let item = firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)),
             case .requestModifier(let modifier) = item
         {
             return modifier
@@ -236,7 +236,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var processor: ImageProcessor {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)),
+        if let item = firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)),
             case .processor(let processor) = item
         {
             return processor
@@ -245,7 +245,7 @@ extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
     }
     
     var cacheSerializer: CacheSerializer {
-        if let item = kf_firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)),
+        if let item = firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)),
             case .cacheSerializer(let cacheSerializer) = item
         {
             return cacheSerializer

+ 12 - 6
Sources/String+MD5.swift

@@ -21,9 +21,15 @@ Permission is granted to anyone to use this software for any purpose,including c
 
 import Foundation
 
-extension String {
-    var kf_MD5: String {
-        if let data = data(using: .utf8) {
+protocol StringType {
+    func data(using encoding: String.Encoding, allowLossyConversion: Bool) -> Data?
+}
+extension String: StringType { }
+extension String: KingfisherCompatible {}
+
+extension Kingfisher where Base: StringType {
+    var md5: Base {
+        if let data = base.data(using: .utf8, allowLossyConversion: true) {
             
             let message = data.withUnsafeBytes { bytes -> [UInt8] in
                 return Array(UnsafeBufferPointer(start: bytes, count: data.count))
@@ -31,15 +37,15 @@ extension String {
             
             let MD5Calculator = MD5(message)
             let MD5Data = MD5Calculator.calculate()
-
+            
             let MD5String = NSMutableString()
             for c in MD5Data {
                 MD5String.appendFormat("%02x", c)
             }
-            return MD5String as String
+            return MD5String as! Base
             
         } else {
-            return self
+            return base
         }
     }
 }

+ 6 - 6
Tests/KingfisherTests/ImageExtensionTests.swift

@@ -42,18 +42,18 @@ class ImageExtensionTests: XCTestCase {
     
     func testImageFormat() {
         var format: ImageFormat
-        format = testImageJEPGData.kf_imageFormat
+        format = testImageJEPGData.kf.imageFormat
         XCTAssertEqual(format, ImageFormat.JPEG)
         
-        format = testImagePNGData.kf_imageFormat
+        format = testImagePNGData.kf.imageFormat
         XCTAssertEqual(format, ImageFormat.PNG)
         
-        format = testImageGIFData.kf_imageFormat
+        format = testImageGIFData.kf.imageFormat
         XCTAssertEqual(format, ImageFormat.GIF)
         
         let raw: [UInt8] = [1, 2, 3, 4, 5, 6, 7, 8]
         
-        format = Data(bytes: raw) .kf_imageFormat
+        format = Data(bytes: raw).kf.imageFormat
         XCTAssertEqual(format, ImageFormat.unknown)
     }
     
@@ -75,12 +75,12 @@ class ImageExtensionTests: XCTestCase {
         let data = image.kf.gifRepresentation()
         
         XCTAssertNotNil(data, "Data should not be nil")
-        XCTAssertEqual(data?.kf_imageFormat, ImageFormat.GIF)
+        XCTAssertEqual(data?.kf.imageFormat, ImageFormat.GIF)
         
         let allLoadImage = Kingfisher<Image>.animated(with: data!, preloadAll: true)!
         let allLoadData = allLoadImage.kf.gifRepresentation()
         XCTAssertNotNil(allLoadData, "Data1 should not be nil")
-        XCTAssertEqual(allLoadData?.kf_imageFormat, ImageFormat.GIF)
+        XCTAssertEqual(allLoadData?.kf.imageFormat, ImageFormat.GIF)
     }
     
     func testGenerateSingleFrameGIFImage() {

+ 1 - 1
Tests/KingfisherTests/StringExtensionTests.swift

@@ -23,7 +23,7 @@ class StringExtensionTests: XCTestCase {
     
     func testStringMD5() {
         let s = "hello"
-        XCTAssertEqual(s.kf_MD5, "5d41402abc4b2a76b9719d911017c592")
+        XCTAssertEqual(s.kf.md5, "5d41402abc4b2a76b9719d911017c592")
     }
     
 }