1
1
mirror of https://github.com/qvacua/vimr.git synced 2024-12-25 06:43:24 +03:00

Merge branch 'develop' into more-rx

This commit is contained in:
Tae Won Ha 2018-05-06 13:39:42 +02:00
commit 18604251ae
No known key found for this signature in database
GPG Key ID: E40743465B5B8B44

View File

@ -5,34 +5,90 @@
import Cocoa
private var colorCache = [Int: NSColor]()
private var cgColorCache = [Int: CGColor]()
private let colorCache = SimpleCache<Int, NSColor>(countLimit: 200)
private let cgColorCache = SimpleCache<Int, CGColor>(countLimit: 200)
class ColorUtils {
static func cgColorIgnoringAlpha(_ rgb: Int) -> CGColor {
if let color = cgColorCache[rgb] {
if let color = cgColorCache.object(forKey: rgb) {
return color
}
let color = self.colorIgnoringAlpha(rgb).cgColor
cgColorCache[rgb] = color
cgColorCache.set(object: color, forKey: rgb)
return color
}
static func colorIgnoringAlpha(_ rgb: Int) -> NSColor {
if let color = colorCache[rgb] {
if let color = colorCache.object(forKey: rgb) {
return color
}
// @formatter:off
let red = (CGFloat((rgb >> 16) & 0xFF)) / 255.0;
let green = (CGFloat((rgb >> 8) & 0xFF)) / 255.0;
let blue = (CGFloat((rgb ) & 0xFF)) / 255.0;
// @formatter:on
let color = NSColor(srgbRed: red, green: green, blue: blue, alpha: 1.0)
colorCache[rgb] = color
colorCache.set(object: color, forKey: rgb)
return color
}
}
class SimpleCache<K: Hashable, V> {
private class ValueBox<T> {
fileprivate let value: T
fileprivate init(_ value: T) {
self.value = value
}
}
private class KeyBox<K: Hashable>: NSObject {
fileprivate let key: K
fileprivate init(_ key: K) {
self.key = key
}
override var hash: Int {
return key.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
return self.key == (object as? KeyBox<K>)?.key
}
}
private let cache = NSCache<KeyBox<K>, ValueBox<V>>()
init(countLimit: Int? = nil) {
if let limit = countLimit {
self.cache.countLimit = limit
}
}
func object(forKey key: K) -> V? {
return self.cache.object(forKey: KeyBox(key))?.value
}
func set(object: V, forKey key: K) {
self.cache.setObject(ValueBox(object), forKey: KeyBox(key))
}
func removeObject(forKey key: K) {
cache.removeObject(forKey: KeyBox(key))
}
func removeAllObjects() {
cache.removeAllObjects()
}
}