ScanCollectionView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. enum typeFilter {
  42. case original
  43. case grayScale
  44. case bn
  45. }
  46. private var filter: typeFilter = typeFilter.grayScale
  47. override var canBecomeFirstResponder: Bool { return true }
  48. //MARK: View Lifecycle Methods
  49. override func viewDidLoad() {
  50. super.viewDidLoad()
  51. self.collectionViewSource.dragInteractionEnabled = true
  52. self.collectionViewSource.dragDelegate = self
  53. self.collectionViewSource.dropDelegate = self
  54. self.collectionViewDestination.dragInteractionEnabled = true
  55. self.collectionViewDestination.dropDelegate = self
  56. self.collectionViewDestination.dragDelegate = self
  57. self.collectionViewDestination.reorderingCadence = .fast //default value - .immediate
  58. self.navigationItem.title = NSLocalizedString("_scanned_images_", comment: "")
  59. cancel.title = NSLocalizedString("_cancel_", comment: "")
  60. save.title = NSLocalizedString("_save_", comment: "")
  61. labelTitlePDFzone.text = NSLocalizedString("_scan_label_document_zone_", comment: "")
  62. segmentControlFilter.setTitle(NSLocalizedString("_filter_grayscale_", comment: ""), forSegmentAt: 0)
  63. segmentControlFilter.setTitle(NSLocalizedString("_filter_bn_", comment: ""), forSegmentAt: 1)
  64. segmentControlFilter.setTitle(NSLocalizedString("_filter_original_", comment: ""), forSegmentAt: 2)
  65. add.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "add"), multiplier:2, color: NCBrandColor.sharedInstance.brand), for: .normal)
  66. let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
  67. add.addGestureRecognizer(longPressRecognizer)
  68. }
  69. override func viewWillAppear(_ animated: Bool) {
  70. super.viewWillAppear(animated)
  71. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  72. labelTitlePDFzone.textColor = NCBrandColor.sharedInstance.brandText
  73. labelTitlePDFzone.backgroundColor = NCBrandColor.sharedInstance.brand
  74. segmentControlFilter.tintColor = NCBrandColor.sharedInstance.brand
  75. // Save button
  76. if imagesDestination.count == 0 {
  77. save.isEnabled = false
  78. } else {
  79. save.isEnabled = true
  80. }
  81. loadImage(atPath: CCUtility.getDirectoryScan(), items: &itemsSource)
  82. }
  83. //MARK: Button Action
  84. @IBAction func cancelAction(sender: UIBarButtonItem) {
  85. self.dismiss(animated: true, completion: nil)
  86. }
  87. @IBAction func saveAction(sender: UIBarButtonItem) {
  88. if imagesDestination.count > 0 {
  89. var images = [UIImage]()
  90. for image in imagesDestination {
  91. images.append(filter(image: image)!)
  92. }
  93. let formViewController = CreateFormUploadScanDocument.init(serverUrl: appDelegate.activeMain.serverUrl, arrayImages: images)
  94. self.navigationController?.pushViewController(formViewController, animated: true)
  95. }
  96. }
  97. @IBAction func add(sender: UIButton) {
  98. NCCreateScanDocument.sharedInstance.openScannerDocument(viewController: self, openScan: false)
  99. }
  100. @IBAction func indexChanged(_ sender: AnyObject) {
  101. switch segmentControlFilter.selectedSegmentIndex
  102. {
  103. case 0:
  104. // Grayscale
  105. filter = typeFilter.grayScale
  106. case 1:
  107. // Original
  108. filter = typeFilter.bn
  109. case 2:
  110. // Original
  111. filter = typeFilter.original
  112. default:
  113. break
  114. }
  115. self.collectionViewDestination.reloadData()
  116. }
  117. //MARK: Private Methods
  118. private func loadImage(atPath: String, items: inout [String]) {
  119. items.removeAll()
  120. do {
  121. let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath)
  122. for fileName in directoryContents {
  123. if fileName.first != "." {
  124. items.append(fileName)
  125. }
  126. }
  127. } catch {
  128. print(error.localizedDescription)
  129. }
  130. self.collectionViewSource.reloadData()
  131. }
  132. func filter(image: UIImage) -> UIImage? {
  133. var inputContrast: Double = 0
  134. if filter == typeFilter.original {
  135. return image
  136. }
  137. if filter == typeFilter.grayScale {
  138. inputContrast = 1
  139. }
  140. if filter == typeFilter.bn {
  141. inputContrast = 4
  142. }
  143. let ciImage = CIImage(image: image)!
  144. let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": inputContrast])
  145. let context:CIContext = CIContext.init(options: nil)
  146. let cgImage:CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
  147. let image:UIImage = UIImage.init(cgImage: cgImage)
  148. return image
  149. }
  150. /// 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.
  151. ///
  152. /// - Parameters:
  153. /// - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
  154. /// - destinationIndexPath: indexpath of the collection view where the user drops the element
  155. /// - collectionView: collectionView in which reordering needs to be done.
  156. private func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  157. let items = coordinator.items
  158. if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {
  159. var dIndexPath = destinationIndexPath
  160. if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
  161. dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
  162. }
  163. collectionView.performBatchUpdates({
  164. if collectionView === self.collectionViewDestination {
  165. self.imagesDestination.remove(at: sourceIndexPath.row)
  166. self.imagesDestination.insert(item.dragItem.localObject as! UIImage, at: dIndexPath.row)
  167. } else {
  168. self.itemsSource.remove(at: sourceIndexPath.row)
  169. self.itemsSource.insert(item.dragItem.localObject as! String, at: dIndexPath.row)
  170. }
  171. collectionView.deleteItems(at: [sourceIndexPath])
  172. collectionView.insertItems(at: [dIndexPath])
  173. })
  174. coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
  175. }
  176. }
  177. /// This method copies a cell from source indexPath in 1st collection view to destination indexPath in 2nd collection view. It works for multiple items.
  178. ///
  179. /// - Parameters:
  180. /// - coordinator: coordinator obtained from performDropWith: UICollectionViewDropDelegate method
  181. /// - destinationIndexPath: indexpath of the collection view where the user drops the element
  182. /// - collectionView: collectionView in which reordering needs to be done.
  183. private func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView)
  184. {
  185. collectionView.performBatchUpdates({
  186. var indexPaths = [IndexPath]()
  187. for (index, item) in coordinator.items.enumerated() {
  188. let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
  189. if collectionView === self.collectionViewDestination {
  190. let fileName = item.dragItem.localObject as! NSString
  191. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + (fileName as String)
  192. guard let data = try? Data(contentsOf: fileNamePathAt.url) else {
  193. return
  194. }
  195. guard let image = UIImage(data: data) else {
  196. return
  197. }
  198. self.imagesDestination.insert(image, at: indexPath.row)
  199. } else {
  200. // NOT PERMITTED
  201. return
  202. }
  203. indexPaths.append(indexPath)
  204. }
  205. collectionView.insertItems(at: indexPaths)
  206. })
  207. }
  208. // MARK: - UIGestureRecognizerv - Paste
  209. @objc func handleLongPressGesture(recognizer: UIGestureRecognizer) {
  210. if recognizer.state == UIGestureRecognizer.State.began {
  211. self.becomeFirstResponder()
  212. let pasteboard = UIPasteboard.general
  213. if let recognizerView = recognizer.view, let recognizerSuperView = recognizerView.superview, pasteboard.hasImages {
  214. UIMenuController.shared.menuItems = [UIMenuItem(title: "Paste", action: #selector(pasteImage))]
  215. UIMenuController.shared.setTargetRect(recognizerView.frame, in: recognizerSuperView)
  216. UIMenuController.shared.setMenuVisible(true, animated:true)
  217. }
  218. }
  219. }
  220. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  221. if action == #selector(pasteImage) {
  222. return true
  223. }
  224. return false
  225. }
  226. @objc func pasteImage() {
  227. let pasteboard = UIPasteboard.general
  228. if pasteboard.hasImages {
  229. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)!
  230. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  231. guard var image = pasteboard.image else {
  232. return
  233. }
  234. // A4 74 DPI : 595 x 842 px
  235. let imageWidthInPixels = image.size.width * image.scale
  236. let imageHeightInPixels = image.size.height * image.scale
  237. if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
  238. image = CCGraphics.scale(image, to: CGSize(width: 595, height: 842), isAspectRation: true)
  239. }
  240. do {
  241. try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  242. } catch {
  243. return
  244. }
  245. loadImage(atPath: CCUtility.getDirectoryScan(), items: &itemsSource)
  246. }
  247. }
  248. }
  249. // MARK: - UICollectionViewDataSource Methods
  250. @available(iOS 11, *)
  251. extension DragDropViewController : UICollectionViewDataSource {
  252. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  253. return collectionView == self.collectionViewSource ? self.itemsSource.count : self.imagesDestination.count
  254. }
  255. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  256. if collectionView == self.collectionViewSource {
  257. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! ScanCell
  258. let fileNamePath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
  259. guard let data = try? Data(contentsOf: fileNamePath.url) else {
  260. return cell
  261. }
  262. cell.customImageView?.image = UIImage(data: data)
  263. // cell.delete.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "no_red"), multiplier:2, color: NCBrandColor.sharedInstance.icon).withRenderingMode(.alwaysOriginal), for: .normal)
  264. cell.delete.addTarget(self, action: #selector(deleteSource(_:)), for: .touchUpInside)
  265. return cell
  266. } else {
  267. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! ScanCell
  268. let image = self.imagesDestination[indexPath.row]
  269. cell.customImageView?.image = self.filter(image: image)
  270. cell.customLabel.text = NSLocalizedString("_scan_document_pdf_page_", comment: "") + " " + "\(indexPath.row+1)"
  271. // cell.delete.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "no_red"), multiplier:2, color: NCBrandColor.sharedInstance.icon).withRenderingMode(.alwaysOriginal), for: .normal)
  272. cell.delete.addTarget(self, action: #selector(deleteDestination(_:)), for: .touchUpInside)
  273. return cell
  274. }
  275. }
  276. @objc func deleteSource(_ sender: UIButton) {
  277. let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionViewSource)
  278. let indexPath:IndexPath = self.collectionViewSource.indexPathForItem(at: buttonPosition)!
  279. let fileNameAtPath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row]
  280. CCUtility.removeFile(atPath: fileNameAtPath)
  281. self.itemsSource.remove(at: indexPath.row)
  282. self.collectionViewSource.reloadData()
  283. }
  284. @objc func deleteDestination(_ sender:UIButton) {
  285. let buttonPosition:CGPoint = sender.convert(.zero, to: self.collectionViewDestination)
  286. let indexPath:IndexPath = self.collectionViewDestination.indexPathForItem(at: buttonPosition)!
  287. self.imagesDestination.remove(at: indexPath.row)
  288. self.collectionViewDestination.reloadData()
  289. // Save button
  290. if imagesDestination.count == 0 {
  291. save.isEnabled = false
  292. } else {
  293. save.isEnabled = true
  294. }
  295. }
  296. }
  297. // MARK: - UICollectionViewDragDelegate Methods
  298. @available(iOS 11, *)
  299. extension DragDropViewController : UICollectionViewDragDelegate
  300. {
  301. func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
  302. if collectionView == self.collectionViewSource {
  303. let item = self.itemsSource[indexPath.row]
  304. let itemProvider = NSItemProvider(object: item as NSString)
  305. let dragItem = UIDragItem(itemProvider: itemProvider)
  306. dragItem.localObject = item
  307. return [dragItem]
  308. } else {
  309. let item = self.imagesDestination[indexPath.row]
  310. let itemProvider = NSItemProvider(object: item as UIImage)
  311. let dragItem = UIDragItem(itemProvider: itemProvider)
  312. dragItem.localObject = item
  313. return [dragItem]
  314. }
  315. }
  316. func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
  317. if collectionView == self.collectionViewSource {
  318. let item = self.itemsSource[indexPath.row]
  319. let itemProvider = NSItemProvider(object: item as NSString)
  320. let dragItem = UIDragItem(itemProvider: itemProvider)
  321. dragItem.localObject = item
  322. return [dragItem]
  323. } else {
  324. let item = self.imagesDestination[indexPath.row]
  325. let itemProvider = NSItemProvider(object: item as UIImage)
  326. let dragItem = UIDragItem(itemProvider: itemProvider)
  327. dragItem.localObject = item
  328. return [dragItem]
  329. }
  330. }
  331. func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
  332. let previewParameters = UIDragPreviewParameters()
  333. if collectionView == self.collectionViewSource {
  334. previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 100, height: 100))
  335. } else {
  336. previewParameters.visiblePath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 80, height: 80))
  337. }
  338. return previewParameters
  339. }
  340. }
  341. // MARK: - UICollectionViewDropDelegate Methods
  342. @available(iOS 11, *)
  343. extension DragDropViewController : UICollectionViewDropDelegate {
  344. func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
  345. return true //session.canLoadObjects(ofClass: NSString.self)
  346. }
  347. func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
  348. if collectionView == self.collectionViewSource {
  349. if collectionView.hasActiveDrag {
  350. return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
  351. } else {
  352. return UICollectionViewDropProposal(operation: .forbidden)
  353. }
  354. } else {
  355. if collectionView.hasActiveDrag {
  356. return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
  357. } else {
  358. return UICollectionViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
  359. }
  360. }
  361. }
  362. func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
  363. let destinationIndexPath: IndexPath
  364. switch coordinator.proposal.operation {
  365. case .move:
  366. if let indexPath = coordinator.destinationIndexPath {
  367. destinationIndexPath = indexPath
  368. } else {
  369. // Get last index path of table view.
  370. let section = collectionView.numberOfSections - 1
  371. let row = collectionView.numberOfItems(inSection: section)
  372. destinationIndexPath = IndexPath(row: row, section: section)
  373. }
  374. self.reorderItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
  375. break
  376. case .copy:
  377. // Get last index path of table view.
  378. let section = collectionView.numberOfSections - 1
  379. let row = collectionView.numberOfItems(inSection: section)
  380. destinationIndexPath = IndexPath(row: row, section: section)
  381. self.copyItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
  382. break
  383. default:
  384. return
  385. }
  386. }
  387. func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) {
  388. self.collectionViewDestination.reloadData()
  389. // Save button
  390. if imagesDestination.count == 0 {
  391. save.isEnabled = false
  392. } else {
  393. save.isEnabled = true
  394. }
  395. }
  396. }