KMBrowserWindowController+CreateFile.swift 31 KB

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