Преглед изворни кода

【页面编辑】KMPDFEditWindowController OC转Swift

tangchao пре 1 година
родитељ
комит
6c53e6b257

+ 9 - 20
PDF Office/PDF Master/Class/Home/ViewController/KMHomeViewController+Action.swift

@@ -1251,27 +1251,16 @@ extension KMHomeViewController {
                 return
             }
             
-//            if !openPanel.url!.path.isPDFValid() {
-//                let alert = NSAlert()
-//                alert.alertStyle = .critical
-//                alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
-//                alert.runModal()
-//                return
-//            }
-//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
-//                NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
-//                    if (error != nil) {
-//                        NSApp.presentError(error!)
-//                        return
-//                    }
-//
-//                    let mainView = (document as! KMMainDocument).mainViewController
-//                    mainView?.enterPageEdit()
-//                }
-//            }
+            if !openPanel.url!.path.isPDFValid() {
+                let alert = NSAlert()
+                alert.alertStyle = .critical
+                alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
+                alert.runModal()
+                return
+            }
             
-            let windowC = KMPDFEditWindowController(windowNibName: "KMPDFEditWindowController")
-            self.km_beginSheet(windowC: windowC)
+            let windowC = KMPDFEditWindowController(filepath: openPanel.url!.path, password: nil)
+            windowC.startModal(nil)
         }
     }
     

+ 89 - 107
PDF Office/PDF Master/Class/PDFTools/PageEdit/Window/KMPDFEditWindowController.swift

