Browse Source

Merge pull request #1926 from nextcloud/fix/quick-look

Fix QuickLook overriding files
Marino Faggiana 3 years ago
parent
commit
76459b1435

+ 0 - 1
.swiftlint.yml

@@ -135,7 +135,6 @@ excluded:
   - iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift
   - iOSClient/Viewer/NCViewerPDF/NCViewerPDFSearch.swift
   - iOSClient/Viewer/NCViewerProviderContextMenu.swift
-  - iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift
   - iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift
 
 

+ 2 - 5
iOSClient/Main/NCFunctionCenter.swift

@@ -77,11 +77,8 @@ import SVGKit
                 editingMode = true
             }
 
-            let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), editingMode: editingMode, metadata: metadata)
-            let navigationController = UINavigationController(rootViewController: viewerQuickLook)
-            navigationController.modalPresentationStyle = .overFullScreen
-
-            self.appDelegate.window?.rootViewController?.present(navigationController, animated: true)
+            let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), isEditingEnabled: editingMode, metadata: metadata)
+            self.appDelegate.window?.rootViewController?.present(viewerQuickLook, animated: true)
 
         case NCGlobal.shared.selectorLoadFileView:
             guard UIApplication.shared.applicationState == UIApplication.State.active else { break }

+ 1 - 2
iOSClient/Settings/CCAdvanced.m

@@ -173,8 +173,7 @@
         row.action.formBlock = ^(XLFormRowDescriptor * sender) {
                     
             [self deselectFormRow:sender];
-            
-            NCViewerQuickLook *viewerQuickLook = [[NCViewerQuickLook alloc] initWith:[NSURL fileURLWithPath:NCCommunicationCommon.shared.filenamePathLog] editingMode:false metadata:nil];
+            NCViewerQuickLook *viewerQuickLook = [[NCViewerQuickLook alloc] initWith:[NSURL fileURLWithPath:NCCommunicationCommon.shared.filenamePathLog] isEditingEnabled:false metadata:nil];
             UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewerQuickLook];
             navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
             

+ 2 - 5
iOSClient/Viewer/NCViewer.swift

@@ -208,11 +208,8 @@ class NCViewer: NSObject {
 
         CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
 
-        let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), editingMode: false, metadata: metadata)
-        let navigationController = UINavigationController(rootViewController: viewerQuickLook)
-        navigationController.modalPresentationStyle = .overFullScreen
-
-        viewController.present(navigationController, animated: true)
+        let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), isEditingEnabled: false, metadata: metadata)
+        viewController.present(viewerQuickLook, animated: true)
     }
 }
 

+ 1 - 1
iOSClient/Viewer/NCViewerMedia/NCViewerMedia.swift

