KMPDFThumbnailView.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. //
  2. // KMPDFThumbnailView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lxy on 2022/12/15.
  6. //
  7. class KMPDFThumbnailView: KMThumbnailView {
  8. var document: CPDFDocument?
  9. var isShowPageSize = false
  10. var thumbnailSzie = NSZeroSize
  11. //标记线
  12. var isNeedMarkerLine: Bool = false
  13. var markerLineView: NSView = NSView()
  14. var markBeginIndexes: IndexSet = IndexSet()
  15. //注释状态
  16. var annotationShowState: KMAnnotationViewShowType = .none {
  17. didSet {
  18. self.collectionView.reloadData()
  19. }
  20. }
  21. //悬浮
  22. var hoverIndex: Int = -1
  23. var filePromiseQueue: OperationQueue = {
  24. let queue = OperationQueue()
  25. return queue
  26. }()
  27. fileprivate var dragFilePath: String?
  28. fileprivate var dragFlag = false
  29. fileprivate var dragIn = false
  30. var limit = false
  31. override func initDefaultValue() {
  32. super.initDefaultValue()
  33. self.wantsLayer = true
  34. self.layer?.backgroundColor = NSColor.km_init(hex: "#F7F8FA").cgColor
  35. self.thumbnailSzie = CGSize(width: 120, height: 155)
  36. self.minimumLineSpacing = 8
  37. self.collectionView.km.register(cell: KMPDFThumbnailItem.self)
  38. self.collectionView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
  39. self.collectionView.setDraggingSourceOperationMask([.copy, .delete], forLocal: false)
  40. }
  41. override func initSubViews() {
  42. super.initSubViews()
  43. self.markerLineView.wantsLayer = true
  44. self.markerLineView.layer?.backgroundColor = NSColor.km_init(hex: "#1770F4").cgColor
  45. self.markerLineView.frame = NSMakeRect(0, 0, 100, 2)
  46. self.collectionView.addSubview(markerLineView)
  47. self.hiddenMarkerLineView()
  48. self.markerLineView.isHidden = true
  49. }
  50. }
  51. extension KMPDFThumbnailView {
  52. override func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  53. if let size_ = self.delegate?.thumbnailView?(thumbanView: self, sizeForItemAt: indexPath) {
  54. return size_
  55. }
  56. var height: CGFloat = 0
  57. if let page = self.document?.page(at: UInt(indexPath.item)) {
  58. height = KMPDFThumbnailItem.sizeToFit(size: self.thumbnailSzie, page: page, isShow: self.isShowPageSize)
  59. }
  60. return NSMakeSize(collectionView.frame.size.width - 20, height)
  61. }
  62. override func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  63. if let count = self.document?.pageCount {
  64. return Int(count)
  65. }
  66. return 0
  67. }
  68. override func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  69. if let item = self.delegate?.thumbnailView?(thumbanView: self, itemForRepresentedObjectAt: indexPath) {
  70. return item
  71. }
  72. let cellView: KMPDFThumbnailItem = collectionView.km.dequeueReusableCell(for: indexPath)
  73. cellView.thumbnailView = self
  74. if let page_ = self.document?.page(at: UInt(indexPath.item)) {
  75. cellView.page = page_
  76. }
  77. cellView.annotationShowState = self.annotationShowState
  78. if indexPath.item == hoverIndex {
  79. cellView.hover = true
  80. } else {
  81. cellView.hover = false
  82. }
  83. cellView.mouseDownAction = { [unowned self] (view, event) in
  84. self.delegate?.thumbnailView?(thumbanView: self, didSelectItemAt: indexPath, object: event)
  85. }
  86. cellView.rightMouseDownAction = { [unowned self] (view, event) in
  87. self.delegate?.thumbnailView?(thumbanView: self, rightMouseDidClick: indexPath, item: view, object: event)
  88. }
  89. cellView.hoverCallBack = { [unowned self] view, mouseEntered in
  90. if let _ = self.collectionView.item(at: hoverIndex)?.view {
  91. let tempCell = self.collectionView.item(at: hoverIndex) as? KMPDFThumbnailItem
  92. tempCell?.hover = false
  93. }
  94. if mouseEntered {
  95. hoverIndex = indexPath.item
  96. if let _ = self.collectionView.item(at: hoverIndex)?.view {
  97. let tempCell = self.collectionView.item(at: hoverIndex) as? KMPDFThumbnailItem
  98. tempCell?.hover = true
  99. }
  100. } else {
  101. hoverIndex = -1
  102. }
  103. }
  104. return cellView
  105. }
  106. override func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexes: IndexSet) {
  107. if self.isNeedMarkerLine {
  108. self.markBeginIndexes = collectionView.selectionIndexes
  109. }
  110. // 将拖拽的page插入临时路径(文档)
  111. var indexs = IndexSet()
  112. for indexpath in self.dragedIndexPaths {
  113. indexs.insert(indexpath.item)
  114. }
  115. // 清空临时数据
  116. if let _path = self.dragTempFilePath, FileManager.default.fileExists(atPath: _path) {
  117. try?FileManager.default.removeItem(atPath: _path)
  118. }
  119. // 重置拖拽标识
  120. self.dragFlag = false
  121. if (indexs.count > 0) {
  122. let document = CPDFDocument()
  123. document?.importPages(indexs, from: self.document, at: 0)
  124. if let data = self.dragTempFloderPath, !FileManager.default.fileExists(atPath: data) {
  125. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  126. }
  127. if let data = self.dragTempFilePath, !FileManager.default.fileExists(atPath: data) {
  128. FileManager.default.createFile(atPath: data, contents: nil)
  129. }
  130. if let data = self.dragTempFilePath {
  131. if (self.limit) {
  132. // let _ = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: data))
  133. } else {
  134. document?.write(to: URL(fileURLWithPath: data))
  135. }
  136. }
  137. self.dragFilePath = self.dragTempFilePath
  138. }
  139. return super.collectionView(collectionView, draggingSession: session, willBeginAt: screenPoint, forItemsAt: indexes)
  140. }
  141. override func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
  142. if self.isNeedMarkerLine {
  143. KMPrint(collectionView)
  144. // if self.markBeginIndexes.count != 0 {
  145. // if !self.markBeginIndexes.contains(proposedDropIndexPath.pointee.item) {
  146. //标记线
  147. // if collectionView == self.collectionView {
  148. if (self.collectionView.item(at: proposedDropIndexPath.pointee.item) != nil) {
  149. var rect = self.collectionView.frameForItem(at: proposedDropIndexPath.pointee.item)
  150. // KMPrint("标记线范围 \(rect)")
  151. rect.size.height = 2
  152. self.markerLineView.frame = rect
  153. self.markerLineView.isHidden = false
  154. } else {
  155. let count = self.collectionView.numberOfItems(inSection: 0)
  156. if proposedDropIndexPath.pointee.item == count {
  157. var rect = self.collectionView.frameForItem(at: count - 1)
  158. // KMPrint("标记线范围 \(rect)")
  159. rect.origin.y += rect.size.height
  160. rect.size.height = 2
  161. self.markerLineView.frame = rect
  162. self.markerLineView.isHidden = false
  163. }
  164. }
  165. //// }
  166. //// }
  167. print(proposedDropIndexPath.pointee.item)
  168. // }
  169. }
  170. // debugPrint("移动中")
  171. if !KMThumbnailManager.manager.dragCollectionViews.contains(collectionView) {
  172. KMThumbnailManager.manager.dragCollectionViews.append(collectionView)
  173. }
  174. return super.collectionView(collectionView, validateDrop: draggingInfo, proposedIndexPath: proposedDropIndexPath, dropOperation: proposedDropOperation)
  175. }
  176. override func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  177. self.hiddenMarkerLineView()
  178. self.markBeginIndexes = IndexSet()
  179. self.dragIn = true
  180. let pboard = draggingInfo.draggingPasteboard
  181. if (pboard.availableType(from: [self.localForDraggedTypes]) != nil) {
  182. guard let dragIndexPath = self.dragedIndexPaths.first else {
  183. return false
  184. }
  185. guard let document = self.document else {
  186. return false
  187. }
  188. let dragIndex = dragIndexPath.item
  189. let toIndex = max(0, indexPath.item)
  190. if dragIndex < 0 || dragIndex > document.pageCount {
  191. return false
  192. }
  193. if (toIndex >= document.pageCount) {
  194. return false
  195. }
  196. if dragIndex == toIndex {
  197. return false
  198. }
  199. return super.collectionView(collectionView, acceptDrop: draggingInfo, indexPath: indexPath, dropOperation: dropOperation)
  200. } else if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  201. if let data = draggingInfo.draggingSource as? NSCollectionView, data.isEqual(to: collectionView) {
  202. // Swift.debugPrint("当前文件拖拽")
  203. return super.collectionView(collectionView, acceptDrop: draggingInfo, indexPath: indexPath, dropOperation: dropOperation)
  204. } else {
  205. // Swift.debugPrint("不同文件拖拽")
  206. if let _urlString = self.dragTempFilePath {
  207. self.delegate?.thumbnailView?(thumbanView: self, didDragAddFiles: [URL(fileURLWithPath: _urlString)], indexpath: indexPath)
  208. }
  209. }
  210. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  211. if let should = self.delegate?.thumbnailView?(thumbanView: self, shouldAcceptDrop: draggingInfo, indexPath: indexPath, dropOperation: dropOperation), !should {
  212. return should
  213. }
  214. guard let pbItems = pboard.pasteboardItems else {
  215. return false
  216. }
  217. //获取url
  218. var array: [URL] = []
  219. for item in pbItems {
  220. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  221. continue
  222. }
  223. let type = _url.pathExtension.lowercased()
  224. if let _allowedFileTypes = self.kmAllowedFileTypes {
  225. if (_allowedFileTypes.contains(type)) {
  226. array.append(_url)
  227. }
  228. } else {
  229. array.append(_url)
  230. }
  231. }
  232. self.delegate?.thumbnailView?(thumbanView: self, didDragAddFiles: array, indexpath: indexPath)
  233. }
  234. return false
  235. }
  236. func collectionView(_ collectionView: NSCollectionView,
  237. pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
  238. if let can = self.delegate?.thumbnailView?(thumbanView: self, canPasteboardWriterForItemAt: indexPath), !can {
  239. return nil
  240. }
  241. if let provider = self.delegate?.thumbnailView?(thumbanView: self, pasteboardWriterForItemAt: indexPath) {
  242. return provider
  243. }
  244. var provider: NSFilePromiseProvider?
  245. // 创建数据提供者
  246. let fileExtension = "pdf"
  247. if #available(macOS 11.0, *) {
  248. if let typeIdentifier = UTType(filenameExtension: fileExtension) {
  249. provider = KMFilePromiseProvider(fileType: typeIdentifier.identifier, delegate: self)
  250. }
  251. } else {
  252. if let typeIdentifier =
  253. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil) {
  254. provider = KMFilePromiseProvider(fileType: typeIdentifier.takeRetainedValue() as String, delegate: self)
  255. }
  256. }
  257. // 记录拖拽索引
  258. self.dragedIndexPaths.append(indexPath)
  259. do {
  260. if let _url = self.document?.documentURL {
  261. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  262. provider?.userInfo = [KMFilePromiseProvider.UserInfoKeys.urlKey: _url,
  263. KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  264. } else {
  265. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  266. provider?.userInfo = [KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  267. }
  268. } catch {
  269. fatalError("failed to archive indexPath to pasteboard")
  270. }
  271. return provider
  272. }
  273. override func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
  274. // if let _ = session.draggingPasteboard.availableType(from: [.localDraggedTypes]) {
  275. // Swift.debugPrint("本地拖拽")
  276. // } else {
  277. if (!self.dragIn) {
  278. var indexpaths = Set<IndexPath>()
  279. for indexpath in self.dragedIndexPaths {
  280. indexpaths.insert(indexpath)
  281. }
  282. // 清空数据
  283. self.dragedIndexPaths.removeAll()
  284. // 刷新数据
  285. self.reloadData()
  286. // 重新选中数据
  287. self.selectionIndexPaths = indexpaths
  288. } else {
  289. Swift.debugPrint("拖入文件 或 本地拖拽")
  290. }
  291. self.dragIn = false
  292. self.hiddenMarkerLineView()
  293. self.markBeginIndexes = IndexSet()
  294. // }
  295. super.collectionView(collectionView, draggingSession: session, endedAt: screenPoint, dragOperation: operation)
  296. }
  297. }
  298. extension KMPDFThumbnailView {
  299. func hiddenMarkerLineView() {
  300. for item in KMThumbnailManager.manager.dragCollectionViews {
  301. let view = item.superview?.superview?.superview as? KMPDFThumbnailView
  302. view?.markerLineView.isHidden = true
  303. }
  304. KMThumbnailManager.manager.dragCollectionViews.removeAll()
  305. }
  306. }
  307. // MARK: - KMExtensions
  308. extension KMPDFThumbnailView {
  309. var dragTempFloderPath: String? {
  310. get {
  311. return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier ?? "").stringByAppendingPathComponent("KMPDFThumbnailView_Drag_Temp")
  312. }
  313. }
  314. var dragTempFilePath: String? {
  315. get {
  316. return self.dragTempFloderPath?.stringByAppendingPathComponent("drag_tmp.pdf")
  317. }
  318. }
  319. }
  320. // MARK: - NSFilePromiseProviderDelegate
  321. extension KMPDFThumbnailView: NSFilePromiseProviderDelegate {
  322. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
  323. var fileName: String = "Untitle"
  324. if let _string = self.document?.documentURL.deletingPathExtension().lastPathComponent {
  325. fileName = _string
  326. }
  327. fileName.append(" pages")
  328. var indexs = IndexSet()
  329. for indexpath in self.dragedIndexPaths {
  330. indexs.insert(indexpath.item)
  331. }
  332. fileName.append(" ")
  333. fileName.append(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  334. fileName.append(".pdf")
  335. return fileName
  336. }
  337. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider,
  338. writePromiseTo url: URL,
  339. completionHandler: @escaping (Error?) -> Void) {
  340. do {
  341. /** Copy the file to the location provided to you. You always do a copy, not a move.
  342. It's important you call the completion handler.
  343. */
  344. if let _urlString = self.dragFilePath, !self.dragFlag {
  345. self.dragFlag = true
  346. if let should = self.delegate?.thumbnailView?(thumbanView: self, shouldPasteboardWriterForItemAt: IndexPath(item: 0, section: 0)), !should {
  347. completionHandler(nil)
  348. return
  349. }
  350. try FileManager.default.copyItem(at: URL(fileURLWithPath: _urlString), to: url)
  351. }
  352. completionHandler(nil)
  353. } catch let error {
  354. OperationQueue.main.addOperation {
  355. if let win = self.window {
  356. self.presentError(error, modalFor: win,
  357. delegate: nil, didPresent: nil, contextInfo: nil)
  358. }
  359. }
  360. completionHandler(error)
  361. }
  362. }
  363. /** You should provide a non main operation queue (e.g. one you create) via this function.
  364. This way you don't stall the main thread while writing the promise file.
  365. */
  366. func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
  367. return self.filePromiseQueue
  368. }
  369. // Utility function to return a PhotoItem object from the NSFilePromiseProvider.
  370. // func photoFromFilePromiserProvider(filePromiseProvider: NSFilePromiseProvider) -> CPDFPage? {
  371. // var result: CPDFPage?
  372. // if let userInfo = filePromiseProvider.userInfo as? [String: AnyObject] {
  373. // do {
  374. // if let indexPathData = userInfo[KMFilePromiseProvider.UserInfoKeys.indexPathKey] as? Data {
  375. // if let indexPath =
  376. // try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(indexPathData) as? IndexPath {
  377. // result = self.document?.page(at: UInt(indexPath.item))
  378. // }
  379. // }
  380. // } catch {
  381. // fatalError("failed to unarchive indexPath from promise provider.")
  382. // }
  383. // }
  384. // return result
  385. // }
  386. }