NCCreateFormUploadScanDocument.swift 30 KB

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