@@ -8,118 +8,100 @@
 import Cocoa
 
 class KMPDFEditWindowController: NSWindowController {
-    /*
-     - (instancetype)initWithPDFFilePath:(NSString *)filePath password:(NSString *)password;
-
-     - (IBAction)startModal:(id)sender;
-     - (IBAction)endModal:(id)sender;
-     */
+    private var _viewController: KMPDFEditViewController?
+    private var _modalSession: NSApplication.ModalSession?
     
-    /*
-     @interface KMPDFEditWindowController ()
-
-     @property (nonatomic,assign) NSModalSession modalSession;
-
-     @property (nonatomic,retain) KMPDFEditViewController *viewController;
-
-     @end
-
-     @implementation KMPDFEditWindowController
-
-     #pragma mark - Init Methods
-
-     - (id)initWithPDFFilePath:(NSString *)filePath password:(nullable NSString *)password{
-         if (self = [super initWithWindowNibName:@"KMPDFEditWindowController"]) {
-             _viewController = [[KMPDFEditViewController alloc] initWithPDFFilePath:filePath password:password];
-         }
-         return self;
-     }
-
-     - (void)dealloc {
-         [_viewController release];
-         [super dealloc];
-     }
-
-     #pragma mark - Window Methods
-
-     - (void)windowDidLoad {
-         [super windowDidLoad];
-         self.window.title = NSLocalizedString(@"Page Edit", nil);
-         if ([self respondsToSelector:@selector(setContentViewController:)]) {
-             [self setContentViewController:self.viewController];
-         } else {
-             self.viewController.view.frame = self.window.contentView.bounds;
-             [self.window.contentView addSubview:self.viewController.view];
-         }
-     }
-
-     - (BOOL)windowShouldClose:(id)sender {
-         if (self.viewController.isEdited) {
-             [self saveCurrentPDFDocument];
-             return NO;
-         } else {
-             [self endModal:sender];
-         }
-         return YES;
-     }
-
-     - (void)close {
-         [super close];
-         [self endModal:nil];
-     }
-
-     - (IBAction)startModal:(id)sender {
-         [self retain];
-         
-         [NSApp stopModal];
-         
-         NSInteger modalCode;
-         self.modalSession = [NSApp beginModalSessionForWindow:self.window];
-         do {
-             modalCode = [NSApp runModalSession:self.modalSession];
-         } while (modalCode == NSRunContinuesResponse);
-     }
-
-     - (IBAction)endModal:(id)sender {
-         if (self.modalSession) {
-             [NSApp stopModal];
-             [NSApp endModalSession:self.modalSession];
-             [self.window orderOut:self];
-             [self release];
-         }
-     }
-
-     - (void)saveCurrentPDFDocument {
-         NSSavePanel *savePanel = [NSSavePanel savePanel];
-         savePanel.nameFieldStringValue = self.viewController.pdfDocument.documentURL.lastPathComponent.stringByDeletingPathExtension;
-         savePanel.allowedFileTypes = @[@"pdf"];
-         [savePanel beginSheetModalForWindow:[NSApp mainWindow] completionHandler:^(NSInteger result) {
-             if (result) {
-                 NSURL *savePath = savePanel.URL;
-                 BOOL didWrite = NO;
-                 if (self.viewController.pdfDocument.isEncrypted && self.viewController.password) {
-                     NSMutableDictionary * dic = [NSMutableDictionary dictionary];
-                     [dic setObject:self.viewController.password forKey:(NSString *)kCGPDFContextUserPassword];
-                     [dic setObject:self.viewController.password forKey:(NSString *)kCGPDFContextOwnerPassword];
-                     didWrite = [[self.viewController pdfDocument] writeToURL:savePath withOptions:dic];
-                 } else {
-                     didWrite = [[self.viewController pdfDocument] writeToURL:savePath];
-                 }
-                 if (didWrite) {
-                     NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
-                     [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:savePath]];
-                 }
-             }
-             [self close];
-         }];
-     }
-
-     */
+    private var _isEdited = false
+    
+    convenience init(filepath: String, password: String?) {
+        self.init(windowNibName: "KMPDFEditWindowController")
+        
+        if let document = CPDFDocument(url: URL(fileURLWithPath: filepath)) {
+            self._viewController = KMPDFEditViewController(document)
+            self._viewController?.documentEditedCallback = { [unowned self] _ in
+                self._isEdited = true
+            }
+        }
+    }
 
     override func windowDidLoad() {
         super.windowDidLoad()
     
-        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
+        self.window?.title = KMLocalizedString("Page Edit", nil)
+        if self.responds(to: NSSelectorFromString("setContentViewController:")) {
+            self.contentViewController = self._viewController
+        } else {
+            if let vc = self._viewController {
+                vc.view.frame = self.window?.contentView?.bounds ?? .zero
+                self.window?.contentView?.addSubview(vc.view)
+            }
+        }
+    }
+    
+    @IBAction func startModal(_ sender: AnyObject?) {
+        NSApp.stopModal()
+        
+        var modalCode: NSApplication.ModalResponse?
+        if let _win = self.window {
+            self._modalSession = NSApp.beginModalSession(for: _win)
+            repeat {
+                modalCode = NSApp.runModalSession(self._modalSession!)
+            } while (modalCode == .continue)
+        }
+    }
+    
+    @IBAction func endModal(_ sender: AnyObject?) {
+        if let session = self._modalSession {
+            NSApp.stopModal()
+            NSApp.endModalSession(session)
+            self.window?.orderOut(self)
+        }
     }
+}
 
+extension KMPDFEditWindowController: NSWindowDelegate {
+    func windowShouldClose(_ sender: NSWindow) -> Bool {
+        if (self._isEdited) {
+            self._saveCurrentPDFDocument()
+            return false
+        } else {
+            self.endModal(sender)
+        }
+        return true
+    }
+    
+    override func close() {
+        super.close()
+        self.endModal(nil)
+    }
+}
+
+// MARK: - Private Methods
+
+extension KMPDFEditWindowController {
+    private func _saveCurrentPDFDocument() {
+        let savePanel = NSSavePanel()
+        savePanel.nameFieldStringValue = self._viewController?.thumbnailView.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
+        savePanel.allowedFileTypes = ["pdf"]
+        savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
+            if result.rawValue > 0 {
+                let savePath = savePanel.url!
+                var didWrite = false
+                guard let _doc = self._viewController?.thumbnailView.document else {
+                    self.close()
+                    return
+                }
+                if (_doc.isEncrypted && _doc.password.isEmpty == false) {
+                    didWrite = _doc.write(to: savePath, withOptions: [.userPasswordOption : _doc.password as Any, .ownerPasswordOption : _doc.password as Any])
+                } else {
+                    didWrite = _doc.write(to: savePath)
+                }
+                if (didWrite) {
+                    let workspace = NSWorkspace.shared
+                    workspace.activateFileViewerSelecting([savePath])
+                }
+            }
+            self.close()
+        }
+    }
 }