KMMainDocument.swift 18 KB

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