// // KMPDFThumbnialPageView.swift // PDF Reader Pro // // Created by tangchao on 2022/11/24. // import Cocoa class KMPDFThumbnialPageView: NSView { private var pendingWordItem: DispatchWorkItem? var page: CPDFPage? { didSet { let path = page?.document.documentURL.path ?? "" let id = "\(String(describing: self.page?.pageIndex())) + \(self.bounds)" let image = KMThumbnailCache.shared.thumbnail(for: path, id: id) if image != nil { self.pageImageIv.image = image } else { self.pageImageIv.image = NSImage() self.performTask() } } } var pageImageIv = NSImageView() var isThumb = false override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.setup(); } required init?(coder: NSCoder) { super.init(coder: coder) } func setup() { self.wantsLayer = true self.layer?.backgroundColor = NSColor.white.cgColor self.shadow = NSShadow() self.layer?.shadowColor = NSColor.black.cgColor self.layer?.shadowOpacity = 0.2 self.layer?.shadowRadius = 3.0 self.layer?.shadowOffset = CGSize(width: 0, height: -3) pageImageIv.wantsLayer = true; self.addSubview(self.pageImageIv) self.pageImageIv.autoresizingMask = [.width, .height]; self.pageImageIv.frame = self.bounds } func performTask() { pendingWordItem?.cancel() let newWorkItem = DispatchWorkItem { self.updateThumbnial() } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute:newWorkItem) pendingWordItem = newWorkItem } func updateThumbnial(needReset: Bool = true) { let pageIndex = self.page?.pageIndex() let path = page?.document.documentURL.path ?? "" let id = "\(String(describing: pageIndex)) + \(self.bounds)" let image = KMThumbnailCache.shared.thumbnail(for: path, id: id) if image != nil && !needReset { self.pageImageIv.image = image } else { self.page?.thumbnail(of: self.bounds.size, needReset: needReset, completion: { [unowned self] image in if (image != nil) { self.pageImageIv.image = image KMThumbnailCache.shared.addThumbnail(for: path, id: id, image: image!) } }) } } }