@@ -41,7 +41,7 @@ class NCViewerMedia: UIViewController {
     private var _autoPlay: Bool = false
 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    var viewerMediaPage: NCViewerMediaPage?
+    weak var viewerMediaPage: NCViewerMediaPage?
     var ncplayer: NCPlayer?
     var image: UIImage?
     var metadata: tableMetadata = tableMetadata()

+ 13 - 14
iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift

@@ -104,9 +104,8 @@ class NCViewerMediaPage: UIViewController {
         NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
     }
 
-    override func viewDidDisappear(_ animated: Bool) {
-        super.viewDidDisappear(animated)
-
+    deinit {
+        print("#deinit NCViewerMediaPage")
         // Clear
         if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
             ncplayer.playerPause()
@@ -117,11 +116,11 @@ class NCViewerMediaPage: UIViewController {
 
         metadatas.removeAll()
         ncplayerLivePhoto = nil
-        
+
         #if MFFFLIB
         MFFF.shared.dismissMessage()
         #endif
-        
+
         // Remove Observer
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
@@ -341,19 +340,19 @@ class NCViewerMediaPage: UIViewController {
         if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
 
             MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = true
-            skipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { event in
+            skipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { [weak self] event in
 
                 let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
-                self.currentViewController.playerToolBar.skip(seconds: seconds)
-                return.success
+                self?.currentViewController.playerToolBar.skip(seconds: seconds)
+                return .success
             }
 
             MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = true
-            skipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { event in
+            skipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { [weak self] event in
 
                 let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
-                self.currentViewController.playerToolBar.skip(seconds: -seconds)
-                return.success
+                self?.currentViewController.playerToolBar.skip(seconds: -seconds)
+                return .success
             }
         }
 
@@ -474,15 +473,15 @@ extension NCViewerMediaPage: UIPageViewControllerDelegate, UIPageViewControllerD
 
         if currentIndex == 0 { return nil }
 
-        let viewerMedia = getViewerMedia(index: currentIndex-1, metadata: metadatas[currentIndex-1])
+        let viewerMedia = getViewerMedia(index: currentIndex - 1, metadata: metadatas[currentIndex - 1])
         return viewerMedia
     }
 
     func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
 
-        if currentIndex == metadatas.count-1 { return nil }
+        if currentIndex == metadatas.count - 1 { return nil }
 
-        let viewerMedia = getViewerMedia(index: currentIndex+1, metadata: metadatas[currentIndex+1])
+        let viewerMedia = getViewerMedia(index: currentIndex + 1, metadata: metadatas[currentIndex + 1])
         return viewerMedia
     }
 

+ 76 - 97
iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift

@@ -4,8 +4,10 @@
 //
 //  Created by Marino Faggiana on 03/05/2020.
 //  Copyright © 2020 Marino Faggiana. All rights reserved.
+//  Copyright © 2022 Henrik Storch. All rights reserved.
 //
 //  Author Marino Faggiana <marino.faggiana@nextcloud.com>
+//  Author Henrik Storch <henrik.storch@nextcloud.com>
 //
 //  This program is free software: you can redistribute it and/or modify
 //  it under the terms of the GNU General Public License as published by
@@ -27,26 +29,24 @@ import NCCommunication
 
 @objc class NCViewerQuickLook: QLPreviewController {
 
-    let appDelegate = UIApplication.shared.delegate as! AppDelegate
-    var url: URL?
+    let url: URL
     var previewItems: [PreviewItem] = []
-    var editingMode: Bool
-    enum saveModeType {
-        case overwrite
-        case copy
-        case discard
-    }
-    var saveMode: saveModeType = .discard
+    var isEditingEnabled: Bool
     var metadata: tableMetadata?
 
+    // if the document has any changes (annotations)
+    var hasChanges = false
+
+    // used to display the save alert
+    var parentVC: UIViewController?
+
     required init?(coder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 
-    @objc init(with url: URL, editingMode: Bool, metadata: tableMetadata?) {
-
+    @objc init(with url: URL, isEditingEnabled: Bool, metadata: tableMetadata?) {
         self.url = url
-        self.editingMode = editingMode
+        self.isEditingEnabled = isEditingEnabled
         if let metadata = metadata {
             self.metadata = tableMetadata.init(value: metadata)
         }
@@ -60,72 +60,46 @@ import NCCommunication
         self.dataSource = self
         self.delegate = self
         self.currentPreviewItemIndex = 0
-
-        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissPreviewController))
     }
 
     override func viewDidLoad() {
         super.viewDidLoad()
-
-        if editingMode && metadata?.classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
-            Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { t in
-                if self.navigationItem.rightBarButtonItems?.count ?? 0 > 1 || !(self.navigationController?.isToolbarHidden ?? false) {
-                    if #available(iOS 14.0, *) {
-                        if self.navigationItem.rightBarButtonItems?.count ?? 0 > 1 {
-                            if let buttonItem = self.navigationItem.rightBarButtonItems?.last {
-                                _ = buttonItem.target?.perform(buttonItem.action, with: buttonItem)
-                            }
-                        } else {
-                            if let buttonItem = self.navigationItem.rightBarButtonItems?.first {
-                                _ = buttonItem.target?.perform(buttonItem.action, with: buttonItem)
-                            }
-                        }
-                    } else {
-                        if let buttonItem = self.navigationItem.rightBarButtonItems?.filter({$0.customView != nil}).first?.customView as? UIButton {
-                            buttonItem.sendActions(for: .touchUpInside)
-                        }
-                    }
-                    t.invalidate()
-                }
-            })
-        }
-
-        if editingMode && metadata?.livePhoto == true {
-            NCContentPresenter.shared.messageNotification("", description: "_message_disable_overwrite_livephoto_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorCharactersForbidden)
+        guard isEditingEnabled else { return }
+
+        if metadata?.livePhoto == true {
+            NCContentPresenter.shared.messageNotification(
+                "", description: "_message_disable_overwrite_livephoto_",
+                delay: NCGlobal.shared.dismissAfterSecond,
+                type: NCContentPresenter.messageType.info,
+                errorCode: NCGlobal.shared.errorCharactersForbidden)
         }
     }
 
-    @objc func dismissPreviewController() {
-
-        if editingMode {
+    override func viewDidAppear(_ animated: Bool) {
+        super.viewDidAppear(animated)
+        // needs to be saved bc in didDisappear presentingVC is already nil
+        self.parentVC = presentingViewController
+    }
 
-            let alertController = UIAlertController(title: NSLocalizedString("_save_", comment: ""), message: "", preferredStyle: .alert)
+    override func viewDidDisappear(_ animated: Bool) {
+        // called after `previewController(:didSaveEditedCopyOf:)`
+        super.viewDidDisappear(animated)
 
-            if metadata?.livePhoto == false {
-                alertController.addAction(UIAlertAction(title: NSLocalizedString("_overwrite_original_", comment: ""), style: .default) { (_: UIAlertAction) in
-                    self.saveMode = .overwrite
-                    self.dismiss(animated: true)
-                })
-            }
+        guard isEditingEnabled, hasChanges else { return }
 
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_save_as_copy_", comment: ""), style: .default) { (_: UIAlertAction) in
-                self.saveMode = .copy
-                self.dismiss(animated: true)
-            })
+        let alertController = UIAlertController(title: NSLocalizedString("_save_", comment: ""), message: "", preferredStyle: .alert)
 
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_discard_changes_", comment: ""), style: .destructive) { (_: UIAlertAction) in
-                self.saveMode = .discard
-                self.dismiss(animated: true)
+        if metadata?.livePhoto == false {
+            alertController.addAction(UIAlertAction(title: NSLocalizedString("_overwrite_original_", comment: ""), style: .default) { _ in
+                self.saveModifiedFile(override: true)
             })
-
-            alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (_: UIAlertAction) in })
-
-            self.present(alertController, animated: true)
-
-        } else {
-
-            self.dismiss(animated: true)
         }
+
+        alertController.addAction(UIAlertAction(title: NSLocalizedString("_save_as_copy_", comment: ""), style: .default) { _ in
+            self.saveModifiedFile(override: false)
+        })
+        alertController.addAction(UIAlertAction(title: NSLocalizedString("_discard_changes_", comment: ""), style: .destructive) { _ in })
+        parentVC?.present(alertController, animated: true)
     }
 }
 
@@ -139,46 +113,51 @@ extension NCViewerQuickLook: QLPreviewControllerDataSource, QLPreviewControllerD
         previewItems[index]
     }
 
