NCCreateFormUploadScanDocument.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. //
  2. // NCCreateFormUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/2018.
  6. // Copyright © 2017 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 Foundation
  24. import WeScan
  25. import NCCommunication
  26. #if GOOGLEMOBILEVISION
  27. import GoogleMobileVision
  28. #endif
  29. class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NCCreateFormUploadConflictDelegate {
  30. enum typeDpiQuality {
  31. case low
  32. case medium
  33. case hight
  34. }
  35. var dpiQuality: typeDpiQuality = typeDpiQuality.medium
  36. var serverUrl = ""
  37. var titleServerUrl = ""
  38. var arrayImages = [UIImage]()
  39. var fileName = CCUtility.createFileNameDate("scan", extension: "pdf")
  40. var password: String = ""
  41. var fileType = "PDF"
  42. #if GOOGLEMOBILEVISION
  43. var textDetector: GMVDetector?
  44. #endif
  45. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  46. convenience init(serverUrl: String, arrayImages: [UIImage]) {
  47. self.init()
  48. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  49. titleServerUrl = "/"
  50. } else {
  51. titleServerUrl = (serverUrl as NSString).lastPathComponent
  52. }
  53. self.serverUrl = serverUrl
  54. self.arrayImages = arrayImages
  55. }
  56. // MARK: - View Life Cycle
  57. override func viewDidLoad() {
  58. super.viewDidLoad()
  59. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  60. self.navigationItem.rightBarButtonItem = saveButton
  61. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  62. // self.tableView.sectionHeaderHeight = 10
  63. // self.tableView.sectionFooterHeight = 10
  64. // self.tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  65. // let row : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  66. // let rowCell = row.cell(forForm: self)
  67. // rowCell.becomeFirstResponder()
  68. #if GOOGLEMOBILEVISION
  69. textDetector = GMVDetector(ofType: GMVDetectorTypeText, options: nil)
  70. #endif
  71. // Theming view
  72. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  73. changeTheming()
  74. }
  75. @objc func changeTheming() {
  76. appDelegate.changeTheming(self, tableView: tableView, collectionView: nil, form: true)
  77. initializeForm()
  78. }
  79. //MARK: XLForm
  80. func initializeForm() {
  81. let form : XLFormDescriptor = XLFormDescriptor(title: NSLocalizedString("_save_settings_", comment: "")) as XLFormDescriptor
  82. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  83. var section : XLFormSectionDescriptor
  84. var row : XLFormRowDescriptor
  85. // Section: Destination Folder
  86. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  87. form.addFormSection(section)
  88. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  89. row.action.formSelector = #selector(changeDestinationFolder(_:))
  90. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  91. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  92. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  93. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  94. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  95. section.addFormRow(row)
  96. // Section: Quality
  97. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
  98. form.addFormSection(section)
  99. row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
  100. row.value = 0.5
  101. row.title = NSLocalizedString("_quality_medium_", comment: "")
  102. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  103. row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.sharedInstance.brand
  104. row.cellConfig["slider.maximumValue"] = 1
  105. row.cellConfig["slider.minimumValue"] = 0
  106. row.cellConfig["steps"] = 2
  107. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
  108. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  109. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  110. section.addFormRow(row)
  111. // Section: Password
  112. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
  113. form.addFormSection(section)
  114. row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
  115. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  116. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  117. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  118. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  119. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  120. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  121. section.addFormRow(row)
  122. // Section: Text recognition
  123. #if GOOGLEMOBILEVISION
  124. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_text_recognition_", comment: ""))
  125. form.addFormSection(section)
  126. row = XLFormRowDescriptor(tag: "textRecognition", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_text_recognition_", comment: ""))
  127. row.value = 0
  128. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  129. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "textRecognition")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  130. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  131. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  132. section.addFormRow(row)
  133. #endif
  134. // Section: File
  135. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
  136. form.addFormSection(section)
  137. row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
  138. if arrayImages.count == 1 {
  139. row.selectorOptions = ["PDF","JPG"]
  140. } else {
  141. row.selectorOptions = ["PDF"]
  142. }
  143. row.value = "PDF"
  144. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  145. row.cellConfig["tintColor"] = NCBrandColor.sharedInstance.brand
  146. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  147. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  148. section.addFormRow(row)
  149. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  150. row.value = self.fileName
  151. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  152. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  153. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  154. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  155. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  156. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  157. section.addFormRow(row)
  158. self.form = form
  159. }
  160. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  161. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  162. if formRow.tag == "textRecognition" {
  163. let rowCompressionQuality: XLFormRowDescriptor = self.form.formRow(withTag: "compressionQuality")!
  164. let rowFileTape: XLFormRowDescriptor = self.form.formRow(withTag: "filetype")!
  165. let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  166. let rowPassword: XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  167. self.form.delegate = nil
  168. if newValue as! Int == 1 {
  169. rowFileTape.selectorOptions = ["PDF","TXT"]
  170. rowFileTape.value = "PDF"
  171. fileType = "PDF"
  172. rowPassword.disabled = true
  173. rowCompressionQuality.disabled = true
  174. } else {
  175. if arrayImages.count == 1 {
  176. rowFileTape.selectorOptions = ["PDF","JPG"]
  177. } else {
  178. rowFileTape.selectorOptions = ["PDF"]
  179. }
  180. rowFileTape.value = "PDF"
  181. fileType = "PDF"
  182. rowPassword.disabled = false
  183. rowCompressionQuality.disabled = false
  184. }
  185. rowFileName.value = createFileName(rowFileName.value as? String)
  186. self.updateFormRow(rowFileName)
  187. self.tableView.reloadData()
  188. self.form.delegate = self
  189. }
  190. if formRow.tag == "fileName" {
  191. self.form.delegate = nil
  192. let fileNameNew = newValue as? String
  193. if fileNameNew != nil {
  194. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
  195. } else {
  196. self.fileName = ""
  197. }
  198. formRow.value = self.fileName
  199. self.updateFormRow(formRow)
  200. self.form.delegate = self
  201. }
  202. if formRow.tag == "compressionQuality" {
  203. self.form.delegate = nil
  204. //let row : XLFormRowDescriptor = self.form.formRow(withTag: "descriptionQuality")!
  205. let newQuality = newValue as? NSNumber
  206. let compressionQuality = (newQuality?.doubleValue)!
  207. if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
  208. formRow.title = NSLocalizedString("_quality_low_", comment: "")
  209. dpiQuality = typeDpiQuality.low
  210. } else if compressionQuality > 0.3 && compressionQuality <= 0.6 {
  211. formRow.title = NSLocalizedString("_quality_medium_", comment: "")
  212. dpiQuality = typeDpiQuality.medium
  213. } else if compressionQuality > 0.6 && compressionQuality <= 1.0 {
  214. formRow.title = NSLocalizedString("_quality_high_", comment: "")
  215. dpiQuality = typeDpiQuality.hight
  216. }
  217. self.updateFormRow(formRow)
  218. self.form.delegate = self
  219. }
  220. if formRow.tag == "password" {
  221. let stringPassword = newValue as? String
  222. if stringPassword != nil {
  223. password = stringPassword!
  224. } else {
  225. password = ""
  226. }
  227. }
  228. if formRow.tag == "filetype" {
  229. fileType = newValue as! String
  230. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  231. let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  232. rowFileName.value = createFileName(rowFileName.value as? String)
  233. self.updateFormRow(rowFileName)
  234. // rowPassword
  235. if fileType == "JPG" || fileType == "TXT" {
  236. rowPassword.value = ""
  237. password = ""
  238. rowPassword.disabled = true
  239. } else {
  240. rowPassword.disabled = false
  241. }
  242. self.updateFormRow(rowPassword)
  243. }
  244. }
  245. override func textFieldDidBeginEditing(_ textField: UITextField) {
  246. let cell = textField.formDescriptorCell()
  247. let tag = cell?.rowDescriptor.tag
  248. if tag == "fileName" {
  249. CCUtility.selectFileName(from: textField)
  250. }
  251. }
  252. func createFileName(_ fileName: String?) -> String {
  253. var name: String = ""
  254. var newFileName: String = ""
  255. if fileName == nil || fileName == "" {
  256. name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf"
  257. } else {
  258. name = fileName!
  259. }
  260. let ext = (name as NSString).pathExtension.uppercased()
  261. if (ext == "") {
  262. newFileName = name + "." + fileType.lowercased()
  263. } else {
  264. newFileName = (name as NSString).deletingPathExtension + "." + fileType.lowercased()
  265. }
  266. return newFileName
  267. }
  268. // MARK: - Action
  269. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  270. if serverUrl != nil {
  271. self.serverUrl = serverUrl!
  272. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  273. self.titleServerUrl = "/"
  274. } else {
  275. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  276. }
  277. // Update
  278. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  279. row.title = self.titleServerUrl
  280. self.updateFormRow(row)
  281. }
  282. }
  283. @objc func save() {
  284. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  285. guard let name = rowFileName.value else {
  286. return
  287. }
  288. if name as! String == "" {
  289. return
  290. }
  291. let ext = (name as! NSString).pathExtension.uppercased()
  292. var fileNameSave = ""
  293. if (ext == "") {
  294. fileNameSave = name as! String + "." + fileType.lowercased()
  295. } else {
  296. fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  297. }
  298. //Create metadata for upload
  299. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.activeAccount, fileName: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, url: appDelegate.activeUrl, contentType: "")
  300. metadataForUpload.session = k_upload_session
  301. metadataForUpload.sessionSelector = selectorUploadFile
  302. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  303. if NCUtility.sharedInstance.getMetadataConflict(account: appDelegate.activeAccount, serverUrl: serverUrl, fileName: fileNameSave) != nil {
  304. guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  305. conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  306. conflictViewController.serverUrl = serverUrl
  307. conflictViewController.metadatasUploadInConflict = [metadataForUpload]
  308. conflictViewController.delegate = self
  309. self.present(conflictViewController, animated: true, completion: nil)
  310. } else {
  311. dismissAndUpload(metadataForUpload)
  312. }
  313. }
  314. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  315. if metadatas != nil && metadatas!.count > 0 {
  316. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  317. self.dismissAndUpload(metadatas![0])
  318. }
  319. }
  320. }
  321. func dismissAndUpload(_ metadata: tableMetadata) {
  322. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  323. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  324. return
  325. }
  326. #if GOOGLEMOBILEVISION
  327. // Text Recognition TXT
  328. if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  329. var textFile = ""
  330. for image in self.arrayImages {
  331. guard let features = self.textDetector?.features(in: image, options: nil) as? [GMVTextBlockFeature] else {
  332. continue
  333. }
  334. for textBlock in features {
  335. guard let text = textBlock.value else {
  336. continue
  337. }
  338. textFile = textFile + text + "\n\n"
  339. }
  340. do {
  341. try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL , atomically: true, encoding: .utf8)
  342. } catch {
  343. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  344. return
  345. }
  346. }
  347. }
  348. #endif
  349. if fileType == "PDF" {
  350. let pdfData = NSMutableData()
  351. if password.count > 0 {
  352. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String : password, kCGPDFContextOwnerPassword as String : password]
  353. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  354. } else {
  355. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  356. }
  357. let context = UIGraphicsGetCurrentContext()
  358. for var image in self.arrayImages {
  359. #if GOOGLEMOBILEVISION
  360. if self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  361. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  362. UIImageView.init(image:image).layer.render(in: context!)
  363. if let features = self.textDetector?.features(in: image, options: nil) as? [GMVTextBlockFeature] {
  364. for textBlock in features {
  365. for textLine in textBlock.lines {
  366. let bounds = textLine.bounds
  367. let text = textLine.value!
  368. var fontColor = UIColor.clear
  369. #if targetEnvironment(simulator)
  370. fontColor = UIColor.red
  371. #endif
  372. //print(text)
  373. let font = UIFont.systemFont(ofSize: bounds.size.height, weight: .regular)
  374. let bestFittingFont = NCUtility.sharedInstance.bestFittingFont(for: text, in: bounds, fontDescriptor: font.fontDescriptor)
  375. text.draw(in: bounds, withAttributes: [NSAttributedString.Key.font: bestFittingFont, NSAttributedString.Key.foregroundColor: fontColor])
  376. }
  377. }
  378. }
  379. } else {
  380. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  381. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  382. UIImageView.init(image:image).layer.render(in: context!)
  383. }
  384. #else
  385. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  386. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  387. UIImageView.init(image:image).layer.render(in: context!)
  388. #endif
  389. }
  390. UIGraphicsEndPDFContext();
  391. do {
  392. try pdfData.write(toFile: fileNameGenerateExport, options: .atomic)
  393. } catch {
  394. print("error catched")
  395. }
  396. }
  397. if fileType == "JPG" {
  398. let image = changeImageFromQuality(self.arrayImages[0], dpiQuality: dpiQuality)
  399. guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else {
  400. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  401. return
  402. }
  403. do {
  404. try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
  405. } catch {
  406. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  407. return
  408. }
  409. }
  410. NCManageDatabase.sharedInstance.addMetadata(metadata)
  411. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: nil, action: Int32(k_action_NULL))
  412. self.appDelegate.startLoadAutoDownloadUpload()
  413. // Request delete all image scanned
  414. let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert)
  415. let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  416. let path = CCUtility.getDirectoryScan()!
  417. do {
  418. let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
  419. for filePath in filePaths {
  420. try FileManager.default.removeItem(atPath: path + "/" + filePath)
  421. }
  422. } catch let error as NSError {
  423. print("Error: \(error.debugDescription)")
  424. }
  425. self.dismiss(animated: true, completion: nil)
  426. }
  427. let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  428. self.dismiss(animated: true, completion: nil)
  429. }
  430. alertController.addAction(actionYes)
  431. alertController.addAction(actionNo)
  432. self.present(alertController, animated: true, completion:nil)
  433. }
  434. func cancel() {
  435. self.dismiss(animated: true, completion: nil)
  436. }
  437. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  438. self.deselectFormRow(sender)
  439. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  440. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  441. let viewController = navigationController.topViewController as! NCSelect
  442. viewController.delegate = self
  443. viewController.hideButtonCreateFolder = false
  444. viewController.includeDirectoryE2EEncryption = true
  445. viewController.includeImages = false
  446. viewController.layoutViewSelect = k_layout_view_move
  447. viewController.selectFile = false
  448. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  449. viewController.type = ""
  450. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  451. self.present(navigationController, animated: true, completion: nil)
  452. }
  453. func changeImageFromQuality(_ image: UIImage, dpiQuality: typeDpiQuality) -> UIImage {
  454. let imageWidthInPixels = image.size.width * image.scale
  455. let imageHeightInPixels = image.size.height * image.scale
  456. switch dpiQuality {
  457. case typeDpiQuality.low: // 72 DPI
  458. if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
  459. return CCGraphics.scale(image, to: CGSize(width: 595, height: 842), isAspectRation: true)
  460. }
  461. case typeDpiQuality.medium: // 150 DPI
  462. if imageWidthInPixels > 1240 || imageHeightInPixels > 1754 {
  463. return CCGraphics.scale(image, to: CGSize(width: 1240, height: 1754), isAspectRation: true)
  464. }
  465. case typeDpiQuality.hight: // 200 DPI
  466. if imageWidthInPixels > 1654 || imageHeightInPixels > 2339 {
  467. return CCGraphics.scale(image, to: CGSize(width: 1654, height: 2339), isAspectRation: true)
  468. }
  469. }
  470. return image
  471. }
  472. }
  473. class NCCreateScanDocument : NSObject, ImageScannerControllerDelegate {
  474. @objc static let sharedInstance: NCCreateScanDocument = {
  475. let instance = NCCreateScanDocument()
  476. return instance
  477. }()
  478. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  479. var viewController: UIViewController?
  480. func openScannerDocument(viewController: UIViewController) {
  481. self.viewController = viewController
  482. let scannerVC = ImageScannerController()
  483. scannerVC.imageScannerDelegate = self
  484. scannerVC.navigationBar.isTranslucent = false
  485. scannerVC.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  486. scannerVC.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  487. scannerVC.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  488. self.viewController?.present(scannerVC, animated: true, completion: nil)
  489. }
  490. func imageScannerController(_ scanner: ImageScannerController, didFinishScanningWithResults results: ImageScannerResults) {
  491. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)!
  492. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  493. let image: UIImage?
  494. if results.doesUserPreferEnhancedScan {
  495. image = results.enhancedScan?.image
  496. } else {
  497. image = results.croppedScan.image
  498. }
  499. if image != nil {
  500. do {
  501. try image!.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath))
  502. } catch { }
  503. }
  504. scanner.dismiss(animated: true, completion: {
  505. if self.viewController is DragDropViewController {
  506. (self.viewController as! DragDropViewController).loadImage()
  507. } else {
  508. let storyboard = UIStoryboard(name: "Scan", bundle: nil)
  509. let controller = storyboard.instantiateInitialViewController()!
  510. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  511. self.viewController?.present(controller, animated: true, completion: nil)
  512. }
  513. })
  514. }
  515. func imageScannerControllerDidCancel(_ scanner: ImageScannerController) {
  516. scanner.dismiss(animated: true, completion: nil)
  517. }
  518. func imageScannerController(_ scanner: ImageScannerController, didFailWithError error: Error) {
  519. NCContentPresenter.shared.messageNotification("_error_", description: error.localizedDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  520. }
  521. }