KMBrowserWindowController+CreateFile.swift 33 KB

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