NCCreateFormUploadScanDocument.swift 30 KB

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