KMPDFThumbnialPageView.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // KMPDFThumbnialPageView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2022/11/24.
  6. //
  7. import Cocoa
  8. class KMPDFThumbnialPageView: NSView {
  9. private var pendingWordItem: DispatchWorkItem?
  10. var page: CPDFPage? {
  11. didSet {
  12. let path = page?.document.documentURL.path ?? ""
  13. let id = "\(String(describing: self.page?.pageIndex())) + \(self.bounds)"
  14. let image = KMThumbnailCache.shared.thumbnail(for: path, id: id)
  15. if image != nil {
  16. self.pageImageIv.image = image
  17. } else {
  18. self.pageImageIv.image = NSImage()
  19. self.performTask()
  20. }
  21. }
  22. }
  23. var pageImageIv = NSImageView()
  24. var isThumb = false
  25. override init(frame frameRect: NSRect) {
  26. super.init(frame: frameRect)
  27. self.setup();
  28. }
  29. required init?(coder: NSCoder) {
  30. super.init(coder: coder)
  31. }
  32. func setup() {
  33. self.wantsLayer = true
  34. self.layer?.backgroundColor = NSColor.white.cgColor
  35. self.shadow = NSShadow()
  36. self.layer?.shadowColor = NSColor.black.cgColor
  37. self.layer?.shadowOpacity = 0.2
  38. self.layer?.shadowRadius = 3.0
  39. self.layer?.shadowOffset = CGSize(width: 0, height: -3)
  40. pageImageIv.wantsLayer = true;
  41. self.addSubview(self.pageImageIv)
  42. self.pageImageIv.autoresizingMask = [.width, .height];
  43. self.pageImageIv.frame = self.bounds
  44. }
  45. func performTask() {
  46. pendingWordItem?.cancel()
  47. let newWorkItem = DispatchWorkItem {
  48. self.updateThumbnial()
  49. }
  50. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute:newWorkItem)
  51. pendingWordItem = newWorkItem
  52. }
  53. func updateThumbnial(needReset: Bool = true) {
  54. let pageIndex = self.page?.pageIndex()
  55. let path = page?.document.documentURL.path ?? ""
  56. let id = "\(String(describing: pageIndex)) + \(self.bounds)"
  57. let image = KMThumbnailCache.shared.thumbnail(for: path, id: id)
  58. if image != nil && !needReset {
  59. self.pageImageIv.image = image
  60. } else {
  61. self.page?.thumbnail(of: self.bounds.size, needReset: needReset, completion: { [unowned self] image in
  62. if (image != nil) {
  63. self.pageImageIv.image = image
  64. KMThumbnailCache.shared.addThumbnail(for: path, id: id, image: image!)
  65. }
  66. })
  67. }
  68. }
  69. }