NCScan.swift 15 KB

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