123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- //
- // 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)
- }
- }
|