NCCreateFormUploadScanDocument.swift 30 KB

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