KMPasswordInputWindow.swift 30 KB

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