KMMainDocument.swift 18 KB

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