KMNThumbnailBaseViewController.swift 28 KB

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