KMNThumbnailBaseViewController.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. for i in pageIndexs {
  248. if i < currentDocument?.pageCount ?? 0 {
  249. let thumbnail = KMNThumbnail.init(document: currentDocument!, currentPageIndex: i)
  250. thumbnail.removeCacheImage()
  251. }
  252. }
  253. reloadDatas()
  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. let indexpathsz = collectionView.selectionIndexPaths
  350. let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz)
  351. let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
  352. thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz, selectionStrings: selectedIndexPathsString)
  353. }
  354. }
  355. func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
  356. if isChangeIndexPaths == false {
  357. let indexpathsz = self.collectionView.selectionIndexPaths
  358. let dex:IndexSet = KMNTools.indexpathsToIndexs(indexpaths: indexpathsz)
  359. let selectedIndexPathsString = KMNTools.parseIndexSet(indexSet: dex)
  360. thumbnailBaseViewDelegate?.changeIndexPathsThumbnailViewControlle?(pageEditVC: self, selectionIndexPaths: indexpathsz, selectionStrings: selectedIndexPathsString)
  361. }
  362. }
  363. // MARK: - NSCollectionViewDelegateFlowLayout
  364. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  365. return pageThumbnailSize
  366. }
  367. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  368. return 16.0
  369. }
  370. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  371. return 24.0
  372. }
  373. public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
  374. return NSEdgeInsetsMake(24.0, 24.0, 24.0, 24.0)
  375. }
  376. //MARK: - NSCollectionViewDelegate
  377. func collectionView(_ collectionView: NSCollectionView,
  378. pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
  379. var provider: NSFilePromiseProvider?
  380. // 创建数据提供者
  381. let fileExtension = "pdf"
  382. if #available(macOS 11.0, *) {
  383. if let typeIdentifier = UTType(filenameExtension: fileExtension) {
  384. provider = KMFilePromiseProvider(fileType: typeIdentifier.identifier, delegate: self)
  385. }
  386. } else {
  387. if let typeIdentifier =
  388. UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil) {
  389. provider = KMFilePromiseProvider(fileType: typeIdentifier.takeRetainedValue() as String, delegate: self)
  390. }
  391. }
  392. do {
  393. if let _url = showDocument?.documentURL {
  394. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  395. provider?.userInfo = [KMFilePromiseProvider.UserInfoKeys.urlKey: _url,
  396. KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  397. } else {
  398. let data = try NSKeyedArchiver.archivedData(withRootObject: indexPath, requiringSecureCoding: false)
  399. provider?.userInfo = [KMFilePromiseProvider.UserInfoKeys.indexPathKey: data]
  400. }
  401. } catch {
  402. fatalError("failed to archive indexPath to pasteboard")
  403. }
  404. return provider
  405. }
  406. func collectionView(_ collectionView: NSCollectionView,
  407. draggingSession session: NSDraggingSession,
  408. willBeginAt screenPoint: NSPoint,
  409. forItemsAt indexPaths: Set<IndexPath>) {
  410. let sortedIndexPaths = indexPaths.sorted { (ip1, ip2) -> Bool in
  411. if ip1.section == ip2.section {
  412. return ip1.item < ip2.item
  413. }
  414. return ip1.section < ip2.section
  415. }
  416. dragLocalityPages = []
  417. for fromIndexPath in sortedIndexPaths {
  418. let page = thumbnails[fromIndexPath.item].thumbnaiPage
  419. if(page != nil) {
  420. dragLocalityPages.append(page!)
  421. }
  422. }
  423. var docmentName = currentDocument?.documentURL.lastPathComponent.deletingPathExtension ?? ""
  424. let pagesName = indexPaths.count > 1 ? " pages" : " page"
  425. var tFileName = pagesName + KMNTools.parseIndexPathsSet(indexSets: collectionView.selectionIndexPaths)
  426. if tFileName.count > 50 {
  427. tFileName = String(tFileName.prefix(50))
  428. }
  429. let cachesDir = dragTempFloderPath
  430. let fileManager = FileManager.default
  431. if !fileManager.fileExists(atPath: cachesDir) {
  432. try? FileManager.default.createDirectory(atPath: cachesDir, withIntermediateDirectories: true, attributes: nil)
  433. }
  434. docmentName = "\(docmentName)\(tFileName)"
  435. if docmentName.count > 50 {
  436. docmentName = String(docmentName.prefix(50))
  437. }
  438. // 将拖拽的page插入临时路径(文档)
  439. var indexs = IndexSet()
  440. for indexpath in indexPaths {
  441. indexs.insert(indexpath.item)
  442. }
  443. // 重置拖拽标识
  444. self.dragFlag = false
  445. if (indexs.count > 0) {
  446. let writePDFDocument = CPDFDocument()
  447. writePDFDocument?.importPages(indexs, from: self.showDocument, at: 0)
  448. let tFileName = docmentName + ".pdf"
  449. let filePathtPath = cachesDir + tFileName
  450. let success = writePDFDocument?.write(to: NSURL(fileURLWithPath: filePathtPath) as URL?, isSaveFontSubset:false)
  451. if(success == true) {
  452. let tFilePath = self.dragTempFloderPath.stringByAppendingPathComponent("drag_tmp.pdf")
  453. if FileManager.default.fileExists(atPath: tFilePath) {
  454. try? FileManager.default.removeItem(atPath: tFilePath)
  455. }
  456. try? FileManager.default.copyItem(atPath: filePathtPath, toPath: tFilePath)
  457. self.dragFilePath = filePathtPath
  458. }
  459. }
  460. }
  461. func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
  462. let pboard = draggingInfo.draggingPasteboard
  463. if dragLocalityPages.count != 0 {
  464. if proposedDropOperation.pointee == .on {
  465. proposedDropOperation.pointee = .before
  466. }
  467. return .move
  468. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  469. guard let pbItems = pboard.pasteboardItems else {
  470. return NSDragOperation(rawValue: 0)
  471. }
  472. var hasValidFile = false
  473. for item in pbItems {
  474. guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
  475. continue
  476. }
  477. let type = url.pathExtension.lowercased()
  478. if (supportDragFileTypes().contains(type)) {
  479. hasValidFile = true
  480. break
  481. }
  482. }
  483. if (!hasValidFile) {
  484. return NSDragOperation(rawValue: 0)
  485. }
  486. }
  487. return .copy
  488. }
  489. func collectionView(_ collectionView: NSCollectionView,
  490. acceptDrop draggingInfo: NSDraggingInfo,
  491. indexPath: IndexPath,
  492. dropOperation: NSCollectionView.DropOperation) -> Bool {
  493. let pboard = draggingInfo.draggingPasteboard
  494. if dragLocalityPages.count != 0 {
  495. movePages(dragPages: dragLocalityPages, destinationDex: indexPath.item)
  496. return true
  497. } else if(pboard.availableType(from: [.localDraggedTypes]) != nil) {
  498. let index = indexPath.item
  499. if let _urlString = self.dragTempFilePath {
  500. insertFromFilePath(fileNames: [_urlString], formDex: 0, indexDex: UInt(index), selectIndexs: []) { newSelectIndexs in
  501. }
  502. }
  503. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  504. let index = indexPath.item
  505. guard let pbItems = pboard.pasteboardItems else {
  506. return false
  507. }
  508. //获取url
  509. var fileNames: [String] = []
  510. for item in pbItems {
  511. guard let data = item.string(forType: .fileURL), let url = URL(string: data) else {
  512. continue
  513. }
  514. let type = url.pathExtension.lowercased()
  515. if (supportDragFileTypes().contains(type)) {
  516. if(FileManager.default.fileExists(atPath: url.path)) {
  517. fileNames.append(url.path)
  518. }
  519. }
  520. }
  521. if(fileNames.count > 0) {
  522. insertFromFilePath(fileNames: fileNames, formDex: 0, indexDex: UInt(index), selectIndexs: []) { newSelectIndexs in
  523. }
  524. return true
  525. }
  526. }
  527. return false
  528. }
  529. func collectionView(_ collectionView: NSCollectionView,
  530. draggingSession session: NSDraggingSession,
  531. endedAt screenPoint: NSPoint,
  532. dragOperation operation: NSDragOperation) {
  533. dragLocalityPages = []
  534. }
  535. }
  536. // MARK: - NSFilePromiseProviderDelegate
  537. extension KMNThumbnailBaseViewController: NSFilePromiseProviderDelegate {
  538. func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
  539. return self.filePromiseQueue
  540. }
  541. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider,
  542. writePromiseTo url: URL,
  543. completionHandler: @escaping (Error?) -> Void) {
  544. do {
  545. /** Copy the file to the location provided to you. You always do a copy, not a move.
  546. It's important you call the completion handler.
  547. */
  548. if let _urlString = dragFilePath, !dragFlag {
  549. dragFlag = true
  550. try FileManager.default.copyItem(at: URL(fileURLWithPath: _urlString), to: url)
  551. }
  552. completionHandler(nil)
  553. } catch let error {
  554. OperationQueue.main.addOperation {
  555. if let win = self.view.window {
  556. self.presentError(error, modalFor: win,
  557. delegate: nil, didPresent: nil, contextInfo: nil)
  558. }
  559. }
  560. completionHandler(error)
  561. }
  562. }
  563. func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
  564. var fileName: String = "Untitle"
  565. if let _string = showDocument?.documentURL.deletingPathExtension().lastPathComponent {
  566. fileName = _string
  567. }
  568. fileName.append(" pages")
  569. var indexs = IndexSet()
  570. for page in dragLocalityPages {
  571. indexs.insert(Int(page.pageIndex()))
  572. }
  573. fileName.append(" ")
  574. fileName.append(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  575. fileName.append(".pdf")
  576. return fileName
  577. }
  578. }