NCViewerQuickLook.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. //
  2. // NCViewerQuickLook.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 03/05/2020.
  6. // Copyright © 2020 Marino Faggiana. All rights reserved.
  7. // Copyright © 2022 Henrik Storch. All rights reserved.
  8. // Copyright © 2023 Marino Faggiana. All rights reserved.
  9. //
  10. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  11. // Author Henrik Storch <henrik.storch@nextcloud.com>
  12. //
  13. // This program is free software: you can redistribute it and/or modify
  14. // it under the terms of the GNU General Public License as published by
  15. // the Free Software Foundation, either version 3 of the License, or
  16. // (at your option) any later version.
  17. //
  18. // This program is distributed in the hope that it will be useful,
  19. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. // GNU General Public License for more details.
  22. //
  23. // You should have received a copy of the GNU General Public License
  24. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. //
  26. import UIKit
  27. import QuickLook
  28. import NextcloudKit
  29. import Mantis
  30. import SwiftUI
  31. protocol NCViewerQuickLookDelegate: AnyObject {
  32. func dismiss(url: URL, hasChanges: Bool)
  33. }
  34. @objc class NCViewerQuickLook: QLPreviewController {
  35. let url: URL
  36. var previewItems: [PreviewItem] = []
  37. var isEditingEnabled: Bool
  38. var metadata: tableMetadata?
  39. var delegateViewer: NCViewerQuickLookDelegate?
  40. // if the document has any changes (annotations)
  41. var hasChanges = false
  42. // used to display the save alert
  43. var parentVC: UIViewController?
  44. // if the Crop is presented
  45. var isPresentCrop = false
  46. required init?(coder: NSCoder) {
  47. fatalError("init(coder:) has not been implemented")
  48. }
  49. @objc init(with url: URL, isEditingEnabled: Bool, metadata: tableMetadata?) {
  50. self.url = url
  51. self.isEditingEnabled = isEditingEnabled
  52. if let metadata = metadata {
  53. self.metadata = tableMetadata.init(value: metadata)
  54. }
  55. let previewItem = PreviewItem()
  56. previewItem.previewItemURL = url
  57. self.previewItems.append(previewItem)
  58. super.init(nibName: nil, bundle: nil)
  59. self.dataSource = self
  60. self.delegate = self
  61. self.currentPreviewItemIndex = 0
  62. }
  63. override func viewDidLoad() {
  64. super.viewDidLoad()
  65. guard isEditingEnabled else { return }
  66. if metadata?.livePhoto == true {
  67. let error = NKError(errorCode: NCGlobal.shared.errorCharactersForbidden, errorDescription: "_message_disable_overwrite_livephoto_")
  68. NCContentPresenter.shared.showInfo(error: error)
  69. }
  70. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_crop_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(crop))
  71. }
  72. override func viewDidAppear(_ animated: Bool) {
  73. super.viewDidAppear(animated)
  74. // needs to be saved bc in didDisappear presentingVC is already nil
  75. self.parentVC = presentingViewController
  76. }
  77. override func viewDidDisappear(_ animated: Bool) {
  78. super.viewDidDisappear(animated)
  79. guard !isPresentCrop else { return }
  80. delegateViewer?.dismiss(url: url, hasChanges: hasChanges)
  81. guard isEditingEnabled, hasChanges, let metadata = metadata else { return }
  82. let alertController = UIAlertController(title: NSLocalizedString("_save_", comment: ""), message: nil, preferredStyle: .alert)
  83. var message: String?
  84. if metadata.livePhoto {
  85. message = NSLocalizedString("_message_disable_overwrite_livephoto_", comment: "")
  86. } else if metadata.lock {
  87. message = NSLocalizedString("_file_locked_no_override_", comment: "")
  88. } else {
  89. alertController.addAction(UIAlertAction(title: NSLocalizedString("_overwrite_original_", comment: ""), style: .default) { _ in
  90. self.saveModifiedFile(override: true)
  91. })
  92. }
  93. alertController.message = message
  94. alertController.addAction(UIAlertAction(title: NSLocalizedString("_save_as_copy_", comment: ""), style: .default) { _ in
  95. self.saveModifiedFile(override: false)
  96. })
  97. alertController.addAction(UIAlertAction(title: NSLocalizedString("_discard_changes_", comment: ""), style: .destructive) { _ in })
  98. parentVC?.present(alertController, animated: true)
  99. }
  100. @objc func crop() {
  101. guard let image = UIImage(contentsOfFile: url.path) else { return }
  102. let config = Mantis.Config()
  103. if let bundleIdentifier = Bundle.main.bundleIdentifier {
  104. config.localizationConfig.bundle = Bundle(identifier: bundleIdentifier)
  105. config.localizationConfig.tableName = "Localizable"
  106. }
  107. let cropViewController = Mantis.cropViewController(image: image, config: config)
  108. cropViewController.delegate = self
  109. cropViewController.modalPresentationStyle = .fullScreen
  110. self.isPresentCrop = true
  111. self.present(cropViewController, animated: true)
  112. }
  113. }
  114. extension NCViewerQuickLook: QLPreviewControllerDataSource, QLPreviewControllerDelegate {
  115. func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  116. previewItems.count
  117. }
  118. func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  119. previewItems[index]
  120. }
  121. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  122. return isEditingEnabled ? .createCopy : .disabled
  123. }
  124. fileprivate func saveModifiedFile(override: Bool) {
  125. guard let metadata = self.metadata else { return }
  126. let ocId = NSUUID().uuidString
  127. let size = NCUtilityFileSystem.shared.getFileSize(filePath: url.path)
  128. if !override {
  129. let fileName = NCUtilityFileSystem.shared.createFileName(metadata.fileNameView, serverUrl: metadata.serverUrl, account: metadata.account)
  130. metadata.fileName = fileName
  131. metadata.fileNameView = fileName
  132. }
  133. guard let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: metadata.fileNameView),
  134. NCUtilityFileSystem.shared.copyFile(atPath: url.path, toPath: fileNamePath) else { return }
  135. let metadataForUpload = NCManageDatabase.shared.createMetadata(
  136. account: metadata.account,
  137. user: metadata.user,
  138. userId: metadata.userId,
  139. fileName: metadata.fileName,
  140. fileNameView: metadata.fileNameView,
  141. ocId: ocId,
  142. serverUrl: metadata.serverUrl,
  143. urlBase: metadata.urlBase,
  144. url: url.path,
  145. contentType: "")
  146. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  147. if override {
  148. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFileNODelete
  149. } else {
  150. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  151. }
  152. metadataForUpload.size = size
  153. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  154. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: [metadataForUpload]) { _ in }
  155. }
  156. func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL) {
  157. // easier to handle that way than to use `.updateContents`
  158. // needs to be moved otherwise it will only be called once!
  159. guard NCUtilityFileSystem.shared.moveFile(atPath: modifiedContentsURL.path, toPath: url.path) else { return }
  160. hasChanges = true
  161. }
  162. }
  163. extension NCViewerQuickLook: CropViewControllerDelegate {
  164. func cropViewControllerDidCrop(_ cropViewController: Mantis.CropViewController, cropped: UIImage, transformation: Mantis.Transformation, cropInfo: Mantis.CropInfo) {
  165. cropViewController.dismiss(animated: true) {
  166. self.isPresentCrop = false
  167. }
  168. guard let data = cropped.jpegData(compressionQuality: 1) else { return }
  169. do {
  170. try data.write(to: self.url)
  171. reloadData()
  172. } catch { }
  173. }
  174. func cropViewControllerDidCancel(_ cropViewController: Mantis.CropViewController, original: UIImage) {
  175. cropViewController.dismiss(animated: true) {
  176. self.isPresentCrop = false
  177. }
  178. }
  179. }
  180. class PreviewItem: NSObject, QLPreviewItem {
  181. var previewItemURL: URL?
  182. }
  183. // MARK: - UIViewControllerRepresentable
  184. struct ViewerQuickLook: UIViewControllerRepresentable {
  185. typealias UIViewControllerType = NCViewerQuickLook
  186. // let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  187. // CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  188. @Binding var fileNamePath: String
  189. @Binding var metadata: tableMetadata?
  190. @Environment(\.presentationMode) var presentationMode
  191. class Coordinator: NCViewerQuickLookDelegate {
  192. var parent: ViewerQuickLook
  193. var isModified: Bool = false
  194. init(_ parent: ViewerQuickLook) {
  195. self.parent = parent
  196. }
  197. // DELEGATE
  198. func dismiss(url: URL, hasChanges: Bool) {
  199. }
  200. }
  201. func makeCoordinator() -> Coordinator {
  202. Coordinator(self)
  203. }
  204. func makeUIViewController(context: Context) -> UIViewControllerType {
  205. let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), isEditingEnabled: true, metadata: metadata)
  206. viewerQuickLook.delegateViewer = context.coordinator
  207. return viewerQuickLook
  208. }
  209. func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { }
  210. }