// // AppDelegate.swift // Cisdem PDFMaster // // Created by Niehaoyu on 2022/9/23. // import Cocoa import UserNotifications @main class AppDelegate: NSObject, NSApplicationDelegate, iRateDelegate{ var rateWindowVC: KMRateWindowController! func applicationWillFinishLaunching(_ notification: Notification) { CPDFConvertKit.setLicenseKey("pwVjLcp4mqoyeB68e8hB4BCy1zhfR2RqFvw21eWf218waYJGiYoR2mm73mvBP0ctmpm7EReGzsWf3bmMEubpqPoJ6iVcx0hXfwtXT00SWh06HY0BJmZsQjebduOWmtjcwa/CGNKbXj+svb9Rn7rw7JqWRx/EOkzo9MMa7EPGWlwG4U5XphLLZJ+Z3FxKrEEsVt7vwAGPdNcNlJZeSnpGl6ilpwXeS8BiSvZSmWz8dpvoZsb57zHUvi3LAAtZpjSeXZD0A+GSs6jNDCSnILJl+C6zp/i4u8xxdH3Gw954GKkp/Q4qtNWTqlzR0rBzh+CTPSbCeDA/VgE2FLCXVAf/RGu0lH1oY17eVN2TRW5amzpVluIgfBYVaYkjt6T5JApf2W8G9zo4Eul5t/EnjYyQEERxob1ji6eXrknf03eZ1m/mFFcrOzq9/Ltqa8PbtYFfhFxgqpxulvUgzfTz4YWf8l7Zgj+iPhAprovkb/TDTucCJrrnDmMLRuMBf8WWqET2nkyPq2L4nW437NrmAOb+LfJf2nePHR5BmbAag9fpeCW5jQfOfu67I6r3O3SjSoV3N9UzCP3KvfOOVJSPslD9k3G9jXTrgx93Y4E9n7RYZcUo4zepltYWoplfONjTZWqeRoNxe9QHXGWMWBc/Ntne3x/a3ZkL84CZ8pvLNnr4BW02+HQbHqDvewW9B5uWL2gyvgt7IOcj0tNlSxXy6ggcZFNhVfyDa0XRQWQNON6lNB8Y7JZwccJY7iRTxaaGIghi") CPDFKit.verify(withKey: "xJPiZ17w3Ajomg/CzxCNqeyaLREGKaffkshdgpdB/q75AQGGecd69qZoQdajnWqw5UBu4WhB3kP75FN72SearnLFi/+AejuVqZbRj0QJq/7Nafia7c6mo+wVn2Vx25v96q9FkOiuqxWHFeDw9b/y31wjj7Nezp8Y8l+13e0kuzeEQ+pcsKQ4IGFvdUlGdwjHaiMl/jSUMq7kwvLAF3PU2HtuprqKRhxIlCuad0yK39EH4/u0BniTqBmJXziHi2iVu/pqtA9M/XkqOmJQN93ZYpTMFS7uuEMHZjWPTRTZwlcdcxYkYxIYvKDjp1Lyu0rux0AgDQMpVTu8lC/4+OAuoGu0lH1oY17eVN2TRW5amzpVluIgfBYVaYkjt6T5JApf2W8G9zo4Eul5t/EnjYyQEOxficyjBUvAWG6kCEHmjfU5/e/i8Unc6t8gZECSL24tn8B1XRyEZ7b33a/pIXQOQV7Zgj+iPhAprovkb/TDTucCJrrnDmMLRuMBf8WWqET2nkyPq2L4nW437NrmAOb+LbjGybUYYV+WNFNio9JbzmW5jQfOfu67I6r3O3SjSoV3N9UzCP3KvfOOVJSPslD9k2b3n5dAuRcBWESauhoiQon4P4qY1CDHbtB2RRUlY2QoUFrIA98TzqKs2rjolMvFknnky6b9UGeVlyoDXkNwOYUdZ5/3bRgnu1u9Y/IS7aylB5kDht8xLnlZc44WdwoQICBB+s3jKoshBxf0wGSTEenyRBslb8cexbgw1j1TMBDqjOrEKmnDg0rhLXi76xNpUg==") ComPDFUIConfig.initializeUIConfig() KMDesignToken.shared.parserExcel(withPath: "") } func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application //通知 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if granted { KMPrint("User authorized notifications") } else { KMPrint("User denied notifications") } } /**本地推送测试 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if granted { // 创建本地推送通知 let content = UNMutableNotificationContent() content.title = "Test Notification" content.body = "This is a test notification!" // 触发条件,例如延迟 5 秒触发 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) // 创建通知请求 let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger) // 添加通知请求到用户通知中心 UNUserNotificationCenter.current().add(request) { error in if let error = error { print("Error adding notification request: \(error)") } else { print("Local notification scheduled") } } } else { print("User denied notifications") } } **/ DispatchQueue.main.async { NSApplication.shared.registerForRemoteNotifications() } //Firebase RemoteConfig #if VERSION_FREE KMKdanRemoteConfig.remoteConfig.fetch { _status, error in } #endif let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? "" let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey) if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending { let sud = UserDefaults.standard if versionString.isEmpty == false { sud.set(versionString, forKey: SKLastVersionLaunchedKey) } // [sud setBool:NO forKey:@"kShowRecentGuideKey"]; // [sud removeObjectForKey:@"kToolbarTipIsShow"]; // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"]; // [sud removeObjectForKey:@"KMTabbingHintShowFlag"]; // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"]; sud.synchronize() } UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true]) let oemInstall = UserDefaults.standard.bool(forKey: "KMOEMRequestStateInstall") if !oemInstall { KMOEMRequestServerManager.defaultManager.oemRequest(state: .install, regCode: "") { wrapper in if wrapper.success { UserDefaults.standard.setValue(true, forKey: "KMOEMRequestStateInstall") } } } let oemUpdate = UserDefaults.standard.string(forKey: "KMOEMRequestStateUpdate") if oemUpdate != KMOEMRequestServerManager.defaultManager.version() { self.checkForUpdates1(NSMenuItem()) } NSApp.servicesProvider = self KMStatusBar.system() // MARK: 广告数据初始化 var appName: KMAdvertisementAppNameType = .PDFReaderProMac #if VERSION_FREE #if VERSION_DMG appName = .PDFReaderProMacDMG #else #endif #else appName = .PDFReaderProMacPro #endif KMAdvertisementManager.manager.initConfig(appName: appName, subscribeType: .unknow, platform: .Mac) // 测试模式,默认false KMAdvertisementManager.manager.debug = true NSApp.appearance = NSAppearance.current KMAnalytics.configure() //第一次开启app let info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount") var count = 0 if info != nil { count = info as? Int ?? 0 } count += 1 UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount") UserDefaults.standard.synchronize() self.initMainMenu() /// pro // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"]; DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj") reopenDocument(forPaths: []) KMPreference.shared.initDataForAppLaunch() self.initiRateData() let appleEventManager = NSAppleEventManager.shared() appleEventManager.setEventHandler(self, andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil) #if VERSION_DMG VerificationManager.default() #else self.initiVersionData() IAPProductsManager.default().initIAP() #endif //AI相关 AIInfoManager.default() NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil) for string in ["Ubuntu-Bold","Ubuntu-Medium"] { let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf") var error: Unmanaged? if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) { print("Failed to register font!") } else { print("Font registered successfully!") } } } func initiRateData() { iRate.sharedInstance().delegate = self #if VERSION_FREE iRate.sharedInstance().appStoreID = 919472673 #else iRate.sharedInstance().appStoreID = 825459243 #endif iRate.sharedInstance().onlyPromptIfLatestVersion = false iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true } //MARK: iRateDelegate func iRateUserDidDeclineToRateApp() { KMVerificationWindowController.verificationFeedback() } func iRateShouldPromptForRating() -> Bool { let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") if !notShow { UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey") UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self) } self.rateWindowVC = KMRateWindowController.init(windowNibName: "KMRateWindowController") self.rateWindowVC.closeBlock = { wc in } self.rateWindowVC.closeBlock = { wc in } self.rateWindowVC.showWindow(nil) return false } @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) { // 在这里处理收到的 URL Scheme KMPrint("Received URL Scheme: \(url.scheme ?? "")") KMPrint("Path: \(url.path)") if NSApp.mainWindow == nil { let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? "" launchApp(bundleIdentifier: bundleIdentifier) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { #if VERSION_DMG // 执行相应的操作 if url.scheme == "subscriptiondmgschemes" { if urlString.contains("open=expired") { KMPrint("刷新用户信息") if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil { _ = KMLoginWindowController.show(window: NSApp.mainWindow!) } else { if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() { _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!) } } } else if urlString.contains("open=success") { if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil { _ = KMLoginWindowController.show(window: NSApp.mainWindow!) } else { KMPurchaseManager.manager.restorePurchases { isSuccess, error in if isSuccess { } else { KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error) } } } } } #endif #if VERSION_FREE // 执行相应的操作 if url.scheme == "subscriptionSchemes" { //刷新用户信息 KMRequestServerManager.manager.getUserInfo { success, data, error, isLocal in } if url.path == "/open" { // 执行打开操作 } else if url.path == "/close" { // 执行关闭操作 } } #endif } } } func launchApp(bundleIdentifier: String) { let workspace = NSWorkspace.shared // Launch the application with the specified bundle identifier if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) { do { try workspace.launchApplication(at: appURL, options: .default, configuration: [:]) } catch { print("Error launching the application: \(error)") } } else { print("Application with bundle identifier '\(bundleIdentifier)' not found.") } } func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() print("Device token:", token) } func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) { } func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { if !flag { let browser: KMBrowser = KMBrowser.init() browser.windowController = KMBrowserWindowController.init(browser: browser) browser.addHomeTabContents() browser.windowController.showWindow(self) } return flag } @IBAction func closeDocument(_ sender: Any) { if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) { guard let windowControler = NSApp.mainWindow?.windowController else { return } windowControler.window?.performClose(nil) return } let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController if let data = windowControler.browser, data.tabCount() >= 2 { // 有两个以上的标签 if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应 return } } windowControler.browser.closeTab() } func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool { if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) { return false } let filepaths = KMPreferenceManager.shared.lastOpenFilepaths if (filepaths == nil || filepaths!.count == 0) { return false } DispatchQueue.main.async { for filepath in filepaths! { NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in } } } return false } func applicationWillTerminate(_ aNotification: Notification) { if (NSDocumentController.shared.documents.count > 0) { var filepaths: [String] = [] for document in NSDocumentController.shared.documents { // KMPrint(document.fileURL as Any) if (document.fileURL?.path != nil) { filepaths.append((document.fileURL?.path)!) } } KMPreferenceManager.shared.lastOpenFilepaths = filepaths } else { KMPreferenceManager.shared.lastOpenFilepaths = nil } } func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { return true } // MARK: private func reopenDocument(forPaths paths: [String]) -> Void { let browser = KMBrowser.init() as KMBrowser browser.windowController = KMBrowserWindowController.init(browser: browser) browser.addHomeTabContents() browser.windowController.showWindow(self) } @objc private func _themeChanged(_ sender: Notification) { let isDarkModel = KMAdvertisementConfig.isDarkModel() if isDarkModel { NSApp.appearance = .init(named: .darkAqua) } else { NSApp.appearance = .init(named: .aqua) } // if let data = NSApp.appearance?.name, data == .darkAqua { // NSApp.appearance = .init(named: .aqua) // } else { // NSApp.appearance = .init(named: .darkAqua) // } NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil) } @objc func AIDeviceStatusChangeNotification() { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { self.refreshAIMenuItemInfo() } } func refreshAIMenuItemInfo() -> Void { let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu for item in appMenu!.items { if item.action == #selector(aiToolsAction) { item.isHidden = true } } } //MARK: - iVersion func initiVersionData() -> Void{ #if VERSION_DMG #else let tVersion = iVersion.sharedInstance() tVersion?.applicationBundleID = Bundle.main.bundleIdentifier var tStr = "New Update Available" tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n" tVersion?.versionLabelFormat = "" tVersion?.groupNotesByVersion = true tVersion?.showOnFirstLaunch = false tVersion?.checkPeriod = 2 tVersion?.remindPeriod = 5 let infoDictionary = Bundle .main.infoDictionary! var appName: String = infoDictionary["CFBundleDisplayName"] as! String if appName.count < 1 { appName = infoDictionary["CFBundleName"] as! String } tStr = "The new version of %@ is available now. Go update for new features."; tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))! tStr = String(format: tStr, appName) tVersion?.inThisVersionTitle = tStr tStr = "UPDATE NOW"; tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr) tStr = "LATER"; tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr) tVersion!.ignoreButtonLabel = "" #endif } // MARK: - Menu func initMainMenu() { // 处理菜单栏多语 let mainMenu = NSApp.mainMenu if (mainMenu == nil) { return } for menu in mainMenu!.items { let subMenu = menu.submenu for item in subMenu!.items { item.title = NSLocalizedString(item.title, comment: "") let itemSubMenu = item.submenu if (itemSubMenu == nil) { continue } for item in itemSubMenu!.items { item.title = NSLocalizedString(item.title, comment: "") } } } let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu #if VERSION_DMG _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 3) _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4) // if ([VerificationManager manager].needUpgradeLicense == NO) { if VerificationManager.default().needUpgradeLicense { _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5) } let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8) accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag #endif #if !VERSION_DMG _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1) #endif if let items = PDFOfficeMenu?.items { for menu in items { let ranges = menu.title.ranges(of: "Cisdem PDFMaster") if let _range = ranges.range.first { menu.title.replaceSubrange(_range, with: KMTools.getAppName()) } } } let fileMenu = mainMenu?.item(at: 1)?.submenu var shareItem: NSMenuItem? if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) { shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil) fileMenu?.insertItem(shareItem!, at: item.index) fileMenu?.insertItem(.separator(), at: item.index) } else { shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil) fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1) } shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil) let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self) let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self) fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1) fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1) fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1) } @objc func sharePageItemAction(sender: NSMenuItem) { if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) { return } let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController let model = windowControler.browser?.tabStripModel if let cnt = model?.count(), cnt <= 0 { return } if let data = model?.activeTabContents()?.isHome, data { return } let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument if let data = document.mainViewController?.saveWatermarkFlag, !data { let represent : NSSharingService = sender.representedObject as! NSSharingService represent.perform(withItems: [document.fileURL as Any]) return } let represent : NSSharingService = sender.representedObject as! NSSharingService represent.perform(withItems: [document.fileURL as Any]) } @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) { KMPrint("deviceCameraMenuItemAciton") NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil) } @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) { KMPrint("deviceScannerMenuItemAciton") NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil) } // MARK: Cisdem PDFMaster Menu @IBAction func openPreferenceWindow(_ sender: Any) { KMPreferenceController.shared.showWindow(self) } @objc @IBAction func manageAcctounMenuAction(_ sender: Any) { if KMLightMemberManager.manager.isLogin() { _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!) } } @IBAction func loginMenuItemAction(_ sender: Any) { // Login & Logout if KMLightMemberManager.manager.isLogin() { } else { _ = KMLoginWindowController.show(window: NSApp.mainWindow!) } } @IBAction func logoutMenuItemAction(_ sender: Any) { // Login & Logout if KMLightMemberManager.manager.isLogin() { KMRequestServerManager.manager.logout { success, result in if success { KMPrint("登出成功") } } } } @IBAction func restoreMenuItemAction(_ sender: Any) { KMPurchaseManager.manager.restorePurchases { isSuccess, error in if isSuccess { } else { if error != .restoreSuccess { KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error) } } } } @objc func accountRefreshAction() { KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in } } @objc func showAccount() { } @objc func resumePurchase() { } // MARK: help Menu @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void { KMTools.openQuickStartStudy() } @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void { KMTools.openFAQWebsite() } @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void { KMTools.openMoreProductWebsite() } @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void { KMTools.openFreePDFTemplatesWebsite() } @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void { KMEmailSubWindowController().showWindow(nil) } @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void { KMTools.openComPDFKitPowerWebsite() } @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void { KMTools.proposeNewFeature() } @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void { KMTools.rateUs() } @objc func restoreSubscriptions(_ sender: NSMenuItem) { #if VERSION_FREE KMPrint("restoreSubscriptions ...") let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController compareWindowVC.showWindowRestore(nil) #else var vc: KMToolCompareWindowController? = nil vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0) vc!.showWindowRestore(sender: (Any).self) #endif } // MARK:- DMG @objc func checkForUpdates1(_ sender: NSMenuItem) { KMOEMRequestServerManager.defaultManager.oemRequest(state: .update, regCode: "") { wrapper in if wrapper.success { if let version = wrapper.data["version"] as? String { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("A new version of Cisdem PDFMaster is available!", comment: "") alert.informativeText = String(format: NSLocalizedString("Cisdem PDFMaster %@ is now available---you have %@. Would you like to download it now?", comment: ""), version, KMOEMRequestServerManager.defaultManager.version()) alert.addButton(withTitle: NSLocalizedString("Yes", comment: "")) alert.addButton(withTitle: NSLocalizedString("Ignore", comment: "")) alert.addButton(withTitle: NSLocalizedString("NO", comment: "")) alert.beginSheetModal(for: NSApplication.shared.keyWindow!) { response in if response == .alertFirstButtonReturn { let defs = UserDefaults.standard if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first { var tStrUrl = "https://www.cisdem.com/pdfmaster.html" if preferredLang.hasPrefix("de") { tStrUrl = "https://www.cisdem.com/de/pdfmaster.html" } else if preferredLang.hasPrefix("fr") { tStrUrl = "https://www.cisdem.com/fr/pdfmaster.html" } else if preferredLang.hasPrefix("it") { tStrUrl = "https://www.cisdem.com/it/pdfmaster.html" } else if preferredLang.hasPrefix("es") { tStrUrl = "https://www.cisdem.com/es/pdfmaster.html" } else if preferredLang.hasPrefix("pt") { tStrUrl = "https://www.cisdem.com/pt/pdfmaster.html" } else if preferredLang.hasPrefix("ja") { tStrUrl = "https://www.cisdem.com/jp/pdfmaster.html" } let tStrHttpUrl = tStrUrl let tWorkSpace = NSWorkspace.shared if !tWorkSpace.open(URL(string: tStrUrl)!) { tWorkSpace.open(URL(string: tStrHttpUrl)!) } } } else if response == .alertSecondButtonReturn { UserDefaults.standard.setValue(KMOEMRequestServerManager.defaultManager.version(), forKey: "KMOEMRequestStateUpdate") } else if response == .alertThirdButtonReturn { // Handle "NO" response if needed } } } } } } @objc func checkForUpdates(_ sender: NSMenuItem) { KMOEMRequestServerManager.defaultManager.oemRequest(state: .update, regCode: "") { wrapper in if wrapper.success { if let version = wrapper.data["version"] as? String { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("A new version of Cisdem PDFMaster is available!", comment: "") alert.informativeText = String(format: NSLocalizedString("Cisdem PDFMaster %@ is now available---you have %@. Would you like to download it now?", comment: ""), version, KMOEMRequestServerManager.defaultManager.version()) alert.addButton(withTitle: NSLocalizedString("Yes", comment: "")) alert.addButton(withTitle: NSLocalizedString("Ignore", comment: "")) alert.addButton(withTitle: NSLocalizedString("NO", comment: "")) alert.beginSheetModal(for: NSApplication.shared.keyWindow!) { response in if response == .alertFirstButtonReturn { let defs = UserDefaults.standard if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first { var tStrUrl = "https://www.cisdem.com/pdfmaster.html" if preferredLang.hasPrefix("de") { tStrUrl = "https://www.cisdem.com/de/pdfmaster.html" } else if preferredLang.hasPrefix("fr") { tStrUrl = "https://www.cisdem.com/fr/pdfmaster.html" } else if preferredLang.hasPrefix("it") { tStrUrl = "https://www.cisdem.com/it/pdfmaster.html" } else if preferredLang.hasPrefix("es") { tStrUrl = "https://www.cisdem.com/es/pdfmaster.html" } else if preferredLang.hasPrefix("pt") { tStrUrl = "https://www.cisdem.com/pt/pdfmaster.html" } else if preferredLang.hasPrefix("ja") { tStrUrl = "https://www.cisdem.com/jp/pdfmaster.html" } let tStrHttpUrl = tStrUrl let tWorkSpace = NSWorkspace.shared if !tWorkSpace.open(URL(string: tStrUrl)!) { tWorkSpace.open(URL(string: tStrHttpUrl)!) } } } else if response == .alertSecondButtonReturn { UserDefaults.standard.setValue(KMOEMRequestServerManager.defaultManager.version(), forKey: "KMOEMRequestStateUpdate") } else if response == .alertThirdButtonReturn { // Handle "NO" response if needed } } } } else { if let code = wrapper.data["code"] as? Int, code == 201 { let alert = NSAlert() alert.alertStyle = .informational alert.messageText = String(format: NSLocalizedString("You're up-to-date! %@ is currently the newest version available.", comment: ""), "Cisdem PDFMaster") alert.addButton(withTitle: NSLocalizedString("Yes", comment: "")) alert.beginSheetModal(for: NSApplication.shared.keyWindow!) { response in if response == .alertFirstButtonReturn { // Handle "Yes" response if needed } } } } } } @objc func enterLicense(_ sender: NSMenuItem) { #if VERSION_DMG if let tManager = VerificationManager.default() { let status = tManager.status if status == ActivityStatusVerifExpire { let vc = KMVerificationWindowController.verification(with: .activateExpired) vc?.showWindow(nil) } else if status == ActivityStatusVerification { let vc = KMVerificationWindowController.verification(with: .info) vc?.showWindow(nil) } else { let vc = KMVerificationWindowController.verification(with: .activate) vc?.showWindow(nil) } } #endif } @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) { #if VERSION_DMG var tStrUrl = "https://www.cisdem.com/pdfmaster-mac/buy.html" let defs = UserDefaults.standard if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first { if preferredLang.hasPrefix("de") { tStrUrl = "https://www.cisdem.com/de/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("fr") { tStrUrl = "https://www.cisdem.com/fr/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("it") { tStrUrl = "https://www.cisdem.com/it/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("es") { tStrUrl = "https://www.cisdem.com/es/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("pt") { tStrUrl = "https://www.cisdem.com/pt/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("ja") { tStrUrl = "https://www.cisdem.com/jp/pdfmaster-mac/buy.html" } } guard let url = URL(string: tStrUrl) else { return } let tWorkSpace = NSWorkspace.shared if tWorkSpace.open(url) == false { tWorkSpace.open(url) } #endif } @IBAction func volumeDiscount(_ sender: NSMenuItem) { var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program" #if VERSION_DMG tStrHttpUrl = "https://www.cisdem.com/volume-license-for-business.html" if SKInspectPublicTool.currentisLanguageHans() { tStrHttpUrl = "https://www.cisdem.com/volume-license-for-business.html" } #else tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp" if SKInspectPublicTool.currentisLanguageHans() { tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp_zh" } #endif guard let url = URL(string: tStrHttpUrl) else { NSSound.beep() return } let tWorkSpace = NSWorkspace.shared if tWorkSpace.open(url) == false { tWorkSpace.open(url) } } @IBAction func crossPlatformAction(_ sender: NSMenuItem) { var tStrUrl = "https://www.cisdem.com/pdfmaster-mac/buy.html" let defs = UserDefaults.standard if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first { if preferredLang.hasPrefix("de") { tStrUrl = "https://www.cisdem.com/de/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("fr") { tStrUrl = "https://www.cisdem.com/fr/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("it") { tStrUrl = "https://www.cisdem.com/it/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("es") { tStrUrl = "https://www.cisdem.com/es/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("pt") { tStrUrl = "https://www.cisdem.com/pt/pdfmaster-mac/buy.html" } else if preferredLang.hasPrefix("ja") { tStrUrl = "https://www.cisdem.com/jp/pdfmaster-mac/buy.html" } } guard let url = URL(string: tStrUrl) else { return } let tWorkSpace = NSWorkspace.shared if tWorkSpace.open(url) == false { tWorkSpace.open(url) } #if VERSION_DMG FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"]) #endif } @IBAction func EducationDiscountAction(_ sender: NSMenuItem) { let (major, minor, bugFix) = KMTools.getSystemVersion() let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)" let appVersion = KMTools.getAppVersion() let appName = KMTools.getAppNameForSupportEmail() let subjects = "\(appName) - \(appVersion);Education Discount;\(versionInfoString)" let email = "sales@cisdem.com" KMMailHelper.newEmail(withContacts: email, andSubjects: subjects) } @IBAction func aiToolsAction(_ sender: NSMenuItem) { #if VERSION_DMG KMPurchaseCompareWindowController.sharedInstance().showWindow(nil) #else AIPurchaseWindowController.currentWC().showWindow(nil) #endif } @IBAction func orderFrontLineInspector(_ sender: Any?) { if let win = KMLineInspector.shared.window { if win.isVisible { win.orderOut(sender) } else { win.orderFront(sender) } } } @IBAction func showDownloads(_ sender: NSMenuItem) -> Void { KMPrint("showDownloads ...") } @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void { self.reopenDocument(forPaths: []) } @IBAction func newsletter(_ sender: NSMenuItem) -> Void { KMEmailSubWindowController().showWindow(nil) } @IBAction func feedback(_ sender: NSMenuItem) -> Void { KMTools.feekback() } @IBAction func reportBug(_ sender: NSMenuItem) -> Void { KMTools.reportBug() } @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void { KMTools.reportGeneralQuestions() } } extension AppDelegate : NSMenuDelegate,NSMenuItemValidation { func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { let action = menuItem.action if action == #selector(manageAcctounMenuAction) { self.updateLoginMenuItem() return KMLightMemberManager.manager.isLogin() } if action == #selector(loginMenuItemAction) { self.updateLoginMenuItem() return !KMLightMemberManager.manager.isLogin() } if action == #selector(logoutMenuItemAction) { self.updateLoginMenuItem() return KMLightMemberManager.manager.isLogin() } if (action == #selector(sharePageItemAction)) { guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else { return false } let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false return !isHome } if action == #selector(closeDocument) { guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else { if NSApp.mainWindow?.windowController != nil { return true } return false } let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false if isNewTab { return true } // let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false // return !isHome } return true } func updateLoginMenuItem() { let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu if firstItem != nil { let item1 = firstItem?.item(withTag: 11) let item2 = firstItem?.item(withTag: 12) let item3 = firstItem?.item(withTag: 13) let item4 = firstItem?.item(withTag: 14) // let item5 = firstItem?.item(withTag: 15) let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag) // if KMLightMemberManager.manager.isLogin() { // item1?.title = KMLightMemberManager.manager.info.email // item1?.isHidden = false // item2?.isHidden = true // item3?.isHidden = false // item4?.isHidden = false //// item5?.isHidden = false // item6?.isHidden = false // } else { // item1?.isHidden = true // item2?.isHidden = false // item3?.isHidden = true // item4?.isHidden = true //// item5?.isHidden = true // item6?.isHidden = true // } item1?.isHidden = true item2?.isHidden = true item3?.isHidden = true item4?.isHidden = true // item5?.isHidden = true item6?.isHidden = true } } @objc func clickOutline(menuItem: NSMenuItem) { KMPrint("更新菜单栏") } func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool { return true } } extension AppDelegate { // MARK: - Services Support func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) { var error: NSError? if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) { // Document opened successfully } else if let error = error { errorString = error.localizedDescription } } func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) { var error: NSError? if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) { // Document opened successfully } else if let error = error { errorString = error.localizedDescription } } func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) { var error: NSError? if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) { // Document opened successfully } else if let error = error { errorString = error.localizedDescription } } } extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 处理用户点击推送通知的操作 completionHandler() } }