NCCreateFormUploadScanDocument.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. //
  2. // NCCreateFormUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/2018.
  6. // Copyright © 2018 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 NCCommunication
  25. import Vision
  26. import VisionKit
  27. @available(iOS 13.0, *)
  28. class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NCCreateFormUploadConflictDelegate {
  29. enum typeQuality {
  30. case low
  31. case medium
  32. case high
  33. }
  34. var quality: typeQuality = .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. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  42. convenience init(serverUrl: String, arrayImages: [UIImage]) {
  43. self.init()
  44. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) {
  45. titleServerUrl = "/"
  46. } else {
  47. titleServerUrl = (serverUrl as NSString).lastPathComponent
  48. }
  49. self.serverUrl = serverUrl
  50. self.arrayImages = arrayImages
  51. }
  52. // MARK: - View Life Cycle
  53. override func viewDidLoad() {
  54. super.viewDidLoad()
  55. self.title = NSLocalizedString("_save_settings_", comment: "")
  56. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  57. self.navigationItem.rightBarButtonItem = saveButton
  58. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  59. // self.tableView.sectionHeaderHeight = 10
  60. // self.tableView.sectionFooterHeight = 10
  61. // self.tableView.backgroundColor = NCBrandColor.shared.backgroundView
  62. // let row : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  63. // let rowCell = row.cell(forForm: self)
  64. // rowCell.becomeFirstResponder()
  65. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  66. changeTheming()
  67. let value = CCUtility.getTextRecognitionStatus()
  68. SetTextRecognition(newValue: value)
  69. }
  70. @objc func changeTheming() {
  71. view.backgroundColor = NCBrandColor.shared.backgroundForm
  72. tableView.backgroundColor = NCBrandColor.shared.backgroundForm
  73. tableView.reloadData()
  74. initializeForm()
  75. }
  76. //MARK: XLForm
  77. func initializeForm() {
  78. let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
  79. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  80. var section : XLFormSectionDescriptor
  81. var row : XLFormRowDescriptor
  82. // Section: Destination Folder
  83. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  84. form.addFormSection(section)
  85. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  86. row.action.formSelector = #selector(changeDestinationFolder(_:))
  87. row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm
  88. row.cellConfig["imageView.image"] = UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25)
  89. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  90. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  91. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.textView
  92. section.addFormRow(row)
  93. // Section: Quality
  94. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
  95. form.addFormSection(section)
  96. row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
  97. row.value = 0.5
  98. row.title = NSLocalizedString("_quality_medium_", comment: "")
  99. row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm
  100. row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.shared.brandElement
  101. row.cellConfig["slider.maximumValue"] = 1
  102. row.cellConfig["slider.minimumValue"] = 0
  103. row.cellConfig["steps"] = 2
  104. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
  105. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  106. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.textView
  107. section.addFormRow(row)
  108. // Section: Password
  109. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
  110. form.addFormSection(section)
  111. row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
  112. row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm
  113. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  114. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.textView
  115. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  116. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  117. row.cellConfig["textField.textColor"] = NCBrandColor.shared.textView
  118. section.addFormRow(row)
  119. // Section: Text recognition
  120. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_text_recognition_", comment: ""))
  121. form.addFormSection(section)
  122. row = XLFormRowDescriptor(tag: "textRecognition", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_text_recognition_", comment: ""))
  123. row.value = 0
  124. row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm
  125. row.cellConfig["imageView.image"] = UIImage(named: "textRecognition")!.image(color: NCBrandColor.shared.brandElement, size: 25)
  126. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  127. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.textView
  128. section.addFormRow(row)
  129. // Section: File
  130. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
  131. form.addFormSection(section)
  132. row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
  133. if arrayImages.count == 1 {
  134. row.selectorOptions = ["PDF","JPG"]
  135. } else {
  136. row.selectorOptions = ["PDF"]
  137. }
  138. row.value = "PDF"
  139. row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm
  140. row.cellConfig["tintColor"] = NCBrandColor.shared.brandElement
  141. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  142. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.textView
  143. section.addFormRow(row)
  144. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  145. row.value = self.fileName
  146. row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm
  147. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  148. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.textView
  149. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  150. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  151. row.cellConfig["textField.textColor"] = NCBrandColor.shared.textView
  152. section.addFormRow(row)
  153. self.form = form
  154. }
  155. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  156. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  157. if formRow.tag == "textRecognition" {
  158. self.SetTextRecognition(newValue: newValue as! Int)
  159. }
  160. if formRow.tag == "fileName" {
  161. self.form.delegate = nil
  162. let fileNameNew = newValue as? String
  163. if fileNameNew != nil {
  164. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
  165. } else {
  166. self.fileName = ""
  167. }
  168. formRow.value = self.fileName
  169. self.updateFormRow(formRow)
  170. self.form.delegate = self
  171. }
  172. if formRow.tag == "compressionQuality" {
  173. self.form.delegate = nil
  174. //let row : XLFormRowDescriptor = self.form.formRow(withTag: "descriptionQuality")!
  175. let newQuality = newValue as? NSNumber
  176. let compressionQuality = (newQuality?.doubleValue)!
  177. if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
  178. formRow.title = NSLocalizedString("_quality_low_", comment: "")
  179. quality = typeQuality.low
  180. } else if compressionQuality > 0.3 && compressionQuality <= 0.6 {
  181. formRow.title = NSLocalizedString("_quality_medium_", comment: "")
  182. quality = typeQuality.medium
  183. } else if compressionQuality > 0.6 && compressionQuality <= 1.0 {
  184. formRow.title = NSLocalizedString("_quality_high_", comment: "")
  185. quality = typeQuality.high
  186. }
  187. self.updateFormRow(formRow)
  188. self.form.delegate = self
  189. }
  190. if formRow.tag == "password" {
  191. let stringPassword = newValue as? String
  192. if stringPassword != nil {
  193. password = stringPassword!
  194. } else {
  195. password = ""
  196. }
  197. }
  198. if formRow.tag == "filetype" {
  199. fileType = newValue as! String
  200. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  201. let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  202. rowFileName.value = createFileName(rowFileName.value as? String)
  203. self.updateFormRow(rowFileName)
  204. // rowPassword
  205. if fileType == "JPG" || fileType == "TXT" {
  206. rowPassword.value = ""
  207. password = ""
  208. rowPassword.disabled = true
  209. } else {
  210. rowPassword.disabled = false
  211. }
  212. self.updateFormRow(rowPassword)
  213. }
  214. }
  215. func SetTextRecognition(newValue: Int) {
  216. let rowCompressionQuality: XLFormRowDescriptor = self.form.formRow(withTag: "compressionQuality")!
  217. let rowFileTape: XLFormRowDescriptor = self.form.formRow(withTag: "filetype")!
  218. let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  219. let rowPassword: XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  220. let rowTextRecognition: XLFormRowDescriptor = self.form.formRow(withTag: "textRecognition")!
  221. self.form.delegate = nil
  222. if newValue == 1 {
  223. rowFileTape.selectorOptions = ["PDF","TXT"]
  224. rowFileTape.value = "PDF"
  225. fileType = "PDF"
  226. rowPassword.disabled = true
  227. rowCompressionQuality.disabled = false
  228. } else {
  229. if arrayImages.count == 1 {
  230. rowFileTape.selectorOptions = ["PDF","JPG"]
  231. } else {
  232. rowFileTape.selectorOptions = ["PDF"]
  233. }
  234. rowFileTape.value = "PDF"
  235. fileType = "PDF"
  236. rowPassword.disabled = false
  237. rowCompressionQuality.disabled = false
  238. }
  239. rowFileName.value = createFileName(rowFileName.value as? String)
  240. self.updateFormRow(rowFileName)
  241. self.tableView.reloadData()
  242. CCUtility.setTextRecognitionStatus(newValue)
  243. rowTextRecognition.value = newValue
  244. self.form.delegate = self
  245. }
  246. func createFileName(_ fileName: String?) -> String {
  247. var name: String = ""
  248. var newFileName: String = ""
  249. if fileName == nil || fileName == "" {
  250. name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf"
  251. } else {
  252. name = fileName!
  253. }
  254. let ext = (name as NSString).pathExtension.uppercased()
  255. if (ext == "") {
  256. newFileName = name + "." + fileType.lowercased()
  257. } else {
  258. newFileName = (name as NSString).deletingPathExtension + "." + fileType.lowercased()
  259. }
  260. return newFileName
  261. }
  262. // MARK: - Action
  263. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], buttonType: String, overwrite: Bool) {
  264. if serverUrl != nil {
  265. CCUtility.setDirectoryScanDocuments(serverUrl!)
  266. self.serverUrl = serverUrl!
  267. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) {
  268. self.titleServerUrl = "/"
  269. } else {
  270. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  271. }
  272. // Update
  273. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  274. row.title = self.titleServerUrl
  275. self.updateFormRow(row)
  276. }
  277. }
  278. @objc func save() {
  279. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  280. guard let name = rowFileName.value else {
  281. return
  282. }
  283. if name as! String == "" {
  284. return
  285. }
  286. let ext = (name as! NSString).pathExtension.uppercased()
  287. var fileNameSave = ""
  288. if (ext == "") {
  289. fileNameSave = name as! String + "." + fileType.lowercased()
  290. } else {
  291. fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  292. }
  293. //Create metadata for upload
  294. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false, chunk: false)
  295. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  296. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  297. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  298. if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: fileNameSave) != nil {
  299. guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  300. conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  301. conflictViewController.serverUrl = serverUrl
  302. conflictViewController.metadatasUploadInConflict = [metadataForUpload]
  303. conflictViewController.delegate = self
  304. self.present(conflictViewController, animated: true, completion: nil)
  305. } else {
  306. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
  307. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  308. self.dismissAndUpload(metadataForUpload)
  309. }
  310. }
  311. }
  312. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  313. if metadatas != nil && metadatas!.count > 0 {
  314. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
  315. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  316. self.dismissAndUpload(metadatas![0])
  317. }
  318. }
  319. }
  320. func dismissAndUpload(_ metadata: tableMetadata) {
  321. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  322. NCUtility.shared.stopActivityIndicator()
  323. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorCreationFile, forced: true)
  324. return
  325. }
  326. // Text Recognition TXT
  327. if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  328. var textFile = ""
  329. for image in self.arrayImages {
  330. let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
  331. let request = VNRecognizeTextRequest { (request, error) in
  332. guard let observations = request.results as? [VNRecognizedTextObservation] else {
  333. NCUtility.shared.stopActivityIndicator()
  334. return
  335. }
  336. for observation in observations {
  337. guard let textLine = observation.topCandidates(1).first else {
  338. continue
  339. }
  340. textFile += textLine.string
  341. textFile += "\n"
  342. }
  343. }
  344. request.recognitionLevel = .accurate
  345. request.usesLanguageCorrection = true
  346. try? requestHandler.perform([request])
  347. }
  348. do {
  349. try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL , atomically: true, encoding: .utf8)
  350. } catch {
  351. NCUtility.shared.stopActivityIndicator()
  352. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorCreationFile, forced: true)
  353. return
  354. }
  355. }
  356. if fileType == "PDF" {
  357. let pdfData = NSMutableData()
  358. if password.count > 0 {
  359. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String : password, kCGPDFContextOwnerPassword as String : password]
  360. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  361. } else {
  362. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  363. }
  364. var fontColor = UIColor.clear
  365. #if targetEnvironment(simulator)
  366. fontColor = UIColor.red
  367. #endif
  368. for var image in self.arrayImages {
  369. image = changeCompressionImage(image)
  370. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  371. if self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  372. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  373. image.draw(in: bounds)
  374. let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
  375. let request = VNRecognizeTextRequest { (request, error) in
  376. guard let observations = request.results as? [VNRecognizedTextObservation] else {
  377. NCUtility.shared.stopActivityIndicator()
  378. return
  379. }
  380. for observation in observations {
  381. guard let textLine = observation.topCandidates(1).first else {
  382. continue
  383. }
  384. var t: CGAffineTransform = CGAffineTransform.identity
  385. t = t.scaledBy(x: image.size.width, y: -image.size.height)
  386. t = t.translatedBy(x: 0, y: -1)
  387. let rect = observation.boundingBox.applying(t)
  388. let text = textLine.string
  389. let font = UIFont.systemFont(ofSize: rect.size.height, weight: .regular)
  390. let attributes = self.bestFittingFont(for: text, in: rect, fontDescriptor: font.fontDescriptor, fontColor: fontColor)
  391. text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
  392. }
  393. }
  394. request.recognitionLevel = .accurate
  395. request.usesLanguageCorrection = true
  396. try? requestHandler.perform([request])
  397. } else {
  398. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  399. image.draw(in: bounds)
  400. }
  401. }
  402. UIGraphicsEndPDFContext();
  403. do {
  404. try pdfData.write(toFile: fileNameGenerateExport, options: .atomic)
  405. } catch {
  406. print("error catched")
  407. }
  408. }
  409. if fileType == "JPG" {
  410. let image = changeCompressionImage(self.arrayImages[0])
  411. guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else {
  412. NCUtility.shared.stopActivityIndicator()
  413. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorCreationFile, forced: true)
  414. return
  415. }
  416. do {
  417. try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
  418. } catch {
  419. NCUtility.shared.stopActivityIndicator()
  420. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorCreationFile, forced: true)
  421. return
  422. }
  423. }
  424. NCUtility.shared.stopActivityIndicator()
  425. NCManageDatabase.shared.addMetadata(metadata)
  426. appDelegate.networkingAutoUpload?.startProcess()
  427. // Request delete all image scanned
  428. let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert)
  429. let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  430. let path = CCUtility.getDirectoryScan()!
  431. do {
  432. let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
  433. for filePath in filePaths {
  434. try FileManager.default.removeItem(atPath: path + "/" + filePath)
  435. }
  436. } catch let error as NSError {
  437. print("Error: \(error.debugDescription)")
  438. }
  439. self.dismiss(animated: true, completion: nil)
  440. }
  441. let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  442. self.dismiss(animated: true, completion: nil)
  443. }
  444. alertController.addAction(actionYes)
  445. alertController.addAction(actionNo)
  446. self.present(alertController, animated: true, completion:nil)
  447. }
  448. func cancel() {
  449. self.dismiss(animated: true, completion: nil)
  450. }
  451. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  452. self.deselectFormRow(sender)
  453. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  454. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  455. let viewController = navigationController.topViewController as! NCSelect
  456. viewController.delegate = self
  457. viewController.hideButtonCreateFolder = false
  458. viewController.includeDirectoryE2EEncryption = true
  459. viewController.includeImages = false
  460. viewController.selectFile = false
  461. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  462. viewController.type = ""
  463. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  464. self.present(navigationController, animated: true, completion: nil)
  465. }
  466. func changeCompressionImage(_ image: UIImage) -> UIImage {
  467. var compressionQuality: CGFloat = 0.5
  468. var baseHeight: Float = 595.2 // A4
  469. var baseWidth: Float = 841.8 // A4
  470. switch quality {
  471. case .low:
  472. baseHeight *= 1
  473. baseWidth *= 1
  474. compressionQuality = 0.3
  475. case .medium:
  476. baseHeight *= 2
  477. baseWidth *= 2
  478. compressionQuality = 0.6
  479. case .high:
  480. baseHeight *= 4
  481. baseWidth *= 4
  482. compressionQuality = 0.9
  483. }
  484. var newHeight = Float(image.size.height)
  485. var newWidth = Float(image.size.width)
  486. var imgRatio: Float = newWidth / newHeight
  487. let baseRatio: Float = baseWidth / baseHeight
  488. if newHeight > baseHeight || newWidth > baseWidth {
  489. if imgRatio < baseRatio {
  490. imgRatio = baseHeight / newHeight
  491. newWidth = imgRatio * newWidth
  492. newHeight = baseHeight
  493. }
  494. else if imgRatio > baseRatio {
  495. imgRatio = baseWidth / newWidth
  496. newHeight = imgRatio * newHeight
  497. newWidth = baseWidth
  498. }
  499. else {
  500. newHeight = baseHeight
  501. newWidth = baseWidth
  502. }
  503. }
  504. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  505. UIGraphicsBeginImageContext(rect.size)
  506. image.draw(in: rect)
  507. let img = UIGraphicsGetImageFromCurrentImageContext()
  508. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  509. UIGraphicsEndImageContext()
  510. return UIImage(data: imageData!) ?? image
  511. }
  512. func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor, fontColor: UIColor) -> [NSAttributedString.Key: Any] {
  513. let constrainingDimension = min(bounds.width, bounds.height)
  514. let properBounds = CGRect(origin: .zero, size: bounds.size)
  515. var attributes: [NSAttributedString.Key: Any] = [:]
  516. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  517. var bestFontSize: CGFloat = constrainingDimension
  518. // Search font (H)
  519. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  520. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  521. attributes[.font] = newFont
  522. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  523. if properBounds.contains(currentFrame) {
  524. bestFontSize = fontSize
  525. break
  526. }
  527. }
  528. // Search kern (W)
  529. let font = UIFont(descriptor: fontDescriptor, size: bestFontSize)
  530. attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: 0] as [NSAttributedString.Key : Any]
  531. for kern in stride(from: 0, through: 100, by: 0.1) {
  532. let attributesTmp = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: kern] as [NSAttributedString.Key : Any]
  533. let size = text.size(withAttributes: attributesTmp).width
  534. if size <= bounds.width {
  535. attributes = attributesTmp
  536. } else {
  537. break
  538. }
  539. }
  540. return attributes
  541. }
  542. }
  543. @available(iOS 13.0, *)
  544. class NCCreateScanDocument : NSObject, VNDocumentCameraViewControllerDelegate {
  545. @objc static let shared: NCCreateScanDocument = {
  546. let instance = NCCreateScanDocument()
  547. return instance
  548. }()
  549. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  550. var viewController: UIViewController?
  551. func openScannerDocument(viewController: UIViewController) {
  552. self.viewController = viewController
  553. guard VNDocumentCameraViewController.isSupported else { return }
  554. let controller = VNDocumentCameraViewController()
  555. controller.delegate = self
  556. self.viewController?.present(controller, animated: true)
  557. }
  558. func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
  559. for pageNumber in 0..<scan.pageCount {
  560. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal)!
  561. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  562. let image = scan.imageOfPage(at: pageNumber)
  563. do {
  564. try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath))
  565. } catch { }
  566. }
  567. controller.dismiss(animated: true) {
  568. if self.viewController is DragDropViewController {
  569. (self.viewController as! DragDropViewController).loadImage()
  570. } else {
  571. let storyboard = UIStoryboard(name: "Scan", bundle: nil)
  572. let controller = storyboard.instantiateInitialViewController()!
  573. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  574. self.viewController?.present(controller, animated: true, completion: nil)
  575. }
  576. }
  577. }
  578. func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
  579. controller.dismiss(animated: true, completion: nil)
  580. }
  581. }