KMMainDocument.swift 15 KB

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