KMDocumentController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. //
  2. // KMDocumentController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/5.
  6. //
  7. import Cocoa
  8. let KMPDFDocumentType: String = "com.adobe.pdf"
  9. let KMPDFBundleDocumentType: String = "net.sourceforge.skim-app.pdfd"
  10. let KMNotesDocumentType: String = "net.sourceforge.skim-app.skimnotes"
  11. let KMNotesTextDocumentType: String = "public.plain-text"
  12. let KMNotesRTFDocumentType: String = "public.rtf"
  13. let KMNotesRTFDDocumentType: String = "com.apple.rtfd"
  14. let KMNotesFDFDocumentType: String = "com.adobe.fdf"
  15. let KMPostScriptDocumentType: String = "com.adobe.postscript"
  16. let KMEncapsulatedPostScriptDocumentType: String = "com.adobe.encapsulated-postscript"
  17. let KMDVIDocumentType: String = "org.tug.tex.dvi"
  18. let KMXDVDocumentType: String = "org.tug.tex.xdv"
  19. let KMFolderDocumentType: String = "public.folder"
  20. let KMDocumentSetupAliasKey: String = "_BDAlias"
  21. let KMDocumentSetupFileNameKey: String = "fileName"
  22. class KMDocumentController: NSDocumentController {
  23. func fetchUniquePath(_ originalPath: String) -> String {
  24. var path = originalPath
  25. let dManager = FileManager.default
  26. if !dManager.fileExists(atPath: path) {
  27. if path.extension.count < 1 {
  28. path = path.stringByAppendingPathExtension("pdf")
  29. }
  30. return path
  31. } else {
  32. let originalFullFileName = path.lastPathComponent
  33. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  34. let originalExtension = path.extension
  35. let startIndex: Int = 0
  36. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  37. let fileLocatePath = originalPath.substring(to: endIndex)
  38. var i = 1
  39. while (1 != 0) {
  40. var newName = String(format: "%@%ld", originalFileName, i)
  41. newName = String(format: "%@%@", newName, originalExtension)
  42. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  43. if !dManager.fileExists(atPath: newPath) {
  44. return newPath
  45. } else {
  46. i+=1
  47. continue
  48. }
  49. }
  50. }
  51. }
  52. func kNewDocumentTempSavePath(_ fileName: String) -> String {
  53. let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  54. let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  55. let append2 = append1!.stringByAppendingPathComponent(String(format: "%@", fileName))
  56. return append2
  57. }
  58. func savePdf(_ filePath: String) -> Void {
  59. let pdfData = try! Data(contentsOf: URL(fileURLWithPath: filePath))
  60. let document = try! self.makeUntitledDocument(ofType: KMPDFDocumentType) as NSDocument
  61. if ((try? document.read(from: pdfData, ofType: KMPDFDocumentType)) != nil) {
  62. self.addDocument(document)
  63. document.makeWindowControllers()
  64. document.showWindows()
  65. }
  66. }
  67. // MARK: Action
  68. @IBAction func importFromFile(_ sender: Any) {
  69. }
  70. @IBAction func openBlankPage(_ sender: Any) {
  71. let fileName = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: ""))
  72. let savePath = fetchUniquePath(kNewDocumentTempSavePath(fileName))
  73. let pdfDocument = CPDFDocument()
  74. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  75. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  76. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  77. if error != nil {
  78. NSApp.presentError(error!)
  79. return
  80. }
  81. if document is KMMainDocument {
  82. let newDocument = document
  83. (newDocument as! KMMainDocument).isNewCreated = false
  84. }
  85. }
  86. }
  87. @IBAction func newDocumentFromImage(_ sender: Any) {
  88. }
  89. @IBAction func importFromWebPage(_ sender: Any) {
  90. }
  91. @IBAction func importFromScanner(_ sender: Any) {
  92. }
  93. override var maximumRecentDocumentCount: Int {
  94. return SettingsManager.sharedInstance.fileListCount
  95. }
  96. }
  97. extension NSDocumentController {
  98. func openDocumentWithURLFromPasteboard(_ pboard: NSPasteboard, showNotes: Bool, outError: NSErrorPointer) -> Any? {
  99. guard let theURLs = NSURL.readURLs(from: pboard), let theURL = theURLs.first else {
  100. if showNotes == false {
  101. outError?.pointee = NSError.readPasteboardError(withLocalizedDescription: NSLocalizedString("Unable to load data from clipboard", comment: "Error description"))
  102. }
  103. return nil
  104. }
  105. // guard (theURL as AnyObject).isFileURL else {
  106. // if showNotes == false {
  107. // return SKDownloadController.shared.addDownload(for: theURL)
  108. // }
  109. // return nil
  110. // }
  111. var document: Any?
  112. do {
  113. let type = try self.typeForContents(of: theURL as! URL)
  114. // if showNotes == false || KMNotesDocument.readableTypes.contains(type) {
  115. // document = try self.openDocument(withContentsOf: theURL as! URL, display: true)
  116. // } else
  117. if KMMainDocument.readableTypes.contains(type) {
  118. for doc in self.documents {
  119. if let sourceURL = (doc as? NSObject)?.value(forKey: "sourceFileURL") as? URL, sourceURL == theURL as! URL {
  120. document = doc
  121. break
  122. }
  123. }
  124. if let existingDoc = document as? NSDocument {
  125. existingDoc.showWindows()
  126. } else {
  127. var error: NSError?
  128. var data: Data?
  129. if NSWorkspace.shared.type(type, conformsToType: KMPDFBundleDocumentType) {
  130. let skimFileURL = try self.bundledFileURLWithExtension("skim", inPDFBundleAtURL: theURL as! URL)
  131. data = try Data(contentsOf: skimFileURL)
  132. }
  133. // else {
  134. // data = try SKNExtendedAttributeManager.shared().extendedAttributeNamed(SKIM_NOTES_KEY, atPath: theURL.path, traverseLink: true)
  135. // }
  136. // let newDocument = try makeUntitledDocument(ofType: KMNotesDocumentType)
  137. // newDocument.sourceFileURL = theURL
  138. //
  139. // if data == nil || newDocument.read(from: data ?? Data(), ofType: KMNotesDocumentType) {
  140. // self.addDocument(newDocument)
  141. // newDocument.makeWindowControllers()
  142. // newDocument.showWindows()
  143. // } else {
  144. // document = nil
  145. // outError?.pointee = error
  146. // }
  147. }
  148. }
  149. } catch {
  150. outError?.pointee = error as NSError
  151. }
  152. return document
  153. }
  154. func bundledFileURLWithExtension(_ extension: String, inPDFBundleAtURL theURL: URL) throws -> URL {
  155. let bundleContents = try FileManager.default.contentsOfDirectory(at: theURL, includingPropertiesForKeys: nil, options: [])
  156. for fileURL in bundleContents {
  157. if fileURL.pathExtension == `extension` {
  158. return fileURL
  159. }
  160. }
  161. throw NSError(domain: "YourDomain", code: 404, userInfo: [NSLocalizedDescriptionKey: "File with extension not found in PDF bundle"])
  162. }
  163. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: NSErrorPointer) -> Any? {
  164. var document: NSDocument?
  165. var data: Data?
  166. var type: String?
  167. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  168. pboard.types
  169. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  170. type = KMPDFDocumentType
  171. } else if pboard.canReadItem(withDataConformingToTypes: [KMEncapsulatedPostScriptDocumentType]) {
  172. pboard.types
  173. data = pboard.data(forType: NSPasteboard.PasteboardType(rawValue: KMEncapsulatedPostScriptDocumentType))
  174. type = isEncapsulatedPostScriptData(data!) ? KMEncapsulatedPostScriptDocumentType : KMPostScriptDocumentType
  175. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  176. pboard.types
  177. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff)!)
  178. type = KMPDFDocumentType
  179. } else {
  180. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:]) as? [NSImage]
  181. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:]) as? [NSAttributedString]
  182. if let images = images, images.count > 0 {
  183. data = convertTIFFDataToPDF(images[0].tiffRepresentation!)
  184. type = KMPDFDocumentType
  185. } else if let strings = strings, strings.count > 0 {
  186. data = KMOCTool.convertStringsToPDF(withString: strings) // convertStringsToPDF(strings!)
  187. type = KMPDFDocumentType
  188. }
  189. }
  190. if let data = data, let type = type {
  191. var error: NSError?
  192. document = try?makeUntitledDocument(ofType: type)
  193. if ((try?document?.read(from: data, ofType:type)) != nil) {
  194. addDocument(document!)
  195. document?.makeWindowControllers()
  196. document?.showWindows()
  197. } else {
  198. document = nil
  199. if let outError = outError {
  200. outError.pointee = error
  201. }
  202. }
  203. } else if let outError = outError {
  204. outError.pointee = NSError.readPasteboardError(withLocalizedDescription: NSLocalizedString("Unable to load data from clipboard", comment: "Error description"))
  205. }
  206. return document
  207. }
  208. func isEncapsulatedPostScriptData(_ data: Data) -> Bool {
  209. let epsHeaderData = Data(bytes: [69, 80, 83, 70, 45], count: 5)
  210. let rg: Range = (14..<20)
  211. return (data.count >= 20 && (data.range(of: epsHeaderData, options: .anchored, in: rg) != nil))
  212. }
  213. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  214. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  215. let pdfData = NSMutableData(capacity: tiffData.count)
  216. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  217. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  218. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  219. ctxt!.beginPDFPage(nil)
  220. ctxt!.draw(cgImage, in: rect)
  221. ctxt!.endPDFPage()
  222. ctxt!.closePDF()
  223. return pdfData as? Data
  224. }
  225. }