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