KMPasswordInputWindow.swift 30 KB

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