KMBrowserWindowController+CreateFile.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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", KMLocalizedString("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 = KMLocalizedString("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. }
  181. }
  182. var selectDocument: KMMainDocument? = nil
  183. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  184. selectDocument = (document as! KMMainDocument)
  185. }
  186. if selectDocument != nil {
  187. selectDocument?.tryToUnlockDocument(pdfDoc!)
  188. if selectDocument?.browser != nil {
  189. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument) ?? 0
  190. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex), userGesture: true)
  191. let isVisible: Bool = selectDocument?.browser.window.isVisible ?? false
  192. let isMiniaturized: Bool = selectDocument?.browser.window.isMiniaturized ?? false
  193. if isVisible {
  194. selectDocument?.browser.window.orderFront(nil)
  195. } else if isMiniaturized {
  196. selectDocument?.browser.window.orderFront(nil)
  197. }
  198. }
  199. } else {
  200. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  201. }
  202. }
  203. } else {
  204. let alert = NSAlert()
  205. alert.alertStyle = .critical
  206. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  207. alert.beginSheetModal(for: NSApp.mainWindow!) { [weak self] result in
  208. }
  209. }
  210. } else {
  211. NSWorkspace.shared.open(url)
  212. }
  213. }
  214. func openImageFile(url: URL) -> Void {
  215. var filePath = url.path
  216. let fileName: NSString = url.lastPathComponent as NSString
  217. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String).deletingLastPathComponent
  218. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  219. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  220. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  221. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  222. }
  223. if (!FileManager.default.fileExists(atPath: path as String)) {
  224. FileManager.default.createFile(atPath: path as String, contents: nil)
  225. }
  226. let document = CPDFDocument.init()
  227. var success = false
  228. if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
  229. NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
  230. let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
  231. if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
  232. FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
  233. }
  234. // 加载 PNG 图像
  235. guard let pngImage = NSImage(contentsOfFile: filePath) else {
  236. KMPrint("Failed to load PNG image")
  237. return
  238. }
  239. // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
  240. let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
  241. guard let bitmap = bitmap else {
  242. return
  243. }
  244. let rect = NSRect(origin: .zero, size: bitmap.size)
  245. bitmap.draw(in: rect)
  246. // 将 PNG 图像数据转换为 JPG 图像数据
  247. guard let jpgData = bitmap.representation(using: .jpeg, properties: [:]) else {
  248. KMPrint("Failed to convert PNG to JPG")
  249. return
  250. }
  251. // 保存 JPG 图像数据到文件
  252. let fileURL = URL(fileURLWithPath: jpgPath)
  253. do {
  254. try jpgData.write(to: fileURL)
  255. filePath = fileURL.path
  256. KMPrint("JPG image saved successfully")
  257. } catch {
  258. KMPrint("Failed to save JPG image: \(error.localizedDescription)")
  259. }
  260. }
  261. let image = NSImage(contentsOfFile: filePath)
  262. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  263. if insertPageSuccess != nil {
  264. //信号量控制异步
  265. let semaphore = DispatchSemaphore(value: 0)
  266. DispatchQueue.global().async {
  267. success = ((document?.write(toFile: path)) != nil)
  268. semaphore.signal()
  269. }
  270. semaphore.wait()
  271. } else {
  272. }
  273. if success {
  274. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, isOpened, error in
  275. if error != nil {
  276. NSApp.presentError(error!)
  277. } else {
  278. if FileManager.default.fileExists(atPath: filePath) {
  279. try? FileManager.default.removeItem(atPath: filePath)
  280. }
  281. if document is KMMainDocument {
  282. let newDocument = document
  283. (newDocument as! KMMainDocument).isNewCreated = true
  284. }
  285. }
  286. }
  287. }
  288. }
  289. func openOfficeFile(url: URL) -> Void {
  290. let filePath = url.path
  291. let folderPath = "convertToPDF.pdf"
  292. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  293. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  294. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  295. }
  296. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  297. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  298. }
  299. if savePath == nil {
  300. return
  301. }
  302. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  303. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  304. if FileManager.default.fileExists(atPath: savePath!) {
  305. try?FileManager.default.removeItem(atPath: savePath!)
  306. }
  307. let alert = NSAlert.init()
  308. alert.alertStyle = .critical
  309. var infoString = ""
  310. if errorDic != nil {
  311. for key in (errorDic! as Dictionary).keys {
  312. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  313. }
  314. }
  315. alert.informativeText = KMLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  316. alert.messageText = KMLocalizedString("Failed to Create PDF", comment: "")
  317. alert.addButton(withTitle: KMLocalizedString("OK", comment: ""))
  318. alert.runModal()
  319. return
  320. }
  321. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { _, _, _ in
  322. }
  323. }
  324. }
  325. func openImageToPdfWindow(urls: Array<URL>) {
  326. self.showBatchWindow(type: .imageToPDF, files: urls)
  327. }
  328. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> Any? {
  329. var document: CPDFDocument? = nil
  330. var data: Data? = nil
  331. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  332. // pboard.types
  333. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  334. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  335. // pboard.types
  336. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  337. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  338. // pboard.types
  339. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  340. } else {
  341. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  342. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  343. if images?.count ?? 0 > 0 {
  344. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  345. } else if strings?.count ?? 0 > 0 {
  346. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  347. }
  348. }
  349. if let data = data {
  350. _ = NSDocumentController.shared
  351. document = CPDFDocument(data: data)
  352. let fileName: NSString = String(format: "%@.pdf", KMLocalizedString("Untitled", comment: "")) as NSString
  353. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  354. let filePath = savePath.deletingLastPathComponent
  355. if FileManager.default.fileExists(atPath: filePath) == false {
  356. try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  357. }
  358. document?.write(to: URL(fileURLWithPath: savePath))
  359. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  360. if error != nil {
  361. NSApp.presentError(error!)
  362. } else {
  363. if document is KMMainDocument {
  364. let newDocument = document
  365. (newDocument as! KMMainDocument).isNewCreated = true
  366. }
  367. }
  368. }
  369. } else if let outError = outError {
  370. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: KMLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  371. }
  372. return document
  373. }
  374. func openDocument(withURLFromPasteboard pboard: NSPasteboard, showNotes: Bool, error outError: inout NSError?) -> Any? {
  375. let theURLs = NSURL.readURLs(from: pboard)
  376. let url = theURLs?.count ?? 0 > 0 ? theURLs?[0] : nil
  377. let theURL: NSURL? = url as? NSURL
  378. let documentC = NSDocumentController.shared
  379. var document: NSDocument? = nil
  380. if (theURL as AnyObject).isFileURL == true {
  381. var _: NSError? = nil
  382. let type = try? documentC.typeForContents(of: theURL as! URL)//ForContents(ofURL: theURL, error: &error)
  383. if showNotes == false || NSDocument.readableTypes.contains(type ?? "") {
  384. documentC.openDocument(withContentsOf: theURL as! URL, display: true, completionHandler: { resultDocument, success, err in
  385. document = resultDocument
  386. })
  387. } else if NSDocument.readableTypes.contains(type ?? "") {
  388. for doc in documentC.documents {
  389. let sel = NSSelectorFromString("sourceFileURL")
  390. if doc.responds(to: sel) && doc.fileURL == theURL as? URL {
  391. document = doc
  392. break
  393. }
  394. }
  395. if let document: NSDocument = document {
  396. document.showWindows()
  397. } else {
  398. if let document = try? documentC.makeUntitledDocument(ofType: KMNotesDocumentType) {
  399. document.fileURL = URL(fileURLWithPath: theURL?.path ?? "")
  400. documentC.addDocument(document)
  401. document.makeWindowControllers()
  402. document.showWindows()
  403. }
  404. }
  405. }
  406. }
  407. return document
  408. }
  409. func showLimitWindowAlert(url: URL?) {
  410. if !KMDataManager.default.isTabbingWin{
  411. KMDataManager.default.isTabbingWin = true
  412. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  413. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  414. KMDataManager.default.isTabbingWin = false
  415. if continueOrNot {
  416. self?.reopenDocument(forPaths: url?.path)
  417. } else {
  418. }
  419. }
  420. self.km_beginSheet(windowC: tabbingWin)
  421. }
  422. }
  423. func fetchUniquePath(_ originalPath: String) -> String {
  424. var path = originalPath
  425. let dManager = FileManager.default
  426. if !dManager.fileExists(atPath: path) {
  427. if path.extension.count < 1 {
  428. path = path.stringByAppendingPathExtension("pdf")
  429. }
  430. return path
  431. } else {
  432. let originalFullFileName = path.lastPathComponent
  433. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  434. let originalExtension = path.extension
  435. let startIndex: Int = 0
  436. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  437. let fileLocatePath = originalPath.substring(to: endIndex)
  438. var i = 1
  439. while (1 != 0) {
  440. var newName = String(format: "%@%ld", originalFileName, i)
  441. newName = String(format: "%@%@", newName, originalExtension)
  442. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  443. if !dManager.fileExists(atPath: newPath) {
  444. return newPath
  445. } else {
  446. i+=1
  447. continue
  448. }
  449. }
  450. }
  451. }
  452. func fetchDifferentFilePath(filePath: String) -> String {
  453. var resultFilePath = filePath
  454. var index: Int = 0
  455. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  456. index += 1
  457. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  458. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  459. }
  460. return resultFilePath;
  461. }
  462. func isDamageImage(image: NSImage?, path: String) -> Bool {
  463. if (image == nil) {
  464. return true
  465. }
  466. let addImageAnnotation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last!.appendingPathComponent(Bundle.main.bundleIdentifier!).appendingPathComponent("addImageAnnotation")
  467. if !FileManager.default.fileExists(atPath: addImageAnnotation.path) {
  468. try? FileManager.default.createDirectory(atPath: addImageAnnotation.path, withIntermediateDirectories: false, attributes: nil)
  469. }
  470. guard let data = image!.tiffRepresentation else { return false }
  471. guard let imageRep = NSBitmapImageRep(data: data) else { return false }
  472. imageRep.size = image!.size
  473. var imageData: Data?
  474. if path.lowercased() == "png" {
  475. imageData = imageRep.representation(using: .png, properties: [:])
  476. } else {
  477. imageData = imageRep.representation(using: .jpeg, properties: [:])
  478. }
  479. let rPath: URL = addImageAnnotation.appendingPathComponent(tagString()).appendingPathExtension("png")
  480. if let data = imageData {
  481. try?data.write(to: rPath)
  482. return false
  483. } else {
  484. return true
  485. }
  486. }
  487. func tagString() -> String {
  488. let dateFormatter = DateFormatter()
  489. dateFormatter.dateFormat = "yyMMddHHmmss"
  490. let currentDate = Date()
  491. let randomNum = Int(arc4random_uniform(10000))
  492. let str = String(format: "%@%04d", dateFormatter.string(from: Date()),randomNum)
  493. return str
  494. }
  495. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  496. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  497. let pdfData = NSMutableData(capacity: tiffData.count)
  498. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  499. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  500. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  501. ctxt!.beginPDFPage(nil)
  502. ctxt!.draw(cgImage, in: rect)
  503. ctxt!.endPDFPage()
  504. ctxt!.closePDF()
  505. return pdfData as? Data
  506. }
  507. func createBaseFoldPath() -> String {
  508. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  509. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  510. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  511. }
  512. return folderPath ?? ""
  513. }
  514. func filePathCheck(path: String) -> String {
  515. var i: Int = 0
  516. let fileURL = URL(fileURLWithPath: path)
  517. var newPath: String = path
  518. let fileManager = FileManager.default
  519. while fileManager.fileExists(atPath: newPath) {
  520. i += 1
  521. newPath = fileURL.deletingPathExtension().path
  522. newPath.append("(\(i))")
  523. newPath.append(".")
  524. newPath.append(fileURL.pathExtension)
  525. }
  526. return newPath
  527. }
  528. func screenShot_SelectArea(_ sender: Any?) {
  529. KMScreenShotHandler.beginScreenshot_SelectRectWithCompleteHandler { ima in
  530. if let image = ima {
  531. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  532. let folderPath = self.createBaseFoldPath()
  533. let savePathOld = folderPath + "/screenShot.pdf"
  534. var savePath = self.filePathCheck(path: savePathOld)
  535. let newDocument = CPDFDocument()
  536. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  537. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  538. if writeSuccess ?? false {
  539. if self.checkOpenNewDocument(path: savePath) {
  540. self.savePdf(savePath)
  541. }
  542. } else {
  543. }
  544. }
  545. }
  546. }
  547. }
  548. func screenShot_Window(_ sender: Any?) {
  549. KMPrint("screenShot_Window")
  550. KMScreenShotHandler.beginScreenShot_SelectWindowCompleteHandler { ima in
  551. if let image = ima {
  552. if image.size.equalTo(.zero) == true {
  553. } else {
  554. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  555. let folderPath = self.createBaseFoldPath()
  556. let savePathOld = folderPath + "/screenShot.pdf"
  557. var savePath = self.filePathCheck(path: savePathOld)
  558. let newDocument = CPDFDocument()
  559. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  560. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  561. if writeSuccess == true {
  562. if self.checkOpenNewDocument(path: savePath) {
  563. self.savePdf(savePath)
  564. }
  565. // try? FileManager.default.removeItem(atPath: savePath)
  566. } else {
  567. }
  568. }
  569. }
  570. }
  571. }
  572. }
  573. func screenShot_FullScreenDelay(_ sender: Any?) {//不延迟
  574. KMPrint("screenShot_FullScreenDelay")
  575. KMScreenShotHandler.beginScreenShot_FullSreenWithDelayTime(0) { ima in
  576. if let image = ima {
  577. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  578. let folderPath = self.createBaseFoldPath()
  579. let savePathOld = folderPath + "/screenShot.pdf"
  580. var savePath = self.filePathCheck(path: savePathOld)
  581. let newDocument = CPDFDocument()
  582. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  583. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  584. if writeSuccess == true {
  585. if self.checkOpenNewDocument(path: savePath) {
  586. self.savePdf(savePath)
  587. }
  588. // try? FileManager.default.removeItem(atPath: savePath)
  589. } else {
  590. }
  591. }
  592. }
  593. }
  594. }
  595. func screenShot_FullScreen(_ sender: Any?) {//延迟3秒
  596. KMPrint("screenShot_FullScreen")
  597. KMScreenShotHandler.beginScreenShot_FullSreenWithDelayTime(3) { ima in
  598. if let image = ima {
  599. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  600. let folderPath = self.createBaseFoldPath()
  601. let savePathOld = folderPath + "/screenShot.pdf"
  602. var savePath = self.filePathCheck(path: savePathOld)
  603. let newDocument = CPDFDocument()
  604. _ = newDocument?.km_insert(imageData: image.jpgData() ?? Data(), pageSize: image.size, at: newDocument?.pageCount ?? 0)
  605. let writeSuccess = newDocument?.write(to: URL(fileURLWithPath: savePath))
  606. if writeSuccess == true {
  607. self.savePdf(savePath)
  608. // try? FileManager.default.removeItem(atPath: savePath)
  609. } else {
  610. }
  611. }
  612. }
  613. }
  614. }
  615. func checkOpenNewDocument(path: String) -> Bool {
  616. let tabCount = self.km_browser?.tabCount() ?? 0
  617. if tabCount > 1{
  618. // if !IAPProductsManager.default().isAvailableAllFunction() {
  619. // let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  620. // if preferenceNoteShow {
  621. // menuItemAction_newTagPageToNewWindow("")
  622. // } else {
  623. // if !KMDataManager.default.isTabbingWin{
  624. // KMDataManager.default.isTabbingWin = true
  625. // let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  626. // tabbingWin.selectCallBack = {[weak self] continueOrNot in
  627. // KMDataManager.default.isTabbingWin = false
  628. // if continueOrNot {
  629. // self?.reopenDocumentForNewWindow(savePath: path)
  630. // } else {
  631. //
  632. // }
  633. // }
  634. // self.km_beginSheet(windowC: tabbingWin)
  635. // }
  636. // }
  637. // return false
  638. // }else {
  639. if KMPreference.shared.openDocumentType == .newWindow {
  640. self.reopenDocumentForNewWindow(savePath: path)
  641. return false
  642. }
  643. // }
  644. }
  645. return true
  646. }
  647. func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  648. if (self.canResponseDocumentAction() == false) {
  649. return
  650. }
  651. self.openNewWindow(sender)
  652. }
  653. func reopenDocumentForNewWindow(savePath: String) {
  654. let browser = KMBrowser.init() as KMBrowser
  655. browser.windowController = KMBrowserWindowController.init(browser: browser)
  656. browser.addHomeTabContents()
  657. browser.windowController.showWindow(self)
  658. self.savePdf(savePath)
  659. }
  660. func savePdf(_ filePath: String) -> Void {
  661. let docVc = KMDocumentController.shared
  662. docVc.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  663. if error != nil {
  664. NSApp.presentError(error!)
  665. } else {
  666. if document is KMMainDocument {
  667. let newDocument = document
  668. (newDocument as! KMMainDocument).isNewCreated = true
  669. }
  670. }
  671. }
  672. }
  673. }