// // KMHomeViewController.swift // PDF Reader Pro // // Created by wanjun on 2022/10/13. // import Cocoa @objc enum KMHomeToolState : Int { case OpenPDF = 0 case CreatePDF case Home case PDFTools case FavoriteDocuments case CloudDocuments } @objc enum KMAIHomeToolState : Int { case Home = 0 case AITranslation case AIRewriting case AIErrorCorrection } @objcMembers class KMHomeViewController: NSViewController { @IBOutlet weak var leftBox: NSBox! @IBOutlet weak var rightBox: NSBox! @IBOutlet weak var homeSplitView: NSSplitView! @IBOutlet weak var homeRightScrollViewView: NSScrollView! @IBOutlet weak var rightTopBox: NSBox! @IBOutlet weak var rightBottomBox: NSBox! @IBOutlet weak var rightFullBox: NSBox! @IBOutlet weak var rightTopBoxHeightConstraint: NSLayoutConstraint! @IBOutlet var fastToolViewController: KMHomeFastToolViewController! @IBOutlet var historyFileViewController: KMHomeHistoryFileViewController! @IBOutlet var pdfToolsViewController: KMPDFToolsViewController! @IBOutlet var cloudDocumentsViewController: KMCloudDocumentsViewController! @IBOutlet weak var dragView: KMHomeDragView! // AI 临时UI @IBOutlet weak var aiHomeBox: KMBox! @IBOutlet weak var aiHomeImageView: NSImageView! @IBOutlet weak var aiHomeLabel: NSTextField! @IBOutlet weak var aiTranslationBox: KMBox! @IBOutlet weak var aiTranslationImageView: NSImageView! @IBOutlet weak var aiTranslationLabel: NSTextField! @IBOutlet weak var aiRewritingBox: KMBox! @IBOutlet weak var aiRewritingImageView: NSImageView! @IBOutlet weak var aiRewritingLabel: NSTextField! @IBOutlet weak var aiErrorCorrectionBox: KMBox! @IBOutlet weak var aiErrorCorrectionImageView: NSImageView! @IBOutlet weak var aiErrorCorrectionLabel: NSTextField! @IBOutlet var aiOpenPDFFilesViewController: KMAIOpenPDFFilesVC! @IBOutlet var aiTranslationViewController: KMAITranslationVC! @IBOutlet var aiRewritingViewController: KMAIRewritingVC! @IBOutlet weak var creatPDFView: KMCreatPDFView! //HomeContentView @IBOutlet weak var homeContentView: KMHomeContentView! //广告 互推 @IBOutlet weak var advertisementTableView: KMAdvertisementTableView! @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var advertisementShowView: KMAdvertisementShowView! //合并 var mergeWindowController: KMMergeWindowController? var aiHomeState: KMAIHomeToolState = .Home let ScrollerViewWidget: CGFloat = 15.0 var homeWindowController : MainWindowController! var isShowQuickTour: Bool = false weak var myDocument: NSDocument? var currentWindowController: NSWindowController? var homeState: KMHomeToolState = .Home var urlToPDFWindowController: KMURLToPDFWindowController? var openPDFButtonVC: KMDesignButton? var createPDFButtonVC: KMDesignButton? var createPDFImage: KMDesignButton? var createPDFAddButtonVC: KMDesignButton? var homeButtonVC: KMTextImageButtonVC? var pdfToolsButtonVC: KMTextImageButtonVC? var cloudDocumentsButtonVC: KMTextImageButtonVC? var pdfSeriesButtonVC: KMTextImageButtonVC? var pdfOthersButtonVC: KMTextImageButtonVC? var popover: NSPopover? var deviceBrowserWC: KMDeviceBrowserWindowController? var progressController: SKProgressController? var timer: Timer? var timerCounter = 0.0 //AI相关 //试用相关 var didTrialExpiredLoad: Bool = false var repeatTrialAlertLoad: Bool = false var guideWindowVC: KMFunctionGuideWindowController! var showCoupon: Bool = true var couponDueWindowVC: KMCouponDueWindowController! @IBOutlet weak var rightBottonHeight: NSLayoutConstraint! var currentController: NSWindowController? deinit { NotificationCenter.default.removeObserver(self) } override func viewWillAppear() { super.viewWillAppear() if !KMLightMemberManager.manager.isLogin() { KMLightMemberManager.manager.canShowAdvancedView = true } self.homeContentView.reloadData() #if VERSION_DMG let kDMGFirstInstallKey = "DMGFirstInstallKey" if KMDataManager.ud_object(forKey: kDMGFirstInstallKey) == nil { KMDataManager.ud_set("Show", forKey: kDMGFirstInstallKey) KMTools.openURL(urlString: "http://www.pdfreaderpro.com/thank-you-for-installation") } #else // [self loadAIInfo]; #endif } override func viewWillDisappear() { super.viewWillDisappear() // self.homeContentView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. openPDFButtonVC = KMDesignButton.init(withType: .Text) createPDFButtonVC = KMDesignButton.init(withType: .Text) createPDFImage = KMDesignButton.init(withType: .Image) createPDFAddButtonVC = KMDesignButton.init(withType: .Image) homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil) pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil) cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil) pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil) pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil) self.homeSplitView.setPosition(270.0, ofDividerAt: 0) self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA") self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA") NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in self.otherMouseDown(with: aEvent) return aEvent } self.initNetworkingData() // self.initLocalization() // self.initializeUI() self.initializeUI_DMG() self.setup() // refreshUI() self.updateUI() self.changeEffectiveAppearance() NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil) // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel()) // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil) // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil) // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil) #if VERSION_DMG NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil) #endif NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil) self.loadFunctionGuide() } override func viewDidAppear() { super.viewDidAppear() refreshScrollView() } override func viewDidLayout() { super.viewDidLayout() refreshScrollView() // self.loadAITipIconGuide() } func initNetworkingData() { 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 self?.advertisementTableView.inputData = content self?.advertisementTableView.didSelect = { view, item in let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL) if string.count != 0 { NSWorkspace.shared.open(URL.init(string: string)!) } } self?.advertisementShowView.inputData = data!.advertisement self?.advertisementShowView.didSelect = { view, item in let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL) if string.count != 0 { NSWorkspace.shared.open(URL.init(string: string)!) } guard let firebaseInfo = item.firebase else { return } KMAdvertisementModelTransition.sendFireBaseEvent(firebase: firebaseInfo) } 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 } } self?.checkTrialEndCouponInfo() } } } } func setup() { //creatPDF self.creatPDFView.openPDFAction = { [unowned self] view, sender in self.openPDFAction(sender) } self.creatPDFView.creatPDFAction = { [unowned self] view, sender in self.creatPDFAction(sender) } //history self.homeContentView.historyDidSelect = { [unowned self] view, item in self.openHistoryFilePath(url: item.url!) } self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in self.historyFile(deleteDocuments: [ item.url!]) } self.homeContentView.historyShowPathAction = { [unowned self] view, item in if FileManager.default.fileExists(atPath: item.url!.path) { NSWorkspace.shared.activateFileViewerSelecting([item.url!]) } } self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in let alert = NSAlert() alert.alertStyle = .critical alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: "")) alert.addButton(withTitle: NSLocalizedString("Delete", comment: "")) alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "")) alert.beginSheetModal(for: self.view.window!) { response in if response == .alertFirstButtonReturn { let urls: Array = NSDocumentController.shared.recentDocumentURLs self.historyFileDeleteAction(urls) } } } //quciktools self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in self.fastToolItemAction(item.type!) } self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in KMBatchQuickActionManager.defaultManager.actionType = .add self.fastToolItemAction(item.type!) } self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in KMBatchQuickActionManager.defaultManager.actionType = .remove self.fastToolItemAction(item.type!) } if IAPProductsManager.default().isAvailableAllFunction() { self.advertisementShowView.isHidden = true } else { self.advertisementShowView.isHidden = false } NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil) } // MARK: Init func initializeUI() { rightTopBox.fillColor = .white rightBottomBox.fillColor = .white rightFullBox.fillColor = .white self.refreshRightBoxUI(.Home) fastToolViewController.delete = self historyFileViewController.delete = self pdfToolsViewController.delete = self dragView.delete = self } func initLocalization() { // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "") homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "") pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "") cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "") openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "") // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "") createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "") // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "") pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "") pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "") } // MARK: Action func initializeUI_DMG() -> Void { rightTopBox.fillColor = .white rightBottomBox.fillColor = .white rightFullBox.fillColor = .white self.aiHomeBox.fillColor = .clear self.aiHomeBox.cornerRadius = 8.0 self.aiHomeImageView.image = NSImage(named: "icon_home") self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "") self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629") self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in if aiHomeState != .Home { if mouseEntered { self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0") } else { self.aiHomeBox.fillColor = .clear } } } self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in if aiHomeState != .Home { if downEntered { self.aiHomeState = .Home self.refreshAIUI() } } } self.aiTranslationBox.fillColor = .clear self.aiTranslationBox.cornerRadius = 8.0 self.aiTranslationImageView.image = NSImage(named: "ic_function_other") self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "") self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629") self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in if aiHomeState != .AITranslation { if mouseEntered { self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0") } else { self.aiTranslationBox.fillColor = .clear } } } self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in if aiHomeState != .AITranslation { if downEntered { self.aiHomeState = .AITranslation self.trackEvent_ai(eventName: "AI Translation") self.refreshAIUI() } } } self.aiRewritingBox.fillColor = .clear self.aiRewritingBox.cornerRadius = 8.0 self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting") self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "") self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629") self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in if aiHomeState != .AIRewriting { if mouseEntered { self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0") } else { self.aiRewritingBox.fillColor = .clear } } } self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in if aiHomeState != .AIRewriting { if downEntered { self.aiHomeState = .AIRewriting self.trackEvent_ai(eventName: "AI Rewriting") self.refreshAIUI() } } } self.aiErrorCorrectionBox.fillColor = .clear self.aiErrorCorrectionBox.cornerRadius = 8.0 self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection") self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "") self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629") self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in if aiHomeState != .AIErrorCorrection { if mouseEntered { self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0") } else { self.aiErrorCorrectionBox.fillColor = .clear } } } self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in if aiHomeState != .AIErrorCorrection { if downEntered { self.aiHomeState = .AIErrorCorrection self.trackEvent_ai(eventName: "AI Correction") self.refreshAIUI() } } } self.refreshAIUI() historyFileViewController.delete = self dragView.delete = self } func updateUI() { self.leftBox.fillColor = KMAppearance.Layout.l0Color() // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color()) } @objc func changeEffectiveAppearance() { let isDarkModel = KMAdvertisementConfig.isDarkModel() if isDarkModel { self.view.appearance = NSAppearance(named: .darkAqua) } else { self.view.appearance = NSAppearance(named: .aqua) } self.updateUI() self.advertisementTableView.reloadData() } // MARK: Public Methods func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void { DispatchQueue.global(qos: .`default`).async { var isSuccessfully = false if pdf.isEncrypted { let dic = [ CPDFDocumentWriteOption.userPasswordOption : password, CPDFDocumentWriteOption.ownerPasswordOption : password ] isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic) } else { isSuccessfully = pdf.write(to: pdf.documentURL) } if !isSuccessfully { if let data = pdf.dataRepresentation() { isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true) } } DispatchQueue.main.sync { if isSuccessfully { let workspace = NSWorkspace.shared let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "") workspace.activateFileViewerSelecting([url]) } else { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "") alert.runModal() } } } } // MARK: Private Methods func refreshUI() -> Void { homeButtonVC?.updateUI() pdfToolsButtonVC?.updateUI() cloudDocumentsButtonVC?.updateUI() } func refreshAIUI() -> Void { self.aiHomeBox.fillColor = .clear self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiTranslationBox.fillColor = .clear self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiRewritingBox.fillColor = .clear self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0) self.aiErrorCorrectionBox.fillColor = .clear self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0) rightFullBox.isHidden = true rightTopBox.isHidden = true rightBottomBox.isHidden = true switch self.aiHomeState { case .Home: self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1) self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0) self.rightTopBox.isHidden = false self.rightBottomBox.isHidden = false self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view self.rightBottomBox.contentView = self.historyFileViewController.view self.rightFullBox.contentView = nil self.rightTopBoxHeightConstraint.constant = 388.0 self.dragView.isHidden = false break case .AITranslation: self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1) self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629") self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0) self.rightFullBox.isHidden = false self.rightTopBox.contentView = nil self.rightBottomBox.contentView = nil self.rightFullBox.contentView = self.aiTranslationViewController.view self.dragView.isHidden = false break case .AIRewriting: self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1) self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629") self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0) self.rightFullBox.isHidden = false self.rightTopBox.contentView = nil self.rightBottomBox.contentView = nil self.rightFullBox.contentView = self.aiRewritingViewController.view // self.aiRewritingViewController.state = .AIRewriting self.aiRewritingViewController.initLocalization() self.aiRewritingViewController.acquisition_uiState() self.dragView.isHidden = true break case .AIErrorCorrection: self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1) self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629") self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0) self.rightFullBox.isHidden = false self.rightTopBox.contentView = nil self.rightBottomBox.contentView = nil self.rightFullBox.contentView = self.aiRewritingViewController.view // self.aiRewritingViewController.state = .AIErrorCorrection self.aiRewritingViewController.initLocalization() self.aiRewritingViewController.acquisition_uiState() self.dragView.isHidden = true break default: break } } 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; } func showProgressWindow() { let progress = SKProgressController() progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B") progress.window?.contentView?.wantsLayer = true progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor progress.progressField.textColor = NSColor.white progress.message = NSLocalizedString("Translating...", comment: "") progress.closeBlock = { [weak self] in } self.progressController = progress self.view.window?.beginSheet(progress.window!) } func hiddenProgressWindow() { DispatchQueue.main.async { self.progressController?.doubleValue = 100.0 } self.stopTimer() if (self.progressController != nil) { self.view.window?.endSheet((self.progressController?.window)!) self.progressController = nil } } func isFileGreaterThan10MB(atPath filePath: String) -> Bool { let fileManager = FileManager.default do { let fileAttributes = try fileManager.attributesOfItem(atPath: filePath) if let fileSize = fileAttributes[.size] as? UInt64 { let megabyteSize = fileSize / (1024 * 1024) return megabyteSize >= 10 } } catch { KMPrint("Error: \(error)") } return false } func isPDFPageCountExceedsLimit(filePath: String) -> Bool { let url = URL(fileURLWithPath: filePath) guard let document = PDFDocument(url: url) else { return false } let pageCount = document.pageCount return pageCount > 30 } @objc func timerTick() { timerCounter += 1.0 self.progressController?.increment(by: 1.0) if timerCounter >= 95 { stopTimer() } } func stopTimer() { timer?.invalidate() timer = nil } // MARK: Common methods func workSpaceOpenUrl(_ url: NSString) { let httpUrl: NSURL = NSURL.init(string: url as String)! let tWorkSpace: NSWorkspace = NSWorkspace.shared if !tWorkSpace.open(httpUrl as URL) { tWorkSpace.open(httpUrl as URL) } } } //MARK: Open Creat PDF extension KMHomeViewController: NSPopoverDelegate { } extension KMHomeViewController { func openPDFAction(_ sender: KMBox) { if needShowTabbingHintWindow() { showTabbingHintWindow() return } let openPanel = NSOpenPanel() openPanel.allowedFileTypes = ["pdf", "PDF"] openPanel.allowsMultipleSelection = false openPanel.beginSheetModal(for: self.view.window!) { (result) in if result == NSApplication.ModalResponse.OK { let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{ self.reopenDocument(forPaths: openPanel.url!) }else { NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in } } } } } func needShowTabbingHintWindow() -> Bool { let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() { return true } return false } func showTabbingHintWindow(){ 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: nil) } else { } } self.km_beginSheet(windowC: tabbingWin) } } func creatPDFAction(_ sender: KMBox) { let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""), NSLocalizedString("New From Images", comment: ""), NSLocalizedString("New From Web Page", comment: ""), NSLocalizedString("Import From Camera", comment: ""), NSLocalizedString("Import From Scanner", comment: "")] let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr) vc.background = KMAppearance.Layout.bgColor() vc.textColor = KMAppearance.Layout.h0Color() vc.enterFillColor = KMAppearance.Interactive.s0Color() let createFilePopover: NSPopover = NSPopover.init() createFilePopover.contentViewController = vc createFilePopover.delegate = self createFilePopover.animates = true createFilePopover.behavior = .semitransient createFilePopover.setValue(true, forKey: "shouldHideAnchor") createFilePopover.show(relativeTo: CGRect(x: sender.bounds.origin.x, y: 10, width: sender.bounds.size.width, height: sender.bounds.size.height), of: sender, preferredEdge: .minY) vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in if count == NSLocalizedString("New Blank Page", comment: "") { self.openBlankPage() } else if count == NSLocalizedString("Import From Camera", comment: "") { self.importFromCamera() } else if count == NSLocalizedString("Import From Scanner", comment: "") { self.importFromScanner() } else if count == NSLocalizedString("New From Web Page", comment: "") { self.importFromWebPage() } else if count == NSLocalizedString("New From Images", comment: "") { self.newFromImages() } createFilePopover.close() } } func openBlankPage() { // let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString // let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String) // let filePath = savePath.deletingLastPathComponent // if FileManager.default.fileExists(atPath: filePath) == false { // try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false) // } // // let pdfDocument = CPDFDocument() // pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0) // pdfDocument?.write(to: URL(fileURLWithPath: savePath)) // let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController // if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{ // self.reopenDocument(forPaths: URL(fileURLWithPath: savePath)) // }else { // NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in // if error != nil { // NSApp.presentError(error!) // } else { // if document is KMMainDocument { // let newDocument = document // (newDocument as! KMMainDocument).isNewCreated = true // } // } // // self.homeContentView?.reloadData() // } // } NSApplication.newBlankDocument() } func importFromWebPage() { self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController")) self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in if FileManager.default.fileExists(atPath: filePath) { NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in if error != nil { NSApp.presentError(error!) } else { if document is KMMainDocument { (document as! KMMainDocument).isNewCreated = true } } // self.homeContentView.reloadData() } } }) } func importFromScanner() { let vc = KMDeviceBrowserWindowController.shared vc.type = .scanner vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in self?.openFile(withFilePath: url as URL) } vc.showWindow(NSApp.mainWindow) } func importFromCamera() { let vc = KMDeviceBrowserWindowController.shared vc.type = .camera vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in self?.openFile(withFilePath: url as URL) } vc.showWindow(NSApp.mainWindow) } func newFromImages() { fastTool_ImageToPDF() // let openPanel = NSOpenPanel() // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes() // if IAPProductsManager.defaultManager().isAvailableAllFunction { // openPanel.allowsMultipleSelection = true // } else { // openPanel.allowsMultipleSelection = false // } // openPanel.message = NSLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on the keyboard and click on the target files one by one.", comment: "") // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in // if result == .OK { // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { // debugPrint("缺少图片转PDF") // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController") // var arr: [KMBatchOperateFile] = [] // for url in openPanel.urls { // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF) // arr.append(file) // } // // if #available(macOS 10.13, *) { // baseWindowController.window?.makeKeyAndOrderFront(nil) // } else { // baseWindowController.showWindow(nil) // } // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr) // if #available(macOS 10.13, *) { // baseWindowController.release() // } // } // } // } } //MARK: Purchase @objc func purchaseStateUpdateNoti() { if IAPProductsManager.default().isAvailableAllFunction() { self.advertisementShowView.isHidden = true let content = self.advertisementTableView.inputData 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 self.advertisementTableView.inputData = content } } //MARK: - AI func showAITypeChooseView() -> Void { let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC() windowVC.chooseCurFileHandle = {[unowned self] windowVC in if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false { let documentArray = NSDocumentController.shared.documents var didFileEdit: Bool = false var curDoc: KMMainDocument! for document in documentArray { if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath { didFileEdit = document.isDocumentEdited curDoc = document as! KMMainDocument break } } if didFileEdit { let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent) if FileManager.default.fileExists(atPath: tempFileURL.path) { do { try FileManager.default.removeItem(at: tempFileURL) } catch { } } if curDoc != nil { curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path) } } windowVC.window?.becomeMain() } } if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true { } else { windowVC.window?.center() windowVC.didSetOriginFrame = true } windowVC.eventLabel = "AITools_Onboard" windowVC.showWindow(nil) } func loadAITipIconGuide() { if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) { let guideWC = KMGuideInfoWindowController.currentWC() guideWC.type = .aiTipIconInfo guideWC.window?.collectionBehavior = [.canJoinAllSpaces] guideWC.finishHandle = { [weak self] windowVC, type in } if self.view.window != nil { var rect = self.view.window?.frame rect!.size.height -= 20 guideWC.window?.setFrame(rect!, display: true) guideWC.window?.minSize = rect!.size guideWC.window?.maxSize = rect!.size self.view.window?.addChildWindow(guideWC.window!, ordered: .above) guideWC.show() } } } //MARK: - 引导 func loadFunctionGuide() -> Void { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { self.loadNewUserGuide() } } // MARK: - what's New func loadNewUserGuide() -> Void { if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) { guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController") guideWindowVC.type = .functionMulti guideWindowVC.showWindow(nil) guideWindowVC.window?.orderFront(nil) KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide) } } func checkRepeatTrialExpiredController() -> Void { //试用过期提示比较表弹窗 if didTrialExpiredLoad == true { return } didTrialExpiredLoad = true let singleTon = KMPurchaseCompareDMGWindowController.init() singleTon.showWindow(nil) if singleTon.className == KMPurchaseCompareDMGWindowController.className() { singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1)) } } func checkRepeatTrialAlertController() -> Void { //允许二次试用时弹出二次试用引导弹窗 if repeatTrialAlertLoad == true { return } repeatTrialAlertLoad = true let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide) vc?.showWindow(nil) } //MARK: 试用到期优惠券弹窗 func checkTrialEndCouponInfo() { KMRequestServerManager.manager.getDeviceRetensionCoupon {[weak self] success, result in if success == true { if result != nil { guard let dataDict = result!["data"] as? NSDictionary else { return } // if dataDict!["pop_up"] as? Bool == true { let discount = dataDict["discount"] as? Int let coupon_code = dataDict["coupon_code"] as? String let end_up_at = dataDict["end_up_at"] as? String let pop_up = dataDict["pop_up"] as? Bool if pop_up == true { if let versionKey = KMAdsInfoManager.shareInstance.couponInfo?.versionKey { if KMAdsInfoManager.shareInstance.couponInfo?.show == true { if (UserDefaults.standard.object(forKey: versionKey) != nil) { } else { UserDefaults.standard.set("Show", forKey: versionKey) UserDefaults.standard.synchronize() self?.showCouponInfoWindow(discount: discount, couponCode: coupon_code, endUpAt: end_up_at) } } } } } } else { #if VERSION_DMG if KMVerificationWindowController.allowsShowExpired() { self?.checkRepeatTrialExpiredController() } else if KMVerificationWindowController.allowRepeatTrialAlertShow() { self?.checkRepeatTrialAlertController() } #endif } } } func showCouponInfoWindow(discount: Int?, couponCode: String?, endUpAt: String?) { if self.couponDueWindowVC == nil { self.couponDueWindowVC = KMCouponDueWindowController(windowNibName: "KMCouponDueWindowController") } self.couponDueWindowVC.disCount = discount ?? 20 self.couponDueWindowVC.couponCode = couponCode ?? "" self.couponDueWindowVC.endUpAt = endUpAt ?? "" self.couponDueWindowVC.showWindow(nil) self.couponDueWindowVC.reloadData() } // MARK: - Noti Actions func deviceVerifyFinishNotification(_ sender: Notification) { #if VERSION_DMG #endif } @objc func aiTipIconViewShowStateChangeNoti() { } }