NSWindowController+Extension.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. }
  15. // MARK: - Sheet
  16. extension NSWindowController {
  17. static var _sheetParentResponderKey = "KMSheetParentResponderKey"
  18. unowned var sheetParentResponder: NSResponder? {
  19. get {
  20. return objc_getAssociatedObject(self, &Self._sheetParentResponderKey) as? NSResponder
  21. }
  22. }
  23. static var _sheetFlagKey = "KMSheetFlagKey"
  24. var sheetFlag: Bool {
  25. get {
  26. return objc_getAssociatedObject(self, &Self._sheetFlagKey) as? Bool ?? false
  27. }
  28. set {
  29. objc_setAssociatedObject(self, &Self._sheetFlagKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
  30. }
  31. }
  32. // MARK: - Private Methods
  33. func _setSheetParentResponder(_ newValue: NSResponder?) {
  34. objc_setAssociatedObject(self, &Self._sheetParentResponderKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
  35. }
  36. }
  37. extension NSWindowController {
  38. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  39. return false
  40. }
  41. }
  42. //MARK: - Password
  43. extension NSWindowController {
  44. static func checkPassword(url: URL, type: KMPasswordInputWindowType, password: String = "", completion: @escaping ((_ success: Bool, _ resultPassword: String) -> Void)) {
  45. // 判断路径 + document
  46. guard let document = CPDFDocument.init(url: url) else {
  47. return completion(false, "")
  48. }
  49. // 判断是否为加密文档
  50. if document.isLocked == false {
  51. if type == .open {
  52. completion(true, "")
  53. return
  54. }
  55. }
  56. if document.isLocked == false && (document.allowsCopying && document.allowsPrinting) {
  57. completion(true, "")
  58. return
  59. }
  60. // 加密文件,尝试解锁
  61. if password.isEmpty == false {
  62. let preStatus = document.permissionsStatus
  63. document.unlock(withPassword: password)
  64. if document.permissionsStatus.rawValue > preStatus.rawValue { // 解密成功
  65. completion(true, password)
  66. return
  67. }
  68. }
  69. // 弹密码弹窗
  70. Task { @MainActor in
  71. KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: type, url: url) { result , password in
  72. if (result == .cancel) {
  73. completion(false, "")
  74. return
  75. } else {
  76. completion(true, password ?? "")
  77. }
  78. }
  79. }
  80. }
  81. }