NCCreateFormUploadScanDocument.swift 29 KB

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