KMPasswordInputWindow.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. //
  2. // KMPasswordInputWindow.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2022/11/29.
  6. //
  7. import Cocoa
  8. import PDFKit
  9. @objc enum KMPasswordInputWindowType: Int {
  10. case open = 1
  11. case owner = 2
  12. }
  13. @objc enum KMPasswordInputWindowResult: Int {
  14. case cancel = 1
  15. case success = 2
  16. }
  17. typealias KMPasswordInputWindowItemClick = (Int, String) -> ()
  18. private var passwordInputWindow: KMPasswordInputWindow?
  19. private var passwordInputWindow_private: KMPasswordInputWindow?
  20. @objcMembers class KMPasswordInputWindow: NSWindow, NibLoadable {
  21. @IBOutlet weak var titleLabel: NSTextField!
  22. @IBOutlet weak var despLabel: NSTextField!
  23. @IBOutlet weak var secureTextFiled: KMSecureTextFiled!
  24. @IBOutlet weak var iconImageView: NSImageView!
  25. @IBOutlet weak var passwordErrorLabel: NSTextField!
  26. @IBOutlet weak var cancelButton: NSButton!
  27. @IBOutlet weak var confirmButton: NSButton!
  28. var confirmButtonVC: KMDesignButton?
  29. var documentURL: URL?
  30. var itemClick: KMPasswordInputWindowItemClick?
  31. var type: KMPasswordInputWindowType = .open {
  32. didSet {
  33. self.titleLabel?.stringValue = NSLocalizedString("Permission Password", comment: "")
  34. var fileName = NSLocalizedString("", comment: "")
  35. if (self.documentURL != nil) {
  36. fileName.append("\(self.documentURL!.lastPathComponent)")
  37. }
  38. self.despLabel?.maximumNumberOfLines = 3
  39. self.despLabel?.lineBreakMode = .byTruncatingTail
  40. self.despLabel?.cell?.truncatesLastVisibleLine = true
  41. let ps = NSMutableParagraphStyle()
  42. ps.lineSpacing = 5
  43. let despLabelString = "\"\(fileName)\"\(NSLocalizedString("This PDF is password protected. Please enter the password below to access this PDF.", comment: ""))"
  44. self.despLabel?.attributedStringValue = NSAttributedString(string: despLabelString, attributes: [.foregroundColor : KMAppearance.Layout.h0Color(), .font : NSFont.SFProTextRegularFont(14), .paragraphStyle : ps])
  45. }
  46. }
  47. static var canEncrpty = false
  48. static var permissionsStatus: CPDFDocumentPermissions = .none
  49. deinit {
  50. KMPrint("KMPasswordInputWindow 已释放了")
  51. }
  52. static var nibName: String? {
  53. return "KMPasswordInputWindow"
  54. }
  55. static func createFromNib(in bundle: Bundle) -> Self? {
  56. guard let nibName = self.nibName else {
  57. return nil
  58. }
  59. var topLevelArray: NSArray? = nil
  60. bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
  61. guard let results = topLevelArray else {
  62. return nil
  63. }
  64. let views = Array<Any>(results).filter { $0 is Self }
  65. return views.last as? Self
  66. }
  67. class func createWindow() -> Self? {
  68. KMPasswordInputWindow.canEncrpty = false
  69. KMPasswordInputWindow.permissionsStatus = .none
  70. return self.createFromNib(in: MainBundle)
  71. }
  72. // func window() -> Self? {
  73. // KMPasswordInputWindow.canEncrpty = false
  74. // KMPasswordInputWindow.permissionsStatus = .none
  75. //
  76. // var topLevelArray: NSArray? = nil
  77. // Bundle.main.loadNibNamed(NSNib.Name("KMPasswordInputWindow"), owner: self, topLevelObjects: &topLevelArray)
  78. // guard let results = topLevelArray else {
  79. // return nil
  80. // }
  81. //
  82. // var passwordInputWindow: KMPasswordInputWindow!
  83. // for object in results {
  84. // let window: NSObject = object as! NSObject
  85. // if window.isKind(of: KMPasswordInputWindow.self) {
  86. // passwordInputWindow = window as! KMPasswordInputWindow?
  87. // }
  88. // }
  89. //
  90. // guard let myWindow = passwordInputWindow else {
  91. // return nil
  92. // }
  93. // return myWindow as? Self
  94. // }
  95. override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
  96. super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag)
  97. }
  98. override func awakeFromNib() {
  99. super.awakeFromNib()
  100. passwordInputWindow_private = self
  101. self.titleLabel.stringValue = NSLocalizedString("Permission Password", comment: "")
  102. self.titleLabel.textColor = KMAppearance.Layout.h0Color()
  103. self.titleLabel.font = NSFont.SFProTextRegularFont(16)
  104. self.despLabel.stringValue = NSLocalizedString("This PDF is password protected. Please enter the password below to access this PDF.", comment: "")
  105. self.despLabel.textColor = KMAppearance.Layout.h0Color()
  106. self.despLabel.font = NSFont.SFProTextRegularFont(14)
  107. self.despLabel.isSelectable = false
  108. let ps = NSMutableParagraphStyle()
  109. ps.lineSpacing = 5
  110. self.despLabel.maximumNumberOfLines = 2
  111. self.despLabel.lineBreakMode = .byTruncatingTail
  112. ps.lineBreakMode = .byTruncatingTail
  113. self.despLabel.attributedStringValue = NSAttributedString(string: despLabel.stringValue, attributes: [.foregroundColor : KMAppearance.Layout.h0Color(), .font : NSFont.SFProTextRegularFont(14), .paragraphStyle : ps])
  114. self.iconImageView.image = NSImage(named: "KMImageNameSecureIcon")
  115. self.secureTextFiled.backgroundView.wantsLayer = true
  116. self.secureTextFiled.backgroundView.layer?.borderWidth = 1
  117. self.secureTextFiled.backgroundView.layer?.borderColor = NSColor.buttonBorderColor().cgColor
  118. self.secureTextFiled.backgroundView.layer?.cornerRadius = 4
  119. self.secureTextFiled.placeholderString = NSLocalizedString("Password", comment: "")
  120. let rightView = NSView()
  121. rightView.frame = NSMakeRect(0, 0, 40, 32);
  122. self.secureTextFiled.rightView = rightView
  123. let clearButton = NSButton()
  124. rightView.addSubview(clearButton)
  125. clearButton.frame = NSMakeRect(10, 6, 20, 20)
  126. clearButton.wantsLayer = true
  127. clearButton.image = NSImage(named: "KMImageNameSecureClearIcon")
  128. clearButton.isBordered = false
  129. clearButton.target = self
  130. clearButton.action = #selector(clearButtonAction)
  131. rightView.isHidden = true
  132. self.secureTextFiled.becomeFirstResponderHandler = { [unowned self] securetextFiled in
  133. let mySecureTextField: KMSecureTextFiled = securetextFiled as! KMSecureTextFiled
  134. mySecureTextField.backgroundView.wantsLayer = true
  135. mySecureTextField.backgroundView.layer?.borderColor = NSColor.km_init(hex: "#1770F4").cgColor
  136. if mySecureTextField.password().isEmpty {
  137. self.secureTextFiled.rightView?.isHidden = true
  138. } else {
  139. self.secureTextFiled.rightView?.isHidden = false
  140. }
  141. self.passwordErrorLabel.isHidden = true
  142. }
  143. self.secureTextFiled.valueDidChange = { [unowned self] view, string in
  144. view.backgroundView.layer?.borderColor = NSColor.km_init(hex: "#1770F4").cgColor
  145. self.passwordErrorLabel.isHidden = true
  146. if string.isEmpty {
  147. view.rightView?.isHidden = true
  148. self.dealConfirmButtonEnabledState(enabled: false)
  149. } else {
  150. view.rightView?.isHidden = false
  151. self.dealConfirmButtonEnabledState(enabled: true)
  152. }
  153. }
  154. self.secureTextFiled.enterAction = { [unowned self] in
  155. self.confirmButtonAction()
  156. }
  157. self.passwordErrorLabel.stringValue = NSLocalizedString("Incorrect password. Please try again.", comment: "")
  158. self.passwordErrorLabel.font = NSFont.systemFont(ofSize: 12)
  159. self.passwordErrorLabel.wantsLayer = true
  160. self.passwordErrorLabel.textColor = NSColor.km_init(hex: "#F3465B")
  161. self.passwordErrorLabel.isHidden = true
  162. for button in [cancelButton, confirmButton] {
  163. // button?.wantsLayer = true
  164. // button?.layer?.cornerRadius = 4
  165. // button?.bezelStyle = .roundRect
  166. // button?.setButtonType(.momentaryPushIn)
  167. button!.target = self
  168. if ((button?.isEqual(to: cancelButton))!) {
  169. // button?.layer?.borderWidth = 1
  170. // button?.layer?.borderColor = NSColor.buttonBorderColor().cgColor
  171. // button?.title = NSLocalizedString("Cancel", comment: "")
  172. // button?.title = ""
  173. // button?.setTitleColor(NSColor.buttonTitleColor())
  174. // button?.font = NSFont.SFProTextRegularFont(14)
  175. // button?.action = #selector(cancelButtonAction)
  176. } else {
  177. // button?.title = NSLocalizedString("Open", comment: "")
  178. // button?.attributedTitle = NSMutableAttributedString(string: button!.title, attributes: [.foregroundColor : NSColor.white])
  179. // button?.font = NSFont.SFProTextRegularFont(14)
  180. // button?.action = #selector(confirmButtonAction)
  181. // button?.title = ""
  182. }
  183. }
  184. let cancelButtonVC = KMDesignButton(withType: .Text)
  185. // self.cancelButton.addSubview(cancelButtonVC.view)
  186. cancelButtonVC.view.frame = self.cancelButton.bounds
  187. cancelButtonVC.view.autoresizingMask = [.width, .height]
  188. cancelButtonVC.stringValue = NSLocalizedString("Cancel", comment: "")
  189. cancelButtonVC.button(type: .Sec_Icon, size: .m)
  190. cancelButtonVC.target = self
  191. cancelButtonVC.action = #selector(cancelButtonAction)
  192. cancelButtonVC.button.keyEquivalent = KMKeyEquivalent.esc.string()
  193. self.cancelButton.title = NSLocalizedString("Cancel", comment: "")
  194. self.cancelButton.action = #selector(cancelButtonAction)
  195. let confirmButtonVC = KMDesignButton(withType: .Text)
  196. // self.confirmButton.addSubview(confirmButtonVC.view)
  197. confirmButtonVC.view.frame = self.confirmButton.bounds
  198. confirmButtonVC.view.autoresizingMask = [.width, .height]
  199. confirmButtonVC.stringValue = NSLocalizedString("Open", comment: "")
  200. confirmButtonVC.button(type: .Cta, size: .m)
  201. confirmButtonVC.target = self
  202. confirmButtonVC.action = #selector(confirmButtonAction)
  203. self.confirmButtonVC = confirmButtonVC
  204. self.confirmButtonVC?.button.keyEquivalent = KMKeyEquivalent.enter
  205. self.confirmButton.title = NSLocalizedString("Open", comment: "")
  206. self.confirmButton.action = #selector(confirmButtonAction)
  207. self.dealConfirmButtonEnabledState(enabled: false)
  208. }
  209. // MARK: - Actions
  210. @objc func cancelButtonAction() {
  211. guard let callback = self.itemClick else {
  212. return
  213. }
  214. callback(1, "")
  215. }
  216. @objc func confirmButtonAction() {
  217. if (!KMPasswordInputWindow.canEncrpty) {
  218. return
  219. }
  220. guard let documentURL = self.documentURL else {
  221. return
  222. }
  223. if (self.type == .open) {
  224. let document: CPDFDocument = CPDFDocument(url: documentURL)
  225. if document.permissionsStatus == .none {
  226. let reuslt = document.unlock(withPassword: secureTextFiled.password())
  227. /// CPDFDocumentPermissionsNone 解锁失败
  228. /// CPDFDocumentPermissionsUser 输入的开启密码
  229. /// CPDFDocumentPermissionsOwner 输入的权限密码
  230. KMPasswordInputWindow.permissionsStatus = document.permissionsStatus
  231. if document.permissionsStatus != CPDFDocumentPermissions.none { /// 密码正确
  232. guard let callback = self.itemClick else {
  233. return
  234. }
  235. callback(2, secureTextFiled.password())
  236. } else { /// 密码错误
  237. self.passwordErrorLabel.isHidden = false
  238. self.passwordErrorLabel.stringValue = NSLocalizedString("Incorrect password. Please try again.", comment: "")
  239. self.secureTextFiled.backgroundView.layer?.borderColor = NSColor.km_init(hex: "#F3465B").cgColor
  240. }
  241. }
  242. return
  243. }
  244. /// 权限密码类型
  245. let document: CPDFDocument = CPDFDocument(url: documentURL)
  246. if (document.isLocked) {
  247. if document.permissionsStatus == CPDFDocumentPermissions.none {
  248. let reuslt = document.unlock(withPassword: secureTextFiled.password())
  249. KMPasswordInputWindow.permissionsStatus = document.permissionsStatus
  250. if document.permissionsStatus == .owner { /// 密码正确
  251. guard let callback = self.itemClick else {
  252. return
  253. }
  254. callback(2, secureTextFiled.password())
  255. } else { /// 密码错误
  256. self.passwordErrorLabel.isHidden = false
  257. self.passwordErrorLabel.stringValue = NSLocalizedString("Incorrect password. Please try again.", comment: "")
  258. self.secureTextFiled.backgroundView.layer?.borderColor = NSColor.km_init(hex: "#F3465B").cgColor
  259. }
  260. }
  261. } else {
  262. if document.permissionsStatus == CPDFDocumentPermissions.user {
  263. document.unlock(withPassword: secureTextFiled.password())
  264. KMPasswordInputWindow.permissionsStatus = document.permissionsStatus
  265. if document.permissionsStatus == .owner { /// 密码正确
  266. guard let callback = self.itemClick else {
  267. return
  268. }
  269. callback(2, secureTextFiled.password())
  270. } else { /// 密码错误
  271. self.passwordErrorLabel.isHidden = false
  272. self.passwordErrorLabel.stringValue = NSLocalizedString("Incorrect password. Please try again.", comment: "")
  273. self.secureTextFiled.backgroundView.layer?.borderColor = NSColor.km_init(hex: "#F3465B").cgColor
  274. }
  275. }
  276. }
  277. }
  278. @objc func clearButtonAction() {
  279. self.secureTextFiled.clear()
  280. }
  281. func dealConfirmButtonEnabledState(enabled: Bool) {
  282. KMPasswordInputWindow.canEncrpty = enabled
  283. // confirmButton.wantsLayer = true
  284. // confirmButton.layer?.backgroundColor = NSColor.buttonFunctionBackgroundColor(enabled: enabled).cgColor
  285. // confirmButton?.title = NSLocalizedString("Open", comment: "")
  286. // var color = NSColor.buttonTitleColor(enabled: enabled)
  287. // if (enabled) {
  288. // color = NSColor.km_init(hex: "#FFFFFF")
  289. // }
  290. // confirmButton?.attributedTitle = NSMutableAttributedString(string: confirmButton!.title, attributes: [.foregroundColor : color])
  291. // if (self.confirmButtonVC != nil) {
  292. // self.confirmButtonVC?.enabled = enabled
  293. // }
  294. self.confirmButton.isEnabled = enabled
  295. }
  296. override func mouseUp(with event: NSEvent) {
  297. super.mouseUp(with: event)
  298. self.makeFirstResponder(nil)
  299. self.secureTextFiled.backgroundView.layer?.borderColor = NSColor.buttonBorderColor().cgColor
  300. self.passwordErrorLabel.isHidden = true
  301. }
  302. }
  303. extension KMPasswordInputWindow {
  304. @objc class func openWindow(window: NSWindow, type: KMPasswordInputWindowType = .open, url: URL, callback: @escaping (KMPasswordInputWindowResult, String?)->Void) -> KMPasswordInputWindow {
  305. let passwordWindow = KMPasswordInputWindow.createWindow()
  306. passwordWindow?.documentURL = url
  307. passwordWindow?.type = type
  308. passwordInputWindow = passwordWindow
  309. passwordWindow?.itemClick = { index, string in
  310. if (passwordInputWindow?.sheetParent != nil) {
  311. passwordInputWindow?.sheetParent?.endSheet(passwordInputWindow!)
  312. }
  313. passwordInputWindow = nil
  314. passwordInputWindow_private = nil
  315. if index == 1 { /// 关闭
  316. callback(.cancel, "")
  317. return
  318. }
  319. /// 解密成功
  320. callback(.success, string)
  321. }
  322. window.beginSheet(passwordWindow!)
  323. return passwordWindow!
  324. }
  325. @objc class func success_openWindow(window: NSWindow, type: KMPasswordInputWindowType = .open, url: URL, callback: @escaping (String)->Void) {
  326. let passwordWindow = KMPasswordInputWindow.createWindow()
  327. passwordWindow?.documentURL = url
  328. passwordWindow?.type = type
  329. passwordInputWindow = passwordWindow
  330. passwordWindow?.itemClick = { index, string in
  331. if (passwordInputWindow?.sheetParent != nil) {
  332. passwordInputWindow?.sheetParent?.endSheet(passwordInputWindow!)
  333. }
  334. passwordInputWindow = nil
  335. passwordInputWindow_private = nil
  336. if index == 1 { /// 关闭
  337. return
  338. }
  339. /// 解密成功
  340. callback(string)
  341. }
  342. window.beginSheet(passwordWindow!)
  343. }
  344. @objc class func openWindow(window: NSWindow, url: URL, needOwner: Bool, callback: @escaping (KMPasswordInputWindowResult, String?)->Void) {
  345. let passwordWindow = KMPasswordInputWindow.createWindow()
  346. passwordWindow?.documentURL = url
  347. let document = CPDFDocument(url: url)
  348. if (document?.isLocked != nil && document!.isLocked) {
  349. passwordWindow?.type = .open
  350. } else if (document?.isEncrypted != nil && document!.isEncrypted) {
  351. passwordWindow?.type = .owner
  352. } else {
  353. passwordWindow?.type = .open
  354. }
  355. passwordInputWindow = passwordWindow
  356. passwordWindow?.itemClick = { index, string in
  357. let type = passwordInputWindow?.type
  358. if (passwordInputWindow?.sheetParent != nil) {
  359. passwordInputWindow?.sheetParent?.endSheet(passwordInputWindow!)
  360. }
  361. passwordInputWindow = nil
  362. passwordInputWindow_private = nil
  363. if index == 1 { /// 关闭
  364. callback(.cancel, "")
  365. return
  366. }
  367. /// 解密成功
  368. if (type == .owner) { // 解除的是权限密码
  369. callback(.success, string)
  370. return
  371. }
  372. // 解除的是开启密码
  373. if (needOwner == false) { // 不需要解除权限密码
  374. callback(.success, string)
  375. return
  376. }
  377. if (document == nil) {
  378. callback(.success, string)
  379. return
  380. }
  381. document?.unlock(withPassword: string)
  382. if (document?.permissionsStatus == .owner) { // 用户是使用的权限密码解密
  383. callback(.success, string)
  384. return
  385. }
  386. if (document!.allowsCopying == true && document!.allowsPrinting == true) { // 文件没有权限限制
  387. callback(.success, string)
  388. return
  389. }
  390. // 需要解除权限密码
  391. KMPasswordInputWindow.openWindow(window: window, type: .owner, url: url) { result, password in
  392. if (result == .cancel) {
  393. callback(.cancel, "")
  394. return
  395. }
  396. callback(.success, password)
  397. }
  398. }
  399. window.beginSheet(passwordWindow!)
  400. }
  401. class func saveDocument(_ document: CPDFDocument) -> Bool {
  402. let toPath = document.documentURL.path
  403. let tempFilePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("\((document.documentURL.lastPathComponent))")
  404. if (FileManager.default.fileExists(atPath: tempFilePath!)) {
  405. /// 清空数据
  406. try?FileManager.default.removeItem(atPath: tempFilePath!)
  407. }
  408. var result: Bool = document.write(to: URL(fileURLWithPath: tempFilePath!))
  409. if (result == false) {
  410. return false
  411. }
  412. try?FileManager.default.removeItem(atPath: toPath)
  413. result = ((try?FileManager.default.moveItem(atPath: tempFilePath!, toPath: toPath)) != nil)
  414. /// 清空数据
  415. try?FileManager.default.removeItem(atPath: tempFilePath!)
  416. return result
  417. }
  418. class func saveDocumentForRemovePassword(_ document: CPDFDocument) -> Bool {
  419. let toPath = document.documentURL.path
  420. let tempFilePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("\((document.documentURL.lastPathComponent))")
  421. if (FileManager.default.fileExists(atPath: tempFilePath!)) {
  422. /// 清空数据
  423. try?FileManager.default.removeItem(atPath: tempFilePath!)
  424. }
  425. var result: Bool = document.writeDecrypt(to: URL(fileURLWithPath: tempFilePath!))
  426. if (result == false) {
  427. return false
  428. }
  429. try?FileManager.default.removeItem(atPath: toPath)
  430. result = ((try?FileManager.default.moveItem(atPath: tempFilePath!, toPath: toPath)) != nil)
  431. /// 清空数据
  432. try?FileManager.default.removeItem(atPath: tempFilePath!)
  433. return result
  434. }
  435. }
  436. extension NSOpenPanel {
  437. /**
  438. * 打开 NSOpenPanel 窗口(如果文档存在开启密码或者权限密码,则会弹密码输入框)
  439. * @param window 弹出 NSOpenPanel 的窗口 [可选] [默认为 主窗口]
  440. * @param needOwner 是否需要限制权限密码(如果存在权限密码,会在解锁后再弹权限密码弹窗(目前未实现)) [可选] [默认为 false]
  441. * @param callback 回调
  442. *
  443. *  默认弹开启密码输入框,needOwner = true 弹权限密码输入框
  444. */
  445. class func km_secure_openPanel(window: NSWindow = NSApp.mainWindow!, needOwner: Bool = false, callback:@escaping (URL?, KMPasswordInputWindowResult? , String?)->Void) {
  446. let panel = NSOpenPanel()
  447. panel.allowedFileTypes = ["pdf"]
  448. panel.beginSheetModal(for: window) { response in
  449. if (response == .cancel) {
  450. callback(nil, nil, nil)
  451. return
  452. }
  453. let document = CPDFDocument(url: panel.url)
  454. if ((document?.isLocked)! == false) {
  455. if (document?.isEncrypted == false) {
  456. callback(panel.url, nil, nil)
  457. return
  458. }
  459. if (!needOwner) {
  460. callback(panel.url, nil, nil)
  461. return
  462. }
  463. KMPasswordInputWindow.openWindow(window: window, type: .owner, url: panel.url!) { result, password in
  464. if (result == .cancel) {
  465. callback(panel.url, .cancel , nil)
  466. return
  467. }
  468. callback(panel.url, .success , password)
  469. }
  470. return
  471. }
  472. /// 已加锁(开启密码)
  473. KMPasswordInputWindow.openWindow(window: window, url: panel.url!) { result, password in
  474. if (result == .cancel) {
  475. callback(panel.url, .cancel, nil)
  476. return
  477. }
  478. if (!needOwner) {
  479. callback(panel.url, .success, password)
  480. return
  481. }
  482. /// 用户输入的是权限密码
  483. if (KMPasswordInputWindow.permissionsStatus == .owner) {
  484. callback(panel.url, .success ,password)
  485. return
  486. }
  487. /// 用户输入的是开启密码 (无法判断是否还有权限未解密)
  488. /// 还有权限密码未解锁
  489. // KMPasswordInputWindow.openWindow(window: window, type: .owner, url: panel.url!) { result, password in
  490. // if (result == .cancel) {
  491. // callback(panel.url, .cancel , nil)
  492. // return
  493. // }
  494. //
  495. // callback(panel.url, .success , password)
  496. // }
  497. callback(panel.url, .success ,password)
  498. }
  499. }
  500. }
  501. /**
  502. * 打开 NSOpenPanel 窗口(如果文档存在开启密码或者权限密码,则会弹密码输入框)
  503. * @param window 弹出 NSOpenPanel 的窗口 [可选] [默认为 主窗口]
  504. * @param needOwner 是否需要限制权限密码(如果存在权限密码,会在解锁后再弹权限密码弹窗(目前未实现)) [可选] [默认为 false]
  505. * @param callback 回调
  506. *
  507. *  默认弹开启密码输入框,needOwner = true 弹权限密码输入框
  508. *  只返回成功的结果, 用户关闭的操作都未回调(如果有需要回调的需求可以使用 km_secure_openPanel 方法)
  509. */
  510. class func km_secure_openPanel_success(window: NSWindow = NSApp.mainWindow!, needOwner: Bool = false, callback:@escaping (URL, String?)->Void) {
  511. let panel = NSOpenPanel()
  512. panel.allowedFileTypes = ["pdf"]
  513. panel.beginSheetModal(for: window) { response in
  514. if (response == .cancel) {
  515. return
  516. }
  517. let document = CPDFDocument(url: panel.url)
  518. if ((document?.isLocked)! == false) {
  519. if (document?.isEncrypted == false) {
  520. callback(panel.url!, nil)
  521. return
  522. }
  523. if (!needOwner) {
  524. callback(panel.url!, nil)
  525. return
  526. }
  527. KMPasswordInputWindow.openWindow(window: window, type: .owner, url: panel.url!) { result, password in
  528. if (result == .cancel) {
  529. return
  530. }
  531. callback(panel.url!, password)
  532. }
  533. return
  534. }
  535. /// 已加锁(开启密码)
  536. KMPasswordInputWindow.openWindow(window: window, url: panel.url!) { result, password in
  537. if (result == .cancel) {
  538. return
  539. }
  540. if (!needOwner) {
  541. callback(panel.url!, password)
  542. return
  543. }
  544. /// 用户输入的是权限密码
  545. if (KMPasswordInputWindow.permissionsStatus == .owner) {
  546. callback(panel.url!, password)
  547. return
  548. }
  549. callback(panel.url!, password)
  550. }
  551. }
  552. }
  553. }