// // PasswordWindowController.swift // PDF Master // // Created by kdanmobile on 2023/11/2. // import Cocoa @objc(PasswordWindowDelegate) protocol PasswordWindowDelegate: AnyObject { @objc optional func didFinshedUnlockFile(_ passwordWindowCtr: PasswordWindowController, password: String) @objc optional func didCancelUnlockFile(_ passwordWindowCtr: PasswordWindowController) } @objc class PasswordWindowController: NSWindowController{ var fileURL: URL? var delegate: PasswordWindowDelegate? var tag: Int = 0 var password: String? @IBOutlet var passwordTextField: NSSecureTextField! @IBOutlet var titleTextField: NSTextField! @IBOutlet var textField: NSTextField! @IBOutlet var openButton: NSButton! @IBOutlet var cancelButton: NSButton! override init(window: NSWindow?) { super.init(window: window) } required init?(coder: NSCoder) { super.init(coder: coder) } override func windowDidLoad() { super.windowDidLoad() titleTextField.stringValue = fileURL?.lastPathComponent ?? "" textField.stringValue = NSLocalizedString("This PDF is password protected. Please enter the password below to access this PDF.", comment: "") openButton.title = NSLocalizedString("Open", comment: "") cancelButton.title = NSLocalizedString("Cancel", comment: "") } @IBAction func cancelAction(_ sender: NSButton) { self.close() } @IBAction func OKAction(_ sender: NSButton) { let pdfDoc = PDFDocument(url: fileURL!) if pdfDoc != nil { let isOk = pdfDoc?.unlock(withPassword: passwordTextField.stringValue) if isOk! { if pdfDoc?.permissionsStatus == .owner { self.password = passwordTextField.stringValue self.close() } else{ self.incorrectPasswordAlert() } } else { self.incorrectPasswordAlert() } } } func incorrectPasswordAlert() { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("Incorrect password. Please check your password and try again.", comment: "") alert.runModal() } @objc func didEndSheet(_ sheet: NSWindow, returnCode: NSInteger, contextInfo: UnsafeMutableRawPointer?) { if contextInfo != nil { let handler = contextInfo!.assumingMemoryBound(to: ((String) -> Void).self).pointee handler(password ?? "") } } func beginSheetModalForWindow(_ window: NSWindow, completionHandler handler: ((String) -> Void)?) { // self.window?.beginSheet(window) NSApp.beginSheet(self.window!, modalFor: window, modalDelegate: self, didEnd: #selector(didEndSheet(_:returnCode:contextInfo:)), contextInfo: handler != nil ? unsafeBitCast(handler, to: UnsafeMutableRawPointer.self) : nil) } override func close() { NSApp.endSheet(self.window!) self.window?.orderOut(self) } }