ScanCollectionView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. //
  2. // ScanCollectionView.swift
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 21/08/18.
  6. // Copyright (c) 2018 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. @available(iOS 11, *)
  25. class DragDropViewController: UIViewController {
  26. //MARK: Private Properties
  27. //Data Source for collectionViewSource
  28. private var itemsSource = [String]()
  29. //Data Source for collectionViewDestination
  30. private var itemsDestination = [String]()
  31. //AppDelegate
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. //MARK: Outlets
  34. @IBOutlet weak var collectionViewSource: UICollectionView!
  35. @IBOutlet weak var collectionViewDestination: UICollectionView!
  36. @IBOutlet weak var cancel: UIBarButtonItem!
  37. @IBOutlet weak var save: UIBarButtonItem!
  38. @IBOutlet weak var add: UIButton!
  39. @IBOutlet weak var labelTitlePDFzone: UILabel!
  40. //MARK: View Lifecycle Methods
  41. override func viewDidLoad() {
  42. super.viewDidLoad()
  43. self.collectionViewSource.dragInteractionEnabled = true
  44. self.collectionViewSource.dragDelegate = self
  45. self.collectionViewSource.dropDelegate = self
  46. self.collectionViewDestination.dragInteractionEnabled = true
  47. self.collectionViewDestination.dropDelegate = self
  48. self.collectionViewDestination.dragDelegate = self
  49. self.collectionViewDestination.reorderingCadence = .fast //default value - .immediate
  50. self.navigationItem.title = NSLocalizedString("_scanned_images_", comment: "")
  51. cancel.title = NSLocalizedString("_cancel_", comment: "")
  52. save.title = NSLocalizedString("_save_", comment: "")
  53. labelTitlePDFzone.text = NSLocalizedString("_scan_label_PDF_zone_", comment: "")
  54. add.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "add"), multiplier:2, color: NCBrandColor.sharedInstance.brand), for: .normal)
  55. }
  56. override func viewWillAppear(_ animated: Bool) {
  57. super.viewWillAppear(animated)
  58. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  59. labelTitlePDFzone.textColor = NCBrandColor.sharedInstance.brandText
  60. labelTitlePDFzone.backgroundColor = NCBrandColor.sharedInstance.brand
  61. loadImage(atPath: CCUtility.getDirectoryScan(), items: &itemsSource)
  62. self.collectionViewSource.reloadData()
  63. }
  64. //MARK: Button Action
  65. @IBAction func cancelAction(sender: UIBarButtonItem) {
  66. self.dismiss(animated: true, completion: nil)
  67. }
  68. @IBAction func saveAction(sender: UIBarButtonItem) {
  69. if itemsDestination.count > 0 {
  70. let formViewController = CreateFormUploadScanDocument.init(serverUrl: appDelegate.activeMain.serverUrl, arrayFileName: self.itemsDestination)
  71. self.navigationController?.pushViewController(formViewController, animated: true)
  72. }
  73. }
  74. @IBAction func add(sender: UIButton) {
  75. NCCreateScanDocument.sharedInstance.openScannerDocument(viewController: self, openScan: false)
  76. }
  77. //MARK: Private Methods
  78. private func loadImage(atPath: String, items: inout [String]) {
  79. items.removeAll()
  80. do {
  81. let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath)
  82. for fileName in directoryContents {
  83. if fileName != "Select" && fileName.first != "." {
  84. items.append(fileName)
  85. }
  86. }
  87. } catch {
  88. print(error.localizedDescription)
  89. }
  90. }
  91. func filter(image: UIImage) -> UIImage? {
  92. let ciImage = CIImage(image: image)!
  93. let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": 1])
  94. let context:CIContext = CIContext.init(options: nil)
  95. let cgImage:CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
  96. let image:UIImage = UIImage.init(cgImage: cgImage)
  97. return image
  98. }
  99. /// This method moves a cell from source indexPath to destination indexPath within the same collection view. It works for only 1 item. If multiple items selected, no reordering happens.
  100. ///
  101. /// - Parameters:
  102. /// - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
  103. /// - destinationIndexPath: indexpath of the collection view where the user drops the element
  104. /// - collectionView: collectionView in which reordering needs to be done.
  105. private func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  106. let items = coordinator.items
  107. if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {
  108. var dIndexPath = destinationIndexPath
  109. if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
  110. dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
  111. }
  112. collectionView.performBatchUpdates({
  113. if collectionView === self.collectionViewDestination {
  114. self.itemsDestination.remove(at: sourceIndexPath.row)
  115. self.itemsDestination.insert(item.dragItem.localObject as! String, at: dIndexPath.row)
  116. } else {
  117. self.itemsSource.remove(at: sourceIndexPath.row)
  118. self.itemsSource.insert(item.dragItem.localObject as! String, at: dIndexPath.row)
  119. }
  120. collectionView.deleteItems(at: [sourceIndexPath])
  121. collectionView.insertItems(at: [dIndexPath])
  122. })
  123. coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
  124. }
  125. }
  126. /// This method copies a cell from source indexPath in 1st collection view to destination indexPath in 2nd collection view. It works for multiple items.
  127. ///
  128. /// - Parameters:
  129. /// - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
  130. /// - destinationIndexPath: indexpath of the collection view where the user drops the element
  131. /// - collectionView: collectionView in which reordering needs to be done.
  132. private func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView)
  133. {
  134. collectionView.performBatchUpdates({
  135. var indexPaths = [IndexPath]()
  136. for (index, item) in coordinator.items.enumerated() {
  137. let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
  138. if collectionView === self.collectionViewDestination {
  139. let fileName = item.dragItem.localObject as! String
  140. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
  141. let fileNamePathTo = CCUtility.getDirectoryScanSelect() + "/" + fileName
  142. guard let data = try? Data(contentsOf: fileNamePathAt.url) else {
  143. return
  144. }
  145. guard let image = UIImage(data: data) else {
  146. return
  147. }
  148. guard let imageFilter = self.filter(image: image) else {
  149. return
  150. }
  151. let imageData = UIImageJPEGRepresentation(imageFilter, 0.5)!
  152. do {
  153. try imageData.write(to: fileNamePathTo.url)
  154. } catch {
  155. return
  156. }
  157. self.itemsDestination.insert(item.dragItem.localObject as! String, at: indexPath.row)
  158. } else {
  159. self.itemsSource.insert(item.dragItem.localObject as! String, at: indexPath.row)
  160. }
  161. indexPaths.append(indexPath)
  162. }
  163. collectionView.insertItems(at: indexPaths)
  164. })
  165. }
  166. }
  167. // MARK: - UICollectionViewDataSource Methods
  168. @available(iOS 11, *)
  169. extension DragDropViewController : UICollectionViewDataSource {
  170. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  171. return collectionView == self.collectionViewSource ? self.itemsSource.count : self.itemsDestination.count
  172. }
  173. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  174. if collectionView == self.collectionViewSource {
  175. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! ScanCell
  176. let fileNamePath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
  177. guard let data = try? Data(contentsOf: fileNamePath.url) else {
  178. return cell
  179. }
  180. cell.customImageView?.image = UIImage(data: data)
  181. // cell.delete.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "no_red"), multiplier:2, color: NCBrandColor.sharedInstance.icon).withRenderingMode(.alwaysOriginal), for: .normal)
  182. cell.delete.addTarget(self, action: #selector(deleteSource(_:)), for: .touchUpInside)
  183. return cell
  184. } else {
  185. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! ScanCell
  186. let fileNamePath = CCUtility.getDirectoryScan() + "/" + self.itemsDestination[indexPath.row]
  187. guard let data = try? Data(contentsOf: fileNamePath.url) else {
  188. return cell
  189. }
  190. guard let image = UIImage(data: data) else {
  191. return cell
  192. }
  193. cell.customImageView?.image = self.filter(image: image)
  194. cell.customLabel.text = NSLocalizedString("_scan_document_pdf_page_", comment: "") + " " + "\(indexPath.row+1)"
  195. // cell.delete.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "no_red"), multiplier:2, color: NCBrandColor.sharedInstance.icon).withRenderingMode(.alwaysOriginal), for: .normal)
  196. cell.delete.addTarget(self, action: #selector(deleteDestination(_:)), for: .touchUpInside)
  197. return cell
  198. }
  199. }
  200. @objc func deleteSource(_ sender: UIButton) {
  201. let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionViewSource)
  202. let indexPath:IndexPath = self.collectionViewSource.indexPathForItem(at: buttonPosition)!
  203. let fileNameAtPath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
  204. CCUtility.removeFile(atPath: fileNameAtPath)
  205. self.itemsSource.remove(at: indexPath.row)
  206. self.collectionViewSource.reloadData()
  207. }
  208. @objc func deleteDestination(_ sender:UIButton) {
  209. let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionViewDestination)
  210. let indexPath:IndexPath = self.collectionViewDestination.indexPathForItem(at: buttonPosition)!
  211. // Remove file only if exist 1 item
  212. var cont = 0
  213. for item in itemsDestination {
  214. if item == self.itemsDestination[indexPath.row] {
  215. cont += 1
  216. }
  217. }
  218. if cont == 1 {
  219. let fileNameAtPath = CCUtility.getDirectoryScanSelect() + "/" + self.itemsDestination[indexPath.row]
  220. CCUtility.removeFile(atPath: fileNameAtPath)
  221. }
  222. self.itemsDestination.remove(at: indexPath.row)
  223. self.collectionViewDestination.reloadData()
  224. }
  225. }
  226. // MARK: - UICollectionViewDragDelegate Methods
  227. @available(iOS 11, *)
  228. extension DragDropViewController : UICollectionViewDragDelegate
  229. {
  230. func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
  231. let item = collectionView == collectionViewSource ? self.itemsSource[indexPath.row] : self.itemsDestination[indexPath.row]
  232. let itemProvider = NSItemProvider(object: item as NSString)
  233. let dragItem = UIDragItem(itemProvider: itemProvider)
  234. dragItem.localObject = item
  235. return [dragItem]
  236. }
  237. func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
  238. let item = collectionView == collectionViewSource ? self.itemsSource[indexPath.row] : self.itemsDestination[indexPath.row]
  239. let itemProvider = NSItemProvider(object: item as NSString)
  240. let dragItem = UIDragItem(itemProvider: itemProvider)
  241. dragItem.localObject = item
  242. return [dragItem]
  243. }
  244. func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
  245. let previewParameters = UIDragPreviewParameters()
  246. if collectionView == self.collectionViewSource {
  247. previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 100, height: 100))
  248. } else {
  249. previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 80, height: 80))
  250. }
  251. return previewParameters
  252. }
  253. }
  254. // MARK: - UICollectionViewDropDelegate Methods
  255. @available(iOS 11, *)
  256. extension DragDropViewController : UICollectionViewDropDelegate {
  257. func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
  258. return session.canLoadObjects(ofClass: NSString.self)
  259. }
  260. func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
  261. if collectionView == self.collectionViewSource {
  262. if collectionView.hasActiveDrag {
  263. return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
  264. } else {
  265. return UICollectionViewDropProposal(operation: .forbidden)
  266. }
  267. } else {
  268. if collectionView.hasActiveDrag {
  269. return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
  270. } else {
  271. return UICollectionViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
  272. }
  273. }
  274. }
  275. func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
  276. let destinationIndexPath: IndexPath
  277. if let indexPath = coordinator.destinationIndexPath {
  278. destinationIndexPath = indexPath
  279. } else {
  280. // Get last index path of table view.
  281. let section = collectionView.numberOfSections - 1
  282. let row = collectionView.numberOfItems(inSection: section)
  283. destinationIndexPath = IndexPath(row: row, section: section)
  284. }
  285. switch coordinator.proposal.operation {
  286. case .move:
  287. self.reorderItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
  288. break
  289. case .copy:
  290. self.copyItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
  291. break
  292. default:
  293. return
  294. }
  295. }
  296. func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) {
  297. self.collectionViewDestination.reloadData()
  298. }
  299. }