NCUploadScanDocument.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. //
  2. // NCUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 28/12/22.
  6. // Copyright © 2022 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 SwiftUI
  24. import NextcloudKit
  25. import Vision
  26. import VisionKit
  27. import Photos
  28. import PDFKit
  29. class NCHostingUploadScanDocumentView: NSObject {
  30. @objc func makeShipDetailsUI(images: [UIImage], userBaseUrl: NCUserBaseUrl, serverUrl: String) -> UIViewController {
  31. let uploadScanDocument = NCUploadScanDocument(images: images, userBaseUrl: userBaseUrl, serverUrl: serverUrl)
  32. let details = UploadScanDocumentView(uploadScanDocument)
  33. let vc = UIHostingController(rootView: details)
  34. // vc.title = NSLocalizedString("_save_settings_", comment: "")
  35. return vc
  36. }
  37. }
  38. class NCUploadScanDocument: ObservableObject {
  39. @Published var userBaseUrl: NCUserBaseUrl
  40. @Published var serverUrl: String
  41. @Published var isTextRecognition: Bool = false
  42. @Published var size: String = ""
  43. @Published var url: URL = Bundle.main.url(forResource: "Reasons to use Nextcloud", withExtension: "pdf")!
  44. let fileNameDefault = NSTemporaryDirectory() + "scandocument.pdf"
  45. var images: [UIImage]
  46. init(images: [UIImage], userBaseUrl: NCUserBaseUrl, serverUrl: String) {
  47. self.images = images
  48. self.userBaseUrl = userBaseUrl
  49. self.serverUrl = serverUrl
  50. createPDF()
  51. }
  52. func createPDF(password: String = "", textRecognition: Bool = false, quality: Double = 1) {
  53. guard !images.isEmpty else { return }
  54. let pdfData = NSMutableData()
  55. if password.isEmpty {
  56. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  57. } else {
  58. for char in password.unicodeScalars {
  59. if !char.isASCII {
  60. NCActivityIndicator.shared.stop()
  61. let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_")
  62. NCContentPresenter.shared.showError(error: error)
  63. return
  64. }
  65. }
  66. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password]
  67. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  68. }
  69. for var image in images {
  70. image = changeCompressionImage(image, quality: quality)
  71. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  72. if textRecognition {
  73. } else {
  74. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  75. image.draw(in: bounds)
  76. }
  77. }
  78. UIGraphicsEndPDFContext()
  79. do {
  80. url = URL(fileURLWithPath: fileNameDefault)
  81. try pdfData.write(to: url, options: .atomic)
  82. } catch {
  83. print("error catched")
  84. }
  85. size = CCUtility.transformedSize(NCUtilityFileSystem.shared.getFileSize(filePath: fileNameDefault))
  86. }
  87. func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  88. var compressionQuality: CGFloat = 0.5
  89. var baseHeight: Float = 595.2 // A4
  90. var baseWidth: Float = 841.8 // A4
  91. switch quality {
  92. case 0:
  93. baseHeight *= 1
  94. baseWidth *= 1
  95. compressionQuality = 0.3
  96. case 1:
  97. baseHeight *= 2
  98. baseWidth *= 2
  99. compressionQuality = 0.6
  100. case 2:
  101. baseHeight *= 4
  102. baseWidth *= 4
  103. compressionQuality = 0.8
  104. case 3:
  105. baseHeight *= 6
  106. baseWidth *= 6
  107. compressionQuality = 0.9
  108. case 4:
  109. baseHeight *= 8
  110. baseWidth *= 8
  111. compressionQuality = 1
  112. default:
  113. break
  114. }
  115. var newHeight = Float(image.size.height)
  116. var newWidth = Float(image.size.width)
  117. var imgRatio: Float = newWidth / newHeight
  118. let baseRatio: Float = baseWidth / baseHeight
  119. if newHeight > baseHeight || newWidth > baseWidth {
  120. if imgRatio < baseRatio {
  121. imgRatio = baseHeight / newHeight
  122. newWidth = imgRatio * newWidth
  123. newHeight = baseHeight
  124. } else if imgRatio > baseRatio {
  125. imgRatio = baseWidth / newWidth
  126. newHeight = imgRatio * newHeight
  127. newWidth = baseWidth
  128. } else {
  129. newHeight = baseHeight
  130. newWidth = baseWidth
  131. }
  132. }
  133. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  134. UIGraphicsBeginImageContext(rect.size)
  135. image.draw(in: rect)
  136. let img = UIGraphicsGetImageFromCurrentImageContext()
  137. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  138. UIGraphicsEndImageContext()
  139. return UIImage(data: imageData!) ?? image
  140. }
  141. }
  142. extension NCUploadScanDocument: NCSelectDelegate {
  143. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  144. if let serverUrl = serverUrl {
  145. CCUtility.setDirectoryScanDocuments(serverUrl)
  146. self.serverUrl = serverUrl
  147. /*
  148. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) {
  149. self.titleServerUrl = "/"
  150. } else {
  151. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  152. }
  153. // Update
  154. let row: XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  155. row.title = self.titleServerUrl
  156. self.updateFormRow(row)
  157. */
  158. }
  159. }
  160. }
  161. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  162. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  163. }
  164. }
  165. // MARK: - Preview / Test
  166. struct UploadScanDocumentView: View {
  167. @State var quality = 2.0
  168. @State var password: String = ""
  169. @State var filename: String = ""
  170. @State var isSecured: Bool = true
  171. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  172. init(_ uploadScanDocument: NCUploadScanDocument) {
  173. self.uploadScanDocument = uploadScanDocument
  174. }
  175. var body: some View {
  176. GeometryReader { geo in
  177. List {
  178. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  179. HStack {
  180. Label {
  181. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadScanDocument.userBaseUrl.urlBase, userId: uploadScanDocument.userBaseUrl.userId) == uploadScanDocument.serverUrl {
  182. Text("/")
  183. .frame(maxWidth: .infinity, alignment: .trailing)
  184. } else {
  185. Text((uploadScanDocument.serverUrl as NSString).lastPathComponent)
  186. .frame(maxWidth: .infinity, alignment: .trailing)
  187. }
  188. } icon: {
  189. Image("folder")
  190. .renderingMode(.template)
  191. .resizable()
  192. .scaledToFit()
  193. .foregroundColor(Color(NCBrandColor.shared.brand))
  194. }
  195. Spacer()
  196. }
  197. .contentShape(Rectangle())
  198. .onTapGesture {
  199. //
  200. }
  201. .complexModifier { view in
  202. if #available(iOS 16, *) {
  203. view.alignmentGuide(.listRowSeparatorLeading) { _ in
  204. return 0
  205. }
  206. }
  207. }
  208. HStack {
  209. Text(NSLocalizedString("_filename_", comment: ""))
  210. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $filename)
  211. .multilineTextAlignment(.trailing)
  212. }
  213. HStack {
  214. Group {
  215. Text(NSLocalizedString("_password_", comment: ""))
  216. if isSecured {
  217. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  218. .multilineTextAlignment(.trailing)
  219. } else {
  220. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  221. .multilineTextAlignment(.trailing)
  222. }
  223. }
  224. Button(action: {
  225. isSecured.toggle()
  226. }) {
  227. Image(systemName: self.isSecured ? "eye.slash" : "eye")
  228. .accentColor(.gray)
  229. }
  230. }
  231. HStack {
  232. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $uploadScanDocument.isTextRecognition)
  233. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  234. .onChange(of: uploadScanDocument.isTextRecognition) { newValue in
  235. }
  236. }
  237. }
  238. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: "")), footer: Text( NSLocalizedString("_file_size_", comment: "") + " \(uploadScanDocument.size)")) {
  239. VStack {
  240. Slider(value: $quality, in: 0...4, step: 1).onChange(of: quality, perform: { quality in
  241. uploadScanDocument.createPDF(quality: quality)
  242. })
  243. .accentColor(Color(NCBrandColor.shared.brand))
  244. }
  245. PDFKitRepresentedView(uploadScanDocument.url)
  246. .frame(maxWidth: .infinity, minHeight: geo.size.height / 2.7)
  247. }.complexModifier { view in
  248. if #available(iOS 15, *) {
  249. view.listRowSeparator(.hidden)
  250. }
  251. }
  252. Button(NSLocalizedString("_save_", comment: "")) {
  253. print("ciao")
  254. }
  255. .buttonStyle(NCButton(disabled: true))
  256. .frame(maxWidth: .infinity, alignment: .center)
  257. .listRowBackground(Color(UIColor.systemGroupedBackground))
  258. }
  259. }
  260. .background(Color(UIColor.systemGroupedBackground))
  261. }
  262. }
  263. struct NCButton: ButtonStyle {
  264. var disabled = false
  265. func makeBody(configuration: Configuration) -> some View {
  266. configuration.label
  267. .padding(.horizontal, 40)
  268. .padding(.vertical, 10)
  269. .background(disabled ? Color(UIColor.systemGray4) : Color(NCBrandColor.shared.brand))
  270. .foregroundColor(.white)
  271. .clipShape(Capsule())
  272. }
  273. }
  274. struct PDFKitRepresentedView: UIViewRepresentable {
  275. let url: URL
  276. init(_ url: URL) {
  277. self.url = url
  278. }
  279. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  280. let pdfView = PDFView()
  281. pdfView.document = PDFDocument(url: self.url)
  282. pdfView.autoScales = true
  283. pdfView.backgroundColor = .clear
  284. pdfView.displayMode = .singlePage
  285. pdfView.displayDirection = .vertical
  286. return pdfView
  287. }
  288. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  289. }
  290. }
  291. struct UploadScanDocumentView_Previews: PreviewProvider {
  292. static var previews: some View {
  293. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  294. let uploadScanDocument = NCUploadScanDocument(images: [], userBaseUrl: appDelegate, serverUrl: "")
  295. UploadScanDocumentView(uploadScanDocument)
  296. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  297. // .previewDisplayName("iPhone 14")
  298. }
  299. }
  300. }