KMBrowserWindowController+CreateFile.swift 31 KB

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