NCCreateFormUploadScanDocument.swift 31 KB

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