KMPasswordInputWindow.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. // 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.SFProTextRegularFont(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.SFProTextRegularFont(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.SFProTextRegularFont(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.SFProTextRegularFont(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.SFProTextRegularFont(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.km_init(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] view, string in
  148. view.backgroundView.layer?.borderColor = NSColor.km_init(hex: "#1770F4").cgColor
  149. if self.passwordErrorLabel != nil {
  150. self.passwordErrorLabel.isHidden = true
  151. }
  152. if string.isEmpty {
  153. view.rightView?.isHidden = true
  154. self.dealConfirmButtonEnabledState(enabled: false)
  155. } else {
  156. view.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.km_init(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.SFProTextRegularFont(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.SFProTextRegularFont(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.km_init(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.km_init(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.km_init(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.km_init(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) -> KMPasswordInputWindow {
  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. return passwordWindow!
  417. }
  418. @objc class func success_openWindow(window: NSWindow, type: KMPasswordInputWindowType = .open, url: URL, callback: @escaping (String)->Void) {
  419. let passwordWindow = KMPasswordInputWindow().window()
  420. passwordWindow?.documentURL = url
  421. passwordWindow?.type = type
  422. passwordInputWindow = passwordWindow
  423. passwordWindow?.itemClick = { index, string in
  424. if (passwordInputWindow?.sheetParent != nil) {
  425. passwordInputWindow?.sheetParent?.endSheet(passwordInputWindow!)
  426. }
  427. passwordInputWindow = nil
  428. passwordInputWindow_private = nil
  429. if index == 1 { /// 关闭
  430. return
  431. }
  432. /// 解密成功
  433. callback(string)
  434. }
  435. window.beginSheet(passwordWindow!)
  436. }
  437. @objc class func openWindow(window: NSWindow, url: URL, needOwner: Bool, callback: @escaping (KMPasswordInputWindowResult, String?)->Void) {
  438. let passwordWindow = KMPasswordInputWindow().window()
  439. passwordWindow?.documentURL = url
  440. let document = CPDFDocument(url: url)
  441. if (document?.isLocked != nil && document!.isLocked) {
  442. passwordWindow?.type = .open
  443. } else if (document?.isEncrypted != nil && document!.isEncrypted) {
  444. passwordWindow?.type = .owner
  445. } else {
  446. passwordWindow?.type = .open
  447. }
  448. passwordInputWindow = passwordWindow
  449. passwordWindow?.itemClick = { index, string in
  450. let type = passwordInputWindow?.type
  451. if (passwordInputWindow?.sheetParent != nil) {
  452. passwordInputWindow?.sheetParent?.endSheet(passwordInputWindow!)
  453. }
  454. passwordInputWindow = nil
  455. passwordInputWindow_private = nil
  456. if index == 1 { /// 关闭
  457. callback(.cancel, "")
  458. return
  459. }
  460. /// 解密成功
  461. if (type == .owner) { // 解除的是权限密码
  462. callback(.success, string)
  463. return
  464. }
  465. // 解除的是开启密码
  466. if (needOwner == false) { // 不需要解除权限密码
  467. callback(.success, string)
  468. return
  469. }
  470. if (document == nil) {
  471. callback(.success, string)
  472. return
  473. }
  474. document?.unlock(withPassword: string)
  475. if (document?.permissionsStatus == .owner) { // 用户是使用的权限密码解密
  476. callback(.success, string)
  477. return
  478. }
  479. if (document!.allowsCopying == true && document!.allowsPrinting == true) { // 文件没有权限限制
  480. callback(.success, string)
  481. return
  482. }
  483. // 需要解除权限密码
  484. KMPasswordInputWindow.openWindow(window: window, type: .owner, url: url) { result, password in
  485. if (result == .cancel) {
  486. callback(.cancel, "")
  487. return
  488. }
  489. callback(.success, password)
  490. }
  491. }
  492. window.beginSheet(passwordWindow!)
  493. }
  494. class func saveDocument(_ document: CPDFDocument) -> Bool {
  495. let toPath = document.documentURL.path
  496. let tempFilePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("\((document.documentURL.lastPathComponent))")
  497. if (FileManager.default.fileExists(atPath: tempFilePath!)) {
  498. /// 清空数据
  499. try?FileManager.default.removeItem(atPath: tempFilePath!)
  500. }
  501. var result: Bool = document.write(to: URL(fileURLWithPath: tempFilePath!))
  502. if (result == false) {
  503. return false
  504. }
  505. try?FileManager.default.removeItem(atPath: toPath)
  506. result = ((try?FileManager.default.moveItem(atPath: tempFilePath!, toPath: toPath)) != nil)
  507. /// 清空数据
  508. try?FileManager.default.removeItem(atPath: tempFilePath!)
  509. return result
  510. }
  511. class func saveDocumentForRemovePassword(_ document: CPDFDocument) -> Bool {
  512. let toPath = document.documentURL.path
  513. let tempFilePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("\((document.documentURL.lastPathComponent))")
  514. if (FileManager.default.fileExists(atPath: tempFilePath!)) {
  515. /// 清空数据
  516. try?FileManager.default.removeItem(atPath: tempFilePath!)
  517. }
  518. var result: Bool = document.writeDecrypt(to: URL(fileURLWithPath: tempFilePath!))
  519. if (result == false) {
  520. return false
  521. }
  522. try?FileManager.default.removeItem(atPath: toPath)
  523. result = ((try?FileManager.default.moveItem(atPath: tempFilePath!, toPath: toPath)) != nil)
  524. /// 清空数据
  525. try?FileManager.default.removeItem(atPath: tempFilePath!)
  526. return result
  527. }
  528. }
  529. extension NSOpenPanel {
  530. /**
  531. * 打开 NSOpenPanel 窗口(如果文档存在开启密码或者权限密码,则会弹密码输入框)
  532. * @param window 弹出 NSOpenPanel 的窗口 [可选] [默认为 主窗口]
  533. * @param needOwner 是否需要限制权限密码(如果存在权限密码,会在解锁后再弹权限密码弹窗(目前未实现)) [可选] [默认为 false]
  534. * @param callback 回调
  535. *
  536. *  默认弹开启密码输入框,needOwner = true 弹权限密码输入框
  537. */
  538. class func km_secure_openPanel(window: NSWindow = NSApp.mainWindow!, needOwner: Bool = false, callback:@escaping (URL?, KMPasswordInputWindowResult? , String?)->Void) {
  539. let panel = NSOpenPanel()
  540. panel.allowedFileTypes = ["pdf"]
  541. panel.beginSheetModal(for: window) { response in
  542. if (response == .cancel) {
  543. callback(nil, nil, nil)
  544. return
  545. }
  546. let document = CPDFDocument(url: panel.url)
  547. if ((document?.isLocked)! == false) {
  548. if (document?.isEncrypted == false) {
  549. callback(panel.url, nil, nil)
  550. return
  551. }
  552. if (!needOwner) {
  553. callback(panel.url, nil, nil)
  554. return
  555. }
  556. KMPasswordInputWindow.openWindow(window: window, type: .owner, url: panel.url!) { result, password in
  557. if (result == .cancel) {
  558. callback(panel.url, .cancel , nil)
  559. return
  560. }
  561. callback(panel.url, .success , password)
  562. }
  563. return
  564. }
  565. /// 已加锁(开启密码)
  566. KMPasswordInputWindow.openWindow(window: window, url: panel.url!) { result, password in
  567. if (result == .cancel) {
  568. callback(panel.url, .cancel, nil)
  569. return
  570. }
  571. if (!needOwner) {
  572. callback(panel.url, .success, password)
  573. return
  574. }
  575. /// 用户输入的是权限密码
  576. if (KMPasswordInputWindow.permissionsStatus == .owner) {
  577. callback(panel.url, .success ,password)
  578. return
  579. }
  580. /// 用户输入的是开启密码 (无法判断是否还有权限未解密)
  581. /// 还有权限密码未解锁
  582. // KMPasswordInputWindow.openWindow(window: window, type: .owner, url: panel.url!) { result, password in
  583. // if (result == .cancel) {
  584. // callback(panel.url, .cancel , nil)
  585. // return
  586. // }
  587. //
  588. // callback(panel.url, .success , password)
  589. // }
  590. callback(panel.url, .success ,password)
  591. }
  592. }
  593. }
  594. /**
  595. * 打开 NSOpenPanel 窗口(如果文档存在开启密码或者权限密码,则会弹密码输入框)
  596. * @param window 弹出 NSOpenPanel 的窗口 [可选] [默认为 主窗口]
  597. * @param needOwner 是否需要限制权限密码(如果存在权限密码,会在解锁后再弹权限密码弹窗(目前未实现)) [可选] [默认为 false]
  598. * @param callback 回调
  599. *
  600. *  默认弹开启密码输入框,needOwner = true 弹权限密码输入框
  601. *  只返回成功的结果, 用户关闭的操作都未回调(如果有需要回调的需求可以使用 km_secure_openPanel 方法)
  602. */
  603. class func km_secure_openPanel_success(window: NSWindow = NSApp.mainWindow!, needOwner: Bool = false, callback:@escaping (URL, String?)->Void) {
  604. let panel = NSOpenPanel()
  605. panel.allowedFileTypes = ["pdf"]
  606. panel.beginSheetModal(for: window) { response in
  607. if (response == .cancel) {
  608. return
  609. }
  610. let document = CPDFDocument(url: panel.url)
  611. if ((document?.isLocked)! == false) {
  612. if (document?.isEncrypted == false) {
  613. callback(panel.url!, nil)
  614. return
  615. }
  616. if (!needOwner) {
  617. callback(panel.url!, nil)
  618. return
  619. }
  620. KMPasswordInputWindow.openWindow(window: window, type: .owner, url: panel.url!) { result, password in
  621. if (result == .cancel) {
  622. return
  623. }
  624. callback(panel.url!, password)
  625. }
  626. return
  627. }
  628. /// 已加锁(开启密码)
  629. KMPasswordInputWindow.openWindow(window: window, url: panel.url!) { result, password in
  630. if (result == .cancel) {
  631. return
  632. }
  633. if (!needOwner) {
  634. callback(panel.url!, password)
  635. return
  636. }
  637. /// 用户输入的是权限密码
  638. if (KMPasswordInputWindow.permissionsStatus == .owner) {
  639. callback(panel.url!, password)
  640. return
  641. }
  642. callback(panel.url!, password)
  643. }
  644. }
  645. }
  646. }