KMThumbnailView.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. //
  2. // KMThumbnailView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/5/4.
  6. //
  7. import Cocoa
  8. @objc enum KMThumbnailViewDragInfoKey: Int {
  9. case dropOperation = 0
  10. case draggingInfo = 1
  11. }
  12. @objc protocol KMThumbnailViewDelegate : NSObjectProtocol {
  13. // layout
  14. @objc optional func thumbnailView(thumbanView: KMThumbnailView, minimumLineSpacingForSectionAt section: Int) -> CGFloat
  15. @objc optional func thumbnailView(thumbanView: KMThumbnailView, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
  16. @objc optional func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets
  17. @objc optional func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize
  18. @objc optional func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int
  19. @objc optional func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem
  20. // Drag & Drop
  21. @objc optional func thumbnailView(thumbanView: KMThumbnailView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexes: IndexSet)
  22. @objc optional func thumbnailView(thumbanView: KMThumbnailView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation)
  23. @objc optional func thumbnailView(thumbanView: KMThumbnailView, canPasteboardWriterForItemAt indexPath: IndexPath) -> Bool
  24. @objc optional func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool
  25. @objc optional func thumbnailView(thumbanView: KMThumbnailView, pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting?
  26. @objc optional func thumbnailView(thumbanView: KMThumbnailView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool
  27. @objc optional func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool
  28. // 本地拖拽
  29. @objc optional func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo:[KMThumbnailViewDragInfoKey.RawValue:Any])
  30. // 外部拖拽
  31. @objc optional func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath)
  32. @objc optional func thumbnailView(thumbanView: KMThumbnailView, didSelectItemAt indexpath: IndexPath, object: AnyObject?)
  33. @objc optional func thumbnailView(thumbanView: KMThumbnailView, rightMouseDidClick indexpath: IndexPath, item: NSCollectionViewItem?, object: AnyObject?)
  34. }
  35. private let _KMThumbnailView_collectionViewDrop_lineViewClassName = "NSCollectionViewDropTargetGapIndicator"
  36. @objc class KMThumbnailView_CollectionView: NSCollectionView {
  37. // 是否点击空白取消选中 默认取消选中
  38. var mouseDownCancelSelected: Bool = true
  39. var hasDragLineView: Bool = true {
  40. didSet {
  41. if (!self.hasDragLineView) {
  42. // 隐藏视图
  43. for view in self.subviews {
  44. guard let lineClass = NSClassFromString(_KMThumbnailView_collectionViewDrop_lineViewClassName) else {
  45. continue
  46. }
  47. if (view.isKind(of: lineClass)) {
  48. // view.frame = NSZeroRect
  49. view.isHidden = true
  50. }
  51. }
  52. }
  53. }
  54. }
  55. override func addSubview(_ view: NSView) {
  56. if (self.hasDragLineView) {
  57. return super.addSubview(view)
  58. }
  59. if let lineClass = NSClassFromString(_KMThumbnailView_collectionViewDrop_lineViewClassName) {
  60. if (view.isKind(of: lineClass)) {
  61. Swift.debugPrint("Find Line View......")
  62. return
  63. } else {
  64. super.addSubview(view)
  65. }
  66. }
  67. super.addSubview(view)
  68. }
  69. override func mouseDown(with event: NSEvent) {
  70. let point = convert(event.locationInWindow, from: nil)
  71. if self.mouseDownCancelSelected {
  72. super.mouseDown(with: event)
  73. } else {
  74. if let indexPath = indexPathForItem(at: point) {
  75. // 用户点击了一个项,处理点击事件
  76. super.mouseDown(with: event)
  77. } else {
  78. // 用户点击了空白区域,不取消选中项
  79. }
  80. }
  81. }
  82. }
  83. @objc class KMThumbnailView: NSView {
  84. open weak var delegate: KMThumbnailViewDelegate?
  85. internal let localForDraggedTypes = kKMLocalForDraggedTypes
  86. internal var dragedIndexPaths: [IndexPath] = []
  87. var kmAllowedFileTypes: [String]?
  88. // 记录拖拽移动后的位置
  89. fileprivate var _dragMoveFlagIndexpath: IndexPath?
  90. fileprivate var _dragMoveFlagIndexs: IndexSet?
  91. // 是否隐藏拖放线 dragMoveEffectAnimated 属性为false才有效
  92. var hasDragLineView: Bool = true {
  93. didSet {
  94. if (!self.dragMoveEffectAnimated) {
  95. self.collectionView_.hasDragLineView = self.hasDragLineView
  96. } else {
  97. self.collectionView_.hasDragLineView = false
  98. }
  99. }
  100. }
  101. // 是否显示拖放移动动效 为true时 hasDragLineView属性设置是
  102. var dragMoveEffectAnimated: Bool = false {
  103. didSet {
  104. self.hasDragLineView = !self.dragMoveEffectAnimated
  105. }
  106. }
  107. override init(frame frameRect: NSRect) {
  108. super.init(frame: frameRect)
  109. self.initDefaultValue()
  110. self.initSubViews()
  111. }
  112. required public init?(coder: NSCoder) {
  113. super.init(coder: coder)
  114. self.initDefaultValue()
  115. self.initSubViews()
  116. }
  117. open var minimumLineSpacing: CGFloat = 0.0 {
  118. didSet {
  119. self.reloadData()
  120. }
  121. }
  122. open var minimumInteritemSpacing: CGFloat = 0.0 {
  123. didSet {
  124. self.reloadData()
  125. }
  126. }
  127. open var itemSize: NSSize = NSMakeSize(60, 80) {
  128. didSet {
  129. self.reloadData()
  130. }
  131. }
  132. open var sectionInset: NSEdgeInsets = NSEdgeInsetsZero {
  133. didSet {
  134. self.reloadData()
  135. }
  136. }
  137. open var numberOfSections: Int = 0 {
  138. didSet {
  139. self.reloadData()
  140. }
  141. }
  142. var selectionIndexPaths: Set<IndexPath> {
  143. get {
  144. return self.collectionView.selectionIndexPaths
  145. }
  146. set {
  147. var indexpaths: Set<IndexPath> = []
  148. for indexpath in newValue {
  149. if (indexpath.section >= self.collectionView.numberOfSections) {
  150. continue
  151. }
  152. if indexpath.section < 0 {
  153. continue
  154. }
  155. if (indexpath.item >= self.collectionView.numberOfItems(inSection: indexpath.section)) {
  156. continue
  157. }
  158. if indexpath.item < 0 {
  159. continue
  160. }
  161. indexpaths.insert(indexpath)
  162. }
  163. self.collectionView.selectionIndexPaths = indexpaths
  164. }
  165. }
  166. // MARK: - Publick Methods
  167. public func initDefaultValue() {
  168. self.collectionView.registerForDraggedTypes([self.localForDraggedTypes, .fileURL,.string,.pdf])
  169. }
  170. public func initSubViews() {
  171. self.addSubview(self.scrollView)
  172. self.scrollView.frame = self.bounds
  173. self.scrollView.autoresizingMask = [.width, .height]
  174. self.scrollView.documentView = self.collectionView
  175. }
  176. // MARK: - register ItemClass
  177. open func register(_ itemClass: AnyClass?) {
  178. guard let itemClass_ = itemClass else {
  179. return
  180. }
  181. self.register(itemClass_, forItemWithIdentifier: NSStringFromClass(itemClass_))
  182. }
  183. open func register(_ itemClass: AnyClass?, forItemWithIdentifier identifier: String) {
  184. self.collectionView.register(itemClass, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: identifier))
  185. }
  186. // MARK: - 刷新UI
  187. public func reloadData(indexs: Set<IndexPath> = []) {
  188. if (indexs.count == 0) {
  189. if (Thread.isMainThread) {
  190. self.collectionView.reloadData()
  191. } else {
  192. DispatchQueue.main.async {
  193. self.collectionView.reloadData()
  194. }
  195. }
  196. } else {
  197. var indexpaths: Set<IndexPath> = []
  198. for index in indexs {
  199. if (index.section >= self.collectionView.numberOfSections) {
  200. continue
  201. }
  202. if (index.item >= self.collectionView.numberOfItems(inSection: index.section)) {
  203. continue
  204. }
  205. indexpaths.insert(index)
  206. }
  207. if (indexpaths.count == 0) {
  208. return
  209. }
  210. if (Thread.isMainThread) {
  211. self.collectionView.reloadItems(at: indexpaths)
  212. } else {
  213. DispatchQueue.main.async {
  214. self.collectionView.reloadItems(at: indexpaths)
  215. }
  216. }
  217. }
  218. }
  219. // MARK: - 属性 【懒加载】
  220. internal lazy var scrollView_: NSScrollView = {
  221. let view = NSScrollView()
  222. view.hasHorizontalScroller = true
  223. view.hasVerticalScroller = true
  224. view.autohidesScrollers = true
  225. view.minMagnification = 1.0
  226. view.scrollerStyle = .overlay
  227. view.wantsLayer = true
  228. view.layer?.backgroundColor = NSColor.clear.cgColor
  229. view.wantsLayer = true
  230. view.contentView.layer?.backgroundColor = .white
  231. return view
  232. }()
  233. var scrollView: NSScrollView {
  234. get {
  235. return self.scrollView_
  236. }
  237. }
  238. internal lazy var collectionView_: KMThumbnailView_CollectionView = {
  239. let view = KMThumbnailView_CollectionView()
  240. view.autoresizingMask = [.width, .height]
  241. let layout = NSCollectionViewFlowLayout()
  242. layout.sectionInset = NSEdgeInsetsMake(8, 15, 8, 15)
  243. layout.minimumLineSpacing = 0
  244. layout.minimumInteritemSpacing = 0
  245. view.collectionViewLayout = layout
  246. view.delegate = self
  247. view.dataSource = self
  248. view.register(NSCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMPDFThumbnailItem"))
  249. view.isSelectable = true
  250. view.wantsLayer = true
  251. view.layer?.backgroundColor = NSColor.km_init(hex: "#F7F8FA").cgColor
  252. return view
  253. }()
  254. var collectionView: KMThumbnailView_CollectionView {
  255. get {
  256. return self.collectionView_
  257. }
  258. }
  259. // MARK: - Private Methods
  260. private func _moveItemForDrag(to toIndexPath: IndexPath) -> Bool {
  261. if (self.dragedIndexPaths.isEmpty) {
  262. Swift.debugPrint("not find selected items.\(self.dragedIndexPaths)")
  263. return false
  264. }
  265. if (self.dragedIndexPaths.contains(toIndexPath) == false) { // 目标位置不在拖放数组里
  266. if (self._dragMoveFlagIndexpath == nil) { // 第一次移动
  267. self.collectionView.animator().moveItem(at: self.dragedIndexPaths.first!, to: toIndexPath)
  268. Swift.debugPrint("moveBegin, \(self.dragedIndexPaths.first!.item)->\(toIndexPath.item)")
  269. // 标记位置
  270. self._dragMoveFlagIndexpath = toIndexPath
  271. return true
  272. } else { // 已有移动
  273. if (self._dragMoveFlagIndexpath! != toIndexPath) {
  274. self.collectionView.animator().moveItem(at: self._dragMoveFlagIndexpath!, to: toIndexPath)
  275. Swift.debugPrint("move..., \(self._dragMoveFlagIndexpath!.item)->\(toIndexPath.item)")
  276. // 标记位置
  277. self._dragMoveFlagIndexpath = toIndexPath
  278. return true
  279. } else {
  280. Swift.debugPrint("drag... ")
  281. }
  282. }
  283. } else if (self._dragMoveFlagIndexpath != nil) { // 目标位置在拖放数组里且已有移动
  284. if (self._dragMoveFlagIndexpath! != toIndexPath) {
  285. self.collectionView.animator().moveItem(at: self._dragMoveFlagIndexpath!, to: toIndexPath)
  286. Swift.debugPrint("move..., \(self._dragMoveFlagIndexpath!.item)->\(toIndexPath.item)")
  287. // 标记位置
  288. self._dragMoveFlagIndexpath = toIndexPath
  289. return true
  290. } else {
  291. Swift.debugPrint("drag... ")
  292. }
  293. }
  294. return false
  295. }
  296. private func _moveItemsForDrag(at itemIndexPaths: Set<IndexPath>, to toIndexPath: IndexPath) -> Bool {
  297. if (itemIndexPaths.isEmpty) {
  298. return false
  299. }
  300. var itemIndexs = IndexSet()
  301. for ip in itemIndexPaths {
  302. itemIndexs.insert(ip.item)
  303. }
  304. return self._moveItemsForDrag(at: itemIndexs, to: toIndexPath.item)
  305. }
  306. private func _moveItemsForDrag(at itemIndexs: IndexSet, to toIndex: Int) -> Bool {
  307. if (itemIndexs.isEmpty) {
  308. return false
  309. }
  310. var flagIndexs = IndexSet()
  311. if (itemIndexs.first! > toIndex) { // 往前拖放
  312. // 3,4 -> 2
  313. // 3->2,4->3
  314. var cnt: Int = 0
  315. for item in itemIndexs {
  316. let indexpath = IndexPath(item: item, section: 0)
  317. let _toIndexPath = IndexPath(item: toIndex+cnt, section: 0)
  318. self.collectionView.animator().moveItem(at: indexpath, to: _toIndexPath)
  319. // 标记位置
  320. flagIndexs.insert(_toIndexPath.item)
  321. cnt += 1
  322. }
  323. } else if (itemIndexs.last! < toIndex) { // 往后拖放
  324. // 1,2 -> 3
  325. // 2->3, 1->2
  326. // 1,2 -> 4
  327. // 2->4, 1->3
  328. // 1,3 -> 4
  329. // 3->4, 1->3
  330. var cnt: Int = 0
  331. for item in itemIndexs.reversed() {
  332. let indexpath = IndexPath(item: item, section: 0)
  333. let _toIndexPath = IndexPath(item: toIndex-cnt, section: 0)
  334. self.collectionView.animator().moveItem(at: indexpath, to: _toIndexPath)
  335. // 标记位置
  336. flagIndexs.insert(_toIndexPath.item)
  337. cnt += 1
  338. }
  339. } else { // 往中间拖放(选中不连续)
  340. // 1,3 -> 2
  341. // 1->2, ...
  342. var cnt: Int = 0
  343. for item in itemIndexs {
  344. let indexpath = IndexPath(item: item, section: 0)
  345. if (cnt == 0) { // 第一个
  346. let _toIndexPath = IndexPath(item: toIndex, section: 0)
  347. self.collectionView.animator().moveItem(at: indexpath, to: _toIndexPath)
  348. flagIndexs.insert(toIndex)
  349. } else { // 第二个...
  350. if (indexpath.item == toIndex + cnt) { // 已在对应的位置
  351. // no doings
  352. flagIndexs.insert(toIndex+cnt)
  353. } else { // 需要移动
  354. let _toIndexPath = IndexPath(item: toIndex+cnt, section: 0)
  355. self.collectionView.animator().moveItem(at: indexpath, to: _toIndexPath)
  356. flagIndexs.insert(_toIndexPath.item)
  357. }
  358. }
  359. cnt += 1
  360. }
  361. }
  362. // 标记位置
  363. self._dragMoveFlagIndexs = flagIndexs
  364. return true
  365. }
  366. private func _doDragMoveEffect(to toIndexPath: IndexPath) -> Bool {
  367. if (self.dragedIndexPaths.isEmpty) {
  368. Swift.debugPrint("not find selected items.\(self.dragedIndexPaths)")
  369. return false
  370. }
  371. if (self.dragedIndexPaths.contains(toIndexPath) == false) { // 目标位置不在拖放数组里
  372. if (self._dragMoveFlagIndexs == nil) { // 第一次移动
  373. var itemIndexPaths = Set<IndexPath>()
  374. for indexpath in self.dragedIndexPaths {
  375. itemIndexPaths.insert(indexpath)
  376. }
  377. return self._moveItemsForDrag(at: itemIndexPaths, to: toIndexPath)
  378. } else { // 已有移动
  379. if (self._dragMoveFlagIndexs!.contains(toIndexPath.item) == false) {
  380. return self._moveItemsForDrag(at: self._dragMoveFlagIndexs!, to: toIndexPath.item)
  381. } else {
  382. Swift.debugPrint("drag... ")
  383. }
  384. }
  385. } else if (self._dragMoveFlagIndexs != nil) { // 目标位置在拖放数组里且已有移动
  386. if (self._dragMoveFlagIndexs!.contains(toIndexPath.item) == false) {
  387. return self._moveItemsForDrag(at: self._dragMoveFlagIndexs!, to: toIndexPath.item)
  388. } else {
  389. Swift.debugPrint("drag... ")
  390. }
  391. }
  392. return false
  393. }
  394. }
  395. // MARK: - NSCollectionViewDataSource, NSCollectionViewDelegate
  396. extension KMThumbnailView: NSCollectionViewDataSource {
  397. public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  398. if let items = self.delegate?.thumbnailView?(thumbanView: self, numberOfItemsInSection: section) {
  399. return items
  400. }
  401. return self.numberOfSections
  402. }
  403. func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  404. if let item = self.delegate?.thumbnailView?(thumbanView: self, itemForRepresentedObjectAt: indexPath) {
  405. return item
  406. }
  407. return NSCollectionViewItem()
  408. }
  409. }
  410. // MARK: - NSCollectionViewDelegate
  411. extension KMThumbnailView: NSCollectionViewDelegate {
  412. func collectionView(_ collectionView: NSCollectionView, shouldSelectItemsAt indexPaths: Set<IndexPath>) -> Set<IndexPath> {
  413. if let lastSelectedIndexPath = collectionView.selectionIndexPaths.first {
  414. if NSApp.currentEvent?.modifierFlags.contains(.shift) == true {
  415. // Shift 键按住,进行连续多选
  416. let selectedIndexPaths = collectionView.selectionIndexPaths
  417. var allIndexPaths = Set<IndexPath>(selectedIndexPaths)
  418. // 获取两个 IndexPath 之间的所有 IndexPath
  419. let startIndex = lastSelectedIndexPath.item
  420. let endIndex = indexPaths.first?.item ?? startIndex
  421. let range = startIndex < endIndex ? startIndex...endIndex : endIndex...startIndex
  422. for index in range {
  423. let indexPath = IndexPath(item: index, section: lastSelectedIndexPath.section)
  424. allIndexPaths.insert(indexPath)
  425. }
  426. return allIndexPaths
  427. }
  428. }
  429. return indexPaths
  430. }
  431. func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {}
  432. func collectionView(_ collectionView: NSCollectionView, shouldDeselectItemsAt indexPaths: Set<IndexPath>) -> Set<IndexPath> {
  433. return indexPaths
  434. }
  435. func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {}
  436. func collectionView(_ collectionView: NSCollectionView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
  437. if let can = self.delegate?.thumbnailView?(thumbanView: self, canDragItemsAt: indexPaths, with: event) {
  438. return can
  439. }
  440. return true
  441. }
  442. func collectionView(_ collectionView: NSCollectionView, writeItemsAt indexPaths: Set<IndexPath>, to pasteboard: NSPasteboard) -> Bool {
  443. let data: Data = try! NSKeyedArchiver.archivedData(withRootObject: indexPaths, requiringSecureCoding: true)
  444. pasteboard.declareTypes([self.localForDraggedTypes], owner: self)
  445. pasteboard.setData(data, forType: self.localForDraggedTypes)
  446. self.dragedIndexPaths.removeAll()
  447. for indexPath in indexPaths {
  448. self.dragedIndexPaths.append(indexPath)
  449. }
  450. return true
  451. }
  452. func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexes: IndexSet) {
  453. self.delegate?.thumbnailView?(thumbanView: self, draggingSession: session, willBeginAt: screenPoint, forItemsAt: indexes)
  454. }
  455. func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
  456. self._dragMoveFlagIndexpath = nil
  457. self._dragMoveFlagIndexs = nil
  458. self.delegate?.thumbnailView?(thumbanView: self, draggingSession: session, endedAt: screenPoint, dragOperation: operation)
  459. }
  460. func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
  461. let pboard = draggingInfo.draggingPasteboard
  462. if (pboard.availableType(from: [self.localForDraggedTypes]) != nil) {
  463. return .move
  464. } else if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  465. if (proposedDropOperation.pointee == .on && self.dragMoveEffectAnimated) {
  466. _ = self._doDragMoveEffect(to: proposedDropIndexPath.pointee as IndexPath)
  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. guard let _allowedFileTypes = self.kmAllowedFileTypes else {
  474. return .generic
  475. }
  476. var hasValidFile = false
  477. for item in pbItems {
  478. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  479. continue
  480. }
  481. let type = _url.pathExtension.lowercased()
  482. if (_allowedFileTypes.contains(type)) {
  483. hasValidFile = true
  484. break
  485. }
  486. }
  487. if (!hasValidFile) {
  488. return NSDragOperation(rawValue: 0)
  489. }
  490. }
  491. return .generic
  492. }
  493. func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  494. if let should = self.delegate?.thumbnailView?(thumbanView: self, shouldAcceptDrop: draggingInfo, indexPath: indexPath, dropOperation: dropOperation), !should {
  495. return should
  496. }
  497. let pboard = draggingInfo.draggingPasteboard
  498. if (pboard.availableType(from: [self.localForDraggedTypes]) != nil) {
  499. let dragInfo = [
  500. KMThumbnailViewDragInfoKey.draggingInfo.rawValue : draggingInfo,
  501. KMThumbnailViewDragInfoKey.dropOperation.rawValue : dropOperation
  502. ] as [Int : Any]
  503. self.delegate?.thumbnailView?(thumbanView: self, didDrag: self.dragedIndexPaths, indexpath: indexPath, dragInfo: dragInfo)
  504. self.dragedIndexPaths.removeAll()
  505. return true
  506. } else if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  507. var _dragIndexpaths = Set<IndexPath>()
  508. draggingInfo.enumerateDraggingItems(
  509. options: NSDraggingItemEnumerationOptions.concurrent,
  510. for: collectionView,
  511. classes: [NSPasteboardItem.self],
  512. searchOptions: [:],
  513. using: {(draggingItem, idx, stop) in
  514. if let pasteboardItem = draggingItem.item as? NSPasteboardItem {
  515. do {
  516. if let indexPathData = pasteboardItem.data(forType: .localDraggedTypes), let _indexPath =
  517. try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(indexPathData) as? IndexPath {
  518. _dragIndexpaths.insert(_indexPath)
  519. }
  520. } catch {
  521. Swift.debugPrint("failed to unarchive indexPath for dropped photo item.")
  522. }
  523. }
  524. })
  525. let dragInfo = [
  526. KMThumbnailViewDragInfoKey.draggingInfo.rawValue : draggingInfo,
  527. KMThumbnailViewDragInfoKey.dropOperation.rawValue : dropOperation
  528. ] as [Int : Any]
  529. self.delegate?.thumbnailView?(thumbanView: self, didDrag: _dragIndexpaths.sorted(), indexpath: indexPath, dragInfo: dragInfo)
  530. self.dragedIndexPaths.removeAll()
  531. return true
  532. } else if ((pboard.availableType(from: [.fileURL])) != nil) {
  533. var array: [URL] = []
  534. for item: NSPasteboardItem in pboard.pasteboardItems! {
  535. let string: String = item.string(forType: NSPasteboard.PasteboardType.fileURL)!
  536. let url = NSURL(string: string)
  537. array.append(url! as URL)
  538. }
  539. self.delegate?.thumbnailView?(thumbanView: self, didDragAddFiles: array, indexpath: indexPath)
  540. return true
  541. }
  542. return false
  543. }
  544. }
  545. // MARK: - NSCollectionViewDelegateFlowLayout
  546. extension KMThumbnailView: NSCollectionViewDelegateFlowLayout {
  547. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
  548. if let size_ = self.delegate?.thumbnailView?(thumbanView: self, sizeForItemAt: indexPath) {
  549. return size_
  550. }
  551. return self.itemSize
  552. }
  553. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  554. if let minimumLineSpacing_ = self.delegate?.thumbnailView?(thumbanView: self, minimumLineSpacingForSectionAt: section) {
  555. return minimumLineSpacing_
  556. }
  557. return self.minimumLineSpacing
  558. }
  559. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  560. if let minimumInteritemSpacing_ = self.delegate?.thumbnailView?(thumbanView: self, minimumInteritemSpacingForSectionAt: section) {
  561. return minimumInteritemSpacing_
  562. }
  563. return self.minimumInteritemSpacing
  564. }
  565. func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
  566. if let inset = self.delegate?.thumbnailView?(thumbanView: self, insetForSectionAt: section) {
  567. return inset
  568. }
  569. return self.sectionInset
  570. }
  571. }