KMMainDocument.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. //
  2. // KMMainDocument.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/6.
  6. //
  7. import Cocoa
  8. typealias KMMainDocumentCloudUploadHanddler = (@escaping(Bool, String)->()) -> ()
  9. @objcMembers class KMMainDocument: CTTabContents {
  10. var mainViewController: KMMainViewController?
  11. var homeWindowController: KMHomeWindowController?
  12. var homeViewController: KMHomeViewController?
  13. var isNewCreated: Bool = false
  14. var closedByUserGestureFlag: Bool = false // 标记 closedByUserGesture 这个状态需要延后存储(如果需要)
  15. var cloud: Bool = false
  16. var cloudUploadHanddler: KMMainDocumentCloudUploadHanddler?
  17. var isUnlockFromKeychain: Bool = false
  18. private var _saveAsing = false
  19. private var _saveToURL: URL?
  20. var saveToURL: URL? {
  21. get {
  22. return self._saveToURL
  23. }
  24. }
  25. override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  26. if (self.isNewCreated) {
  27. // if let data = self.mainViewController, !data.isPDFDocumentEdited && !data.needSave && !self.isDocumentEdited {
  28. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  29. return
  30. // }
  31. }
  32. if (!self.needSaveWatermark()) {
  33. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  34. return
  35. }
  36. self._km_saveForWatermark { [unowned self] needSave in
  37. if (needSave) {
  38. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  39. }
  40. }
  41. }
  42. override func makeWindowControllers() {
  43. // Returns the storyboard that contains your document window.
  44. if ((self.fileURL?.path) != nil) {
  45. if !self.fileURL!.path.isPDFValid() {
  46. let alert = NSAlert()
  47. alert.alertStyle = .critical
  48. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  49. alert.runModal()
  50. return
  51. }
  52. }
  53. let mainWindow = NSApp.mainWindow
  54. var currentWindowController: KMBrowserWindowController?
  55. if mainWindow != nil {
  56. let windowController = mainWindow!.windowController
  57. if windowController is KMBrowserWindowController {
  58. currentWindowController = (windowController as! KMBrowserWindowController)
  59. } else {
  60. for window in NSApp.windows {
  61. let windowController = window.windowController
  62. if windowController is KMBrowserWindowController {
  63. currentWindowController = (windowController as! KMBrowserWindowController)
  64. break
  65. }
  66. }
  67. }
  68. } else {
  69. for window in NSApp.windows {
  70. let windowController = window.windowController
  71. if windowController is KMBrowserWindowController {
  72. currentWindowController = (windowController as! KMBrowserWindowController)
  73. break
  74. }
  75. }
  76. }
  77. if (currentWindowController == nil) && (self.fileURL != nil) {
  78. let browser = KMBrowser.init() as KMBrowser
  79. browser.addHomeTabContents()
  80. browser.windowController = KMBrowserWindowController.init(browser: browser)
  81. currentWindowController = browser.windowController as? KMBrowserWindowController
  82. }
  83. mainViewController = KMMainViewController.init()
  84. mainViewController?.myDocument = self
  85. if ((self.fileURL?.path) != nil) {
  86. let pdfDocument = CPDFDocument.init(url: URL(fileURLWithPath: self.fileURL!.path))
  87. mainViewController?.document = pdfDocument
  88. }
  89. self.view = mainViewController?.view
  90. if currentWindowController != nil {
  91. if currentWindowController?.browser != nil {
  92. // currentWindowController?.browser.add(self, at: Int32()-1, inForeground: true)
  93. // self.addWindowController(currentWindowController!)
  94. // mainViewController.browserWindowController = currentWindowController
  95. let activeBrowser = (currentWindowController?.browser.activeTabContents())! as CTTabContents
  96. let activeIndex = Int((currentWindowController?.browser.activeTabIndex())!)
  97. self.addWindowController(currentWindowController!)
  98. self.mainViewController?.browserWindowController = currentWindowController
  99. let ishome = activeBrowser.isHome as Bool
  100. let isfirstTab = (activeIndex == 0)
  101. if ishome && !isfirstTab {
  102. // 替换 document
  103. currentWindowController?.browser.replaceTabContents(at: Int32(activeIndex), with: self)
  104. // 刷新标签
  105. currentWindowController?.browser.updateTabState(at: Int32(activeIndex))
  106. // 刷新 home icon
  107. if let tabStripController = currentWindowController?.tabStripController {
  108. if let view = tabStripController.view(at: UInt(activeIndex)) as? CTTabView {
  109. view.controller().isHome = self.isHome
  110. view.controller().isNewTab = self.isNewTab
  111. view.controller().updateUI()
  112. }
  113. }
  114. } else {
  115. currentWindowController?.browser.add(self, at: Int32()-1, inForeground: true)
  116. }
  117. }
  118. }
  119. }
  120. override func showWindows() {
  121. super.showWindows()
  122. self.setDataFromTmpData()
  123. }
  124. override func windowControllerDidLoadNib(_ aController: NSWindowController) {
  125. super.windowControllerDidLoadNib(aController)
  126. self.setDataFromTmpData()
  127. }
  128. override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) async throws {
  129. do {
  130. try await super.save(to: url, ofType: typeName, for: saveOperation)
  131. } catch let outError {
  132. Swift.print(outError)
  133. }
  134. }
  135. override func write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  136. try self._km_write(to: url, ofType: typeName, for: saveOperation, originalContentsURL: absoluteOriginalContentsURL)
  137. }
  138. override func canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  139. let isPrompt = KMPreferenceManager.shared.closeFileIsPrompt()
  140. if (isPrompt) {
  141. super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
  142. return
  143. }
  144. if (self.isNewCreated) {
  145. self.save(nil)
  146. } else if (self.isDocumentEdited) {
  147. self.save(nil)
  148. } else if (mainViewController != nil) {
  149. if self.mainViewController!.isPDFDocumentEdited || self.mainViewController!.needSave {
  150. self.save(nil)
  151. }
  152. }
  153. super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
  154. }
  155. override func saveAs(_ sender: Any?) {
  156. if (!self.needSaveWatermark()) {
  157. self._km_saveAs(sender)
  158. return
  159. }
  160. self._km_saveForWatermark { [unowned self] needSave in
  161. if (needSave) {
  162. self._km_saveAs(sender)
  163. }
  164. }
  165. }
  166. override func runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  167. if (self.isNewCreated) {
  168. // if let data = self.mainViewController, !data.isPDFDocumentEdited && !data.needSave && !self.isDocumentEdited {
  169. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  170. return
  171. // }
  172. }
  173. if (!self.needSaveWatermark()) {
  174. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  175. return
  176. }
  177. self._km_saveForWatermark { [unowned self] needSave in
  178. if (needSave) {
  179. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  180. }
  181. }
  182. }
  183. override func save(_ sender: Any?) {
  184. if (!self.needSaveWatermark()) {
  185. self._km_save(sender)
  186. return
  187. }
  188. self._km_saveForWatermark { [unowned self] needSave in
  189. if (needSave) {
  190. self._km_save(sender)
  191. }
  192. }
  193. }
  194. override func read(from absoluteURL: URL, ofType typeName: String) throws {
  195. do {
  196. try super.read(from: absoluteURL, ofType: typeName)
  197. updateChangeCount(.changeCleared)
  198. } catch let outError {
  199. Swift.print(outError)
  200. }
  201. }
  202. override func read(from data: Data, ofType typeName: String) throws {
  203. // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
  204. // Alternatively, you could remove this method and override read(from:ofType:) instead. If you do, you should also override isEntireFileLoaded to return false if the contents are lazily loaded.
  205. let pdfDocument = CPDFDocument.init(data: data)
  206. if pdfDocument == nil {
  207. throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
  208. }
  209. }
  210. // MARK: Autosaving
  211. override func close() {
  212. if self.isActive {
  213. if browser != nil {
  214. var activeIndex = 0
  215. let dex = browser.index(of: self)
  216. if dex == browser.tabCount() - 1 {
  217. activeIndex = Int(browser.tabCount()-2)
  218. } else {
  219. activeIndex = Int(dex + 1)
  220. }
  221. let activeContents = browser.tabContents(at: Int32(activeIndex))
  222. activeContents?.addWindowController(browser.windowController)
  223. }
  224. }
  225. super.close()
  226. }
  227. // MARK: init
  228. override init() {
  229. super.init()
  230. // Add your subclass-specific initialization here.
  231. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewAnnotationsAttributeHasChangeNotification"), object: nil)
  232. // NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFViewDocumentChangedNotification"), object: nil)
  233. // NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFViewPageChangedNotification"), object: nil)
  234. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewDidAddAnnotationNotification"), object: nil)
  235. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewDidRemoveAnnotationNotification"), object: nil)
  236. }
  237. override init?(baseTabContents baseContents: CTTabContents?) {
  238. super.init(baseTabContents: baseContents)
  239. if isHome {
  240. homeViewController = KMHomeViewController.init()
  241. homeViewController?.myDocument = self
  242. self.view = homeViewController?.view
  243. }
  244. }
  245. // MARK: Handling User Actions
  246. override var title: String? {
  247. get {
  248. if isHome {
  249. if (self.isNewTab) {
  250. return NSLocalizedString("New Tab", comment: "")
  251. } else {
  252. return NSLocalizedString("Home", comment: "")
  253. }
  254. } else {
  255. return fileURL?.lastPathComponent
  256. }
  257. }
  258. set {
  259. super.title = newValue
  260. }
  261. }
  262. func needSaveWatermark() -> Bool {
  263. if let need = self.mainViewController?.saveWatermarkFlag {
  264. return need
  265. }
  266. return false
  267. }
  268. // MARK: Private Methods
  269. func pdfChangedNotification(_ notification: Notification) -> Void {
  270. if !isHome {
  271. let mainViewController = mainViewController
  272. var document: CPDFDocument!
  273. let dic = notification.object as? NSDictionary
  274. if dic?["object"] is CPDFAnnotation {
  275. let annotation : CPDFAnnotation = dic?["object"] as? CPDFAnnotation ?? CPDFAnnotation()
  276. document = annotation.page.document
  277. } else if dic?["object"] is CPDFListView {
  278. let pdflistView = notification.object as? CPDFListView
  279. document = pdflistView?.document
  280. }
  281. if mainViewController != nil {
  282. if document == mainViewController!.document {
  283. updateChangeCount(.changeDone)
  284. }
  285. }
  286. }
  287. }
  288. override func updateChangeCount(_ change: NSDocument.ChangeType) {
  289. let mainWindow = NSApp.mainWindow
  290. var currentWindowController: KMBrowserWindowController?
  291. if mainWindow != nil {
  292. let windowController = mainWindow!.windowController
  293. if windowController is KMBrowserWindowController {
  294. currentWindowController = (windowController as! KMBrowserWindowController)
  295. } else {
  296. for window in NSApp.windows {
  297. let windowController = window.windowController
  298. if windowController is KMBrowserWindowController {
  299. currentWindowController = (windowController as! KMBrowserWindowController)
  300. break
  301. }
  302. }
  303. }
  304. } else {
  305. for window in NSApp.windows {
  306. let windowController = window.windowController
  307. if windowController is KMBrowserWindowController {
  308. currentWindowController = (windowController as! KMBrowserWindowController)
  309. break
  310. }
  311. }
  312. }
  313. if currentWindowController != nil {
  314. if currentWindowController?.browser != nil {
  315. let activeBrowser = (currentWindowController?.browser.activeTabContents())! as CTTabContents
  316. let activeIndex = Int((currentWindowController?.browser.activeTabIndex())!)
  317. if self == activeBrowser {
  318. super.updateChangeCount(change)
  319. return
  320. }
  321. }
  322. }
  323. super.updateChangeCount(.changeCleared)
  324. }
  325. func uploadToCloud(_ callback: (@escaping(Bool, String)->())) {
  326. guard let handdler = self.cloudUploadHanddler else {
  327. return
  328. }
  329. handdler(callback)
  330. }
  331. func isPDFDocument() -> Bool {
  332. return true
  333. }
  334. func setDataFromTmpData() {
  335. guard let _document = self.mainViewController?.document else {
  336. return
  337. }
  338. // self.tryToUnlockDocument(document!)
  339. if (_document.permissionsStatus != .owner) {
  340. var password: NSString? = nil
  341. let fileId = self.fileId(for: _document)
  342. if (fileId.isEmpty) {
  343. return
  344. }
  345. self.getPassword(&password, fileId: fileId)
  346. if (password != nil) {
  347. self.isUnlockFromKeychain = true
  348. // document.unlock(withPassword: password! as String)
  349. self.mainViewController?.password = password as String?
  350. }
  351. }
  352. }
  353. func tryToUnlockDocument(_ document: CPDFDocument) {
  354. if (document.permissionsStatus != .owner) {
  355. var password: NSString? = nil
  356. let fileId = self.fileId(for: document)
  357. if (fileId.isEmpty) {
  358. return
  359. }
  360. self.getPassword(&password, fileId: fileId)
  361. if (password != nil) {
  362. self.isUnlockFromKeychain = true
  363. document.unlock(withPassword: password! as String)
  364. }
  365. }
  366. }
  367. func km_updateChangeCount(_ change: NSDocument.ChangeType) {
  368. super.updateChangeCount(change)
  369. }
  370. private func _km_write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  371. var success = true
  372. if !self.isHome {
  373. if mainViewController != nil {
  374. if mainViewController?.document != nil {
  375. self.mainViewController?.commitEditingIfNeed()
  376. // if mainViewController!.document!.isEncrypted {
  377. // success = mainViewController!.document!.write(to: url)
  378. // } else {
  379. if (mainViewController!.needSave) {
  380. if let options = self.mainViewController?.secureOptions, !options.isEmpty {
  381. success = self.mainViewController!.document!.write(to: url, withOptions: options)
  382. } else if let flag = self.mainViewController?.removeSecureFlag, flag {
  383. success = self.mainViewController!.document!.writeDecrypt(to: url)
  384. } else {
  385. success = mainViewController!.document!.write(to: url)
  386. }
  387. } else {
  388. success = mainViewController!.document!.write(to: url)
  389. }
  390. // }
  391. self.mainViewController?.needSave = false
  392. self.mainViewController?.clearSecureOptions()
  393. self.mainViewController?.clearRemoveSecureFlag()
  394. }
  395. }
  396. } else {
  397. success = false
  398. }
  399. if (success && self._saveAsing) {
  400. if let tabView = self.browser?.windowController?.tabStripController?.activeTabView() as? CTTabView {
  401. tabView.controller()?.title = url.lastPathComponent
  402. }
  403. self._saveAsing = false
  404. }
  405. if success && isNewCreated && NSDocument.SaveOperationType.saveAsOperation == saveOperation {
  406. isNewCreated = false
  407. }
  408. }
  409. private func _km_saveForWatermark(callback:@escaping (_ needSave: Bool)->Void) {
  410. Task { @MainActor in
  411. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  412. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!) { isSubscribeSuccess, isWaterMarkExport, isClose in
  413. if (isClose) {
  414. callback(false)
  415. return
  416. }
  417. if (isSubscribeSuccess) {
  418. callback(true)
  419. return
  420. }
  421. if (isWaterMarkExport) {
  422. guard let _document = self.mainViewController?.document else {
  423. callback(false)
  424. return
  425. }
  426. // 提交文本编辑的内容
  427. self.mainViewController?.commitEditingIfNeed()
  428. DispatchQueue.main.async {
  429. NSPanel.savePanel(NSApp.mainWindow!, true, panel:{ panel in
  430. if (!self.isNewCreated) {
  431. panel.directoryURL = _document.documentURL.deletingLastPathComponent()
  432. }
  433. panel.nameFieldStringValue = _document.documentURL.lastPathComponent
  434. }) { response, url, isOpen in
  435. if (response == .cancel) {
  436. callback(false)
  437. return
  438. }
  439. guard let _url = KMTools.saveWatermarkDocument(document: _document, to: url!, secureOptions: self.mainViewController?.secureOptions, removePWD: self.mainViewController!.removeSecureFlag) else {
  440. callback(false)
  441. return
  442. }
  443. callback(false)
  444. if (isOpen) {
  445. NSDocumentController.shared.km_safe_openDocument(withContentsOf: _url, display: true) { _, _, _ in
  446. }
  447. } else {
  448. NSWorkspace.shared.activateFileViewerSelecting([_url])
  449. }
  450. }
  451. }
  452. return
  453. }
  454. callback(true)
  455. }
  456. return
  457. }
  458. callback(true)
  459. }
  460. }
  461. private func _km_save(_ sender: Any?) {
  462. super.save(sender)
  463. }
  464. private func _km_save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  465. self._saveToURL = url
  466. super.save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  467. }
  468. private func _km_saveAs(_ sender: Any?) {
  469. super.saveAs(sender)
  470. self._saveAsing = true
  471. }
  472. private func _km_runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  473. super.runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  474. }
  475. }
  476. extension NSDocument {
  477. @objc class func isDamage(url: URL) -> Bool {
  478. // 文件路径是否存在
  479. if (FileManager.default.fileExists(atPath: url.path) == false) {
  480. return true
  481. }
  482. /// PDF 格式文件
  483. if (url.pathExtension.lowercased() == "pdf") {
  484. let document = PDFDocument(url: url)
  485. if (document == nil) {
  486. return true
  487. }
  488. if (document!.isLocked) { // 加锁文件不在这里判断
  489. return false
  490. }
  491. if (document!.pageCount <= 0) {
  492. return true
  493. }
  494. return false
  495. }
  496. // 支持的图片格式
  497. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  498. let isImage = imageExts.contains(url.pathExtension.lowercased())
  499. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  500. return false
  501. }
  502. // 图片格式
  503. let image = NSImage(contentsOf: url)
  504. let data = image?.tiffRepresentation
  505. if (data == nil) {
  506. return true
  507. }
  508. let imageRep = NSBitmapImageRep(data: data!)
  509. imageRep!.size = image!.size
  510. var imageData: NSData?
  511. if (url.pathExtension.lowercased() == "png") {
  512. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  513. } else {
  514. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  515. }
  516. if (imageData == nil) {
  517. return true
  518. }
  519. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  520. if (FileManager.default.fileExists(atPath: path!) == false) {
  521. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  522. }
  523. var tagString: String = ""
  524. let dateFormatter = DateFormatter()
  525. dateFormatter.dateFormat = "yyMMddHHmmss"
  526. tagString.append(dateFormatter.string(from: Date()))
  527. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  528. let filePath = path?.appending("/\(tagString).png")
  529. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  530. return true
  531. }
  532. // 删除临时图片
  533. try?FileManager.default.removeItem(atPath: filePath!)
  534. return false
  535. }
  536. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  537. let result = self.isDamage(url: url)
  538. if (result == false) {
  539. return false
  540. }
  541. if (need == false) {
  542. return true
  543. }
  544. let alert = NSAlert()
  545. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  546. alert.runModal()
  547. return true
  548. }
  549. }
  550. // MARK: -
  551. // MARK: 保存密码
  552. extension NSDocument {
  553. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  554. if (document.isLocked || password.isEmpty) {
  555. return
  556. }
  557. let fileId = self.fileId(for: document)
  558. if (fileId.isEmpty) {
  559. return
  560. }
  561. // let status: SKPasswordStatus =
  562. let label = "PDF Master: \(self.displayName!)"
  563. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  564. }
  565. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  566. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  567. // if (status == .found) {
  568. // }
  569. }
  570. fileprivate func fileId(for document: CPDFDocument) -> String {
  571. return "\(document.documentURL.path.hash)"
  572. }
  573. private func passwordServiceName() -> String {
  574. return "PDF Master password"
  575. }
  576. }