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