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