NSWindowController+Extension.swift 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // NSWindowController+Extension.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2024/10/17.
  6. //
  7. import Foundation
  8. extension NSWindowController {
  9. //MARK: - show方法,确保居中显示
  10. func showKMWindow(_ sender: Any?) {
  11. self.window?.center()
  12. self.showWindow(sender)
  13. }
  14. func showCheckPassword(url: URL, type: KMPasswordInputWindowType, password: String = "", completion: @escaping ((_ success: Bool, _ resultPassword: String) -> Void)) {
  15. // 判断路径 + document
  16. guard let document = CPDFDocument.init(url: url) else {
  17. return completion(false, "")
  18. }
  19. // 判断是否为加密文档
  20. if document.isLocked == false {
  21. if type == .open {
  22. completion(true, "")
  23. return
  24. }
  25. }
  26. if document.isLocked == false && (document.allowsCopying && document.allowsPrinting) {
  27. completion(true, "")
  28. return
  29. }
  30. // 加密文件,尝试解锁
  31. if password.isEmpty == false {
  32. let preStatus = document.permissionsStatus
  33. document.unlock(withPassword: password)
  34. if document.permissionsStatus.rawValue > preStatus.rawValue { // 解密成功
  35. completion(true, password)
  36. return
  37. }
  38. }
  39. // 弹密码弹窗
  40. Task { @MainActor in
  41. KMPasswordInputWindow.openWindow(window: self.window!, type: type, url: url) { result , password in
  42. if (result == .cancel) {
  43. completion(false, "")
  44. return
  45. } else {
  46. completion(true, password ?? "")
  47. }
  48. }
  49. }
  50. }
  51. }
  52. // MARK: - Sheet
  53. extension NSWindowController {
  54. static var _sheetParentResponderKey = "KMSheetParentResponderKey"
  55. unowned var sheetParentResponder: NSResponder? {
  56. get {
  57. return objc_getAssociatedObject(self, &Self._sheetParentResponderKey) as? NSResponder
  58. }
  59. }
  60. static var _sheetFlagKey = "KMSheetFlagKey"
  61. var sheetFlag: Bool {
  62. get {
  63. return objc_getAssociatedObject(self, &Self._sheetFlagKey) as? Bool ?? false
  64. }
  65. set {
  66. objc_setAssociatedObject(self, &Self._sheetFlagKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
  67. }
  68. }
  69. // MARK: - Private Methods
  70. func _setSheetParentResponder(_ newValue: NSResponder?) {
  71. objc_setAssociatedObject(self, &Self._sheetParentResponderKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
  72. }
  73. }
  74. extension NSWindowController {
  75. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  76. return false
  77. }
  78. }