KMMainDocument.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. }
  175. override init?(baseTabContents baseContents: CTTabContents?) {
  176. super.init(baseTabContents: baseContents)
  177. if isHome {
  178. homeViewController = KMHomeViewController.init()
  179. homeViewController?.myDocument = self
  180. self.view = homeViewController?.view
  181. }
  182. }
  183. // MARK: Handling User Actions
  184. override var title: String? {
  185. get {
  186. if isHome {
  187. return NSLocalizedString("Home", comment: "")
  188. } else {
  189. return fileURL?.lastPathComponent
  190. }
  191. }
  192. set {
  193. super.title = newValue
  194. }
  195. }
  196. // MARK: Private Methods
  197. func pdfChangedNotification(_ notification: Notification) -> Void {
  198. if !isHome {
  199. let mainViewController = mainViewController
  200. // let document = notification.object as? CPDFDocument
  201. let annotation = notification.object as? CPDFAnnotation
  202. let document = annotation?.page.document
  203. if mainViewController != nil {
  204. // if document == mainViewController!.document {
  205. if document == mainViewController!.document {
  206. if notification.userInfo != nil {
  207. updateChangeCount(.changeCleared)
  208. } else {
  209. updateChangeCount(.changeDone)
  210. }
  211. }
  212. }
  213. }
  214. }
  215. override func updateChangeCount(_ change: NSDocument.ChangeType) {
  216. let mainWindow = NSApp.mainWindow
  217. var currentWindowController: KMBrowserWindowController?
  218. if mainWindow != nil {
  219. let windowController = mainWindow!.windowController
  220. if windowController is KMBrowserWindowController {
  221. currentWindowController = (windowController as! KMBrowserWindowController)
  222. } else {
  223. for window in NSApp.windows {
  224. let windowController = window.windowController
  225. if windowController is KMBrowserWindowController {
  226. currentWindowController = (windowController as! KMBrowserWindowController)
  227. break
  228. }
  229. }
  230. }
  231. } else {
  232. for window in NSApp.windows {
  233. let windowController = window.windowController
  234. if windowController is KMBrowserWindowController {
  235. currentWindowController = (windowController as! KMBrowserWindowController)
  236. break
  237. }
  238. }
  239. }
  240. if currentWindowController != nil {
  241. if currentWindowController?.browser != nil {
  242. let activeBrowser = (currentWindowController?.browser.activeTabContents())! as CTTabContents
  243. let activeIndex = Int((currentWindowController?.browser.activeTabIndex())!)
  244. if self == activeBrowser {
  245. super.updateChangeCount(change)
  246. return
  247. }
  248. }
  249. }
  250. super.updateChangeCount(.changeCleared)
  251. }
  252. func uploadToCloud(_ callback: (@escaping(Bool, String)->())) {
  253. guard let handdler = self.cloudUploadHanddler else {
  254. return
  255. }
  256. handdler(callback)
  257. }
  258. func isPDFDocument() -> Bool {
  259. return true
  260. }
  261. func setDataFromTmpData() {
  262. if self.mainViewController == nil {
  263. return
  264. }
  265. let document = self.mainViewController!.document
  266. if (document == nil) {
  267. return
  268. }
  269. // self.tryToUnlockDocument(document!)
  270. if (document!.permissionsStatus != .owner) {
  271. var password: NSString? = nil
  272. let fileId = self.fileId(for: document!)
  273. if (fileId.isEmpty) {
  274. return
  275. }
  276. self.getPassword(&password, fileId: fileId)
  277. if (password != nil) {
  278. self.isUnlockFromKeychain = true
  279. // document.unlock(withPassword: password! as String)
  280. self.mainViewController!.password = password as String?
  281. }
  282. }
  283. }
  284. func tryToUnlockDocument(_ document: CPDFDocument) {
  285. if (document.permissionsStatus != .owner) {
  286. var password: NSString? = nil
  287. let fileId = self.fileId(for: document)
  288. if (fileId.isEmpty) {
  289. return
  290. }
  291. self.getPassword(&password, fileId: fileId)
  292. if (password != nil) {
  293. self.isUnlockFromKeychain = true
  294. document.unlock(withPassword: password! as String)
  295. }
  296. }
  297. }
  298. }
  299. extension NSDocument {
  300. @objc class func isDamage(url: URL) -> Bool {
  301. // 文件路径是否存在
  302. if (FileManager.default.fileExists(atPath: url.path) == false) {
  303. return true
  304. }
  305. /// PDF 格式文件
  306. if (url.pathExtension.lowercased() == "pdf") {
  307. let document = PDFDocument(url: url)
  308. if (document == nil) {
  309. return true
  310. }
  311. if (document!.isLocked) { // 加锁文件不在这里判断
  312. return false
  313. }
  314. if (document!.pageCount <= 0) {
  315. return true
  316. }
  317. return false
  318. }
  319. // 支持的图片格式
  320. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  321. let isImage = imageExts.contains(url.pathExtension.lowercased())
  322. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  323. return false
  324. }
  325. // 图片格式
  326. let image = NSImage(contentsOf: url)
  327. let data = image?.tiffRepresentation
  328. if (data == nil) {
  329. return true
  330. }
  331. let imageRep = NSBitmapImageRep(data: data!)
  332. imageRep!.size = image!.size
  333. var imageData: NSData?
  334. if (url.pathExtension.lowercased() == "png") {
  335. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  336. } else {
  337. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  338. }
  339. if (imageData == nil) {
  340. return true
  341. }
  342. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  343. if (FileManager.default.fileExists(atPath: path!) == false) {
  344. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  345. }
  346. var tagString: String = ""
  347. let dateFormatter = DateFormatter()
  348. dateFormatter.dateFormat = "yyMMddHHmmss"
  349. tagString.append(dateFormatter.string(from: Date()))
  350. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  351. let filePath = path?.appending("/\(tagString).png")
  352. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  353. return true
  354. }
  355. // 删除临时图片
  356. try?FileManager.default.removeItem(atPath: filePath!)
  357. return false
  358. }
  359. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  360. let result = self.isDamage(url: url)
  361. if (result == false) {
  362. return false
  363. }
  364. if (need == false) {
  365. return true
  366. }
  367. let alert = NSAlert()
  368. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  369. alert.runModal()
  370. return true
  371. }
  372. }
  373. // MARK: -
  374. // MARK: 保存密码
  375. extension NSDocument {
  376. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  377. if (document.isLocked || password.isEmpty) {
  378. return
  379. }
  380. let fileId = self.fileId(for: document)
  381. if (fileId.isEmpty) {
  382. return
  383. }
  384. // let status: SKPasswordStatus =
  385. let label = "PDF Master: \(self.displayName!)"
  386. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  387. }
  388. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  389. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  390. // if (status == .found) {
  391. // }
  392. }
  393. fileprivate func fileId(for document: CPDFDocument) -> String {
  394. return "\(document.documentURL.path.hash)"
  395. }
  396. private func passwordServiceName() -> String {
  397. return "PDF Master password"
  398. }
  399. }