KMThumbnailView.swift 27 KB

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