KMThumbnailView.swift 27 KB

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