KMMainDocument.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. // isWaterMarkExport
  194. if (isWaterMarkExport) {
  195. DispatchQueue.main.async {
  196. NSPanel.savePanel(NSApp.mainWindow!, true, panel:{ panel in
  197. panel.nameFieldStringValue = (self.mainViewController?.document?.documentURL.lastPathComponent)!
  198. }) { response, url, isOpen in
  199. if (response == .cancel) {
  200. return
  201. }
  202. if let _document = self.mainViewController?.document {
  203. let watermark = CPDFWatermark(document: _document, type: .image)
  204. watermark?.image = NSImage(named: "KMImageNameWatermark")
  205. watermark?.horizontalPosition = .left
  206. watermark?.verticalPosition = .top
  207. watermark?.scale = 0.3
  208. _document.addWatermark(watermark)
  209. let linkA = self.mainViewController?.listView.addAnnotation(with: .link, selection: nil, page: _document.page(at: 0), bounds: NSMakeRect(0, _document.page(at: 0).bounds.size.height-20, 70, 20))
  210. if let _linka = linkA as? CPDFLinkAnnotation {
  211. _linka.setURL("https://www.baidu.com")
  212. }
  213. _document.write(to: url)
  214. if (isOpen) {
  215. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
  216. }
  217. } else {
  218. NSWorkspace.shared.activateFileViewerSelecting([url!])
  219. }
  220. }
  221. }
  222. }
  223. }
  224. }
  225. return
  226. }
  227. super.save(sender)
  228. }
  229. }
  230. override func read(from absoluteURL: URL, ofType typeName: String) throws {
  231. do {
  232. try super.read(from: absoluteURL, ofType: typeName)
  233. updateChangeCount(.changeCleared)
  234. } catch let outError {
  235. Swift.print(outError)
  236. }
  237. }
  238. override func read(from data: Data, ofType typeName: String) throws {
  239. // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
  240. // 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.
  241. let pdfDocument = CPDFDocument.init(data: data)
  242. if pdfDocument == nil {
  243. throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
  244. }
  245. }
  246. // MARK: Autosaving
  247. override func close() {
  248. if self.isActive {
  249. if browser != nil {
  250. var activeIndex = 0
  251. let dex = browser.index(of: self)
  252. if dex == browser.tabCount() - 1 {
  253. activeIndex = Int(browser.tabCount()-2)
  254. } else {
  255. activeIndex = Int(dex + 1)
  256. }
  257. let activeContents = browser.tabContents(at: Int32(activeIndex))
  258. activeContents?.addWindowController(browser.windowController)
  259. }
  260. }
  261. super.close()
  262. }
  263. // MARK: init
  264. override init() {
  265. super.init()
  266. // Add your subclass-specific initialization here.
  267. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewAnnotationsAttributeHasChangeNotification"), object: nil)
  268. // NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFViewDocumentChangedNotification"), object: nil)
  269. // NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFViewPageChangedNotification"), object: nil)
  270. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewDidAddAnnotationNotification"), object: nil)
  271. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewDidRemoveAnnotationNotification"), object: nil)
  272. }
  273. override init?(baseTabContents baseContents: CTTabContents?) {
  274. super.init(baseTabContents: baseContents)
  275. if isHome {
  276. homeViewController = KMHomeViewController.init()
  277. homeViewController?.myDocument = self
  278. self.view = homeViewController?.view
  279. }
  280. }
  281. // MARK: Handling User Actions
  282. override var title: String? {
  283. get {
  284. if isHome {
  285. if (self.isNewTab) {
  286. return NSLocalizedString("New Tab", comment: "")
  287. } else {
  288. return NSLocalizedString("Home", comment: "")
  289. }
  290. } else {
  291. return fileURL?.lastPathComponent
  292. }
  293. }
  294. set {
  295. super.title = newValue
  296. }
  297. }
  298. // MARK: Private Methods
  299. func pdfChangedNotification(_ notification: Notification) -> Void {
  300. if !isHome {
  301. let mainViewController = mainViewController
  302. var document: CPDFDocument!
  303. let dic = notification.object as? NSDictionary
  304. if dic?["object"] is CPDFAnnotation {
  305. let annotation : CPDFAnnotation = dic?["object"] as? CPDFAnnotation ?? CPDFAnnotation()
  306. document = annotation.page.document
  307. } else if dic?["object"] is CPDFListView {
  308. let pdflistView = notification.object as? CPDFListView
  309. document = pdflistView?.document
  310. }
  311. if mainViewController != nil {
  312. if document == mainViewController!.document {
  313. updateChangeCount(.changeDone)
  314. }
  315. }
  316. }
  317. }
  318. override func updateChangeCount(_ change: NSDocument.ChangeType) {
  319. let mainWindow = NSApp.mainWindow
  320. var currentWindowController: KMBrowserWindowController?
  321. if mainWindow != nil {
  322. let windowController = mainWindow!.windowController
  323. if windowController is KMBrowserWindowController {
  324. currentWindowController = (windowController as! KMBrowserWindowController)
  325. } else {
  326. for window in NSApp.windows {
  327. let windowController = window.windowController
  328. if windowController is KMBrowserWindowController {
  329. currentWindowController = (windowController as! KMBrowserWindowController)
  330. break
  331. }
  332. }
  333. }
  334. } else {
  335. for window in NSApp.windows {
  336. let windowController = window.windowController
  337. if windowController is KMBrowserWindowController {
  338. currentWindowController = (windowController as! KMBrowserWindowController)
  339. break
  340. }
  341. }
  342. }
  343. if currentWindowController != nil {
  344. if currentWindowController?.browser != nil {
  345. let activeBrowser = (currentWindowController?.browser.activeTabContents())! as CTTabContents
  346. let activeIndex = Int((currentWindowController?.browser.activeTabIndex())!)
  347. if self == activeBrowser {
  348. super.updateChangeCount(change)
  349. return
  350. }
  351. }
  352. }
  353. super.updateChangeCount(.changeCleared)
  354. }
  355. func uploadToCloud(_ callback: (@escaping(Bool, String)->())) {
  356. guard let handdler = self.cloudUploadHanddler else {
  357. return
  358. }
  359. handdler(callback)
  360. }
  361. func isPDFDocument() -> Bool {
  362. return true
  363. }
  364. func setDataFromTmpData() {
  365. if self.mainViewController == nil {
  366. return
  367. }
  368. let document = self.mainViewController!.document
  369. if (document == nil) {
  370. return
  371. }
  372. // self.tryToUnlockDocument(document!)
  373. if (document!.permissionsStatus != .owner) {
  374. var password: NSString? = nil
  375. let fileId = self.fileId(for: document!)
  376. if (fileId.isEmpty) {
  377. return
  378. }
  379. self.getPassword(&password, fileId: fileId)
  380. if (password != nil) {
  381. self.isUnlockFromKeychain = true
  382. // document.unlock(withPassword: password! as String)
  383. self.mainViewController!.password = password as String?
  384. }
  385. }
  386. }
  387. func tryToUnlockDocument(_ document: CPDFDocument) {
  388. if (document.permissionsStatus != .owner) {
  389. var password: NSString? = nil
  390. let fileId = self.fileId(for: document)
  391. if (fileId.isEmpty) {
  392. return
  393. }
  394. self.getPassword(&password, fileId: fileId)
  395. if (password != nil) {
  396. self.isUnlockFromKeychain = true
  397. document.unlock(withPassword: password! as String)
  398. }
  399. }
  400. }
  401. }
  402. extension NSDocument {
  403. @objc class func isDamage(url: URL) -> Bool {
  404. // 文件路径是否存在
  405. if (FileManager.default.fileExists(atPath: url.path) == false) {
  406. return true
  407. }
  408. /// PDF 格式文件
  409. if (url.pathExtension.lowercased() == "pdf") {
  410. let document = PDFDocument(url: url)
  411. if (document == nil) {
  412. return true
  413. }
  414. if (document!.isLocked) { // 加锁文件不在这里判断
  415. return false
  416. }
  417. if (document!.pageCount <= 0) {
  418. return true
  419. }
  420. return false
  421. }
  422. // 支持的图片格式
  423. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  424. let isImage = imageExts.contains(url.pathExtension.lowercased())
  425. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  426. return false
  427. }
  428. // 图片格式
  429. let image = NSImage(contentsOf: url)
  430. let data = image?.tiffRepresentation
  431. if (data == nil) {
  432. return true
  433. }
  434. let imageRep = NSBitmapImageRep(data: data!)
  435. imageRep!.size = image!.size
  436. var imageData: NSData?
  437. if (url.pathExtension.lowercased() == "png") {
  438. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  439. } else {
  440. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  441. }
  442. if (imageData == nil) {
  443. return true
  444. }
  445. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  446. if (FileManager.default.fileExists(atPath: path!) == false) {
  447. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  448. }
  449. var tagString: String = ""
  450. let dateFormatter = DateFormatter()
  451. dateFormatter.dateFormat = "yyMMddHHmmss"
  452. tagString.append(dateFormatter.string(from: Date()))
  453. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  454. let filePath = path?.appending("/\(tagString).png")
  455. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  456. return true
  457. }
  458. // 删除临时图片
  459. try?FileManager.default.removeItem(atPath: filePath!)
  460. return false
  461. }
  462. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  463. let result = self.isDamage(url: url)
  464. if (result == false) {
  465. return false
  466. }
  467. if (need == false) {
  468. return true
  469. }
  470. let alert = NSAlert()
  471. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  472. alert.runModal()
  473. return true
  474. }
  475. }
  476. // MARK: -
  477. // MARK: 保存密码
  478. extension NSDocument {
  479. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  480. if (document.isLocked || password.isEmpty) {
  481. return
  482. }
  483. let fileId = self.fileId(for: document)
  484. if (fileId.isEmpty) {
  485. return
  486. }
  487. // let status: SKPasswordStatus =
  488. let label = "PDF Master: \(self.displayName!)"
  489. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  490. }
  491. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  492. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  493. // if (status == .found) {
  494. // }
  495. }
  496. fileprivate func fileId(for document: CPDFDocument) -> String {
  497. return "\(document.documentURL.path.hash)"
  498. }
  499. private func passwordServiceName() -> String {
  500. return "PDF Master password"
  501. }
  502. }