KMPDFThumbnailView.swift 17 KB

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