KMThumbnailCache.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // KMThumbnailCache.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2024/8/9.
  6. //
  7. class KMThumbnailCache: NSObject {
  8. static let shared = KMThumbnailCache()
  9. private let maxCacheSize = 50
  10. // 外层字典以文档路径为键,内层字典以缩略图 ID 为键
  11. private var thumbnails: [String: [String: NSImage]] = [:]
  12. private var order: [String: [String]] = [:] // 记录每个文档路径的插入顺序
  13. // 添加缩略图及其文档路径
  14. func addThumbnail(for path: String, id: String, image: NSImage) {
  15. // 确保每个路径都有自己的字典和顺序数组
  16. if thumbnails[path] == nil {
  17. thumbnails[path] = [:]
  18. order[path] = []
  19. }
  20. // 获取当前路径的字典和顺序数组
  21. var currentThumbnails = thumbnails[path]!
  22. var currentOrder = order[path]!
  23. // 检查并维持每个路径的最大缓存大小
  24. if currentThumbnails.count >= maxCacheSize {
  25. if let oldestID = currentOrder.first {
  26. currentThumbnails.removeValue(forKey: oldestID)
  27. currentOrder.removeFirst()
  28. }
  29. }
  30. // 添加新缩略图
  31. currentThumbnails[id] = image
  32. currentOrder.append(id)
  33. // 更新字典和顺序数组
  34. thumbnails[path] = currentThumbnails
  35. order[path] = currentOrder
  36. }
  37. // 根据路径和 ID 获取缩略图
  38. func thumbnail(for path: String, id: String) -> NSImage? {
  39. return thumbnails[path]?[id]
  40. }
  41. // 根据路径和 ID 移除缩略图
  42. func removeThumbnail(for path: String, id: String) {
  43. guard var currentThumbnails = thumbnails[path],
  44. var currentOrder = order[path] else {
  45. print("Path or ID not found")
  46. return
  47. }
  48. if let index = currentOrder.firstIndex(of: id) {
  49. currentThumbnails.removeValue(forKey: id)
  50. currentOrder.remove(at: index)
  51. } else {
  52. print("ID not found in the given path")
  53. }
  54. // 更新字典和顺序数组
  55. thumbnails[path] = currentThumbnails
  56. order[path] = currentOrder
  57. }
  58. // 清空缓存
  59. func clearCache(for path: String? = nil) {
  60. if let path = path {
  61. thumbnails[path]?.removeAll()
  62. order[path]?.removeAll()
  63. } else {
  64. thumbnails.removeAll()
  65. order.removeAll()
  66. }
  67. }
  68. }