|
@@ -9,36 +9,72 @@ class KMThumbnailCache: NSObject {
|
|
|
static let shared = KMThumbnailCache()
|
|
|
|
|
|
private let maxCacheSize = 50
|
|
|
- private var thumbnails: [Int: NSImage] = [:]
|
|
|
- private var order: [Int] = [] // 记录插入顺序的数组
|
|
|
+ // 外层字典以文档路径为键,内层字典以缩略图 ID 为键
|
|
|
+ private var thumbnails: [String: [Int: NSImage]] = [:]
|
|
|
+ private var order: [String: [Int]] = [:] // 记录每个文档路径的插入顺序
|
|
|
|
|
|
- func addThumbnail(id: Int, image: NSImage) {
|
|
|
- if thumbnails.count >= maxCacheSize {
|
|
|
- if let oldestID = order.first {
|
|
|
- thumbnails.removeValue(forKey: oldestID)
|
|
|
- order.removeFirst()
|
|
|
+ // 添加缩略图及其文档路径
|
|
|
+ func addThumbnail(for path: String, id: Int, image: NSImage) {
|
|
|
+ // 确保每个路径都有自己的字典和顺序数组
|
|
|
+ if thumbnails[path] == nil {
|
|
|
+ thumbnails[path] = [:]
|
|
|
+ order[path] = []
|
|
|
+ }
|
|
|
+
|
|
|
+ // 获取当前路径的字典和顺序数组
|
|
|
+ var currentThumbnails = thumbnails[path]!
|
|
|
+ var currentOrder = order[path]!
|
|
|
+
|
|
|
+ // 检查并维持每个路径的最大缓存大小
|
|
|
+ if currentThumbnails.count >= maxCacheSize {
|
|
|
+ if let oldestID = currentOrder.first {
|
|
|
+ currentThumbnails.removeValue(forKey: oldestID)
|
|
|
+ currentOrder.removeFirst()
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- thumbnails[id] = image
|
|
|
- order.append(id)
|
|
|
+ // 添加新缩略图
|
|
|
+ currentThumbnails[id] = image
|
|
|
+ currentOrder.append(id)
|
|
|
+
|
|
|
+ // 更新字典和顺序数组
|
|
|
+ thumbnails[path] = currentThumbnails
|
|
|
+ order[path] = currentOrder
|
|
|
}
|
|
|
-
|
|
|
- func thumbnail(for id: Int) -> NSImage? {
|
|
|
- return thumbnails[id]
|
|
|
+
|
|
|
+ // 根据路径和 ID 获取缩略图
|
|
|
+ func thumbnail(for path: String, id: Int) -> NSImage? {
|
|
|
+ return thumbnails[path]?[id]
|
|
|
}
|
|
|
-
|
|
|
- func removeThumbnail(for id: Int) {
|
|
|
- if let index = order.firstIndex(of: id) {
|
|
|
- thumbnails.removeValue(forKey: id)
|
|
|
- order.remove(at: index)
|
|
|
+
|
|
|
+ // 根据路径和 ID 移除缩略图
|
|
|
+ func removeThumbnail(for path: String, id: Int) {
|
|
|
+ guard var currentThumbnails = thumbnails[path],
|
|
|
+ var currentOrder = order[path] else {
|
|
|
+ print("Path or ID not found")
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ if let index = currentOrder.firstIndex(of: id) {
|
|
|
+ currentThumbnails.removeValue(forKey: id)
|
|
|
+ currentOrder.remove(at: index)
|
|
|
} else {
|
|
|
- print("ID not found")
|
|
|
+ print("ID not found in the given path")
|
|
|
}
|
|
|
+
|
|
|
+ // 更新字典和顺序数组
|
|
|
+ thumbnails[path] = currentThumbnails
|
|
|
+ order[path] = currentOrder
|
|
|
}
|
|
|
-
|
|
|
- func clearCache() {
|
|
|
- thumbnails.removeAll()
|
|
|
- order.removeAll()
|
|
|
+
|
|
|
+ // 清空缓存
|
|
|
+ func clearCache(for path: String? = nil) {
|
|
|
+ if let path = path {
|
|
|
+ thumbnails[path]?.removeAll()
|
|
|
+ order[path]?.removeAll()
|
|
|
+ } else {
|
|
|
+ thumbnails.removeAll()
|
|
|
+ order.removeAll()
|
|
|
+ }
|
|
|
}
|
|
|
}
|