KMMainDocument.swift 23 KB

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