KMBrowserWindowController+CreateFile.swift 31 KB

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