NCScan.swift 16 KB

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