NCScan.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //
  2. // NCScan.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 13.0, *)
  25. class NCScan: UIViewController {
  26. // Data Source for collectionViewSource
  27. internal var itemsSource: [String] = []
  28. // Data Source for collectionViewDestination
  29. internal var imagesDestination: [UIImage] = []
  30. internal var itemsDestination: [String] = []
  31. internal 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. internal var filter: TypeFilter = TypeFilter.original
  48. override var canBecomeFirstResponder: Bool { return true }
  49. // MARK: - View Life Cycle
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. view.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
  53. navigationItem.title = NSLocalizedString("_scanned_images_", comment: "")
  54. collectionViewSource.dragInteractionEnabled = true
  55. collectionViewSource.dragDelegate = self
  56. collectionViewSource.dropDelegate = self
  57. collectionViewSource.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
  58. collectionViewDestination.dragInteractionEnabled = true
  59. collectionViewDestination.dropDelegate = self
  60. collectionViewDestination.dragDelegate = self
  61. collectionViewDestination.reorderingCadence = .fast // default value - .immediate
  62. collectionViewDestination.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground
  63. cancel.title = NSLocalizedString("_cancel_", comment: "")
  64. save.title = NSLocalizedString("_save_", comment: "")
  65. labelTitlePDFzone.text = NSLocalizedString("_scan_label_document_zone_", comment: "")
  66. labelTitlePDFzone.backgroundColor = NCBrandColor.shared.systemGray6
  67. labelTitlePDFzone.textColor = NCBrandColor.shared.label
  68. segmentControlFilter.setTitle(NSLocalizedString("_filter_original_", comment: ""), forSegmentAt: 0)
  69. segmentControlFilter.setTitle(NSLocalizedString("_filter_grayscale_", comment: ""), forSegmentAt: 1)
  70. segmentControlFilter.setTitle(NSLocalizedString("_filter_bn_", comment: ""), forSegmentAt: 2)
  71. add.setImage(UIImage(named: "plus")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
  72. transferDown.setImage(UIImage(named: "transferDown")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
  73. let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
  74. collectionViewSource.addGestureRecognizer(longPressRecognizer)
  75. let longPressRecognizerPlus = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
  76. add.addGestureRecognizer(longPressRecognizerPlus)
  77. collectionViewSource.reloadData()
  78. collectionViewDestination.reloadData()
  79. loadImage()
  80. }
  81. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  82. super.traitCollectionDidChange(previousTraitCollection)
  83. add.setImage(UIImage(named: "plus")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
  84. transferDown.setImage(UIImage(named: "transferDown")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
  85. }
  86. @IBAction func cancelAction(sender: UIBarButtonItem) {
  87. self.dismiss(animated: true, completion: nil)
  88. }
  89. @IBAction func saveAction(sender: UIBarButtonItem) {
  90. if !imagesDestination.isEmpty {
  91. var images: [UIImage] = []
  92. let serverUrl = appDelegate.activeServerUrl
  93. for image in imagesDestination {
  94. images.append(filter(image: image)!)
  95. }
  96. // if let directory = CCUtility.getDirectoryScanDocuments() {
  97. // serverUrl = directory
  98. // }
  99. let formViewController = NCCreateFormUploadScanDocument(serverUrl: serverUrl, arrayImages: images)
  100. self.navigationController?.pushViewController(formViewController, animated: true)
  101. }
  102. }
  103. @IBAction func add(sender: UIButton) {
  104. NCCreateScanDocument.shared.openScannerDocument(viewController: self)
  105. }
  106. @IBAction func transferDown(sender: UIButton) {
  107. for fileName in itemsSource {
  108. if !itemsDestination.contains(fileName) {
  109. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
  110. guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)) else { return }
  111. guard let image = UIImage(data: data) else { return }
  112. imagesDestination.append(image)
  113. itemsDestination.append(fileName)
  114. }
  115. }
  116. // Save button
  117. if imagesDestination.isEmpty {
  118. save.isEnabled = false
  119. } else {
  120. save.isEnabled = true
  121. }
  122. collectionViewDestination.reloadData()
  123. }
  124. @IBAction func indexChanged(_ sender: AnyObject) {
  125. switch segmentControlFilter.selectedSegmentIndex {
  126. case 0:
  127. filter = .original
  128. case 1:
  129. filter = .grayScale
  130. case 2:
  131. filter = .bn
  132. default:
  133. break
  134. }
  135. collectionViewDestination.reloadData()
  136. }
  137. func loadImage() {
  138. itemsSource.removeAll()
  139. do {
  140. let atPath = CCUtility.getDirectoryScan()!
  141. let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath)
  142. for fileName in directoryContents where fileName.first != "." {
  143. itemsSource.append(fileName)
  144. }
  145. } catch {
  146. print(error.localizedDescription)
  147. }
  148. itemsSource = itemsSource.sorted()
  149. collectionViewSource.reloadData()
  150. // Save button
  151. if imagesDestination.isEmpty {
  152. save.isEnabled = false
  153. } else {
  154. save.isEnabled = true
  155. }
  156. }
  157. func filter(image: UIImage) -> UIImage? {
  158. var inputContrast: Double = 0
  159. if filter == .original {
  160. return image
  161. }
  162. if filter == .grayScale {
  163. inputContrast = 1
  164. }
  165. if filter == .bn {
  166. inputContrast = 4
  167. }
  168. let ciImage = CIImage(image: image)!
  169. let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": inputContrast])
  170. let context: CIContext = CIContext(options: nil)
  171. let cgImage: CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
  172. let image: UIImage = UIImage(cgImage: cgImage)
  173. return image
  174. }
  175. func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  176. let items = coordinator.items
  177. if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {
  178. var dIndexPath = destinationIndexPath
  179. if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
  180. dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
  181. }
  182. collectionView.performBatchUpdates({
  183. if collectionView === collectionViewDestination {
  184. imagesDestination.remove(at: sourceIndexPath.row)
  185. imagesDestination.insert((item.dragItem.localObject as? UIImage)!, at: dIndexPath.row)
  186. let fileName = itemsDestination[sourceIndexPath.row]
  187. itemsDestination.remove(at: sourceIndexPath.row)
  188. itemsDestination.insert(fileName, at: dIndexPath.row)
  189. } else {
  190. itemsSource.remove(at: sourceIndexPath.row)
  191. itemsSource.insert((item.dragItem.localObject as? String)!, at: dIndexPath.row)
  192. }
  193. collectionView.deleteItems(at: [sourceIndexPath])
  194. collectionView.insertItems(at: [dIndexPath])
  195. })
  196. coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
  197. }
  198. }
  199. func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  200. collectionView.performBatchUpdates({
  201. var indexPaths: [IndexPath] = []
  202. for (index, item) in coordinator.items.enumerated() {
  203. let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
  204. if collectionView === collectionViewDestination {
  205. let fileName = (item.dragItem.localObject as? String)!
  206. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
  207. guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)) else {
  208. return
  209. }
  210. guard let image = UIImage(data: data) else {
  211. return
  212. }
  213. imagesDestination.insert(image, at: indexPath.row)
  214. itemsDestination.insert(fileName, at: indexPath.row)
  215. } else {
  216. // NOT PERMITTED
  217. return
  218. }
  219. indexPaths.append(indexPath)
  220. }
  221. collectionView.insertItems(at: indexPaths)
  222. })
  223. }
  224. @objc func handleLongPressGesture(recognizer: UIGestureRecognizer) {
  225. if recognizer.state == UIGestureRecognizer.State.began {
  226. self.becomeFirstResponder()
  227. let pasteboard = UIPasteboard.general
  228. if let recognizerView = recognizer.view, let recognizerSuperView = recognizerView.superview, pasteboard.hasImages {
  229. UIMenuController.shared.menuItems = [UIMenuItem(title: "Paste", action: #selector(pasteImage))]
  230. UIMenuController.shared.setTargetRect(recognizerView.frame, in: recognizerSuperView)
  231. UIMenuController.shared.setMenuVisible(true, animated: true)
  232. }
  233. }
  234. }
  235. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  236. if action == #selector(pasteImage) {
  237. return true
  238. }
  239. return false
  240. }
  241. @objc func pasteImage() {
  242. let pasteboard = UIPasteboard.general
  243. if pasteboard.hasImages {
  244. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(),
  245. fileType: PHAssetMediaType.image,
  246. keyFileName: NCGlobal.shared.keyFileNameMask,
  247. keyFileNameType: NCGlobal.shared.keyFileNameType,
  248. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  249. forcedNewFileName: true)!
  250. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  251. guard let image = pasteboard.image?.fixedOrientation() else {
  252. return
  253. }
  254. do {
  255. try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  256. } catch {
  257. return
  258. }
  259. loadImage()
  260. }
  261. }
  262. }
  263. extension UIImage {
  264. func rotate(radians: Float) -> UIImage? {
  265. var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
  266. // Trim off the extremely small float value to prevent core graphics from rounding it up
  267. newSize.width = floor(newSize.width)
  268. newSize.height = floor(newSize.height)
  269. UIGraphicsBeginImageContextWithOptions(newSize, true, self.scale)
  270. let context = UIGraphicsGetCurrentContext()!
  271. // Move origin to middle
  272. context.translateBy(x: newSize.width / 2, y: newSize.height / 2)
  273. // Rotate around middle
  274. context.rotate(by: CGFloat(radians))
  275. // Draw the image at its center
  276. self.draw(in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
  277. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  278. UIGraphicsEndImageContext()
  279. return newImage
  280. }
  281. }