KMPasswordInputWindow.swift 26 KB

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