NCScan.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. import Photos
  25. import EasyTipView
  26. @available(iOS 13.0, *)
  27. class NCScan: UIViewController, NCScanCellCellDelegate {
  28. @IBOutlet weak var collectionViewSource: UICollectionView!
  29. @IBOutlet weak var collectionViewDestination: UICollectionView!
  30. @IBOutlet weak var cancel: UIBarButtonItem!
  31. @IBOutlet weak var save: UIBarButtonItem!
  32. @IBOutlet weak var add: UIButton!
  33. @IBOutlet weak var transferDown: UIButton!
  34. @IBOutlet weak var labelTitlePDFzone: UILabel!
  35. @IBOutlet weak var segmentControlFilter: UISegmentedControl!
  36. // Data Source for collectionViewSource
  37. internal var itemsSource: [String] = []
  38. // Data Source for collectionViewDestination
  39. internal var imagesDestination: [UIImage] = []
  40. internal var itemsDestination: [String] = []
  41. internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  42. private var tipView: EasyTipView?
  43. enum TypeFilter {
  44. case original
  45. case grayScale
  46. case bn
  47. }
  48. internal var filter: TypeFilter = TypeFilter.original
  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. // TIP
  78. var preferences = EasyTipView.Preferences()
  79. preferences.drawing.foregroundColor = .white
  80. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  81. preferences.drawing.textAlignment = .left
  82. preferences.drawing.arrowPosition = .left
  83. preferences.drawing.cornerRadius = 10
  84. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  85. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  86. preferences.animating.showInitialAlpha = 0
  87. preferences.animating.showDuration = 1.5
  88. preferences.animating.dismissDuration = 1.5
  89. tipView = EasyTipView(text: NSLocalizedString("_tip_addcopyimage_", comment: ""), preferences: preferences, delegate: self)
  90. collectionViewSource.reloadData()
  91. collectionViewDestination.reloadData()
  92. loadImage()
  93. }
  94. override func viewDidAppear(_ animated: Bool) {
  95. super.viewDidAppear(animated)
  96. // TIP
  97. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCScanAddImage) {
  98. self.tipView?.show(forView: add, withinSuperview: self.view)
  99. }
  100. }
  101. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  102. super.traitCollectionDidChange(previousTraitCollection)
  103. add.setImage(UIImage(named: "plus")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
  104. transferDown.setImage(UIImage(named: "transferDown")?.image(color: NCBrandColor.shared.label, size: 25), for: .normal)
  105. }
  106. override var canBecomeFirstResponder: Bool { return true }
  107. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  108. if action == #selector(pasteImage) {
  109. return true
  110. }
  111. return false
  112. }
  113. @IBAction func cancelAction(sender: UIBarButtonItem) {
  114. self.dismiss(animated: true, completion: nil)
  115. }
  116. @IBAction func saveAction(sender: UIBarButtonItem) {
  117. if !imagesDestination.isEmpty {
  118. var images: [UIImage] = []
  119. let serverUrl = appDelegate.activeServerUrl
  120. for image in imagesDestination {
  121. images.append(filter(image: image)!)
  122. }
  123. let formViewController = NCCreateFormUploadScanDocument(serverUrl: serverUrl, arrayImages: images)
  124. self.navigationController?.pushViewController(formViewController, animated: true)
  125. }
  126. }
  127. @IBAction func add(sender: UIButton) {
  128. // TIP
  129. dismissTip()
  130. NCCreateScanDocument.shared.openScannerDocument(viewController: self)
  131. }
  132. @IBAction func transferDown(sender: UIButton) {
  133. for fileName in itemsSource {
  134. if !itemsDestination.contains(fileName) {
  135. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
  136. guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)), let image = UIImage(data: data) else { return }
  137. imagesDestination.append(image)
  138. itemsDestination.append(fileName)
  139. }
  140. }
  141. // Save button
  142. if imagesDestination.isEmpty {
  143. save.isEnabled = false
  144. } else {
  145. save.isEnabled = true
  146. }
  147. collectionViewDestination.reloadData()
  148. }
  149. @IBAction func indexChanged(_ sender: AnyObject) {
  150. switch segmentControlFilter.selectedSegmentIndex {
  151. case 0:
  152. filter = .original
  153. case 1:
  154. filter = .grayScale
  155. case 2:
  156. filter = .bn
  157. default:
  158. break
  159. }
  160. collectionViewDestination.reloadData()
  161. }
  162. func loadImage() {
  163. itemsSource.removeAll()
  164. do {
  165. let atPath = CCUtility.getDirectoryScan()!
  166. let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath)
  167. for fileName in directoryContents where fileName.first != "." {
  168. itemsSource.append(fileName)
  169. }
  170. } catch {
  171. print(error.localizedDescription)
  172. }
  173. itemsSource = itemsSource.sorted()
  174. collectionViewSource.reloadData()
  175. // Save button
  176. if imagesDestination.isEmpty {
  177. save.isEnabled = false
  178. } else {
  179. save.isEnabled = true
  180. }
  181. }
  182. func filter(image: UIImage) -> UIImage? {
  183. var inputContrast: Double = 0
  184. if filter == .original {
  185. return image
  186. }
  187. if filter == .grayScale {
  188. inputContrast = 1
  189. }
  190. if filter == .bn {
  191. inputContrast = 4
  192. }
  193. let ciImage = CIImage(image: image)!
  194. let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": inputContrast])
  195. let context: CIContext = CIContext(options: nil)
  196. let cgImage: CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
  197. let image: UIImage = UIImage(cgImage: cgImage)
  198. return image
  199. }
  200. // destinationIndexPath: indexpath of the collection view where the user drops the element
  201. // collectionView: collectionView in which reordering needs to be done.
  202. func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  203. let items = coordinator.items
  204. if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {
  205. var dIndexPath = destinationIndexPath
  206. if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
  207. dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
  208. }
  209. collectionView.performBatchUpdates({
  210. if collectionView === collectionViewDestination {
  211. imagesDestination.remove(at: sourceIndexPath.row)
  212. imagesDestination.insert((item.dragItem.localObject as? UIImage)!, at: dIndexPath.row)
  213. let fileName = itemsDestination[sourceIndexPath.row]
  214. itemsDestination.remove(at: sourceIndexPath.row)
  215. itemsDestination.insert(fileName, at: dIndexPath.row)
  216. } else {
  217. itemsSource.remove(at: sourceIndexPath.row)
  218. itemsSource.insert((item.dragItem.localObject as? String)!, at: dIndexPath.row)
  219. }
  220. collectionView.deleteItems(at: [sourceIndexPath])
  221. collectionView.insertItems(at: [dIndexPath])
  222. })
  223. coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
  224. }
  225. }
  226. func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
  227. collectionView.performBatchUpdates({
  228. var indexPaths: [IndexPath] = []
  229. for (index, item) in coordinator.items.enumerated() {
  230. let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
  231. if collectionView === collectionViewDestination {
  232. let fileName = (item.dragItem.localObject as? String)!
  233. let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName
  234. guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)), let image = UIImage(data: data) else { return }
  235. imagesDestination.insert(image, at: indexPath.row)
  236. itemsDestination.insert(fileName, at: indexPath.row)
  237. } else {
  238. // NOT PERMITTED
  239. return
  240. }
  241. indexPaths.append(indexPath)
  242. }
  243. collectionView.insertItems(at: indexPaths)
  244. })
  245. }
  246. @objc func handleLongPressGesture(recognizer: UIGestureRecognizer) {
  247. if recognizer.state == UIGestureRecognizer.State.began {
  248. self.becomeFirstResponder()
  249. let pasteboard = UIPasteboard.general
  250. if let recognizerView = recognizer.view, let recognizerSuperView = recognizerView.superview, pasteboard.hasImages {
  251. UIMenuController.shared.menuItems = [UIMenuItem(title: "Paste", action: #selector(pasteImage))]
  252. UIMenuController.shared.setTargetRect(recognizerView.frame, in: recognizerSuperView)
  253. UIMenuController.shared.setMenuVisible(true, animated: true)
  254. }
  255. // TIP
  256. dismissTip()
  257. }
  258. }
  259. @objc func pasteImage() {
  260. let pasteboard = UIPasteboard.general
  261. if pasteboard.hasImages {
  262. guard let image = pasteboard.image?.fixedOrientation() else { return }
  263. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(),
  264. fileType: PHAssetMediaType.image,
  265. keyFileName: NCGlobal.shared.keyFileNameMask,
  266. keyFileNameType: NCGlobal.shared.keyFileNameType,
  267. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  268. forcedNewFileName: true)!
  269. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  270. do {
  271. try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  272. } catch {
  273. return
  274. }
  275. loadImage()
  276. }
  277. }
  278. func delete(with imageIndex: Int, sender: Any) {
  279. imagesDestination.remove(at: imageIndex)
  280. itemsDestination.remove(at: imageIndex)
  281. // Save button
  282. if imagesDestination.isEmpty {
  283. save.isEnabled = false
  284. } else {
  285. save.isEnabled = true
  286. }
  287. collectionViewDestination.reloadData()
  288. }
  289. func rotate(with imageIndex: Int, sender: Any) {
  290. let indexPath = IndexPath(row: imageIndex, section: 0)
  291. if let cell = collectionViewDestination.cellForItem(at: indexPath) as? NCScanCell {
  292. var image = imagesDestination[imageIndex]
  293. image = image.rotate(radians: .pi / 2)!
  294. imagesDestination[imageIndex] = image
  295. cell.customImageView.image = image
  296. }
  297. }
  298. }
  299. @available(iOS 13.0, *)
  300. extension NCScan: EasyTipViewDelegate {
  301. // TIP
  302. func easyTipViewDidTap(_ tipView: EasyTipView) {
  303. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCScanAddImage)
  304. }
  305. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  306. func dismissTip() {
  307. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCScanAddImage)
  308. self.tipView?.dismiss()
  309. }
  310. }