KMPDFThumbnialPageView.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 image = KMThumbnailCache.shared.thumbnail(for: Int(self.page?.pageIndex() ?? UInt(Int.max)))
  13. if image != nil {
  14. self.pageImageIv.image = image
  15. } else {
  16. self.pageImageIv.image = NSImage()
  17. self.performTask()
  18. }
  19. }
  20. }
  21. var pageImageIv = NSImageView()
  22. var isThumb = false
  23. override init(frame frameRect: NSRect) {
  24. super.init(frame: frameRect)
  25. self.setup();
  26. }
  27. required init?(coder: NSCoder) {
  28. super.init(coder: coder)
  29. }
  30. func setup() {
  31. self.wantsLayer = true
  32. self.layer?.backgroundColor = NSColor.white.cgColor
  33. self.shadow = NSShadow()
  34. self.layer?.shadowColor = NSColor.black.cgColor
  35. self.layer?.shadowOpacity = 0.2
  36. self.layer?.shadowRadius = 3.0
  37. self.layer?.shadowOffset = CGSize(width: 0, height: -3)
  38. pageImageIv.wantsLayer = true;
  39. self.addSubview(self.pageImageIv)
  40. self.pageImageIv.autoresizingMask = [.width, .height];
  41. self.pageImageIv.frame = self.bounds
  42. }
  43. func performTask() {
  44. pendingWordItem?.cancel()
  45. let newWorkItem = DispatchWorkItem {
  46. self.updateThumbnial()
  47. }
  48. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute:newWorkItem)
  49. pendingWordItem = newWorkItem
  50. }
  51. func updateThumbnial(needReset: Bool = false) {
  52. let image = KMThumbnailCache.shared.thumbnail(for: Int(self.page?.pageIndex() ?? UInt(Int.max)))
  53. if image != nil {
  54. self.pageImageIv.image = image
  55. } else {
  56. let pageIndex = self.page?.pageIndex()
  57. self.page?.thumbnail(of: self.bounds.size, needReset: needReset, completion: { [unowned self] image in
  58. if (image != nil) {
  59. self.pageImageIv.image = image
  60. KMThumbnailCache.shared.addThumbnail(id: Int(pageIndex ?? UInt(Int.max)), image: image!)
  61. }
  62. })
  63. }
  64. }
  65. }