KMPasswordInputWindow.swift 30 KB

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