KMBrowserWindowController+CreateFile.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. //
  2. // KMBrowserWindowController+CreateFile.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2025/1/17.
  6. //
  7. import Foundation
  8. extension KMBrowserWindowController {
  9. func newFromFile() {
  10. let openPanel = NSOpenPanel()
  11. var fileTypes = KMBatchManager.supportedImageTypes()
  12. fileTypes.append("PDF")
  13. fileTypes.append("pdf")
  14. openPanel.allowedFileTypes = fileTypes
  15. openPanel.allowsMultipleSelection = true
  16. openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.")
  17. if IAPProductsManager.default().isAvailableAllFunction(){
  18. openPanel.allowsMultipleSelection = true
  19. } else {
  20. openPanel.allowsMultipleSelection = false
  21. }
  22. openPanel.beginSheetModal(for: NSWindow.currentWindow()) {[weak self] result in
  23. if result == NSApplication.ModalResponse.OK {
  24. guard let weakSelf = self else { return }
  25. let urls = openPanel.urls as [URL]
  26. for url in urls {
  27. weakSelf.openFile(withFilePath: url)
  28. }
  29. }
  30. }
  31. }
  32. func newFromImageFile() {
  33. let openPanel = NSOpenPanel()
  34. openPanel.allowedFileTypes = KMBatchManager.supportedImageTypes()
  35. //MARK: 允许多选还是单选,如果是付费用户允许多选
  36. openPanel.allowsMultipleSelection = true
  37. openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.")
  38. if IAPProductsManager.default().isAvailableAllFunction(){
  39. openPanel.allowsMultipleSelection = true
  40. } else {
  41. openPanel.allowsMultipleSelection = false
  42. }
  43. openPanel.beginSheetModal(for: NSWindow.currentWindow()) {[weak self] result in
  44. if result == NSApplication.ModalResponse.OK {
  45. guard let weakSelf = self else { return }
  46. let urls = openPanel.urls as [URL]
  47. self?.showBatchWindow(type: .imageToPDF, files: urls)
  48. }
  49. }
  50. }
  51. func newBlankPage() {
  52. let panel = NSSavePanel()
  53. panel.allowedFileTypes = ["pdf"]
  54. let resp = panel.runModal()
  55. if resp != .OK {
  56. return
  57. }
  58. let saveUrl = panel.url!
  59. let pdfDocument = CPDFDocument()
  60. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  61. pdfDocument?.write(toFile: saveUrl.path)
  62. self.openFile(withFilePath: saveUrl)
  63. }
  64. func newFromWebPage() {
  65. createWC.own_beginSheetModal(for: self.window) {[weak self] string in
  66. guard let weakSelf = self else { return }
  67. if let path = string {
  68. self?.openFile(withFilePath: URL(fileURLWithPath: path))
  69. }
  70. }
  71. }
  72. func newFromClipboard() {
  73. var error: NSError?
  74. let pboard = NSPasteboard.general
  75. var document = openDocumentWithImageFromPasteboard(pboard, error: &error)
  76. if document == nil{
  77. document = openDocument(withURLFromPasteboard: pboard, showNotes: false, error: &error)
  78. }
  79. }
  80. func importFromScanner() {
  81. let vc = KMDeviceBrowserWindowController.shared
  82. vc.type = .scanner
  83. vc.importScannerFileCallback = { [weak self] (url: NSURL) -> Void in
  84. self?.openFile(withFilePath: url as URL)
  85. }
  86. vc.showWindowInCenter(nil)
  87. }
  88. //MARK: Batch
  89. func showBatchWindow(type: KMBatchCollectionViewType, subType: Int = 0, files: [URL]?) {
  90. let batchWindowController = KMBatchWindowController.manager
  91. batchWindowController.window?.makeKeyAndOrderFront("")
  92. // var datas: [KMBatchProcessingTableViewModel] = []
  93. // for file in files! {
  94. // let data = KMBatchProcessingTableViewModel.initWithFilePath(url: file)
  95. // datas.append(data)
  96. // }
  97. batchWindowController.inputData = files ?? []
  98. batchWindowController.type = type
  99. batchWindowController.inputSubType = subType
  100. }
  101. func openFile(withFilePath path: URL) -> Void {
  102. let type = path.pathExtension.lowercased()
  103. if (type == "pdf") {
  104. self.openHistoryFilePath(url: path)
  105. } else if (type == "jpg") ||
  106. (type == "cur") ||
  107. (type == "bmp") ||
  108. (type == "jpeg") ||
  109. (type == "gif") ||
  110. (type == "png") ||
  111. (type == "tiff") ||
  112. (type == "tif") ||
  113. (type == "ico") ||
  114. (type == "icns") ||
  115. (type == "tga") ||
  116. (type == "psd") ||
  117. (type == "eps") ||
  118. (type == "hdr") ||
  119. (type == "jp2") ||
  120. (type == "jpc") ||
  121. (type == "pict") ||
  122. (type == "sgi") ||
  123. (type == "heic") {
  124. openImageFile(url: path)
  125. } else if (type == "doc") ||
  126. (type == "docx") ||
  127. (type == "xls") ||
  128. (type == "xlsx") ||
  129. (type == "ppt") ||
  130. (type == "pptx") ||
  131. (type == "pptx") {
  132. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  133. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  134. openOfficeFile(url: path)
  135. }
  136. }
  137. func openHistoryFilePath(url: URL) -> Void {
  138. if !url.path.isPDFValid() {
  139. let alert = NSAlert()
  140. alert.alertStyle = .critical
  141. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  142. alert.beginSheetModal(for: NSApp.mainWindow!) { [weak self] result in
  143. }
  144. return
  145. }
  146. if url.pathExtension.lowercased() == "pdf" {
  147. let pdfDoc = CPDFDocument.init(url: url)
  148. if pdfDoc != nil {
  149. let document = NSDocumentController.shared.document(for: url)
  150. var alreadyOpen = false
  151. for openDocument in NSDocumentController.shared.documents {
  152. if document == openDocument {
  153. alreadyOpen = true
  154. }
  155. }
  156. if !alreadyOpen {
  157. if self.browser?.tabCount() ?? 0 > 1{
  158. if !IAPProductsManager.default().isAvailableAllFunction() {
  159. showLimitWindowAlert(url: url)
  160. return
  161. }else {
  162. }
  163. }
  164. }
  165. var selectDocument: KMMainDocument? = nil
  166. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  167. selectDocument = (document as! KMMainDocument)
  168. }
  169. if selectDocument != nil {
  170. selectDocument?.tryToUnlockDocument(pdfDoc!)
  171. if selectDocument?.browser != nil {
  172. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument) ?? 0
  173. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex), userGesture: true)
  174. let isVisible: Bool = selectDocument?.browser.window.isVisible ?? false
  175. let isMiniaturized: Bool = selectDocument?.browser.window.isMiniaturized ?? false
  176. if isVisible {
  177. selectDocument?.browser.window.orderFront(nil)
  178. } else if isMiniaturized {
  179. selectDocument?.browser.window.orderFront(nil)
  180. }
  181. }
  182. } else {
  183. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  184. }
  185. }
  186. } else {
  187. let alert = NSAlert()
  188. alert.alertStyle = .critical
  189. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  190. alert.beginSheetModal(for: NSApp.mainWindow!) { [weak self] result in
  191. }
  192. }
  193. } else {
  194. NSWorkspace.shared.open(url)
  195. }
  196. }
  197. func openImageFile(url: URL) -> Void {
  198. var filePath = url.path
  199. let fileName: NSString = url.lastPathComponent as NSString
  200. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String).deletingLastPathComponent
  201. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  202. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  203. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  204. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  205. }
  206. if (!FileManager.default.fileExists(atPath: path as String)) {
  207. FileManager.default.createFile(atPath: path as String, contents: nil)
  208. }
  209. let document = CPDFDocument.init()
  210. var success = false
  211. if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
  212. NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
  213. let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
  214. if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
  215. FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
  216. }
  217. // 加载 PNG 图像
  218. guard let pngImage = NSImage(contentsOfFile: filePath) else {
  219. KMPrint("Failed to load PNG image")
  220. return
  221. }
  222. // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
  223. let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
  224. guard let bitmap = bitmap else {
  225. return
  226. }
  227. let rect = NSRect(origin: .zero, size: bitmap.size)
  228. bitmap.draw(in: rect)
  229. // 将 PNG 图像数据转换为 JPG 图像数据
  230. guard let jpgData = bitmap.representation(using: .jpeg, properties: [:]) else {
  231. KMPrint("Failed to convert PNG to JPG")
  232. return
  233. }
  234. // 保存 JPG 图像数据到文件
  235. let fileURL = URL(fileURLWithPath: jpgPath)
  236. do {
  237. try jpgData.write(to: fileURL)
  238. filePath = fileURL.path
  239. KMPrint("JPG image saved successfully")
  240. } catch {
  241. KMPrint("Failed to save JPG image: \(error.localizedDescription)")
  242. }
  243. }
  244. let image = NSImage(contentsOfFile: filePath)
  245. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  246. if insertPageSuccess != nil {
  247. //信号量控制异步
  248. let semaphore = DispatchSemaphore(value: 0)
  249. DispatchQueue.global().async {
  250. success = ((document?.write(toFile: path)) != nil)
  251. semaphore.signal()
  252. }
  253. semaphore.wait()
  254. } else {
  255. }
  256. if success {
  257. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, isOpened, error in
  258. if error != nil {
  259. NSApp.presentError(error!)
  260. } else {
  261. if FileManager.default.fileExists(atPath: filePath) {
  262. try? FileManager.default.removeItem(atPath: filePath)
  263. }
  264. if document is KMMainDocument {
  265. let newDocument = document
  266. (newDocument as! KMMainDocument).isNewCreated = true
  267. }
  268. }
  269. }
  270. }
  271. }
  272. func openOfficeFile(url: URL) -> Void {
  273. let filePath = url.path
  274. let folderPath = "convertToPDF.pdf"
  275. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  276. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  277. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  278. }
  279. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  280. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  281. }
  282. if savePath == nil {
  283. return
  284. }
  285. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  286. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  287. if FileManager.default.fileExists(atPath: savePath!) {
  288. try?FileManager.default.removeItem(atPath: savePath!)
  289. }
  290. let alert = NSAlert.init()
  291. alert.alertStyle = .critical
  292. var infoString = ""
  293. if errorDic != nil {
  294. for key in (errorDic! as Dictionary).keys {
  295. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  296. }
  297. }
  298. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  299. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  300. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  301. alert.runModal()
  302. return
  303. }
  304. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { _, _, _ in
  305. }
  306. }
  307. }
  308. func openImageToPdfWindow(urls: Array<URL>) {
  309. self.showBatchWindow(type: .imageToPDF, files: urls)
  310. }
  311. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> Any? {
  312. var document: CPDFDocument? = nil
  313. var data: Data? = nil
  314. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  315. // pboard.types
  316. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  317. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  318. // pboard.types
  319. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  320. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  321. // pboard.types
  322. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  323. } else {
  324. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  325. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  326. if images?.count ?? 0 > 0 {
  327. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  328. } else if strings?.count ?? 0 > 0 {
  329. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  330. }
  331. }
  332. if let data = data {
  333. _ = NSDocumentController.shared
  334. document = CPDFDocument(data: data)
  335. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  336. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  337. let filePath = savePath.deletingLastPathComponent
  338. if FileManager.default.fileExists(atPath: filePath) == false {
  339. try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  340. }
  341. document?.write(to: URL(fileURLWithPath: savePath))
  342. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  343. if error != nil {
  344. NSApp.presentError(error!)
  345. } else {
  346. if document is KMMainDocument {
  347. let newDocument = document
  348. (newDocument as! KMMainDocument).isNewCreated = true
  349. }
  350. }
  351. }
  352. } else if let outError = outError {
  353. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  354. }
  355. return document
  356. }
  357. func openDocument(withURLFromPasteboard pboard: NSPasteboard, showNotes: Bool, error outError: inout NSError?) -> Any? {
  358. let theURLs = NSURL.readURLs(from: pboard)
  359. let url = theURLs?.count ?? 0 > 0 ? theURLs?[0] : nil
  360. let theURL: NSURL? = url as? NSURL
  361. let documentC = NSDocumentController.shared
  362. var document: NSDocument? = nil
  363. if (theURL as AnyObject).isFileURL == true {
  364. var _: NSError? = nil
  365. let type = try? documentC.typeForContents(of: theURL as! URL)//ForContents(ofURL: theURL, error: &error)
  366. if showNotes == false || NSDocument.readableTypes.contains(type ?? "") {
  367. documentC.openDocument(withContentsOf: theURL as! URL, display: true, completionHandler: { resultDocument, success, err in
  368. document = resultDocument
  369. })
  370. } else if NSDocument.readableTypes.contains(type ?? "") {
  371. for doc in documentC.documents {
  372. let sel = NSSelectorFromString("sourceFileURL")
  373. if doc.responds(to: sel) && doc.fileURL == theURL as? URL {
  374. document = doc
  375. break
  376. }
  377. }
  378. if let document: NSDocument = document {
  379. document.showWindows()
  380. } else {
  381. if let document = try? documentC.makeUntitledDocument(ofType: KMNotesDocumentType) {
  382. document.fileURL = URL(fileURLWithPath: theURL?.path ?? "")
  383. documentC.addDocument(document)
  384. document.makeWindowControllers()
  385. document.showWindows()
  386. }
  387. }
  388. }
  389. }
  390. return document
  391. }
  392. func showLimitWindowAlert(url: URL?) {
  393. if !KMDataManager.default.isTabbingWin{
  394. KMDataManager.default.isTabbingWin = true
  395. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  396. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  397. KMDataManager.default.isTabbingWin = false
  398. if continueOrNot {
  399. self?.reopenDocument(forPaths: url?.path)
  400. } else {
  401. }
  402. }
  403. self.km_beginSheet(windowC: tabbingWin)
  404. }
  405. }
  406. func fetchUniquePath(_ originalPath: String) -> String {
  407. var path = originalPath
  408. let dManager = FileManager.default
  409. if !dManager.fileExists(atPath: path) {
  410. if path.extension.count < 1 {
  411. path = path.stringByAppendingPathExtension("pdf")
  412. }
  413. return path
  414. } else {
  415. let originalFullFileName = path.lastPathComponent
  416. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  417. let originalExtension = path.extension
  418. let startIndex: Int = 0
  419. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  420. let fileLocatePath = originalPath.substring(to: endIndex)
  421. var i = 1
  422. while (1 != 0) {
  423. var newName = String(format: "%@%ld", originalFileName, i)
  424. newName = String(format: "%@%@", newName, originalExtension)
  425. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  426. if !dManager.fileExists(atPath: newPath) {
  427. return newPath
  428. } else {
  429. i+=1
  430. continue
  431. }
  432. }
  433. }
  434. }
  435. func fetchDifferentFilePath(filePath: String) -> String {
  436. var resultFilePath = filePath
  437. var index: Int = 0
  438. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  439. index += 1
  440. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  441. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  442. }
  443. return resultFilePath;
  444. }
  445. func isDamageImage(image: NSImage?, path: String) -> Bool {
  446. if (image == nil) {
  447. return true
  448. }
  449. let addImageAnnotation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last!.appendingPathComponent(Bundle.main.bundleIdentifier!).appendingPathComponent("addImageAnnotation")
  450. if !FileManager.default.fileExists(atPath: addImageAnnotation.path) {
  451. try? FileManager.default.createDirectory(atPath: addImageAnnotation.path, withIntermediateDirectories: false, attributes: nil)
  452. }
  453. guard let data = image!.tiffRepresentation else { return false }
  454. guard let imageRep = NSBitmapImageRep(data: data) else { return false }
  455. imageRep.size = image!.size
  456. var imageData: Data?
  457. if path.lowercased() == "png" {
  458. imageData = imageRep.representation(using: .png, properties: [:])
  459. } else {
  460. imageData = imageRep.representation(using: .jpeg, properties: [:])
  461. }
  462. let rPath: URL = addImageAnnotation.appendingPathComponent(tagString()).appendingPathExtension("png")
  463. if let data = imageData {
  464. try?data.write(to: rPath)
  465. return false
  466. } else {
  467. return true
  468. }
  469. }
  470. func tagString() -> String {
  471. let dateFormatter = DateFormatter()
  472. dateFormatter.dateFormat = "yyMMddHHmmss"
  473. let currentDate = Date()
  474. let randomNum = Int(arc4random_uniform(10000))
  475. let str = String(format: "%@%04d", dateFormatter.string(from: Date()),randomNum)
  476. return str
  477. }
  478. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  479. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  480. let pdfData = NSMutableData(capacity: tiffData.count)
  481. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  482. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  483. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  484. ctxt!.beginPDFPage(nil)
  485. ctxt!.draw(cgImage, in: rect)
  486. ctxt!.endPDFPage()
  487. ctxt!.closePDF()
  488. return pdfData as? Data
  489. }
  490. func createBaseFoldPath() -> String {
  491. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  492. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  493. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  494. }
  495. return folderPath ?? ""
  496. }
  497. func filePathCheck(path: String) -> String {
  498. var i: Int = 0
  499. let fileURL = URL(fileURLWithPath: path)
  500. var newPath: String = path
  501. let fileManager = FileManager.default
  502. while fileManager.fileExists(atPath: newPath) {
  503. i += 1
  504. newPath = fileURL.deletingPathExtension().path
  505. newPath.append("(\(i))")
  506. newPath.append(".")
  507. newPath.append(fileURL.pathExtension)
  508. }
  509. return newPath
  510. }
  511. func screenShot_SelectArea(_ sender: Any?) {
  512. KMScreenShotHandler.beginScreenshot_SelectRectWithCompleteHandler { ima in
  513. if let image = ima {
  514. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  515. let folderPath = self.createBaseFoldPath()
  516. let savePathOld = folderPath + "/screenShot.pdf"
  517. var savePath = self.filePathCheck(path: savePathOld)
  518. let newDocument = CPDFDocument()
  519. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  520. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  521. if writeSuccess ?? false {
  522. if self.checkOpenNewDocument(path: savePath) {
  523. self.savePdf(savePath)
  524. }
  525. } else {
  526. }
  527. }
  528. }
  529. }
  530. }
  531. func screenShot_Window(_ sender: Any?) {
  532. KMPrint("screenShot_Window")
  533. KMScreenShotHandler.beginScreenShot_SelectWindowCompleteHandler { ima in
  534. if let image = ima {
  535. if image.size.equalTo(.zero) == true {
  536. } else {
  537. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  538. let folderPath = self.createBaseFoldPath()
  539. let savePathOld = folderPath + "/screenShot.pdf"
  540. var savePath = self.filePathCheck(path: savePathOld)
  541. let newDocument = CPDFDocument()
  542. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  543. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  544. if writeSuccess == true {
  545. if self.checkOpenNewDocument(path: savePath) {
  546. self.savePdf(savePath)
  547. }
  548. // try? FileManager.default.removeItem(atPath: savePath)
  549. } else {
  550. }
  551. }
  552. }
  553. }
  554. }
  555. }
  556. func screenShot_FullScreenDelay(_ sender: Any?) {//不延迟
  557. KMPrint("screenShot_FullScreenDelay")
  558. KMScreenShotHandler.beginScreenShot_FullSreenWithDelayTime(0) { ima in
  559. if let image = ima {
  560. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  561. let folderPath = self.createBaseFoldPath()
  562. let savePathOld = folderPath + "/screenShot.pdf"
  563. var savePath = self.filePathCheck(path: savePathOld)
  564. let newDocument = CPDFDocument()
  565. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  566. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  567. if writeSuccess == true {
  568. if self.checkOpenNewDocument(path: savePath) {
  569. self.savePdf(savePath)
  570. }
  571. // try? FileManager.default.removeItem(atPath: savePath)
  572. } else {
  573. }
  574. }
  575. }
  576. }
  577. }
  578. func screenShot_FullScreen(_ sender: Any?) {//延迟3秒
  579. KMPrint("screenShot_FullScreen")
  580. KMScreenShotHandler.beginScreenShot_FullSreenWithDelayTime(3) { ima in
  581. if let image = ima {
  582. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  583. let folderPath = self.createBaseFoldPath()
  584. let savePathOld = folderPath + "/screenShot.pdf"
  585. var savePath = self.filePathCheck(path: savePathOld)
  586. let newDocument = CPDFDocument()
  587. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  588. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  589. if writeSuccess == true {
  590. self.savePdf(savePath)
  591. // try? FileManager.default.removeItem(atPath: savePath)
  592. } else {
  593. }
  594. }
  595. }
  596. }
  597. }
  598. func checkOpenNewDocument(path: String) -> Bool {
  599. let tabCount = self.km_browser?.tabCount() ?? 0
  600. if tabCount > 1{
  601. if !IAPProductsManager.default().isAvailableAllFunction() {
  602. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  603. if preferenceNoteShow {
  604. menuItemAction_newTagPageToNewWindow("")
  605. } else {
  606. if !KMDataManager.default.isTabbingWin{
  607. KMDataManager.default.isTabbingWin = true
  608. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  609. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  610. KMDataManager.default.isTabbingWin = false
  611. if continueOrNot {
  612. self?.reopenDocumentForNewWindow(savePath: path)
  613. } else {
  614. }
  615. }
  616. self.km_beginSheet(windowC: tabbingWin)
  617. }
  618. }
  619. return false
  620. }else {
  621. if KMPreference.shared.openDocumentType == .newWindow {
  622. self.reopenDocumentForNewWindow(savePath: path)
  623. return false
  624. }
  625. }
  626. }
  627. return true
  628. }
  629. func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  630. if (self.canResponseDocumentAction() == false) {
  631. return
  632. }
  633. self.openNewWindow(sender)
  634. }
  635. func reopenDocumentForNewWindow(savePath: String) {
  636. let browser = KMBrowser.init() as KMBrowser
  637. browser.windowController = KMBrowserWindowController.init(browser: browser)
  638. browser.addHomeTabContents()
  639. browser.windowController.showWindow(self)
  640. self.savePdf(savePath)
  641. }
  642. func savePdf(_ filePath: String) -> Void {
  643. let docVc = KMDocumentController.shared
  644. docVc.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  645. if error != nil {
  646. NSApp.presentError(error!)
  647. } else {
  648. if document is KMMainDocument {
  649. let newDocument = document
  650. (newDocument as! KMMainDocument).isNewCreated = true
  651. }
  652. }
  653. }
  654. }
  655. }