KMPDFThumbnailView.swift 17 KB

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