NCScan.swift 16 KB

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