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