ScanCollectionView.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. //Data Source for collectionViewSource
  27. private var itemsSource = [String]()
  28. //Data Source for collectionViewDestination
  29. private var imagesDestination = [UIImage]()
  30. //AppDelegate
  31. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. //MARK: Outlets
  33. @IBOutlet weak var collectionViewSource: UICollectionView!
  34. @IBOutlet weak var collectionViewDestination: UICollectionView!
  35. @IBOutlet weak var cancel: UIBarButtonItem!
  36. @IBOutlet weak var save: UIBarButtonItem!
  37. @IBOutlet weak var add: UIButton!
  38. @IBOutlet weak var labelTitlePDFzone: UILabel!
  39. @IBOutlet weak var segmentControlFilter: UISegmentedControl!
  40. // filter
  41. private var filterGrayscale = true;
  42. //MARK: View Lifecycle Methods
  43. override func viewDidLoad() {
  44. super.viewDidLoad()
  45. self.collectionViewSource.dragInteractionEnabled = true
  46. self.collectionViewSource.dragDelegate = self
  47. self.collectionViewSource.dropDelegate = self
  48. self.collectionViewDestination.dragInteractionEnabled = true
  49. self.collectionViewDestination.dropDelegate = self
  50. self.collectionViewDestination.dragDelegate = self
  51. self.collectionViewDestination.reorderingCadence = .fast //default value - .immediate
  52. self.navigationItem.title = NSLocalizedString("_scanned_images_", comment: "")
  53. cancel.title = NSLocalizedString("_cancel_", comment: "")
  54. save.title = NSLocalizedString("_save_", comment: "")
  55. labelTitlePDFzone.text = NSLocalizedString("_scan_label_PDF_zone_", comment: "")
  56. segmentControlFilter.setTitle(NSLocalizedString("_filter_grayscale_", comment: ""), forSegmentAt: 0)
  57. segmentControlFilter.setTitle(NSLocalizedString("_filter_original_", comment: ""), forSegmentAt: 1)
  58. add.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "add"), multiplier:2, color: NCBrandColor.sharedInstance.brand), for: .normal)
  59. }
  60. override func viewWillAppear(_ animated: Bool) {
  61. super.viewWillAppear(animated)
  62. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  63. labelTitlePDFzone.textColor = NCBrandColor.sharedInstance.brandText
  64. labelTitlePDFzone.backgroundColor = NCBrandColor.sharedInstance.brand
  65. segmentControlFilter.tintColor = NCBrandColor.sharedInstance.brand
  66. // Save button
  67. if imagesDestination.count == 0 {
  68. save.isEnabled = false
  69. } else {
  70. save.isEnabled = true
  71. }
  72. loadImage(atPath: CCUtility.getDirectoryScan(), items: &itemsSource)
  73. self.collectionViewSource.reloadData()
  74. }
  75. //MARK: Button Action
  76. @IBAction func cancelAction(sender: UIBarButtonItem) {
  77. self.dismiss(animated: true, completion: nil)
  78. }
  79. @IBAction func saveAction(sender: UIBarButtonItem) {
  80. if imagesDestination.count > 0 {
  81. var images = [UIImage]()
  82. for image in imagesDestination {
  83. images.append(filter(image: image)!)
  84. }
  85. let formViewController = CreateFormUploadScanDocument.init(serverUrl: appDelegate.activeMain.serverUrl, arrayImages: images)
  86. self.navigationController?.pushViewController(formViewController, animated: true)
  87. }
  88. }
  89. @IBAction func add(sender: UIButton) {
  90. NCCreateScanDocument.sharedInstance.openScannerDocument(viewController: self, openScan: false)
  91. }
  92. @IBAction func indexChanged(_ sender: AnyObject) {
  93. switch segmentControlFilter.selectedSegmentIndex
  94. {
  95. case 0:
  96. // Grayscale
  97. filterGrayscale = true
  98. case 1:
  99. // Original
  100. filterGrayscale = false
  101. default:
  102. break
  103. }
  104. self.collectionViewDestination.reloadData()
  105. }
  106. //MARK: Private Methods
  107. private func loadImage(atPath: String, items: inout [String]) {
  108. items.removeAll()
  109. do {
  110. let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath)
  111. for fileName in directoryContents {
  112. if fileName != "Select" && fileName.first != "." {
  113. items.append(fileName)
  114. }
  115. }
  116. } catch {
  117. print(error.localizedDescription)
  118. }
  119. }
  120. func filter(image: UIImage) -> UIImage? {
  121. if filterGrayscale == false {
  122. return image
  123. }
  124. let ciImage = CIImage(image: image)!
  125. let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": 1])
  126. let context:CIContext = CIContext.init(options: nil)
  127. let cgImage:CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
  128. let image:UIImage = UIImage.init(cgImage: cgImage)
  129. return image
  130. }
  131. /// 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.
  132. ///
  133. /// - Parameters:
  134. /// - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
  135. /// - destinationIndexPath: indexpath of the collection view where the user drops the element
  136. /// - collectionView: collectionView in which reordering needs to be done.
  137. private func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  138. let items = coordinator.items
  139. if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {
  140. var dIndexPath = destinationIndexPath
  141. if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
  142. dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
  143. }
  144. collectionView.performBatchUpdates({
  145. if collectionView === self.collectionViewDestination {
  146. self.imagesDestination.remove(at: sourceIndexPath.row)
  147. self.imagesDestination.insert(item.dragItem.localObject as! UIImage, at: dIndexPath.row)
  148. } else {
  149. self.itemsSource.remove(at: sourceIndexPath.row)
  150. self.itemsSource.insert(item.dragItem.localObject as! String, at: dIndexPath.row)
  151. }
  152. collectionView.deleteItems(at: [sourceIndexPath])
  153. collectionView.insertItems(at: [dIndexPath])
  154. })
  155. coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
  156. }
  157. }
  158. /// This method copies a cell from source indexPath in 1st collection view to destination indexPath in 2nd collection view. It works for multiple items.
  159. ///
  160. /// - Parameters:
  161. /// - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
  162. /// - destinationIndexPath: indexpath of the collection view where the user drops the element
  163. /// - collectionView: collectionView in which reordering needs to be done.
  164. private func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView)
  165. {
  166. collectionView.performBatchUpdates({
  167. var indexPaths = [IndexPath]()
  168. for (index, item) in coordinator.items.enumerated() {
  169. let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
  170. if collectionView === self.collectionViewDestination {
  171. let fileName = item.dragItem.localObject as! NSString
  172. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + (fileName as String)
  173. guard let data = try? Data(contentsOf: fileNamePathAt.url) else {
  174. return
  175. }
  176. guard let image = UIImage(data: data) else {
  177. return
  178. }
  179. self.imagesDestination.insert(image, at: indexPath.row)
  180. } else {
  181. // NOT PERMITTED
  182. return
  183. }
  184. indexPaths.append(indexPath)
  185. }
  186. collectionView.insertItems(at: indexPaths)
  187. })
  188. }
  189. }
  190. // MARK: - UICollectionViewDataSource Methods
  191. @available(iOS 11, *)
  192. extension DragDropViewController : UICollectionViewDataSource {
  193. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  194. return collectionView == self.collectionViewSource ? self.itemsSource.count : self.imagesDestination.count
  195. }
  196. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  197. if collectionView == self.collectionViewSource {
  198. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! ScanCell
  199. let fileNamePath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
  200. guard let data = try? Data(contentsOf: fileNamePath.url) else {
  201. return cell
  202. }
  203. cell.customImageView?.image = UIImage(data: data)
  204. // cell.delete.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "no_red"), multiplier:2, color: NCBrandColor.sharedInstance.icon).withRenderingMode(.alwaysOriginal), for: .normal)
  205. cell.delete.addTarget(self, action: #selector(deleteSource(_:)), for: .touchUpInside)
  206. return cell
  207. } else {
  208. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! ScanCell
  209. let image = self.imagesDestination[indexPath.row]
  210. cell.customImageView?.image = self.filter(image: image)
  211. cell.customLabel.text = NSLocalizedString("_scan_document_pdf_page_", comment: "") + " " + "\(indexPath.row+1)"
  212. // cell.delete.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "no_red"), multiplier:2, color: NCBrandColor.sharedInstance.icon).withRenderingMode(.alwaysOriginal), for: .normal)
  213. cell.delete.addTarget(self, action: #selector(deleteDestination(_:)), for: .touchUpInside)
  214. return cell
  215. }
  216. }
  217. @objc func deleteSource(_ sender: UIButton) {
  218. let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionViewSource)
  219. let indexPath:IndexPath = self.collectionViewSource.indexPathForItem(at: buttonPosition)!
  220. let fileNameAtPath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
  221. CCUtility.removeFile(atPath: fileNameAtPath)
  222. self.itemsSource.remove(at: indexPath.row)
  223. self.collectionViewSource.reloadData()
  224. }
  225. @objc func deleteDestination(_ sender:UIButton) {
  226. let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionViewDestination)
  227. let indexPath:IndexPath = self.collectionViewDestination.indexPathForItem(at: buttonPosition)!
  228. self.imagesDestination.remove(at: indexPath.row)
  229. self.collectionViewDestination.reloadData()
  230. // Save button
  231. if imagesDestination.count == 0 {
  232. save.isEnabled = false
  233. } else {
  234. save.isEnabled = true
  235. }
  236. }
  237. }
  238. // MARK: - UICollectionViewDragDelegate Methods
  239. @available(iOS 11, *)
  240. extension DragDropViewController : UICollectionViewDragDelegate
  241. {
  242. func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
  243. if collectionView == self.collectionViewSource {
  244. let item = self.itemsSource[indexPath.row]
  245. let itemProvider = NSItemProvider(object: item as NSString)
  246. let dragItem = UIDragItem(itemProvider: itemProvider)
  247. dragItem.localObject = item
  248. return [dragItem]
  249. } else {
  250. let item = self.imagesDestination[indexPath.row]
  251. let itemProvider = NSItemProvider(object: item as UIImage)
  252. let dragItem = UIDragItem(itemProvider: itemProvider)
  253. dragItem.localObject = item
  254. return [dragItem]
  255. }
  256. }
  257. func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
  258. if collectionView == self.collectionViewSource {
  259. let item = self.itemsSource[indexPath.row]
  260. let itemProvider = NSItemProvider(object: item as NSString)
  261. let dragItem = UIDragItem(itemProvider: itemProvider)
  262. dragItem.localObject = item
  263. return [dragItem]
  264. } else {
  265. let item = self.imagesDestination[indexPath.row]
  266. let itemProvider = NSItemProvider(object: item as UIImage)
  267. let dragItem = UIDragItem(itemProvider: itemProvider)
  268. dragItem.localObject = item
  269. return [dragItem]
  270. }
  271. }
  272. func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
  273. let previewParameters = UIDragPreviewParameters()
  274. if collectionView == self.collectionViewSource {
  275. previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 100, height: 100))
  276. } else {
  277. previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 80, height: 80))
  278. }
  279. return previewParameters
  280. }
  281. }
  282. // MARK: - UICollectionViewDropDelegate Methods
  283. @available(iOS 11, *)
  284. extension DragDropViewController : UICollectionViewDropDelegate {
  285. func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
  286. return true //session.canLoadObjects(ofClass: NSString.self)
  287. }
  288. func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
  289. if collectionView == self.collectionViewSource {
  290. if collectionView.hasActiveDrag {
  291. return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
  292. } else {
  293. return UICollectionViewDropProposal(operation: .forbidden)
  294. }
  295. } else {
  296. if collectionView.hasActiveDrag {
  297. return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
  298. } else {
  299. return UICollectionViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
  300. }
  301. }
  302. }
  303. func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
  304. let destinationIndexPath: IndexPath
  305. if let indexPath = coordinator.destinationIndexPath {
  306. destinationIndexPath = indexPath
  307. } else {
  308. // Get last index path of table view.
  309. let section = collectionView.numberOfSections - 1
  310. let row = collectionView.numberOfItems(inSection: section)
  311. destinationIndexPath = IndexPath(row: row, section: section)
  312. }
  313. switch coordinator.proposal.operation {
  314. case .move:
  315. self.reorderItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
  316. break
  317. case .copy:
  318. self.copyItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
  319. break
  320. default:
  321. return
  322. }
  323. }
  324. func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) {
  325. self.collectionViewDestination.reloadData()
  326. // Save button
  327. if imagesDestination.count == 0 {
  328. save.isEnabled = false
  329. } else {
  330. save.isEnabled = true
  331. }
  332. }
  333. }