KMMainDocument.swift 32 KB

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