ScanCollectionView.swift 24 KB

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