-    func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
-    }
-
     @available(iOS 13.0, *)
     func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
-        if editingMode {
-            return .createCopy
-        } else {
-            return .disabled
-        }
+        return isEditingEnabled ? .createCopy : .disabled
     }
 
-    func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL) {
-
-        if saveMode != .discard {
+    fileprivate func saveModifiedFile(override: Bool) {
+        guard let metadata = self.metadata else { return }
 
-            guard let metadata = self.metadata else { return }
-            let ocId = NSUUID().uuidString
-            let size = NCUtilityFileSystem.shared.getFileSize(filePath: modifiedContentsURL.path)
+        let ocId = NSUUID().uuidString
+        let size = NCUtilityFileSystem.shared.getFileSize(filePath: url.path)
 
-            if saveMode == .copy {
-                let fileName = NCUtilityFileSystem.shared.createFileName(metadata.fileNameView, serverUrl: metadata.serverUrl, account: metadata.account)
-                metadata.fileName = fileName
-                metadata.fileNameView = fileName
-            }
-
-            let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: metadata.fileNameView)!
-
-            if NCUtilityFileSystem.shared.copyFile(atPath: modifiedContentsURL.path, toPath: fileNamePath) {
-
-                let metadataForUpload = NCManageDatabase.shared.createMetadata(account: metadata.account, user: metadata.user, userId: metadata.userId, fileName: metadata.fileName, fileNameView: metadata.fileNameView, ocId: ocId, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, url: modifiedContentsURL.path, contentType: "", livePhoto: false)
+        if !override {
+            let fileName = NCUtilityFileSystem.shared.createFileName(metadata.fileNameView, serverUrl: metadata.serverUrl, account: metadata.account)
+            metadata.fileName = fileName
+            metadata.fileNameView = fileName
+        }
 
-                metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
-                metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
-                metadataForUpload.size = size
-                metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
+        guard let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: metadata.fileNameView),
+              NCUtilityFileSystem.shared.copyFile(atPath: url.path, toPath: fileNamePath) else { return }
+
+        let metadataForUpload = NCManageDatabase.shared.createMetadata(
+            account: metadata.account,
+            user: metadata.user,
+            userId: metadata.userId,
+            fileName: metadata.fileName,
+            fileNameView: metadata.fileNameView,
+            ocId: ocId,
+            serverUrl: metadata.serverUrl,
+            urlBase: metadata.urlBase,
+            url: url.path,
+            contentType: "",
+            livePhoto: false)
+
+        metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
+        metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
+        metadataForUpload.size = size
+        metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
+        (UIApplication.shared.delegate as? AppDelegate)?.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload])
+    }
 
-                appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload])
-            }
-        }
+    func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL) {
+        // easier to handle that way than to use `.updateContents`
+        // needs to be moved otherwise it will only be called once!
+        guard NCUtilityFileSystem.shared.moveFile(atPath: modifiedContentsURL.path, toPath: url.path) else { return }
+        hasChanges = true
     }
 }