// // AppDelegate.swift // PDF Master // // Created by Niehaoyu on 2022/9/23. // import Cocoa import KMAdvertisement @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) { let appTarget = KMTools_OC.getAppTarget() if (appTarget == .free) { CPDFKit.setLicenseKey("cdq2EJ0yq9HmBQy/AlHPtC/+pnZCKi9HaV8t+N2McjPDNTB0Z8xK+4hw4/xn55GNsnWlNbSB7RTkRMQ45T0IZ4Bhsb2wTjMKZgLHXOYCVs+y/A54hwA/v1fm5F6/mdCjqyFpy2uq7LVxNwsCbVVT+PuHmXDUuWqkErl02537Y3E=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4p9ms/F1zY6gZ1RBu8mNJH8VDCh7HQsi+BJS7RukFVBsD3jYTYlv7OHV9TgoY0SmO6Ptvguf6vCH30IoM4xINMau4aGVjtYuk+Uxs/kosIBwyxQV1SVCQFsC27oMGz5P/rBQYv0T/D0N0z+Um3U+I+tTRwFO+iE6+0emjaIlX2OMDXw8/CDEmc6oakb9zq80YfY7KtZ0LxrqSdyM0ZMT4i8IZqTxD9KkvMj3/O+zX155uoFv1BTjCeXlkEOSDvmglU=") CPDFConvertKit.setLicenseKey("HcZ7sehqdnIvgtFnAF85D2B6tQjbMAklBEZyrSKYYSY/bdNOfGvcNIKpDTUchwAtZLw1fkJ3uN49bgUVSz8UEHm2LpoXPcRK9b+laQ17UHE7qFx6twVZ2IIyEURhMClmFSDD5yAxxpndYl8mmwjIoWspgAdDGX8pixFDQUE3/9w=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4qccr16WMBclnQACarlyblNUvAm/S8uFbhXMvxwgBSgULSsrbuyF/SIZ3I+dl0qU8GohiEHQBcAOj1ste3ppDvnC1Ca6fL/tThqwHk5EkhX8DeDWXm8oYxIQxh+yoOd+MxU9avJIxe/9rGTVfLJgjbpoOXUTNa/8X/QbDtDTanKkAwWgQy2MrGRWbL6WItb270=") } else if (appTarget == .DMG) { CPDFKit.setLicenseKey("anWsjwnFLewcxYRZbdvBVgX9bZ2Ofz9Yy+tje+KJ6BktwciBCx51vZBUDXpFdUrDugu0t4yVSEh+yOhXXRPgiaeCh1dJX+IR7ztnArFoCS8HQDk3ROXjYWkFOmWioOljbNuORZ/zrsv8l0jRNMLUCPxPbga271sOcUVDeHNn/8c=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4rCrm/O2+fI9yUYXNZ/JY1KPbFCeKgG+lEVwrbGHrpAyXATqjrt8ApqRYhafFooQjwAFgayISwZT/pa4NjR459gu4aGVjtYuk+Uxs/kosIBw9vgMz/YdzEMZoMhFEbmUEc6H4o/0cJmYd/bLPc1WFIlJ3VN41JnIqAKG97dQtCXYUplTxrh5mQs6SZcN0B2PF/dEupdk9Zstt+VbVf6kPXvj9NGZMFeJwC3Ilgq78L0gg==") CPDFConvertKit.setLicenseKey("SVRr1XuTMVrF85Sp+DpK2q/NpcumFDTxBWajzl08eWpk7DomcFajxwMpgfhLCSCNn5jgMumR/diO8X+tZhrBuPs0UP2gYX1lstnpKPqRx8ZnHCTFMyS06zkIrVGTghH+DHNWyXfMFVGQtIVO/+X77wGOtmn5S4/uUHLJDSgLkmw=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4qccr16WMBclnQACarlyblNUvAm/S8uFbhXMvxwgBSgULSsrbuyF/SIZ3I+dl0qU8GohiEHQBcAOj1ste3ppDvnC1Ca6fL/tThqwHk5EkhX8DeDWXm8oYxIQxh+yoOd+MwekFC/LCdvQ96bASGL15ECoOXUTNa/8X/QbDtDTanKkAwWgQy2MrGRWbL6WItb270=") } else { CPDFKit.setLicenseKey("cdq2EJ0yq9HmBQy/AlHPtC/+pnZCKi9HaV8t+N2McjPDNTB0Z8xK+4hw4/xn55GNsnWlNbSB7RTkRMQ45T0IZ4Bhsb2wTjMKZgLHXOYCVs+y/A54hwA/v1fm5F6/mdCjqyFpy2uq7LVxNwsCbVVT+PuHmXDUuWqkErl02537Y3E=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4p9ms/F1zY6gZ1RBu8mNJH8VDCh7HQsi+BJS7RukFVBsD3jYTYlv7OHV9TgoY0SmO6Ptvguf6vCH30IoM4xINMau4aGVjtYuk+Uxs/kosIBwyxQV1SVCQFsC27oMGz5P/rBQYv0T/D0N0z+Um3U+I+tTRwFO+iE6+0emjaIlX2OMDXw8/CDEmc6oakb9zq80YfY7KtZ0LxrqSdyM0ZMT4i8IZqTxD9KkvMj3/O+zX155uoFv1BTjCeXlkEOSDvmglU=") CPDFConvertKit.setLicenseKey("HcZ7sehqdnIvgtFnAF85D2B6tQjbMAklBEZyrSKYYSY/bdNOfGvcNIKpDTUchwAtZLw1fkJ3uN49bgUVSz8UEHm2LpoXPcRK9b+laQ17UHE7qFx6twVZ2IIyEURhMClmFSDD5yAxxpndYl8mmwjIoWspgAdDGX8pixFDQUE3/9w=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4qccr16WMBclnQACarlyblNUvAm/S8uFbhXMvxwgBSgULSsrbuyF/SIZ3I+dl0qU8GohiEHQBcAOj1ste3ppDvnC1Ca6fL/tThqwHk5EkhX8DeDWXm8oYxIQxh+yoOd+MxU9avJIxe/9rGTVfLJgjbpoOXUTNa/8X/QbDtDTanKkAwWgQy2MrGRWbL6WItb270=") } // CDocumentAIKit.sharedInstance().setLicenseKey("1F8B081800599C640000616C7068610034413635373236463644363535393631364536370001F0010FFE33C3D4634F3E0B148EA10B8E59B57FA6B17EC34749CDBBD02D697F1A481C00666DCDDC517B4F576C4F8A9961080E556DF332DA7C816D3A3C212DCBE34749B6845E561A60C7E13BF8F84EC77FCF314333E1DFFC92E88A6CD97F65F6153452E9677F7A248FD45C98E87647367A29D678DA15EECB5E28854C674FE4DFE810740CB43F4DC1A7444B1EFA3C8C3E3F4D5859A9BAEDF1CF87917E86E6541B924A1AD0FBEC61BDFA0886A1E8FDFECCDE64FCCB645A89323F0177FE0B3CB7E3D72EA9A3DE1823FEB5D967F90751F46B6C97A1C250B669FD145747ADF6571859F78FDA05DA5B963B799DA5CC53ECE0FB8D53165EB3B0188FF8BB201D8AD7A34F01EC1BA855378F2CB8B9176EE463B1F2B1D8BD776113BAEF4C9A78EE7BC12EF192DABD2FBAB2E252A09B38A85BFCD76B4AFBEFF5A4E9FFE499A77B76E97B9C01CC7485688CD696FD1145D47AD969074FD300783583B70460617A0EC2D7579D0EC5AC33DB3F32E0CC920AC25B6D8F177D2F73FF26457534D6233844BEB4B223A37AA59EFB3D2469C8367C0CBF29C8A3E505AA53E62661FFC59771E77C3C274B51E2C066E87C796BA6AC2D2567D25560A7E9DFE3433FC5233A2C0CB4320D57EB8C0422B416CB5E25F94DB1CC0DCE1A39684827B61BCAE552A05607748113F3D6194A29A8C5C400A02FE3C69204D754550FA5E24BC3FF068B99DDF0010000") ComPDFUIConfig.initializeUIConfig(); KMDesignToken.shared.parserExcel(withPath: "") } func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application #if VERSION_DMG let updater = SUUpdater.shared() updater!.delegate = self updater!.automaticallyChecksForUpdates = true #else #endif // MARK: 广告数据初始化 KMAdvertisementManager.manager.initConfig(appName: .PDFReaderProMac, subscribeType: .unsubscribed, platform: .Mac) // 测试模式,默认false KMAdvertisementManager.manager.debug = true // 初版不支持暗黑模式 NSApp.appearance = NSAppearance(named: .aqua) KMAnalytics.configure() //第一次开启app var 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() // //restore if KMInAppPurchaseManager.manager.state == .subscription { debugPrint("是订阅状态 需要restore") KMPurchaseManager.manager.restorePurchases { isSuccess, error in } } self.initMainMenu() /// pro // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"]; DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj") reopenDocument(forPaths: []) KMPreference.shared.initDataForAppLaunch() let appleEventManager = NSAppleEventManager.shared() appleEventManager.setEventHandler(self, andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) } @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 { [weak self] 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) { } 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 } 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 (NSApp.orderedDocuments.count > 0) { var filepaths: [String] = [] for document in NSApp.orderedDocuments { // 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) } // 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 let appTarget = KMTools_OC.getAppTarget() if (appTarget == .DMG) { PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 1) let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8) accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag } if let items = PDFOfficeMenu?.items { for menu in items { let ranges = menu.title.ranges(of: "PDF Master") let appTarget = KMTools_OC.getAppTarget() var appName = "PDF Master" if (appTarget == .pro) { appName = "PDF Master Pro" } else if (appTarget == .DMG) { appName = "PDF Master" } if let _range = ranges.range.first { menu.title.replaceSubrange(_range, with: appName) } } } let fileMenu = mainMenu?.item(at: 1)?.submenu let shareItem: NSMenuItem = 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 viewMenu = mainMenu?.item(at: 3)?.submenu var zoomMenu: NSMenu? for item in viewMenu!.items { if (item.title == NSLocalizedString("Zoom", comment: "")) { zoomMenu = item.submenu break } } if (zoomMenu != nil) { for item in zoomMenu!.items { if (item.title == NSLocalizedString("Zoom In", comment: "")) { item.keyEquivalent = "+" item.keyEquivalentModifierMask = [.command] break } } } } @objc func sharePageItemAction(sender: NSMenuItem) { if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) { return } let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController let model: CTTabStripModel = windowControler.browser.tabStripModel if (model.count() <= 0) { return } if (model.activeTabContents().isHome) { 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 } // 有使用付费功能 Task { @MainActor in if await (KMLightMemberManager.manager.canPayFunction() == false) { let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in if (isClose) { return } if (isSubscribeSuccess) { let represent : NSSharingService = sender.representedObject as! NSSharingService represent.perform(withItems: [document.fileURL as Any]) return } if (isWaterMarkExport) { let doucumentURL = document.fileURL let docDir = NSTemporaryDirectory() let documentName : String = doucumentURL!.path.lastPathComponent let path = docDir.stringByAppendingPathComponent(documentName) let data = KMTools.saveWatermarkDocument(document: document.mainViewController!.document!, to: URL(fileURLWithPath: path), secureOptions: document.mainViewController!.secureOptions, removePWD: document.mainViewController!.removeSecureFlag) let writeSuccess = data != nil if writeSuccess == false { __NSBeep() return; } let represent : NSSharingService = sender.representedObject as! NSSharingService represent.perform(withItems: [data as Any]) return } } return } let represent : NSSharingService = sender.representedObject as! NSSharingService represent.perform(withItems: [document.fileURL as Any]) } } // MARK: PDF Master Menu @IBAction func openPreferenceWindow(_ sender: Any) { KMPreferenceWindowController.shared.showWindow(nil) } @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.feekback() } @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void { } // MARK:- DMG @objc func checkForUpdates(_ sender: NSMenuItem) { let appTarget = KMTools_OC.getAppTarget() if (appTarget != .DMG) { return } #if VERSION_DMG SUUpdater.shared().checkForUpdates(sender) #endif } } 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 } return !_windowC.browser.activeTabContents().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 } } } @objc func clickOutline(menuItem: NSMenuItem) { KMPrint("更新菜单栏") } func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool { return true } } #if VERSION_DMG extension AppDelegate : SUUpdaterDelegate { func updaterWillRelaunchApplication(_ updater: SUUpdater) { } func feedURLString(for updater: SUUpdater) -> String? { #if DEBUG return "http://test-pdf-pro.kdan.cn:3021/downloads/pdfmasterprocast.xml" #else return "https://www.pdfreaderpro.com/downloads/pdfmasterprocast.xml" #endif } func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool { return false } func upgradeAPP(with updater: SUUpdater) { let string = "macappstore://apps.apple.com/cn/app/pdf-master-ai-pdf/id6446781258?mt=12" let url: URL = URL(string: string)! NSWorkspace.shared.open(url) } func upgradeButtonString(for updater: SUUpdater) -> String { return NSLocalizedString("PDF Master", comment: "") } } #endif