NCCreateFormUploadScanDocument.swift 32 KB

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