NCScan.swift 16 KB

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