AppDelegate.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. //
  2. // AppDelegate.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2022/9/23.
  6. //
  7. import Cocoa
  8. import UserNotifications
  9. @main
  10. class AppDelegate: NSObject, NSApplicationDelegate, iRateDelegate{
  11. func applicationWillFinishLaunching(_ notification: Notification) {
  12. #if VERSION_FREE
  13. #if VERSION_DMG
  14. 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==")
  15. #else
  16. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmN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fO1vBwf9Gih2qz4tARI2xVuzABfsMzje7wUE0bm1cpFckwV66yFU3arnx3YKFgKb3I+cfej7P32Ul15YgJWcFJ73lHjkMG6INyw1EEf1rPimDxLz3UnfnLfC0R03ceOgzTYO9/asHtjQN6JLAJ6RPMQGvvr0we4wc3psyfAnokxsRHkgtxfepvazk4kx4MMiYLkEkH3o/9D3jycmgmtJNNDOYy9ariKo6bXDBPENEd2iIDr6sby+Jm3qii6n3/VWRZQv/eghUvrDc0/BlUHjx8TSsbRmzsSDkeM/v3k1jSCw==")
  22. ComPDFUIConfig.initializeUIConfig()
  23. KMDesignToken.shared.parserExcel(withPath: "")
  24. }
  25. func applicationDidFinishLaunching(_ aNotification: Notification) {
  26. // Insert code here to initialize your application
  27. //通知
  28. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  29. if granted {
  30. KMPrint("User authorized notifications")
  31. } else {
  32. KMPrint("User denied notifications")
  33. }
  34. }
  35. /**本地推送测试
  36. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  37. if granted {
  38. // 创建本地推送通知
  39. let content = UNMutableNotificationContent()
  40. content.title = "Test Notification"
  41. content.body = "This is a test notification!"
  42. // 触发条件,例如延迟 5 秒触发
  43. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  44. // 创建通知请求
  45. let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
  46. // 添加通知请求到用户通知中心
  47. UNUserNotificationCenter.current().add(request) { error in
  48. if let error = error {
  49. print("Error adding notification request: \(error)")
  50. } else {
  51. print("Local notification scheduled")
  52. }
  53. }
  54. } else {
  55. print("User denied notifications")
  56. }
  57. }
  58. **/
  59. DispatchQueue.main.async {
  60. NSApplication.shared.registerForRemoteNotifications()
  61. }
  62. #if VERSION_DMG
  63. let updater = SUUpdater.shared()
  64. updater?.delegate = self
  65. updater?.automaticallyChecksForUpdates = true
  66. #else
  67. #endif
  68. //Firebase RemoteConfig
  69. #if VERSION_FREE
  70. KMKdanRemoteConfig.remoteConfig.fetch { _status, error in
  71. }
  72. #endif
  73. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  74. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  75. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  76. let sud = UserDefaults.standard
  77. if versionString.isEmpty == false {
  78. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  79. }
  80. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  81. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  82. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  83. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  84. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  85. sud.synchronize()
  86. }
  87. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  88. NSApp.servicesProvider = self
  89. KMKdanRemoteConfig.remoteConfig.fetchWithRemoteConfigCompletionHandler { status, error in
  90. }
  91. KMStatusBar.system()
  92. // MARK: 广告数据初始化
  93. var appName: KMAdvertisementAppNameType = .PDFReaderProMac
  94. #if VERSION_FREE
  95. #if VERSION_DMG
  96. appName = .PDFReaderProMacDMG
  97. #else
  98. #endif
  99. #else
  100. appName = .PDFReaderProMacPro
  101. #endif
  102. KMAdvertisementManager.manager.initConfig(appName: appName,
  103. subscribeType: .unknow,
  104. platform: .Mac)
  105. // 测试模式,默认false
  106. KMAdvertisementManager.manager.debug = true
  107. NSApp.appearance = NSAppearance.current
  108. KMAnalytics.configure()
  109. //第一次开启app
  110. let info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount")
  111. var count = 0
  112. if info != nil {
  113. count = info as? Int ?? 0
  114. }
  115. count += 1
  116. UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount")
  117. UserDefaults.standard.synchronize()
  118. self.initMainMenu()
  119. /// pro
  120. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  121. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  122. reopenDocument(forPaths: [])
  123. KMPreference.shared.initDataForAppLaunch()
  124. self.initiRateData()
  125. let appleEventManager = NSAppleEventManager.shared()
  126. appleEventManager.setEventHandler(self,
  127. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  128. forEventClass: AEEventClass(kInternetEventClass),
  129. andEventID: AEEventID(kAEGetURL))
  130. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  131. #if VERSION_DMG
  132. VerificationManager.default()
  133. KMDMGProductsManager.shareInstance.getProductDatas()
  134. #else
  135. self.initiVersionData()
  136. IAPProductsManager.default().initIAP()
  137. #endif
  138. //AI相关
  139. AIInfoManager.default()
  140. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  141. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  142. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  143. var error: Unmanaged<CFError>?
  144. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  145. print("Failed to register font!")
  146. } else {
  147. print("Font registered successfully!")
  148. }
  149. }
  150. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  151. for item in appMenu!.items {
  152. if item.action == #selector(aiToolsAction) {
  153. if let tManager = VerificationManager.default() {
  154. let status = tManager.status
  155. if status == ActivityStatusNone {
  156. item.isHidden = true
  157. }
  158. }
  159. }
  160. }
  161. NotificationCenter.default.addObserver(self, selector: #selector(deviceActivateStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  162. self.initAccountRights()
  163. }
  164. func initAccountRights() {
  165. if let token = KMDataManager.ud_string(forKey: kAccountTokenKey), token.isEmpty == false {
  166. let header = ["Token" : token]
  167. KMHTTP.OEM_POST(urlString: kURLAPI_oemGetPermissions, parameter: nil, headers: header) { success, dataModel, err in
  168. if success == false { // App 启动 Token 过期 退出登陆 & 解除设备绑定,需用户重新登陆再绑定
  169. KMDataManager.ud_set("", forKey: kAccountTokenKey)
  170. AccountManager.manager.isVip = false
  171. AccountManager.manager.hasAiPermissions = false
  172. VerificationManager.default().unactivateDeviceWithcomplention { status, infoDict, err in
  173. VerificationManager.default().verification {status1 , infoDict1, err1 in
  174. }
  175. }
  176. return
  177. }
  178. let model = AccountRightModel(dict: dataModel?.data as? [String : Any] ?? [:])
  179. AccountManager.manager.isVip = model.isVip == 1
  180. AccountManager.manager.hasAiPermissions = model.hasAiPermissions == 1
  181. }
  182. }
  183. }
  184. func initiRateData() {
  185. iRate.sharedInstance().delegate = self
  186. #if VERSION_FREE
  187. iRate.sharedInstance().appStoreID = 919472673
  188. #else
  189. iRate.sharedInstance().appStoreID = 825459243
  190. #endif
  191. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  192. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  193. }
  194. //MARK: iRateDelegate
  195. func iRateUserDidDeclineToRateApp() {
  196. KMVerificationWindowController.verificationFeedback()
  197. }
  198. func iRateShouldPromptForRating() -> Bool {
  199. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  200. if !notShow {
  201. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  202. UserDefaults.standard.synchronize()
  203. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  204. }
  205. return false
  206. }
  207. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  208. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  209. let url = URL(string: urlString) {
  210. // 在这里处理收到的 URL Scheme
  211. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  212. KMPrint("Path: \(url.path)")
  213. if NSApp.mainWindow == nil {
  214. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  215. launchApp(bundleIdentifier: bundleIdentifier)
  216. }
  217. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  218. #if VERSION_DMG
  219. // 执行相应的操作
  220. if url.scheme == "subscriptiondmgschemes" {
  221. if urlString.contains("open=expired") {
  222. KMPrint("刷新用户信息")
  223. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  224. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  225. } else {
  226. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  227. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  228. }
  229. }
  230. } else if urlString.contains("open=success") {
  231. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  232. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  233. } else {
  234. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  235. if isSuccess {
  236. } else {
  237. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  238. }
  239. }
  240. }
  241. }
  242. }
  243. #endif
  244. #if VERSION_FREE
  245. // 执行相应的操作
  246. if url.scheme == "subscriptionSchemes" {
  247. //刷新用户信息
  248. KMRequestServerManager.manager.getUserInfo { success, data, error, isLocal in
  249. }
  250. if url.path == "/open" {
  251. // 执行打开操作
  252. } else if url.path == "/close" {
  253. // 执行关闭操作
  254. }
  255. }
  256. #endif
  257. }
  258. }
  259. }
  260. func launchApp(bundleIdentifier: String) {
  261. let workspace = NSWorkspace.shared
  262. // Launch the application with the specified bundle identifier
  263. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  264. do {
  265. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  266. } catch {
  267. print("Error launching the application: \(error)")
  268. }
  269. } else {
  270. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  271. }
  272. }
  273. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  274. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  275. print("Device token:", token)
  276. }
  277. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  278. }
  279. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  280. if !flag {
  281. let browser: KMBrowser = KMBrowser.init()
  282. browser.windowController = KMBrowserWindowController.init(browser: browser)
  283. browser.addHomeTabContents()
  284. browser.windowController.showWindow(self)
  285. }
  286. return flag
  287. }
  288. @IBAction func closeDocument(_ sender: Any) {
  289. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  290. guard let windowControler = NSApp.mainWindow?.windowController else {
  291. return
  292. }
  293. windowControler.window?.performClose(nil)
  294. return
  295. }
  296. let windowControler = NSApp.mainWindow?.windowController as? KMBrowserWindowController
  297. if let data = windowControler?.browser, data.tabCount() >= 2 { // 有两个以上的标签
  298. if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应
  299. return
  300. }
  301. }
  302. if let browser = windowControler?.browser {
  303. if browser.tabCount() == 1 {
  304. windowControler?.window?.close()
  305. } else {
  306. if let _ = windowControler?.window?.attachedSheet {
  307. NSSound.beep()
  308. return
  309. }
  310. browser.closeTab()
  311. }
  312. } else {
  313. windowControler?.window?.close()
  314. }
  315. }
  316. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  317. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  318. return false
  319. }
  320. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  321. if (filepaths == nil || filepaths!.count == 0) {
  322. return false
  323. }
  324. DispatchQueue.main.async {
  325. for filepath in filepaths! {
  326. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  327. }
  328. }
  329. }
  330. return false
  331. }
  332. func applicationWillTerminate(_ aNotification: Notification) {
  333. if (NSDocumentController.shared.documents.count > 0) {
  334. var filepaths: [String] = []
  335. for document in NSDocumentController.shared.documents {
  336. // KMPrint(document.fileURL as Any)
  337. if (document.fileURL?.path != nil) {
  338. filepaths.append((document.fileURL?.path)!)
  339. }
  340. }
  341. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  342. } else {
  343. KMPreferenceManager.shared.lastOpenFilepaths = nil
  344. }
  345. }
  346. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  347. return true
  348. }
  349. // MARK: private
  350. func reopenDocument(forPaths paths: [String]) -> Void {
  351. let browser = KMBrowser.init() as KMBrowser
  352. browser.windowController = KMBrowserWindowController.init(browser: browser)
  353. browser.addHomeTabContents()
  354. browser.windowController.showWindow(self)
  355. }
  356. @objc private func _themeChanged(_ sender: Notification) {
  357. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  358. if isDarkModel {
  359. NSApp.appearance = .init(named: .darkAqua)
  360. } else {
  361. NSApp.appearance = .init(named: .aqua)
  362. }
  363. // if let data = NSApp.appearance?.name, data == .darkAqua {
  364. // NSApp.appearance = .init(named: .aqua)
  365. // } else {
  366. // NSApp.appearance = .init(named: .darkAqua)
  367. // }
  368. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  369. }
  370. @objc func AIDeviceStatusChangeNotification() {
  371. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  372. self.refreshAIMenuItemInfo()
  373. }
  374. }
  375. @objc func deviceActivateStatusChangeNotification() {
  376. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  377. for item in appMenu!.items {
  378. if item.action == #selector(aiToolsAction) {
  379. if let tManager = VerificationManager.default() {
  380. let status = tManager.status
  381. if status == ActivityStatusNone {
  382. item.isHidden = true
  383. }
  384. }
  385. }
  386. }
  387. }
  388. func refreshAIMenuItemInfo() -> Void {
  389. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  390. for item in appMenu!.items {
  391. if item.action == #selector(aiToolsAction) {
  392. item.isHidden = true
  393. }
  394. }
  395. }
  396. //MARK: - iVersion
  397. func initiVersionData() -> Void{
  398. #if VERSION_DMG
  399. #else
  400. let tVersion = iVersion.sharedInstance()
  401. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  402. var tStr = "New Update Available"
  403. tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n"
  404. tVersion?.versionLabelFormat = ""
  405. tVersion?.groupNotesByVersion = true
  406. tVersion?.showOnFirstLaunch = false
  407. tVersion?.checkPeriod = 2
  408. tVersion?.remindPeriod = 5
  409. let infoDictionary = Bundle .main.infoDictionary!
  410. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  411. if appName.count < 1 {
  412. appName = infoDictionary["CFBundleName"] as! String
  413. }
  414. tStr = "The new version of %@ is available now. Go update for new features.";
  415. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  416. tStr = String(format: tStr, appName)
  417. tVersion?.inThisVersionTitle = tStr
  418. tStr = "UPDATE NOW";
  419. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  420. tStr = "LATER";
  421. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  422. tVersion!.ignoreButtonLabel = ""
  423. #endif
  424. }
  425. // MARK: - Menu
  426. func initMainMenu() {
  427. // 处理菜单栏多语
  428. let mainMenu = NSApp.mainMenu
  429. if (mainMenu == nil) {
  430. return
  431. }
  432. for menu in mainMenu!.items {
  433. let subMenu = menu.submenu
  434. for item in subMenu!.items {
  435. item.title = NSLocalizedString(item.title, comment: "")
  436. let itemSubMenu = item.submenu
  437. if (itemSubMenu == nil) {
  438. continue
  439. }
  440. for item in itemSubMenu!.items {
  441. item.title = NSLocalizedString(item.title, comment: "")
  442. let itemSubMenu = item.submenu
  443. if (itemSubMenu == nil) {
  444. continue
  445. }
  446. for item in itemSubMenu!.items {
  447. item.title = NSLocalizedString(item.title, comment: "")
  448. }
  449. }
  450. }
  451. }
  452. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  453. #if VERSION_DMG
  454. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 3)
  455. // _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4)
  456. // if ([VerificationManager manager].needUpgradeLicense == NO) {
  457. if VerificationManager.default().needUpgradeLicense {
  458. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5)
  459. }
  460. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  461. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  462. #endif
  463. #if !VERSION_DMG
  464. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  465. #endif
  466. if let items = PDFOfficeMenu?.items {
  467. for menu in items {
  468. let ranges = menu.title.ranges(of: "PDFull")
  469. if let _range = ranges.range.first {
  470. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  471. }
  472. }
  473. }
  474. let fileMenu = mainMenu?.item(at: 1)?.submenu
  475. var shareItem: NSMenuItem?
  476. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  477. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  478. fileMenu?.insertItem(shareItem!, at: item.index)
  479. fileMenu?.insertItem(.separator(), at: item.index)
  480. } else {
  481. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  482. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  483. }
  484. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  485. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  486. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  487. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  488. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  489. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  490. }
  491. @objc func sharePageItemAction(sender: NSMenuItem) {
  492. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  493. return
  494. }
  495. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  496. let model = windowControler.browser?.tabStripModel
  497. if let cnt = model?.count(), cnt <= 0 {
  498. return
  499. }
  500. if let data = model?.activeTabContents()?.isHome, data {
  501. return
  502. }
  503. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  504. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  505. let represent : NSSharingService = sender.representedObject as! NSSharingService
  506. represent.perform(withItems: [document.fileURL as Any])
  507. return
  508. }
  509. let represent : NSSharingService = sender.representedObject as! NSSharingService
  510. represent.perform(withItems: [document.fileURL as Any])
  511. }
  512. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  513. KMPrint("deviceCameraMenuItemAciton")
  514. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil)
  515. }
  516. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  517. KMPrint("deviceScannerMenuItemAciton")
  518. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil)
  519. }
  520. // MARK: PDF Reader Pro Menu
  521. @IBAction func openPreferenceWindow(_ sender: Any) {
  522. KMPreferenceController.shared.showWindow(self)
  523. }
  524. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  525. if KMLightMemberManager.manager.isLogin() {
  526. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  527. }
  528. }
  529. @IBAction func loginMenuItemAction(_ sender: Any) {
  530. // Login & Logout
  531. if KMLightMemberManager.manager.isLogin() {
  532. } else {
  533. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  534. }
  535. }
  536. @IBAction func logoutMenuItemAction(_ sender: Any) {
  537. // Login & Logout
  538. if KMLightMemberManager.manager.isLogin() {
  539. KMRequestServerManager.manager.logout { success, result in
  540. if success {
  541. KMPrint("登出成功")
  542. }
  543. }
  544. }
  545. }
  546. @IBAction func restoreMenuItemAction(_ sender: Any) {
  547. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  548. if isSuccess {
  549. } else {
  550. if error != .restoreSuccess {
  551. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  552. }
  553. }
  554. }
  555. }
  556. @objc func accountRefreshAction() {
  557. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  558. }
  559. }
  560. @objc func showAccount() {
  561. }
  562. @objc func resumePurchase() {
  563. }
  564. // MARK: help Menu
  565. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  566. KMTools.openQuickStartStudy()
  567. }
  568. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  569. KMTools.openFAQWebsite()
  570. }
  571. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  572. KMTools.openFreePDFTemplatesWebsite()
  573. }
  574. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  575. KMEmailSubWindowController().showWindow(nil)
  576. }
  577. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  578. KMTools.proposeNewFeature()
  579. }
  580. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  581. #if VERSION_FREE
  582. KMPrint("restoreSubscriptions ...")
  583. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  584. compareWindowVC.showWindowRestore(nil)
  585. #else
  586. var vc: KMToolCompareWindowController? = nil
  587. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  588. vc!.showWindowRestore(sender: (Any).self)
  589. #endif
  590. }
  591. // MARK:- DMG
  592. @objc func checkForUpdates(_ sender: NSMenuItem) {
  593. #if VERSION_DMG
  594. SUUpdater.shared().checkForUpdates(sender)
  595. #endif
  596. }
  597. @objc func enterLicense(_ sender: NSMenuItem) {
  598. #if VERSION_DMG
  599. if let tManager = VerificationManager.default() {
  600. let status = tManager.status
  601. if status == ActivityStatusVerifExpire {
  602. // let vc = KMVerificationWindowController.verification(with: .activateExpired)
  603. // vc?.showWindow(nil)
  604. } else if status == ActivityStatusVerification {
  605. // let vc = KMVerificationWindowController.verification(with: .info)
  606. // vc?.showWindow(nil)
  607. } else {
  608. // let vc = KMVerificationWindowController.verification(with: .activate)
  609. // vc?.showWindow(nil)
  610. }
  611. }
  612. #endif
  613. }
  614. @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) {
  615. #if VERSION_DMG
  616. var url = URL(string: "https://www.anyrecover.com/buy-pdf-editor-reader-converter")
  617. if SKInspectPublicTool.currentisLanguageHans() {
  618. url = URL(string: "https://www.anyrecover.com/buy-pdf-editor-reader-converter")
  619. }
  620. let tWorkSpace = NSWorkspace.shared
  621. if tWorkSpace.open(url!) == false {
  622. tWorkSpace.open(url!)
  623. }
  624. #endif
  625. // var url = URL(string: Store_Link + "?product_code=product_2")
  626. // let tWorkSpace = NSWorkspace.shared
  627. // if tWorkSpace.open(url!) == false {
  628. // tWorkSpace.open(url!)
  629. // }
  630. // let embeddedWC = KMPurchaseEmbeddedWindowController.currentFirstTrialWC("com.brother.pdfreaderpro.mac.product_2")
  631. // embeddedWC.showWindow(nil)
  632. // embeddedWC.window?.center()
  633. }
  634. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  635. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  636. #if VERSION_DMG
  637. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  638. #else
  639. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  640. #endif
  641. guard let url = URL(string: tStrHttpUrl) else {
  642. NSSound.beep()
  643. return
  644. }
  645. let tWorkSpace = NSWorkspace.shared
  646. if tWorkSpace.open(url) == false {
  647. tWorkSpace.open(url)
  648. }
  649. }
  650. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  651. var tStrHttpUrl = CrossPlatform_Link
  652. guard let url = URL(string: tStrHttpUrl) else {
  653. return
  654. }
  655. let tWorkSpace = NSWorkspace.shared
  656. if tWorkSpace.open(url) == false {
  657. tWorkSpace.open(url)
  658. }
  659. #if VERSION_DMG
  660. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  661. #endif
  662. }
  663. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  664. let tStrHttpUrl = Store_Edu_Link
  665. guard let url = URL(string: tStrHttpUrl) else {
  666. return
  667. }
  668. let tWorkSpace = NSWorkspace.shared
  669. if tWorkSpace.open(url) == false {
  670. tWorkSpace.open(url)
  671. }
  672. #if VERSION_DMG
  673. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  674. #endif
  675. }
  676. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  677. #if VERSION_DMG
  678. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  679. #else
  680. AIPurchaseWindowController.currentWC().showWindow(nil)
  681. #endif
  682. }
  683. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  684. if let win = KMLineInspector.shared.window {
  685. if win.isVisible {
  686. win.orderOut(sender)
  687. } else {
  688. win.orderFront(sender)
  689. }
  690. }
  691. }
  692. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  693. KMPrint("showDownloads ...")
  694. }
  695. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  696. self.reopenDocument(forPaths: [])
  697. }
  698. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  699. KMEmailSubWindowController().showWindow(nil)
  700. }
  701. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  702. KMTools.feekback()
  703. }
  704. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  705. KMTools.reportBug()
  706. }
  707. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  708. KMTools.reportGeneralQuestions()
  709. }
  710. }
  711. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  712. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  713. let action = menuItem.action
  714. if action == #selector(manageAcctounMenuAction) {
  715. self.updateLoginMenuItem()
  716. return KMLightMemberManager.manager.isLogin()
  717. }
  718. if action == #selector(loginMenuItemAction) {
  719. self.updateLoginMenuItem()
  720. return !KMLightMemberManager.manager.isLogin()
  721. }
  722. if action == #selector(logoutMenuItemAction) {
  723. self.updateLoginMenuItem()
  724. return KMLightMemberManager.manager.isLogin()
  725. }
  726. if (action == #selector(sharePageItemAction)) {
  727. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  728. return false
  729. }
  730. let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  731. return !isHome
  732. }
  733. if action == #selector(closeDocument) {
  734. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  735. if NSApp.mainWindow?.windowController != nil {
  736. return true
  737. }
  738. return false
  739. }
  740. let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false
  741. if isNewTab {
  742. return true
  743. }
  744. // let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  745. // return !isHome
  746. }
  747. return true
  748. }
  749. func updateLoginMenuItem() {
  750. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  751. if firstItem != nil {
  752. let item1 = firstItem?.item(withTag: 11)
  753. let item2 = firstItem?.item(withTag: 12)
  754. let item3 = firstItem?.item(withTag: 13)
  755. let item4 = firstItem?.item(withTag: 14)
  756. // let item5 = firstItem?.item(withTag: 15)
  757. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  758. // if KMLightMemberManager.manager.isLogin() {
  759. // item1?.title = KMLightMemberManager.manager.info.email
  760. // item1?.isHidden = false
  761. // item2?.isHidden = true
  762. // item3?.isHidden = false
  763. // item4?.isHidden = false
  764. //// item5?.isHidden = false
  765. // item6?.isHidden = false
  766. // } else {
  767. // item1?.isHidden = true
  768. // item2?.isHidden = false
  769. // item3?.isHidden = true
  770. // item4?.isHidden = true
  771. //// item5?.isHidden = true
  772. // item6?.isHidden = true
  773. // }
  774. item1?.isHidden = true
  775. item2?.isHidden = true
  776. item3?.isHidden = true
  777. item4?.isHidden = true
  778. // item5?.isHidden = true
  779. item6?.isHidden = true
  780. }
  781. }
  782. @objc func clickOutline(menuItem: NSMenuItem) {
  783. KMPrint("更新菜单栏")
  784. }
  785. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  786. return true
  787. }
  788. }
  789. #if VERSION_DMG
  790. extension AppDelegate : SUUpdaterDelegate {
  791. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  792. }
  793. func feedURLString(for updater: SUUpdater) -> String? {
  794. var hostURL = "https://static.anyrecover.com/download/"
  795. //#if DEBUG
  796. // hostURL = "http://test-pdf-pro.kdan.cn:3021/downloads/"
  797. //#else
  798. // hostURL = "https://www.pdfreaderpro.com/downloads/"
  799. //#endif
  800. return hostURL+NSLocalizedString("pdfull-mac-update.xml", comment: "")
  801. }
  802. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  803. return false
  804. }
  805. func upgradeAPP(with updater: SUUpdater) {
  806. let string = "macappstore://apps.apple.com/app/id825459243?mt=12"
  807. let url: URL = URL(string: string)!
  808. NSWorkspace.shared.open(url)
  809. }
  810. func upgradeButtonString(for updater: SUUpdater) -> String {
  811. return NSLocalizedString("PDFull", comment: "")
  812. }
  813. }
  814. #endif
  815. extension AppDelegate {
  816. // MARK: - Services Support
  817. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  818. var error: NSError?
  819. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  820. // Document opened successfully
  821. } else if let error = error {
  822. errorString = error.localizedDescription
  823. }
  824. }
  825. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  826. var error: NSError?
  827. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  828. // Document opened successfully
  829. } else if let error = error {
  830. errorString = error.localizedDescription
  831. }
  832. }
  833. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  834. var error: NSError?
  835. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  836. // Document opened successfully
  837. } else if let error = error {
  838. errorString = error.localizedDescription
  839. }
  840. }
  841. }
  842. extension AppDelegate: UNUserNotificationCenterDelegate {
  843. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  844. // 处理用户点击推送通知的操作
  845. completionHandler()
  846. }
  847. }