NCCreateFormUploadScanDocument.swift 32 KB

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