NCScan.swift 15 KB

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