NCCreateFormUploadScanDocument.swift 29 KB

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