KMNThumbnailBaseViewController.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //
  2. // KMNThumbnailBaseViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by 丁林圭 on 2024/10/21.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. @objc protocol KMNThumbnailBaseViewDelegate: AnyObject {
  10. @objc optional func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int)
  11. @objc optional func insertPDFThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,pdfDocment:CPDFDocument?)
  12. @objc optional func changeIndexPathsThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,selectionIndexPaths: Set<IndexPath>,selectionStrings:String )
  13. @objc optional func thumbnailViewControlleHaveChange(pageEditVC:KMNThumbnailBaseViewController)
  14. }
  15. enum KMNThumbnailChoosePageStyle: Int {
  16. case odd
  17. case even
  18. case horizontal
  19. case vertical
  20. case allPage
  21. case custom
  22. }
  23. internal let kmnThumLocalForDraggedTypes = NSPasteboard.PasteboardType(rawValue: "kmnThumLocalForDraggedTypes")
  24. let topThumOffset: CGFloat = 12.0 // 缩图顶部高度
  25. let infoThumTitleHeight: CGFloat = 16.0 //文字高度
  26. let infoThumTitleBottom: CGFloat = 16.0 // 底部高度
  27. struct KMNMenuStruct {
  28. var menuitems: [ComponentMenuitemProperty]
  29. var viewHeight: CGFloat // 不可变属性
  30. }
  31. class KMNThumbnailBaseViewController: KMNBaseViewController,NSCollectionViewDelegate, NSCollectionViewDataSource,NSCollectionViewDelegateFlowLayout {
  32. let maxCellHeight: CGFloat = 320.0 - infoThumTitleBottom - infoThumTitleHeight - topThumOffset * 2
  33. let minCellHeight: CGFloat = 80.0 - infoThumTitleBottom - infoThumTitleHeight - topThumOffset - topThumOffset * 2
  34. weak open var thumbnailBaseViewDelegate: KMNThumbnailBaseViewDelegate?
  35. @IBOutlet var backViewBox: NSBox!
  36. @IBOutlet var scrollView: NSScrollView!
  37. @IBOutlet var collectionView: KMNThumbnailCollectionView!
  38. @IBOutlet var flowLayout: KMNThumCustomCollectionViewFlowLayout!
  39. private var currentDocument:CPDFDocument?
  40. private var isChangeIndexPaths = false
  41. private var selectCount = 0 //防止点击缩图后 listview回调
  42. var lockedFiles: [URL] = []
  43. var filePromiseQueue: OperationQueue = {
  44. let queue = OperationQueue()
  45. return queue
  46. }()
  47. var dragTempFloderPath: String {
  48. get {
  49. var cachesDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  50. cachesDir = cachesDir.appendingPathComponent("PageEdit_Pasteboard")
  51. return cachesDir.path
  52. }
  53. }
  54. fileprivate var dragFilePath: String?
  55. var dragTempFilePath: String? {
  56. get {
  57. return self.dragTempFloderPath.stringByAppendingPathComponent("drag_tmp.pdf")
  58. }
  59. }
  60. fileprivate var dragFlag = false
  61. public var thumbnails:[KMNThumbnail] = []
  62. public var dragLocalityPages: [CPDFPage] = []
  63. public var currentUndoManager:UndoManager?
  64. public var showDocument: CPDFDocument? {
  65. return currentDocument
  66. }
  67. public var changeDocument:CPDFDocument? {
  68. didSet {
  69. if(changeDocument != nil && changeDocument != currentDocument) {
  70. currentDocument = changeDocument
  71. refreshDatas()
  72. collectionView.reloadData()
  73. }
  74. }
  75. }
  76. public var thumbnailChoosePageStyle:KMNThumbnailChoosePageStyle = .custom {
  77. didSet {
  78. var tSelectionIndexPaths: Set<IndexPath> = []
  79. let pageCount = currentDocument?.pageCount ?? 0
  80. switch thumbnailChoosePageStyle {
  81. case .even:
  82. for i in 0 ..< pageCount {
  83. if(i % 2 == 0) {
  84. tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
  85. }
  86. }
  87. case .odd:
  88. for i in 0 ..< pageCount {
  89. if(i % 2 != 0) {
  90. tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
  91. }
  92. }
  93. case .allPage:
  94. for i in 0 ..< pageCount {
  95. tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
  96. }
  97. case .vertical:
  98. for i in 0 ..< pageCount {
  99. let page = showDocument?.page(at: i)
  100. if(page != nil) {
  101. if(page!.rotation % 180 != 0) {
  102. tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
  103. }
  104. }
  105. }
  106. case .horizontal:
  107. for i in 0 ..< pageCount {
  108. let page = showDocument?.page(at: i)
  109. if(page != nil) {
  110. if(page!.rotation % 180 == 0) {
  111. tSelectionIndexPaths.insert(IndexPath(item: Int(i), section: 0))
  112. }
  113. }
  114. }
  115. default: break
  116. }
  117. isChangeIndexPaths = true
  118. collectionView.selectionIndexPaths = tSelectionIndexPaths
  119. isChangeIndexPaths = false
  120. }
  121. }
  122. var pdfviewSelectionIndexPaths: Set<IndexPath> = []
  123. var selectionIndexPaths: Set<IndexPath> = [] {
  124. didSet {
  125. if selectCount != 0 {
  126. selectCount -= 1
  127. return
  128. }
  129. pdfviewSelectionIndexPaths = selectionIndexPaths
  130. var indexpaths: Set<IndexPath> = []
  131. for indexpath in selectionIndexPaths {
  132. if (indexpath.section >= collectionView.numberOfSections) {
  133. continue
  134. }
  135. if indexpath.section < 0 {
  136. continue
  137. }
  138. if (indexpath.item >= collectionView.numberOfItems(inSection: indexpath.section)) {
  139. continue
  140. }
  141. if indexpath.item < 0 {
  142. continue
  143. }
  144. indexpaths.insert(indexpath)
  145. }
  146. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {//页面跳转进入时未直接滚动和选中
  147. if indexpaths.count > 0 {
  148. let indexpath = indexpaths.first
  149. guard let layoutAttributes = self.collectionView.layoutAttributesForItem(at: indexpath!) else { return }
  150. // 获取 CollectionView 的可见区域
  151. let visibleRect = self.collectionView.visibleRect
  152. // 判断目标 Cell 是否完全可见
  153. if !visibleRect.contains(layoutAttributes.frame) {
  154. // 如果不可见或部分可见,滚动到顶部
  155. self.collectionView.scrollToItems(at: [indexpath!], scrollPosition: .top)
  156. }
  157. }
  158. self.isChangeIndexPaths = true
  159. self.collectionView.selectionIndexPaths = indexpaths
  160. self.isChangeIndexPaths = false
  161. }
  162. }
  163. }
  164. public var isShowPageSize:Bool = false {
  165. didSet {
  166. if oldValue != isShowPageSize {
  167. var pageSize = pageThumbnailSize
  168. if(isShowPageSize) {
  169. pageSize.height += infoThumTitleHeight
  170. } else {
  171. pageSize.height -= infoThumTitleHeight
  172. }
  173. pageThumbnailSize = pageSize
  174. collectionView.reloadData()
  175. }
  176. }
  177. }
  178. public var pageThumbnailSize:CGSize = CGSizeMake(185.0, 260) {
  179. didSet {
  180. collectionView.reloadData()
  181. }
  182. }
  183. public let defaultItemSize = NSMakeSize(185.0, 260)
  184. deinit {
  185. thumbnailBaseViewDelegate = nil
  186. KMPrint("KMNThumbnailBaseViewController deinit.")
  187. }
  188. init(_ document: CPDFDocument?) {
  189. super.init(nibName: "KMNThumbnailBaseViewController", bundle: nil)
  190. currentDocument = document
  191. }
  192. init(_ filePath: String,password:String?) {
  193. super.init(nibName: "KMNThumbnailBaseViewController", bundle: nil)
  194. let document = CPDFDocument.init(url: URL(fileURLWithPath: filePath))
  195. if password != nil {
  196. document?.unlock(withPassword: password as String?)
  197. }
  198. if document?.allowsCopying == false || document?.allowsPrinting == false {
  199. exitCurrentView()
  200. } else {
  201. currentDocument = document
  202. }
  203. }
  204. required init?(coder: NSCoder) {
  205. fatalError("init(coder:) has not been implemented")
  206. }
  207. override func viewDidLoad() {
  208. super.viewDidLoad()
  209. collectionView.delegate = self
  210. collectionView.dataSource = self
  211. collectionView.isSelectable = true //支持拖拽需设置未True
  212. collectionView.allowsMultipleSelection = true
  213. collectionView.enclosingScrollView?.hasVerticalScroller = false
  214. collectionView.enclosingScrollView?.hasHorizontalScroller = false
  215. scrollView.scrollerStyle = .overlay
  216. collectionView.register(KMNThumbnailCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "thumbnailCollectionViewItem"))
  217. collectionView.registerForDraggedTypes([.fileURL,.string,.pdf])
  218. collectionView.setDraggingSourceOperationMask(.every, forLocal: false)
  219. collectionView.setDraggingSourceOperationMask(.every, forLocal: true)
  220. collectionView.collectionSelectChanges = {[weak self] in
  221. if self?.isChangeIndexPaths == false {
  222. let indexpathsz = self?.collectionView.selectionIndexPaths
  223. let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz ?? [])
  224. let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
  225. self?.thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz ?? [], selectionStrings: selectedIndexPathsString)
  226. }
  227. }
  228. refreshDatas()
  229. }
  230. public func exitCurrentView() {
  231. let minIndexPath = selectionIndexPaths.max(by: { $0.item < $1.item })
  232. thumbnailBaseViewDelegate?.clickThumbnailViewControlle?(pageEditVC: self, currentIndex: minIndexPath?.item ?? 0)
  233. }
  234. public func supportDragFileTypes()->[String] {
  235. let supportFiles = KMNConvertTool.pdfExtensions + KMConvertPDFManager.supportFileType()
  236. return supportFiles
  237. }
  238. public func refreshDatas() {
  239. thumbnails = []
  240. if currentDocument != nil {
  241. for i in 0 ..< currentDocument!.pageCount {
  242. let thumbnail = KMNThumbnail.init(document: currentDocument!, currentPageIndex: Int(i))
  243. thumbnails.append(thumbnail)
  244. }
  245. }
  246. }
  247. public func reloadDatas() {
  248. refreshDatas()
  249. collectionView.reloadData()
  250. }
  251. public func reloadDataWithIndexs(pageIndexs: IndexSet) {
  252. if currentDocument != nil {
  253. KMNThumbnailManager.reloadThumImage(document: currentDocument!, pageIndexs: pageIndexs)
  254. }
  255. }
  256. // MARK: - private
  257. public func clickMenu(point:NSPoint)->KMNMenuStruct {
  258. let copyPages: [CPDFPage] = KMNThumbnailManager.manager.copyPages
  259. let selectedIndexPaths = collectionView.selectionIndexPaths
  260. var viewHeight: CGFloat = 8
  261. var menuItemArr: [ComponentMenuitemProperty] = []
  262. var items: [(String, String)] = []
  263. if selectedIndexPaths.count > 0 {
  264. items.append(("Copy", ThumbnailMenuIdentifier_Copy))
  265. items.append(("Cut", ThumbnailMenuIdentifier_Cut))
  266. if(copyPages.count > 0) {
  267. items.append(("Paste", ThumbnailMenuIdentifier_Paste))
  268. }
  269. items.append(("Delete", ThumbnailMenuIdentifier_Delete))
  270. items.append(("", ""))
  271. items.append(("90° CW", ThumbnailMenuIdentifier_RotateRight))
  272. items.append(("90° CCW", ThumbnailMenuIdentifier_RotateLeft))
  273. items.append(("", ""))
  274. if(selectedIndexPaths.count == 1) {
  275. items.append(("Insert File", ThumbnailMenuIdentifier_InsertFile))
  276. items.append(("Insert a Blank Page", ThumbnailMenuIdentifier_InsertBlank))
  277. items.append(("Replace", ThumbnailMenuIdentifier_Replace))
  278. }
  279. items.append(("Extract", ThumbnailMenuIdentifier_Export))
  280. items.append(("Share", ThumbnailMenuIdentifier_Share))
  281. items.append(("", ""))
  282. items.append(("Display Page Size", ThumbnailMenuIdentifier_FileShowSize))
  283. } else {
  284. if(copyPages.count > 0) {
  285. items.append(("Paste", ThumbnailMenuIdentifier_Paste))
  286. items.append(("", ""))
  287. } else {
  288. items.append(("Paste", ThumbnailMenuIdentifier_PastNull))
  289. items.append(("", ""))
  290. }
  291. items.append(("Display Page Size", ThumbnailMenuIdentifier_FileShowSize))
  292. }
  293. for (i, value) in items {
  294. if value.count == 0 {
  295. let property: ComponentMenuitemProperty = ComponentMenuitemProperty.divider()
  296. menuItemArr.append(property)
  297. viewHeight += 8
  298. } else {
  299. var isDisabled = false
  300. if(value == ThumbnailMenuIdentifier_PastNull) {
  301. isDisabled = true
  302. }
  303. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  304. itemSelected: false,
  305. isDisabled: isDisabled,
  306. keyEquivalent: nil,
  307. text: KMLocalizedString(i),
  308. identifier: value,representedObject: point)
  309. if value == ThumbnailMenuIdentifier_Copy {
  310. properties_Menuitem.keyEquivalent = "⌘ C"
  311. } else if value == ThumbnailMenuIdentifier_Cut {
  312. properties_Menuitem.keyEquivalent = "⌘ x"
  313. } else if value == ThumbnailMenuIdentifier_Paste {
  314. properties_Menuitem.keyEquivalent = "⌘ v"
  315. } else if value == ThumbnailMenuIdentifier_PastNull {
  316. properties_Menuitem.keyEquivalent = "⌘ v"
  317. } else if value == ThumbnailMenuIdentifier_Delete {
  318. properties_Menuitem.keyEquivalent = "⌘ " + "⌫"
  319. } else if value == ThumbnailMenuIdentifier_RotateRight {
  320. properties_Menuitem.keyEquivalent = "⌥ ⌘ R"
  321. } else if value == ThumbnailMenuIdentifier_RotateLeft {
  322. properties_Menuitem.keyEquivalent = "⌥ ⌘ L"
  323. }
  324. if(value == ThumbnailMenuIdentifier_FileShowSize && isShowPageSize) {
  325. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  326. }
  327. menuItemArr.append(properties_Menuitem)
  328. viewHeight += 36
  329. }
  330. }
  331. let menuStruct = KMNMenuStruct(menuitems: menuItemArr, viewHeight: viewHeight)
  332. return menuStruct
  333. }
  334. // MARK: - NSCollectionViewDataSource
  335. func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  336. return thumbnails.count
  337. }
  338. func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  339. let item: KMNThumbnailCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "thumbnailCollectionViewItem"), for: indexPath) as! KMNThumbnailCollectionViewItem
  340. item.isShowFileSize = isShowPageSize
  341. item.doubleClickBack = { [weak self] in
  342. self?.thumbnailBaseViewDelegate?.clickThumbnailViewControlle?(pageEditVC: self, currentIndex: indexPath.item)
  343. }
  344. item.thumbnailMode = thumbnails[indexPath.item]
  345. return item
  346. }
  347. func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
  348. if isChangeIndexPaths == false {
  349. selectCount += 1
  350. let indexpathsz = collectionView.selectionIndexPaths
  351. let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz)
  352. let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
  353. thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz, selectionStrings: selectedIndexPathsString)
  354. }
  355. }
  356. func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
  357. if isChangeIndexPaths == false {
  358. let indexpathsz = self.collectionView.selectionIndexPaths
  359. let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz)
  360. let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
  361. thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz, selectionStrings: selectedIndexPathsString)
  362. }
  363. }
  364. // MARK: - NSCollectionViewDelegateFlowLayout
  365. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  366. return pageThumbnailSize
  367. }
  368. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  369. return 16.0
  370. }
  371. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  372. return 24.0
  373. }
  374. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
  375. return NSEdgeInsetsMake(24.0, 24.0, 24.0, 24.0)
  376. }
  377. //MARK: - NSCollectionViewDelegate
  378. func collectionView(_ collectionView: NSCollectionView,
  379. pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
  380. var provider: NSFilePromiseProvider?
  381. // 创建数据提供者
  382. let fileExtension = "pdf"
  383. if #available(macOS 11.0, *) {
  384. if let typeIdentifier = UTType(filenameExtension: fileExtension) {
  385. provider = KMFilePromiseProvider(fileType: typeIdentifier.identifier, delegate: self)
  386. }
  387. } else {
  388. if let typeIdentifier =
  389. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil) {
  390. provider = KMFilePromiseProvider(fileType: typeIdentifier.takeRetainedValue() as String, delegate: self)
  391. }
  392. }
  393. do {
  394. if let _url = showDocument?.documentURL {
  395. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  396. provider?.userInfo = [KMFilePromiseProvider.UserInfoKeys.urlKey: _url,
  397. KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  398. } else {
  399. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  400. provider?.userInfo = [KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  401. }
  402. } catch {
  403. fatalError("failed to archive indexPath to pasteboard")
  404. }
  405. return provider
  406. }
  407. func collectionView(_ collectionView: NSCollectionView,
  408. draggingSession session: NSDraggingSession,
  409. willBeginAt screenPoint: NSPoint,
  410. forItemsAt indexPaths: Set<IndexPath>) {
  411. let sortedIndexPaths = indexPaths.sorted { (ip1, ip2) -> Bool in
  412. if ip1.section == ip2.section {
  413. return ip1.item < ip2.item
  414. }
  415. return ip1.section < ip2.section
  416. }
  417. dragLocalityPages = []
  418. for fromIndexPath in sortedIndexPaths {
  419. let page = thumbnails[fromIndexPath.item].thumbnaiPage
  420. if(page != nil) {
  421. dragLocalityPages.append(page!)
  422. }
  423. }
  424. var docmentName = currentDocument?.documentURL.lastPathComponent.deletingPathExtension ?? ""
  425. let pagesName = indexPaths.count > 1 ? " pages" : " page"
  426. var tFileName = pagesName + KMNTools.parseIndexPathsSet(indexSets: collectionView.selectionIndexPaths)
  427. if tFileName.count > 50 {
  428. tFileName = String(tFileName.prefix(50))
  429. }
  430. let cachesDir = dragTempFloderPath
  431. let fileManager = FileManager.default
  432. if !fileManager.fileExists(atPath: cachesDir) {
  433. try? FileManager.default.createDirectory(atPath: cachesDir, withIntermediateDirectories: true, attributes: nil)
  434. }
  435. docmentName = "\(docmentName)\(tFileName)"
  436. if docmentName.count > 50 {
  437. docmentName = String(docmentName.prefix(50))
  438. }
  439. // 将拖拽的page插入临时路径(文档)
  440. var indexs = IndexSet()
  441. for indexpath in indexPaths {
  442. indexs.insert(indexpath.item)
  443. }
  444. // 重置拖拽标识
  445. self.dragFlag = false
  446. if (indexs.count > 0) {
  447. let writePDFDocument = CPDFDocument()
  448. writePDFDocument?.importPages(indexs, from: self.showDocument, at: 0)
  449. let tFileName = docmentName + ".pdf"
  450. let filePathtPath = cachesDir + tFileName
  451. let success = writePDFDocument?.write(to: NSURL(fileURLWithPath: filePathtPath) as URL?, isSaveFontSubset:false)
  452. if(success == true) {
  453. let tFilePath = self.dragTempFloderPath.stringByAppendingPathComponent("drag_tmp.pdf")
  454. if FileManager.default.fileExists(atPath: tFilePath) {
  455. try? FileManager.default.removeItem(atPath: tFilePath)
  456. }
  457. try? FileManager.default.copyItem(atPath: filePathtPath, toPath: tFilePath)
  458. self.dragFilePath = filePathtPath
  459. }
  460. }
  461. }
  462. func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
  463. let pboard = draggingInfo.draggingPasteboard
  464. if dragLocalityPages.count != 0 {
  465. if proposedDropOperation.pointee == .on {
  466. proposedDropOperation.pointee = .before
  467. }
  468. return .move
  469. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  470. guard let pbItems = pboard.pasteboardItems else {
  471. return NSDragOperation(rawValue: 0)
  472. }
  473. var hasValidFile = false
  474. for item in pbItems {
  475. guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
  476. continue
  477. }
  478. let type = url.pathExtension.lowercased()
  479. if (supportDragFileTypes().contains(type)) {
  480. hasValidFile = true
  481. break
  482. }
  483. }
  484. if (!hasValidFile) {
  485. return NSDragOperation(rawValue: 0)
  486. }
  487. }
  488. return .copy
  489. }
  490. func collectionView(_ collectionView: NSCollectionView,
  491. acceptDrop draggingInfo: NSDraggingInfo,
  492. indexPath: IndexPath,
  493. dropOperation: NSCollectionView.DropOperation) -> Bool {
  494. let pboard = draggingInfo.draggingPasteboard
  495. if dragLocalityPages.count != 0 {
  496. movePages(dragPages: dragLocalityPages, destinationDex: indexPath.item)
  497. return true
  498. } else if(pboard.availableType(from: [.localDraggedTypes]) != nil) {
  499. let index = indexPath.item
  500. if let _urlString = self.dragTempFilePath {
  501. insertFromFilePath(fileNames: [_urlString], formDex: 0, indexDex: UInt(index), selectIndexs: []) { newSelectIndexs in
  502. }
  503. }
  504. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  505. let index = indexPath.item
  506. guard let pbItems = pboard.pasteboardItems else {
  507. return false
  508. }
  509. //获取url
  510. var fileNames: [String] = []
  511. for item in pbItems {
  512. guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
  513. continue
  514. }
  515. let type = url.pathExtension.lowercased()
  516. if (supportDragFileTypes().contains(type)) {
  517. if(FileManager.default.fileExists(atPath: url.path)) {
  518. fileNames.append(url.path)
  519. }
  520. }
  521. }
  522. if(fileNames.count > 0) {
  523. insertFromFilePath(fileNames: fileNames, formDex: 0, indexDex: UInt(index), selectIndexs: []) { newSelectIndexs in
  524. }
  525. return true
  526. }
  527. }
  528. return false
  529. }
  530. func collectionView(_ collectionView: NSCollectionView,
  531. draggingSession session: NSDraggingSession,
  532. endedAt screenPoint: NSPoint,
  533. dragOperation operation: NSDragOperation) {
  534. dragLocalityPages = []
  535. }
  536. }
  537. // MARK: - NSFilePromiseProviderDelegate
  538. extension KMNThumbnailBaseViewController: NSFilePromiseProviderDelegate {
  539. func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
  540. return self.filePromiseQueue
  541. }
  542. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider,
  543. writePromiseTo url: URL,
  544. completionHandler: @escaping (Error?) -> Void) {
  545. do {
  546. /** Copy the file to the location provided to you. You always do a copy, not a move.
  547. It's important you call the completion handler.
  548. */
  549. if let _urlString = dragFilePath, !dragFlag {
  550. dragFlag = true
  551. try FileManager.default.copyItem(at: URL(fileURLWithPath: _urlString), to: url)
  552. }
  553. completionHandler(nil)
  554. } catch let error {
  555. OperationQueue.main.addOperation {
  556. if let win = self.view.window {
  557. self.presentError(error, modalFor: win,
  558. delegate: nil, didPresent: nil, contextInfo: nil)
  559. }
  560. }
  561. completionHandler(error)
  562. }
  563. }
  564. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
  565. var fileName: String = "Untitle"
  566. if let _string = showDocument?.documentURL.deletingPathExtension().lastPathComponent {
  567. fileName = _string
  568. }
  569. fileName.append(" pages")
  570. var indexs = IndexSet()
  571. for page in dragLocalityPages {
  572. indexs.insert(Int(page.pageIndex()))
  573. }
  574. fileName.append(" ")
  575. fileName.append(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  576. fileName.append(".pdf")
  577. return fileName
  578. }
  579. }