KMMainDocument.swift 21 KB

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