123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014 |
- //
- // AppDelegate.swift
- // PDF Reader Pro
- //
- // Created by Niehaoyu on 2022/9/23.
- //
- import Cocoa
- import UserNotifications
- @main
- class AppDelegate: NSObject, NSApplicationDelegate, iRateDelegate{
-
-
- func applicationWillFinishLaunching(_ notification: Notification) {
- #if VERSION_FREE
- #if VERSION_DMG
- CPDFConvertKit.setLicenseKey("O/Gy6kRnVkPniZrtkbxVR1TE40NTE5pBLNTKURABKTzsIIbuxTL/T5Heoq7dR8rnIucE+QnyQFm7qD1M8FYPSLa7rFNhYndz6r/tOJ/zprEPTIOC/Nw4EX6spV9KH48rd1SHQTNhzbLFaNJvDgu2/ejACIaxDQphAukW2sq99tdKa8c5i0ZVoXbf6/8I2Z3Od3majxVC1KDcp/GFYQBaZ76754mYrYfmjEUPZ7S8iUjyFIQsowcxzlliSKY7wSyLw4M0H9PYB5U9haTiQ64gBLYRmw0VtvUwqO4H/hQ9LGi6X8lGqylnDe1XlN5rXwEMSiDCAhvbmLCRDsRibJkkHmu0lH1oY17eVN2TRW5amzqhpkGcUFF17VJJZII5FrASG54RG2l/P/4nIMUZUpkQWzt+ywu1ETx64wnEWVCLqsbdRblIYesSaSBLC+ue5qj5IaZ5NrlUIullyFVfqhe0wgJTOAqc3sItd6982pDUUOfO1vBwf9Gih2qz4tARI2xVuzABfsMzje7wUE0bm1cpFckwV66yFU3arnx3YKFgKb3I+cfej7P32Ul15YgJWcFJ73lHjkMG6INyw1EEf1rPimDxLz3UnfnLfC0R03ceOgzTYO9/asHtjQN6JLAJ6RPMQGvvr0we4wc3psyfAnokxsRHkgtxfepvazk4kx4MMiYLkEkH3o/9D3jycmgmtJNNDOYy9ariKo6bXDBPENEd2iIDr6sby+Jm3qii6n3/VWRZQv/eghUvrDc0/BlUHjx8TSsbRmzsSDkeM/v3k1jSCw==")
- #else
- CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+v5w339rXeJw+v0hh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ABfsMzje7wUE0bm1cpFckwV66yFU3arnx3YKFgKb3I+cfej7P32Ul15YgJWcFJ73lHjkMG6INyw1EEf1rPimDxLz3UnfnLfC0R03ceOgzTYO9/asHtjQN6JLAJ6RPMQGvvr0we4wc3psyfAnokxsRHkgtxfepvazk4kx4MMiYLkEkH3o/9D3jycmgmtJNNDOYy9ariKo6bXDBPENEd2iIDr6sby+Jm3qii6n3/VWRZQv/eghUvrDc0/BlUHjx8TSsbRmzsSDkeM/v3k1jSCw==")
-
- 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()
- }
-
- #if VERSION_DMG
- let updater = SUUpdater.shared()
- updater?.delegate = self
- updater?.automaticallyChecksForUpdates = true
- #else
- #endif
- //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])
-
- NSApp.servicesProvider = self
-
- KMKdanRemoteConfig.remoteConfig.fetchWithRemoteConfigCompletionHandler { status, error in
-
- }
- 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()
- KMDMGProductsManager.shareInstance.getProductDatas()
- #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<CFError>?
- if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
- print("Failed to register font!")
- } else {
- print("Font registered successfully!")
- }
-
- }
-
- let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
- for item in appMenu!.items {
- if item.action == #selector(aiToolsAction) {
- if let tManager = VerificationManager.default() {
- let status = tManager.status
- if status == ActivityStatusNone {
- item.isHidden = true
- }
- }
- }
- }
- NotificationCenter.default.addObserver(self, selector: #selector(deviceActivateStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
-
- self.initAccountRights()
- }
-
- func initAccountRights() {
- if let token = KMDataManager.ud_string(forKey: kAccountTokenKey), token.isEmpty == false {
- let header = ["Token" : token]
- KMHTTP.OEM_POST(urlString: kURLAPI_oemGetPermissions, parameter: nil, headers: header) { success, dataModel, err in
- if success == false { // App 启动 Token 过期 退出登陆 & 解除设备绑定,需用户重新登陆再绑定
- KMDataManager.ud_set("", forKey: kAccountTokenKey)
- AccountManager.manager.saveRights(model: nil)
-
- NotificationCenter.default.post(name: .loginStatusChanged, object: nil)
-
- VerificationManager.default().unactivateDeviceWithcomplention { status, infoDict, err in
- VerificationManager.default().verification {status1 , infoDict1, err1 in
-
- }
- }
- return
- }
- let model = AccountRightModel(dict: dataModel?.data as? [String : Any] ?? [:])
- AccountManager.manager.saveRights(model: model)
-
- NotificationCenter.default.post(name: .loginStatusChanged, object: nil)
-
- if let data = model.memberInfo?.email, data.isEmpty == false {
- self.activateDevice(email: data)
- }
- }
- }
- }
-
- func activateDevice(email: String) {
- // if IAPProductsManager.default().isAvailableAllFunction() {
- // return
- // }
-
- VerificationManager.default().activateDevice(withInfo: ["email" : email]) { status, info, err in
- VerificationManager.default().verification { status, info, err in
-
- }
- }
- }
-
- 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)
- }
- 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
- }
- }
-
- if let browser = windowControler?.browser {
- if browser.tabCount() == 1 {
- windowControler?.window?.close()
- } else {
- if let _ = windowControler?.window?.attachedSheet {
- NSSound.beep()
- return
- }
- browser.closeTab()
- }
- } else {
- windowControler?.window?.close()
- }
- }
-
- 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()
- }
- }
-
- @objc func deviceActivateStatusChangeNotification() {
- let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
- for item in appMenu!.items {
- if item.action == #selector(aiToolsAction) {
- if let tManager = VerificationManager.default() {
- let status = tManager.status
- if status == ActivityStatusNone {
- item.isHidden = true
- }
- }
- }
- }
- }
-
- 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 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: "PDFull")
- 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: PDF Reader Pro 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_freePDFTemplate(_ sender: NSMenuItem) -> Void {
- KMTools.openFreePDFTemplatesWebsite()
- }
-
- @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
- KMEmailSubWindowController().showWindow(nil)
- }
-
- @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
- KMTools.proposeNewFeature()
- }
-
- @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 checkForUpdates(_ sender: NSMenuItem) {
- #if VERSION_DMG
- SUUpdater.shared().checkForUpdates(sender)
- #endif
- }
-
- @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 url = URL(string: "https://www.anyrecover.com/buy-pdf-editor-reader-converter")
- if SKInspectPublicTool.currentisLanguageHans() {
- url = URL(string: "https://www.anyrecover.com/buy-pdf-editor-reader-converter")
- }
- let tWorkSpace = NSWorkspace.shared
- if tWorkSpace.open(url!) == false {
- tWorkSpace.open(url!)
- }
- #endif
- // var url = URL(string: Store_Link + "?product_code=product_2")
- // let tWorkSpace = NSWorkspace.shared
- // if tWorkSpace.open(url!) == false {
- // tWorkSpace.open(url!)
- // }
- // let embeddedWC = KMPurchaseEmbeddedWindowController.currentFirstTrialWC("com.brother.pdfreaderpro.mac.product_2")
- // embeddedWC.showWindow(nil)
- // embeddedWC.window?.center()
- }
-
- @IBAction func volumeDiscount(_ sender: NSMenuItem) {
- var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
- #if VERSION_DMG
- tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
- #else
- tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
- #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 tStrHttpUrl = CrossPlatform_Link
- guard let url = URL(string: tStrHttpUrl) 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 tStrHttpUrl = Store_Edu_Link
- guard let url = URL(string: tStrHttpUrl) 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_EduDiscount"])
- #endif
- }
-
- @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
- }
- }
- #if VERSION_DMG
- extension AppDelegate : SUUpdaterDelegate {
- func updaterWillRelaunchApplication(_ updater: SUUpdater) {
- }
-
- func feedURLString(for updater: SUUpdater) -> String? {
- var hostURL = "https://static.anyrecover.com/download/"
- //#if DEBUG
- // hostURL = "http://test-pdf-pro.kdan.cn:3021/downloads/"
- //#else
- // hostURL = "https://www.pdfreaderpro.com/downloads/"
- //#endif
- return hostURL+NSLocalizedString("pdfull-mac-update.xml", comment: "")
- }
-
- func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
- return false
- }
-
- func upgradeAPP(with updater: SUUpdater) {
- let string = "macappstore://apps.apple.com/app/id825459243?mt=12"
- let url: URL = URL(string: string)!
- NSWorkspace.shared.open(url)
- }
-
- func upgradeButtonString(for updater: SUUpdater) -> String {
- return NSLocalizedString("PDFull", comment: "")
- }
- }
- #endif
- 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()
- }
- }
|