KMMainDocument.swift 20 KB

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