ScanCollectionView.swift 23 KB

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