NCCreateFormUploadScanDocument.swift 32 KB

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