KMPDFThumbnailView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. var rect = self.collectionView.frameForItem(at: proposedDropIndexPath.pointee.item)
  139. rect.size.height = 2
  140. self.markerLineView.frame = rect
  141. self.markerLineView.isHidden = false
  142. }
  143. }
  144. }
  145. return super.collectionView(collectionView, validateDrop: draggingInfo, proposedIndexPath: proposedDropIndexPath, dropOperation: proposedDropOperation)
  146. }
  147. override func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  148. self.markerLineView.isHidden = true
  149. self.markBeginIndexes = IndexSet()
  150. self.dragIn = true
  151. let pboard = draggingInfo.draggingPasteboard
  152. if (pboard.availableType(from: [self.localForDraggedTypes]) != nil) {
  153. let dragIndexPath = self.dragedIndexPaths.first
  154. if (dragIndexPath == nil) {
  155. return false
  156. }
  157. let dragIndex = dragIndexPath!.item
  158. let toIndex = max(0, indexPath.item)
  159. if dragIndex < 0 || dragIndex > self.document!.pageCount {
  160. return false
  161. }
  162. if (toIndex >= self.document!.pageCount) {
  163. return false
  164. }
  165. if dragIndex == toIndex {
  166. return false
  167. }
  168. return super.collectionView(collectionView, acceptDrop: draggingInfo, indexPath: indexPath, dropOperation: dropOperation)
  169. } else if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  170. if let data = draggingInfo.draggingSource as? NSCollectionView, data.isEqual(to: collectionView) {
  171. // Swift.debugPrint("当前文件拖拽")
  172. return super.collectionView(collectionView, acceptDrop: draggingInfo, indexPath: indexPath, dropOperation: dropOperation)
  173. } else {
  174. // Swift.debugPrint("不同文件拖拽")
  175. if let _urlString = self.dragTempFilePath {
  176. self.delegate?.thumbnailView?(thumbanView: self, didDragAddFiles: [URL(fileURLWithPath: _urlString)], indexpath: indexPath)
  177. }
  178. }
  179. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  180. guard let pbItems = pboard.pasteboardItems else {
  181. return false
  182. }
  183. //获取url
  184. var array: [URL] = []
  185. for item in pbItems {
  186. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  187. continue
  188. }
  189. let type = _url.pathExtension.lowercased()
  190. if let _allowedFileTypes = self.kmAllowedFileTypes {
  191. if (_allowedFileTypes.contains(type)) {
  192. array.append(_url)
  193. }
  194. } else {
  195. array.append(_url)
  196. }
  197. }
  198. self.delegate?.thumbnailView?(thumbanView: self, didDragAddFiles: array, indexpath: indexPath)
  199. }
  200. return false
  201. }
  202. func collectionView(_ collectionView: NSCollectionView,
  203. pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
  204. var provider: NSFilePromiseProvider?
  205. // 创建数据提供者
  206. let fileExtension = "pdf"
  207. if #available(macOS 11.0, *) {
  208. let typeIdentifier = UTType(filenameExtension: fileExtension)
  209. provider = KMFilePromiseProvider(fileType: typeIdentifier!.identifier, delegate: self)
  210. } else {
  211. let typeIdentifier =
  212. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)
  213. provider = KMFilePromiseProvider(fileType: typeIdentifier!.takeRetainedValue() as String, delegate: self)
  214. }
  215. // 记录拖拽索引
  216. self.dragedIndexPaths.append(indexPath)
  217. do {
  218. if let _url = self.document?.documentURL {
  219. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  220. provider!.userInfo = [KMFilePromiseProvider.UserInfoKeys.urlKey: _url,
  221. KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  222. } else {
  223. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  224. provider!.userInfo = [KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  225. }
  226. } catch {
  227. fatalError("failed to archive indexPath to pasteboard")
  228. }
  229. return provider
  230. }
  231. func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
  232. // if let _ = session.draggingPasteboard.availableType(from: [.localDraggedTypes]) {
  233. // Swift.debugPrint("本地拖拽")
  234. // } else {
  235. if (!self.dragIn) {
  236. var indexpaths = Set<IndexPath>()
  237. for indexpath in self.dragedIndexPaths {
  238. indexpaths.insert(indexpath)
  239. }
  240. // 清空数据
  241. self.dragedIndexPaths.removeAll()
  242. // 刷新数据
  243. self.reloadData()
  244. // 重新选中数据
  245. self.selectionIndexPaths = indexpaths
  246. } else {
  247. Swift.debugPrint("拖入文件 或 本地拖拽")
  248. }
  249. self.dragIn = false
  250. // }
  251. }
  252. }
  253. // MARK: - KMExtensions
  254. extension KMPDFThumbnailView {
  255. var dragTempFloderPath: String? {
  256. get {
  257. return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("KMPDFThumbnailView_Drag_Temp")
  258. }
  259. }
  260. var dragTempFilePath: String? {
  261. get {
  262. return self.dragTempFloderPath?.stringByAppendingPathComponent("drag_tmp.pdf")
  263. }
  264. }
  265. }
  266. // MARK: - NSFilePromiseProviderDelegate
  267. extension KMPDFThumbnailView: NSFilePromiseProviderDelegate {
  268. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
  269. var fileName: String = "Untitle"
  270. if let _string = self.document?.documentURL.deletingPathExtension().lastPathComponent {
  271. fileName = _string
  272. }
  273. fileName.append(" pages")
  274. var indexs = IndexSet()
  275. for indexpath in self.dragedIndexPaths {
  276. indexs.insert(indexpath.item)
  277. }
  278. fileName.append(" ")
  279. fileName.append(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  280. fileName.append(".pdf")
  281. return fileName
  282. }
  283. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider,
  284. writePromiseTo url: URL,
  285. completionHandler: @escaping (Error?) -> Void) {
  286. do {
  287. /** Copy the file to the location provided to you. You always do a copy, not a move.
  288. It's important you call the completion handler.
  289. */
  290. if let _urlString = self.dragFilePath, !self.dragFlag {
  291. self.dragFlag = true
  292. try FileManager.default.copyItem(at: URL(fileURLWithPath: _urlString), to: url)
  293. }
  294. completionHandler(nil)
  295. } catch let error {
  296. OperationQueue.main.addOperation {
  297. self.presentError(error, modalFor: self.window!,
  298. delegate: nil, didPresent: nil, contextInfo: nil)
  299. }
  300. completionHandler(error)
  301. }
  302. }
  303. /** You should provide a non main operation queue (e.g. one you create) via this function.
  304. This way you don't stall the main thread while writing the promise file.
  305. */
  306. func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
  307. return self.filePromiseQueue
  308. }
  309. // Utility function to return a PhotoItem object from the NSFilePromiseProvider.
  310. // func photoFromFilePromiserProvider(filePromiseProvider: NSFilePromiseProvider) -> CPDFPage? {
  311. // var result: CPDFPage?
  312. // if let userInfo = filePromiseProvider.userInfo as? [String: AnyObject] {
  313. // do {
  314. // if let indexPathData = userInfo[KMFilePromiseProvider.UserInfoKeys.indexPathKey] as? Data {
  315. // if let indexPath =
  316. // try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(indexPathData) as? IndexPath {
  317. // result = self.document?.page(at: UInt(indexPath.item))
  318. // }
  319. // }
  320. // } catch {
  321. // fatalError("failed to unarchive indexPath from promise provider.")
  322. // }
  323. // }
  324. // return result
  325. // }
  326. }