// // KMNHomeViewController.swift // PDF Reader Pro // // Created by Niehaoyu on 2024/10/8. // import Cocoa import KMComponentLibrary class KMNHomeViewController: NSViewController { @IBOutlet var leftContendBox: NSBox! @IBOutlet var homeOpenView: KMHomeOpenView! @IBOutlet var homeRecommondView: KMHomeRecommondView! @IBOutlet var rightInfoView: KMHomeRightView! @IBOutlet var homeDragView: KMHomeDragView! var demoVC: WCCompWindowController = WCCompWindowController(windowNibName: "WCCompWindowController") override func viewDidLoad() { super.viewDidLoad() // Do view setup here. self.configLeftContendView() self.configRightContendView() self.initAdvertisementData() homeDragView.delegate = self } override func viewDidAppear() { super.viewDidAppear() rightInfoView.resetScrollerStyle() rightInfoView.reloadData() } func configLeftContendView() { leftContendBox.fillColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle") homeOpenView.delegate = self self.homeRecommondView.reloadData() } func configRightContendView() { rightInfoView.delegate = self rightInfoView.reloadData() } func initAdvertisementData() { KMAdvertisementManager.manager.fetchDataWithResponseObject { [weak self] data, responseObject, error in KMPrint("获取广告数据成功") if data != nil { let content = data!.recommondContent let item = content?.recommondContentPDFPro var infos: [KMAdvertisementItemInfo] = [] for info in item?.content ?? [] { if info.version == "recommondPDF-PDFtoOfficePack" { if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false { infos.append(info) } } else { infos.append(info) } } item?.content = infos if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 { if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] { let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary let array: [[String: Any]] = infoDict["content"] as! [[String : Any]] let arrM = NSMutableArray.init() for dict in array { let adsInfo = KMAdsInfo.init() let mutableDictionary = NSMutableDictionary(dictionary: dict) adsInfo.infoDict = mutableDictionary arrM.add(adsInfo) } KMAdsInfoManager.shareInstance.adsInfoArrM = arrM } if let couponInfo = KMAdvertisementManager.manager.infoDict["couponContent"] { let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["couponContent"] as! NSDictionary let array: [[String: Any]] = infoDict["content"] as! [[String : Any]] if array.isEmpty == false { let dict = array[0] let adsInfo = KMCouponInfo.init() let mutableDictionary = NSMutableDictionary(dictionary: dict) adsInfo.infoDict = mutableDictionary KMAdsInfoManager.shareInstance.couponInfo = adsInfo } } } } DispatchQueue.main.async { self?.homeRecommondView.reloadData() } } } @IBAction func showDemo(_ sender: Any) { demoVC.window?.center() demoVC.showWindow(nil) } } //MARK: - KMHomeOpenViewDelegate extension KMNHomeViewController: KMHomeOpenViewDelegate { func homeOpenViewDidChooseFileURLs(_ view: KMHomeOpenView?, _ urls: [URL]) { if let url = urls.first { } } } //MARK: - KMHomeRightViewDelegate extension KMNHomeViewController: KMHomeRightViewDelegate { //点击管理快捷工具按钮 func homeRightViewDidManageQuickTools(_ view: KMHomeRightView) { let quickToolWindowController: KMNQuickToolWindowController = KMNQuickToolWindowController.init(windowNibName: "KMNQuickToolWindowController") quickToolWindowController.own_beginSheetModal(for: self.view.window) { string in } } //点击快捷工具列表中的某一项 func homeRightViewDidQuickToolsItemClicked(_ view: KMHomeRightView, _ toolType: HomeQuickToolType) { print("HomeQuickToolType = %d", toolType.rawValue) } //最近文件列表删除更新结束后回调 func homeRightViewDidRecentFilesUpdated(_ view: KMHomeRightView) { } //选择打开文件 func homeRightViewDidChooseFileToOpen(_ view: KMHomeRightView, _ fileURL: URL) { } } //MARK: - KMNQuickToolWindowDelegate extension KMNHomeViewController: KMNQuickToolWindowDelegate { func quickToolWindowControllerUpdate() { // KMNHomeQuickToolManager.defaultManager.quickToolsItemMutableArray } } //MARK: - KMHomeDragViewDelegate extension KMNHomeViewController: KMHomeDragViewDelegate { func homeDragView(_ viewController: KMHomeDragView, filePath: URL) { self.openFile(withFilePath: filePath) } } //MARK: - Open Files extension KMNHomeViewController { func openFile(withFilePath path: URL) -> Void { let type = path.pathExtension.lowercased() if (type == "pdf") { self.openHistoryFilePath(url: path) } else if (type == "jpg") || (type == "cur") || (type == "bmp") || (type == "jpeg") || (type == "gif") || (type == "png") || (type == "tiff") || (type == "tif") || (type == "ico") || (type == "icns") || (type == "tga") || (type == "psd") || (type == "eps") || (type == "hdr") || (type == "jp2") || (type == "jpc") || (type == "pict") || (type == "sgi") || (type == "heic") { openImageFile(url: path) } else if (type == "doc") || (type == "docx") || (type == "xls") || (type == "xlsx") || (type == "ppt") || (type == "pptx") || (type == "pptx") { let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String) openOfficeFile(url: path) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { self.rightInfoView.reloadData() } } func openHistoryFilePath(url: URL) -> Void { if !url.path.isPDFValid() { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "") alert.beginSheetModal(for: view.window!) { [weak self] result in self?.rightInfoView.reloadData() } return } if url.pathExtension.lowercased() == "pdf" { let pdfDoc = CPDFDocument.init(url: url) if pdfDoc != nil { let document = NSDocumentController.shared.document(for: url) var alreadyOpen = false for openDocument in NSDocumentController.shared.documents { if document == openDocument { alreadyOpen = true } } if !alreadyOpen { let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController if controll?.browser?.tabCount() ?? 0 > 1{ if !IAPProductsManager.default().isAvailableAllFunction() { showLimitWindowAlert(url: url) return }else { } } } KMMainDocument().tryToUnlockDocument(pdfDoc!) var selectDocument: KMMainDocument? = nil if ((document?.isKind(of: KMMainDocument.self)) != nil) { selectDocument = (document as! KMMainDocument) } if selectDocument != nil { if selectDocument?.browser != nil { let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument) ?? 0 selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex), userGesture: true) let isVisible: Bool = selectDocument?.browser.window.isVisible ?? false let isMiniaturized: Bool = selectDocument?.browser.window.isMiniaturized ?? false if isVisible { selectDocument?.browser.window.orderFront(nil) } else if isMiniaturized { selectDocument?.browser.window.orderFront(nil) } } } else { NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in } } } else { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "") alert.beginSheetModal(for: view.window!) { [weak self] result in self?.rightInfoView.reloadData() } } } else { NSWorkspace.shared.open(url) } } func openImageFile(url: URL) -> Void { var filePath = url.path let fileName: NSString = url.lastPathComponent as NSString let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String).deletingLastPathComponent let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf") if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) { try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil) } if (!FileManager.default.fileExists(atPath: path as String)) { FileManager.default.createFile(atPath: path as String, contents: nil) } let document = CPDFDocument.init() var success = false if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" || NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" { let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg") if (!FileManager.default.fileExists(atPath: jpgPath as String)) { FileManager.default.createFile(atPath: jpgPath as String, contents: nil) } // 加载 PNG 图像 guard let pngImage = NSImage(contentsOfFile: filePath) else { KMPrint("Failed to load PNG image") return } // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中 let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!) guard let bitmap = bitmap else { return } let rect = NSRect(origin: .zero, size: bitmap.size) bitmap.draw(in: rect) // 将 PNG 图像数据转换为 JPG 图像数据 guard let jpgData = bitmap.representation(using: .jpeg, properties: [:]) else { KMPrint("Failed to convert PNG to JPG") return } // 保存 JPG 图像数据到文件 let fileURL = URL(fileURLWithPath: jpgPath) do { try jpgData.write(to: fileURL) filePath = fileURL.path KMPrint("JPG image saved successfully") } catch { KMPrint("Failed to save JPG image: \(error.localizedDescription)") } } let image = NSImage(contentsOfFile: filePath) let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount) if insertPageSuccess != nil { //信号量控制异步 let semaphore = DispatchSemaphore(value: 0) DispatchQueue.global().async { success = ((document?.write(toFile: path)) != nil) semaphore.signal() } semaphore.wait() } else { } if success { NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, isOpened, error in if error != nil { NSApp.presentError(error!) } else { if FileManager.default.fileExists(atPath: filePath) { try? FileManager.default.removeItem(atPath: filePath) } if document is KMMainDocument { let newDocument = document (newDocument as! KMMainDocument).isNewCreated = true } } } } } func openOfficeFile(url: URL) -> Void { let filePath = url.path let folderPath = "convertToPDF.pdf" let savePath: String? = folderPath.kUrlToPDFFolderPath() as String if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) { try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil) } if (!FileManager.default.fileExists(atPath: savePath! as String)) { FileManager.default.createFile(atPath: savePath! as String, contents: nil) } if savePath == nil { return } KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) { if FileManager.default.fileExists(atPath: savePath!) { try?FileManager.default.removeItem(atPath: savePath!) } let alert = NSAlert.init() alert.alertStyle = .critical var infoString = "" if errorDic != nil { for key in (errorDic! as Dictionary).keys { infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg) } } alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "") alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "") alert.addButton(withTitle: NSLocalizedString("OK", comment: "")) alert.runModal() return } NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { _, _, _ in } } } func showLimitWindowAlert(url: URL?) { if !KMDataManager.default.isTabbingWin{ KMDataManager.default.isTabbingWin = true let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController() tabbingWin.selectCallBack = {[weak self] continueOrNot in KMDataManager.default.isTabbingWin = false if continueOrNot { self?.reopenDocument(forPaths: url) } else { } } self.km_beginSheet(windowC: tabbingWin) } } func reopenDocument(forPaths path: URL?) -> Void { if path == nil { let browser = KMBrowser.init() as KMBrowser browser.windowController = KMBrowserWindowController.init(browser: browser) browser.addHomeTabContents() browser.windowController.showWindow(self) }else { let browser = KMBrowser.init() as KMBrowser browser.windowController = KMBrowserWindowController.init(browser: browser) browser.addHomeTabContents() browser.windowController.showWindow(self) NSDocumentController.shared.km_safe_openDocument(withContentsOf: path!, display: true) { doc, open, err in } } } func fetchUniquePath(_ originalPath: String) -> String { var path = originalPath let dManager = FileManager.default if !dManager.fileExists(atPath: path) { if path.extension.count < 1 { path = path.stringByAppendingPathExtension("pdf") } return path } else { let originalFullFileName = path.lastPathComponent let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent let originalExtension = path.extension let startIndex: Int = 0 let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1 let fileLocatePath = originalPath.substring(to: endIndex) var i = 1 while (1 != 0) { var newName = String(format: "%@%ld", originalFileName, i) newName = String(format: "%@%@", newName, originalExtension) let newPath = fileLocatePath.stringByAppendingPathComponent(newName) if !dManager.fileExists(atPath: newPath) { return newPath } else { i+=1 continue } } } } func fetchDifferentFilePath(filePath: String) -> String { var resultFilePath = filePath var index: Int = 0 while (FileManager.default.fileExists(atPath: resultFilePath)) { index += 1 let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")" resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)! } return resultFilePath; } }