KMMainDocument.swift 33 KB

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