KMNThumbnailBaseViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //
  2. // KMNThumbnailBaseViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by 丁林圭 on 2024/10/21.
  6. //
  7. import Cocoa
  8. @objc protocol KMNThumbnailBaseViewDelegate: AnyObject {
  9. @objc optional func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int)
  10. @objc optional func insertPDFThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,pdfDocment:CPDFDocument?)
  11. }
  12. internal let kmnThumLocalForDraggedTypes = NSPasteboard.PasteboardType(rawValue: "kmnThumLocalForDraggedTypes")
  13. class KMNThumbnailBaseViewController: NSViewController,NSCollectionViewDelegate, NSCollectionViewDataSource,NSCollectionViewDelegateFlowLayout {
  14. weak open var thumbnailBaseViewDelegate: KMNThumbnailBaseViewDelegate?
  15. @IBOutlet var backViewBox: NSBox!
  16. @IBOutlet var collectionView: NSCollectionView!
  17. let subTitleHeight: CGFloat = 20.0
  18. let maxCellHeight: CGFloat = 280.0
  19. private var currentDocument:CPDFDocument?
  20. public var currentUndoManager:UndoManager?
  21. public var showDocument: CPDFDocument? {
  22. return currentDocument
  23. }
  24. private var thumbnails:[KMNThumbnail] = []
  25. var selectionIndexPaths: Set<IndexPath> = [] {
  26. didSet {
  27. var indexpaths: Set<IndexPath> = []
  28. for indexpath in selectionIndexPaths {
  29. if (indexpath.section >= collectionView.numberOfSections) {
  30. continue
  31. }
  32. if indexpath.section < 0 {
  33. continue
  34. }
  35. if (indexpath.item >= collectionView.numberOfItems(inSection: indexpath.section)) {
  36. continue
  37. }
  38. if indexpath.item < 0 {
  39. continue
  40. }
  41. indexpaths.insert(indexpath)
  42. }
  43. collectionView.selectionIndexPaths = indexpaths
  44. collectionView.scrollToItems(at: indexpaths, scrollPosition: .top)
  45. }
  46. }
  47. public var clickPageIndex: Int{
  48. let minIndexPath = selectionIndexPaths.min(by: { $0.item < $1.item })
  49. return minIndexPath?.item ?? 0
  50. }
  51. public var isAdjustWidth:Bool = false
  52. public var isShowPageSize:Bool = false {
  53. didSet {
  54. if oldValue != isShowPageSize {
  55. var pageSize = pageThumbnailSize
  56. if(isShowPageSize) {
  57. pageSize.height -= subTitleHeight
  58. } else {
  59. pageSize.height += subTitleHeight
  60. }
  61. pageThumbnailSize = pageSize
  62. }
  63. }
  64. }
  65. public var pageThumbnailSize:CGSize = CGSizeMake(185.0, 260) {
  66. didSet {
  67. collectionView.reloadData()
  68. }
  69. }
  70. var dragLocalityIndexPaths: Set<IndexPath> = []
  71. deinit {
  72. thumbnailBaseViewDelegate = nil
  73. KMPrint("KMNThumbnailBaseViewController deinit.")
  74. }
  75. init(_ document: CPDFDocument?) {
  76. super.init(nibName: "KMNThumbnailBaseViewController", bundle: nil)
  77. currentDocument = document
  78. }
  79. init(_ filePath: String,password:String?) {
  80. super.init(nibName: "KMNThumbnailBaseViewController", bundle: nil)
  81. let document = CPDFDocument.init(url: URL(fileURLWithPath: filePath))
  82. if password != nil {
  83. document?.unlock(withPassword: password as String?)
  84. }
  85. if document?.allowsCopying == false || document?.allowsPrinting == false {
  86. self.exitCurrentView()
  87. } else {
  88. currentDocument = document
  89. }
  90. }
  91. required init?(coder: NSCoder) {
  92. fatalError("init(coder:) has not been implemented")
  93. }
  94. override func viewDidLoad() {
  95. super.viewDidLoad()
  96. thumbnails = []
  97. if currentDocument != nil {
  98. for i in 0 ... currentDocument!.pageCount {
  99. let thumbnail = KMNThumbnail.init(document: currentDocument!, currentPageIndex: Int(i))
  100. thumbnails.append(thumbnail)
  101. }
  102. }
  103. collectionView.delegate = self
  104. collectionView.dataSource = self
  105. collectionView.isSelectable = true //支持拖拽需设置未True
  106. collectionView.allowsMultipleSelection = true
  107. collectionView.register(KMNThumbnailCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "thumbnailCollectionViewItem"))
  108. collectionView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
  109. collectionView.registerForDraggedTypes([kmnThumLocalForDraggedTypes, .fileURL,.string,.pdf])
  110. }
  111. public func exitCurrentView() {
  112. thumbnailBaseViewDelegate?.clickThumbnailViewControlle?(pageEditVC: self, currentIndex: clickPageIndex)
  113. }
  114. private func supportDragFileTypes()->[String] {
  115. let supportFiles = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType()
  116. return supportFiles
  117. }
  118. private func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  119. var pagesName = ""
  120. if (itemIndexes.count > 1) {
  121. pagesName.append(" pages")
  122. } else {
  123. pagesName.append(" page")
  124. }
  125. let docmentName = currentDocument?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  126. let tFileName = String(format: "%@ %@", pagesName,KMNTools.parseIndexSet(indexSet: itemIndexes))
  127. return String(format: "%@%@", docmentName,tFileName)
  128. }
  129. public func insertFormPDF(insertPages: [CPDFPage],pageDex:Int) {
  130. var pageIndexDex: Int = pageDex
  131. var indexpaths = Set<IndexPath>()
  132. for page in insertPages {
  133. currentDocument?.insertPageObject(page, at: UInt(pageIndexDex))
  134. indexpaths.insert(IndexPath(item: pageIndexDex, section: 0))
  135. pageIndexDex += 1
  136. }
  137. collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
  138. // (currentUndoManager?.prepare(withInvocationTarget: self) as KMNThumbnailBaseViewController).deletePDFPages(indexpaths: indexpaths, scroIndex: pageDex)
  139. }
  140. public func deletePDFPages(indexpaths:Set<IndexPath>,scroIndex:Int) {
  141. collectionView.reloadData()
  142. collectionView.scrollToItems(at: [IndexPath(item: scroIndex, section: 0)], scrollPosition: .centeredVertically)
  143. }
  144. // MARK: - NSCollectionViewDataSource
  145. func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  146. return thumbnails.count
  147. }
  148. func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  149. let item: KMNThumbnailCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "thumbnailCollectionViewItem"), for: indexPath) as! KMNThumbnailCollectionViewItem
  150. item.isShowFileSize = isShowPageSize
  151. item.doubleClickBack = { [weak self] in
  152. self?.thumbnailBaseViewDelegate?.clickThumbnailViewControlle?(pageEditVC: self, currentIndex: indexPath.item)
  153. }
  154. item.thumbnailMode = thumbnails[indexPath.item]
  155. return item
  156. }
  157. // MARK: - NSCollectionViewDelegateFlowLayout
  158. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  159. if isAdjustWidth == false {
  160. return pageThumbnailSize
  161. } else {
  162. let thumbnailMode: KMNThumbnail = thumbnails[indexPath.item]
  163. let pageSize = thumbnailMode.pageSize
  164. var cellHeight = pageSize.width / ((pageThumbnailSize.width - 32) * pageThumbnailSize.height)
  165. var cellWidth = pageThumbnailSize.width
  166. if cellHeight > maxCellHeight {
  167. cellHeight = 280.0
  168. cellWidth = cellHeight/pageSize.height * pageSize.width
  169. }
  170. return CGSize(width: cellWidth, height: cellHeight)
  171. }
  172. }
  173. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  174. return 16.0
  175. }
  176. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  177. return 24.0
  178. }
  179. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
  180. return NSEdgeInsetsMake(24.0, 24.0, 24.0, 24.0)
  181. }
  182. //MARK: - NSCollectionViewDelegate
  183. func collectionView(_ collectionView: NSCollectionView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
  184. return IAPProductsManager.default().isAvailableAllFunction()
  185. }
  186. func collectionView(_ collectionView: NSCollectionView, writeItemsAt indexPaths: Set<IndexPath>, to pasteboard: NSPasteboard) -> Bool {
  187. let data: Data = try! NSKeyedArchiver.archivedData(withRootObject: indexPaths, requiringSecureCoding: true)
  188. pasteboard.declareTypes([kmnThumLocalForDraggedTypes], owner: self)
  189. pasteboard.setData(data, forType: kmnThumLocalForDraggedTypes)
  190. dragLocalityIndexPaths.removeAll()
  191. dragLocalityIndexPaths = indexPaths
  192. return true
  193. }
  194. func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
  195. let pboard = draggingInfo.draggingPasteboard
  196. if (pboard.availableType(from: [kmnThumLocalForDraggedTypes]) != nil) {
  197. return .move
  198. } else if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  199. return .move
  200. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  201. guard let pbItems = pboard.pasteboardItems else {
  202. return NSDragOperation(rawValue: 0)
  203. }
  204. let allowedFileTypes = supportDragFileTypes()
  205. var hasValidFile = false
  206. for item in pbItems {
  207. guard let data = item.string(forType: .fileURL), let fileUrl = URL(string: data) else {
  208. continue
  209. }
  210. let type = fileUrl.pathExtension.lowercased()
  211. if (allowedFileTypes.contains(type)) {
  212. hasValidFile = true
  213. break
  214. }
  215. }
  216. if (!hasValidFile) {
  217. return NSDragOperation(rawValue: 0)
  218. }
  219. }
  220. return .generic
  221. }
  222. func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  223. let result = false
  224. if !IAPProductsManager.default().isAvailableAllFunction() {
  225. return result
  226. }
  227. let pboard = draggingInfo.draggingPasteboard
  228. if (pboard.availableType(from: [kmnThumLocalForDraggedTypes]) != nil) {
  229. } else if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  230. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  231. guard let pbItems = pboard.pasteboardItems else {
  232. return false
  233. }
  234. //获取url
  235. var array: [URL] = []
  236. for item in pbItems {
  237. guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
  238. continue
  239. }
  240. let allowedFileTypes = supportDragFileTypes()
  241. let type = url.pathExtension.lowercased()
  242. if (allowedFileTypes.contains(type)) {
  243. array.append(url)
  244. }
  245. }
  246. }
  247. return true
  248. }
  249. func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
  250. print("6")
  251. dragLocalityIndexPaths = []
  252. }
  253. }