NCCreateFormUploadScanDocument.swift 30 KB

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