AppDelegate.swift 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. var rateWindowVC: KMRateWindowController!
  12. func applicationWillFinishLaunching(_ notification: Notification) {
  13. #if VERSION_FREE
  14. #if VERSION_DMG
  15. // CPDFKit.setLicenseKey("1vz4jXcu5aWfQMr627tGjHjWHG+72WKPzgwSoeGqDlRtLAxe4CTHas7qUep1D46CjreeqLWWV06cFepolm8wCBlZscJaV9/dCyDMi/zMTh47O+sIky0oYdusH/8+jyGruF4pgtinJ/oZg/P95jw4/E0HpoZ9AH9eGpD2XRy8mHk=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4rCrm/O2+fI9yUYXNZ/JY1KPbFCeKgG+lEVwrbGHrpAyXATqjrt8ApqRYhafFooQjwAFgayISwZT/pa4NjR459gu4aGVjtYuk+Uxs/kosIBwyxQV1SVCQFsC27oMGz5P/rBQYv0T/D0N0z+Um3U+I+tG7BHAIgXXXaVusko5CeqTvQgas5D7/+aJEhkQvgEI0O+1BYV01oFLnRch1j6tFihDymhFKcLuOq5fKgsuDdHcA==")
  16. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvM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QSTXQlmZfbxpitFoKX83UBkha60z3+yyZvjzxnVmPLWTnX0u13CDIXEvC3V6mR2aaKvVJnE5h5fVw9F2s3H5Q55YkTYg==")
  26. ComPDFUIConfig.initializeUIConfig()
  27. KMDesignToken.shared.parserExcel(withPath: "")
  28. }
  29. func applicationDidFinishLaunching(_ aNotification: Notification) {
  30. KMDataManager.default.initLaunchData()
  31. KMCheckInManager.default.initLaunchData()
  32. initNotifications()
  33. //通知
  34. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  35. if granted {
  36. KMPrint("User authorized notifications")
  37. } else {
  38. KMPrint("User denied notifications")
  39. }
  40. }
  41. /**本地推送测试
  42. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  43. if granted {
  44. // 创建本地推送通知
  45. let content = UNMutableNotificationContent()
  46. content.title = "Test Notification"
  47. content.body = "This is a test notification!"
  48. // 触发条件,例如延迟 5 秒触发
  49. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  50. // 创建通知请求
  51. let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
  52. // 添加通知请求到用户通知中心
  53. UNUserNotificationCenter.current().add(request) { error in
  54. if let error = error {
  55. print("Error adding notification request: \(error)")
  56. } else {
  57. print("Local notification scheduled")
  58. }
  59. }
  60. } else {
  61. print("User denied notifications")
  62. }
  63. }
  64. **/
  65. DispatchQueue.main.async {
  66. NSApplication.shared.registerForRemoteNotifications()
  67. }
  68. #if VERSION_DMG
  69. let updater = SUUpdater.shared()
  70. updater?.delegate = self
  71. updater?.automaticallyChecksForUpdates = true
  72. #else
  73. #endif
  74. NSApp.appearance = NSAppearance.current
  75. KMAnalytics.configure()
  76. //Firebase RemoteConfig
  77. #if VERSION_FREE
  78. KMKdanRemoteConfig.remoteConfig.fetch { _status, error in
  79. }
  80. #endif
  81. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  82. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  83. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  84. let sud = UserDefaults.standard
  85. if versionString.isEmpty == false {
  86. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  87. }
  88. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  89. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  90. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  91. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  92. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  93. sud.synchronize()
  94. }
  95. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  96. NSApp.servicesProvider = self
  97. KMKdanRemoteConfig.remoteConfig.fetchWithRemoteConfigCompletionHandler { status, error in
  98. }
  99. let token = UserDefaults.standard.value(forKey: "MemberAccessToken")
  100. if token is String {
  101. if (token as! String).count > 0 {
  102. KMMemberInfo.shared.access_token = token as! String
  103. KMUserInfoVCModel().refreshUserInfo { success, msg,dic in
  104. if success {
  105. KMMemberInfo.shared.isLogin = true
  106. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MemberCenterLoginSuccess"), object: nil)
  107. } else {
  108. KMMemberInfo.shared.isLogin = false
  109. }
  110. #if VERSION_DMG
  111. let model = KMProductModel.shared
  112. model.getDMGProductDatas(discountCode: "") { [weak self] success, result in
  113. }
  114. #endif
  115. KMNewUserGiftManager.default.loginProgressState = .success
  116. let cnt = KMCancelSubscribeSuccessWindowController.shared.couponsShowCount()
  117. if cnt == 1 { // 有显示过
  118. if KMCancelSubscribeSuccessWindowController.shared.appLaunchCountOfCoupons() == 2 {
  119. KMMemberCenterManager.judgeTrailCancel { success, resultModel, error in
  120. if success && resultModel?.result == true { // 试用退订
  121. KMCancelSubscribeSuccessWindowController.shared.openCouponsWindow()
  122. KMCheckInManager.default.trailCancel = true
  123. }
  124. }
  125. }
  126. }
  127. self.openWindowsForLogin()
  128. }
  129. } else {
  130. KMNewUserGiftManager.default.loginProgressState = .success
  131. openWindowsForLogin()
  132. }
  133. } else {
  134. #if VERSION_DMG
  135. let model = KMProductModel.shared
  136. model.getDMGProductDatas(discountCode: "") { [weak self] success, result in
  137. }
  138. #endif
  139. KMNewUserGiftManager.default.loginProgressState = .success
  140. openWindowsForLogin()
  141. }
  142. KMStatusBar.system()
  143. // MARK: 广告数据初始化
  144. var appName: KMAdvertisementAppNameType = .PDFReaderProMac
  145. #if VERSION_FREE
  146. #if VERSION_DMG
  147. appName = .PDFReaderProMacDMG
  148. #else
  149. #endif
  150. #else
  151. appName = .PDFReaderProMacPro
  152. #endif
  153. KMAdvertisementManager.manager.initConfig(appName: appName,
  154. subscribeType: .unknow,
  155. platform: .Mac)
  156. // 测试模式,默认false
  157. KMAdvertisementManager.manager.debug = true
  158. self.initMainMenu()
  159. /// pro
  160. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  161. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  162. reopenDocument(forPaths: [])
  163. KMPreference.shared.initDataForAppLaunch()
  164. self.initiRateData()
  165. let appleEventManager = NSAppleEventManager.shared()
  166. appleEventManager.setEventHandler(self,
  167. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  168. forEventClass: AEEventClass(kInternetEventClass),
  169. andEventID: AEEventID(kAEGetURL))
  170. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  171. #if VERSION_DMG
  172. VerificationManager.default()
  173. KMDMGProductsManager.shareInstance.getProductDatas()
  174. #else
  175. self.initiVersionData()
  176. IAPProductsManager.default().initIAP()
  177. #if VERSION_FREE
  178. if #available(macOS 12.0, *) {
  179. _ = TransactionObserver.shared
  180. } else {
  181. // Fallback on earlier versions
  182. }
  183. #endif
  184. #endif
  185. //AI相关
  186. AIInfoManager.default()
  187. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  188. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  189. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  190. var error: Unmanaged<CFError>?
  191. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  192. print("Failed to register font!")
  193. } else {
  194. print("Font registered successfully!")
  195. }
  196. }
  197. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  198. for item in appMenu!.items {
  199. if item.action == #selector(aiToolsAction) {
  200. if let tManager = VerificationManager.default() {
  201. let status = tManager.status
  202. if status == ActivityStatusNone {
  203. item.isHidden = true
  204. }
  205. }
  206. }
  207. }
  208. // initDidFinish()
  209. openWindowsForAppLaunch()
  210. }
  211. func initNotifications() {
  212. NotificationCenter.default.addObserver(self, selector: #selector(deviceActivateStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  213. NotificationCenter.default.addObserver(self, selector: #selector(iapSubscriptionLoadedNotification), name: .KMIAPSubscriptionLoaded, object: nil)
  214. NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: .deviceVerifyFinish, object: nil)
  215. NotificationCenter.default.addObserver(self, selector: #selector(iapProdcutLoadedNotification), name: .KMIAPProductLoaded, object: nil)
  216. NotificationCenter.default.addObserver(self, selector: #selector(advertisementDidLoadedNotification), name: NSNotification.Name(rawValue: KMAdvertisementDidLoadedNotificationName), object: nil)
  217. }
  218. func openWindowsForAppLaunch() {}
  219. func openWindowsForLogin() {
  220. if KMCancelSubscribeSuccessWindowController.shared.couponsShowCount() == 1 {
  221. KMCancelSubscribeSuccessWindowController.shared.recordAppLaunchCountOfCoupons()
  222. }
  223. // 新手礼窗口
  224. if KMNewUserGiftWindowController.shared.needShow() {
  225. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  226. KMNewUserGiftWindowController.shared.openWindow()
  227. }
  228. } else {
  229. #if VERSION_DMG
  230. #else
  231. #if VERSION_FREE
  232. let iVersion = iVersion.sharedInstance()
  233. if iVersion?.shouldCheckForNewVersion() == true {
  234. iVersion?.checkForNewVersion()
  235. } else {
  236. // if KMWinBackWindowController.shared.needShow() {
  237. // KMWinBackWindowController.shared.openWindow()
  238. // }
  239. if KMMemberInfo.shared.isLogin == false {
  240. let cnt = KMCancelSubscribeSuccessWindowController.shared.couponsShowCount()
  241. if cnt == 1 && KMNewUserGiftManager.default.fetchReceiptProgressState != .none { // 有显示过 && 票据已经请求完成
  242. if KMCancelSubscribeSuccessWindowController.shared.appLaunchCountOfCoupons() == 3 {
  243. KMCancelSubscribeSuccessWindowController.shared.openCouponsWindow()
  244. }
  245. }
  246. if KMCheckInManager.default.advancedYearSubscribeTrailCancelForLocal() {
  247. KMCheckInManager.default.openCancelSubscribeWindow()
  248. }
  249. }
  250. }
  251. #endif
  252. #endif
  253. }
  254. // 退订挽回窗口
  255. KMCheckInManager.default.fetchCancelSubscribe(callback: nil)
  256. // 签到
  257. KMCheckInManager.default.checkIn(refreshData: true, callback: nil)
  258. }
  259. func openWindowForIAPSubscriptionLoaded() {
  260. // 新手礼窗口
  261. if KMNewUserGiftWindowController.shared.needShow() {
  262. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  263. KMNewUserGiftWindowController.shared.openWindow()
  264. }
  265. } else {
  266. #if VERSION_DMG
  267. #else
  268. #if VERSION_FREE
  269. let iVersion = iVersion.sharedInstance()
  270. if iVersion?.shouldCheckForNewVersion() == true {
  271. iVersion?.checkForNewVersion()
  272. } else {
  273. // if KMWinBackWindowController.shared.needShow() {
  274. // KMWinBackWindowController.shared.openWindow()
  275. // }
  276. }
  277. if KMNewUserGiftManager.default.loginProgressState != .none && KMCheckInManager.default.advancedYearSubscribeTrailCancelForLocal() {
  278. KMCheckInManager.default.openCancelSubscribeWindow()
  279. }
  280. if KMNewUserGiftManager.default.loginProgressState != .none && KMMemberInfo.shared.isLogin == false {
  281. let cnt = KMCancelSubscribeSuccessWindowController.shared.couponsShowCount()
  282. if cnt == 1 { // 有显示过
  283. if KMCancelSubscribeSuccessWindowController.shared.appLaunchCountOfCoupons() == 3 {
  284. KMCancelSubscribeSuccessWindowController.shared.openCouponsWindow()
  285. }
  286. }
  287. }
  288. #endif
  289. #endif
  290. }
  291. }
  292. func openWindowForAdvertisementDidLoaded() {
  293. // 新手礼窗口
  294. if KMNewUserGiftWindowController.shared.needShow() {
  295. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  296. KMNewUserGiftWindowController.shared.openWindow()
  297. }
  298. } else {
  299. #if VERSION_DMG
  300. #else
  301. #if VERSION_FREE
  302. let iVersion = iVersion.sharedInstance()
  303. if iVersion?.shouldCheckForNewVersion() == true {
  304. iVersion?.checkForNewVersion()
  305. }
  306. #endif
  307. #endif
  308. }
  309. }
  310. func initDidFinish() {
  311. #if VERSION_DMG
  312. // DispatchQueue.main.async {
  313. //// DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
  314. // let memberInfo: KMMemberInfo = KMMemberInfo.shared
  315. // if KMMemberInfo.shared.isMemberAllFunction == false && memberInfo.isLogin == false {
  316. // self.checkLoginAndPrompt()
  317. // }
  318. // }
  319. #endif
  320. }
  321. func checkLoginAndPrompt() {
  322. let lastPromptDateKey = "kUserfreehaveDMGAIlastPromptDate"
  323. let userDefaults = UserDefaults.standard
  324. let lastPromptDate = userDefaults.object(forKey: lastPromptDateKey) as? Date
  325. if let lastDate = lastPromptDate {
  326. // 如果距离上次提示超过7天,则再次提示
  327. if Calendar.current.date(byAdding: .day, value: 7, to: lastDate)! <= Date() {
  328. KMOpenDMGPopupBootWC.shared.showWindow(nil)
  329. userDefaults.set(Date(), forKey: lastPromptDateKey) // 更新提示日期
  330. }
  331. } else {
  332. // 如果没有记录,则显示提示
  333. KMOpenDMGPopupBootWC.shared.showWindow(nil)
  334. userDefaults.set(Date(), forKey: lastPromptDateKey) // 保存提示日期
  335. }
  336. }
  337. func initiRateData() {
  338. iRate.sharedInstance().delegate = self
  339. #if VERSION_FREE
  340. iRate.sharedInstance().appStoreID = 919472673
  341. #else
  342. iRate.sharedInstance().appStoreID = 825459243
  343. #endif
  344. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  345. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  346. }
  347. //MARK: iRateDelegate
  348. func iRateUserDidDeclineToRateApp() {
  349. KMVerificationWindowController.verificationFeedback()
  350. }
  351. func iRateShouldPromptForRating() -> Bool {
  352. // let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  353. // if !notShow {
  354. // UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  355. // UserDefaults.standard.synchronize()
  356. // NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  357. // }
  358. //
  359. // self.rateWindowVC = KMRateWindowController.init(windowNibName: "KMRateWindowController")
  360. //
  361. // self.rateWindowVC.closeBlock = { wc in
  362. //
  363. // }
  364. // self.rateWindowVC.closeBlock = { wc in
  365. //
  366. // }
  367. // self.rateWindowVC.showWindow(nil)
  368. return false
  369. }
  370. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  371. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  372. let url = URL(string: urlString) {
  373. // 在这里处理收到的 URL Scheme
  374. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  375. KMPrint("Path: \(url.path)")
  376. if NSApp.mainWindow == nil {
  377. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  378. launchApp(bundleIdentifier: bundleIdentifier)
  379. }
  380. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  381. #if VERSION_DMG
  382. // 执行相应的操作
  383. if url.scheme == "subscriptiondmgschemes" {
  384. if urlString.contains("open=expired") {
  385. KMPrint("刷新用户信息")
  386. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  387. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  388. } else {
  389. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  390. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  391. }
  392. }
  393. } else if urlString.contains("open=success") {
  394. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  395. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  396. } else {
  397. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  398. if isSuccess {
  399. } else {
  400. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  401. }
  402. }
  403. }
  404. }
  405. }
  406. #endif
  407. #if VERSION_FREE
  408. // 执行相应的操作
  409. if url.scheme == "subscriptionSchemes" {
  410. //刷新用户信息
  411. KMRequestServerManager.manager.getUserInfo { success, data, error, isLocal in
  412. }
  413. if url.path == "/open" {
  414. // 执行打开操作
  415. } else if url.path == "/close" {
  416. // 执行关闭操作
  417. }
  418. }
  419. #endif
  420. }
  421. }
  422. }
  423. func launchApp(bundleIdentifier: String) {
  424. let workspace = NSWorkspace.shared
  425. // Launch the application with the specified bundle identifier
  426. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  427. do {
  428. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  429. } catch {
  430. print("Error launching the application: \(error)")
  431. }
  432. } else {
  433. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  434. }
  435. }
  436. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  437. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  438. print("Device token:", token)
  439. }
  440. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  441. }
  442. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  443. if !flag {
  444. let browser: KMBrowser = KMBrowser.init()
  445. browser.windowController = KMBrowserWindowController.init(browser: browser)
  446. browser.addHomeTabContents()
  447. browser.windowController.showWindow(self)
  448. }
  449. return flag
  450. }
  451. @IBAction func closeDocument(_ sender: Any) {
  452. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  453. guard let windowControler = NSApp.mainWindow?.windowController else {
  454. return
  455. }
  456. windowControler.window?.performClose(nil)
  457. return
  458. }
  459. let windowControler = NSApp.mainWindow?.windowController as? KMBrowserWindowController
  460. if let data = windowControler?.browser, data.tabCount() >= 2 { // 有两个以上的标签
  461. if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应
  462. return
  463. }
  464. }
  465. if let browser = windowControler?.browser {
  466. if browser.tabCount() == 1 {
  467. windowControler?.window?.close()
  468. if KMAdvertisementManager.manager.appClosedCount == 0 {
  469. KMAdvertisementManager.manager.appClosedCount = 1
  470. }
  471. } else {
  472. if let _ = windowControler?.window?.attachedSheet {
  473. NSSound.beep()
  474. return
  475. }
  476. browser.closeTab()
  477. }
  478. } else {
  479. windowControler?.window?.close()
  480. }
  481. }
  482. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  483. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  484. return false
  485. }
  486. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  487. if (filepaths == nil || filepaths!.count == 0) {
  488. return false
  489. }
  490. DispatchQueue.main.async {
  491. for filepath in filepaths! {
  492. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  493. }
  494. }
  495. }
  496. return false
  497. }
  498. func applicationWillTerminate(_ aNotification: Notification) {
  499. if (NSDocumentController.shared.documents.count > 0) {
  500. var filepaths: [String] = []
  501. for document in NSDocumentController.shared.documents {
  502. // KMPrint(document.fileURL as Any)
  503. if (document.fileURL?.path != nil) {
  504. filepaths.append((document.fileURL?.path)!)
  505. }
  506. }
  507. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  508. } else {
  509. KMPreferenceManager.shared.lastOpenFilepaths = nil
  510. }
  511. }
  512. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  513. return true
  514. }
  515. // MARK: private
  516. func reopenDocument(forPaths paths: [String]) -> Void {
  517. let browser = KMBrowser.init() as KMBrowser
  518. browser.windowController = KMBrowserWindowController.init(browser: browser)
  519. browser.addHomeTabContents()
  520. browser.windowController.showWindow(self)
  521. }
  522. @objc private func _themeChanged(_ sender: Notification) {
  523. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  524. if isDarkModel {
  525. NSApp.appearance = NSAppearance(named: .darkAqua)
  526. } else {
  527. NSApp.appearance = NSAppearance(named: .aqua)
  528. }
  529. // if let data = NSApp.appearance?.name, data == .darkAqua {
  530. // NSApp.appearance = .init(named: .aqua)
  531. // } else {
  532. // NSApp.appearance = .init(named: .darkAqua)
  533. // }
  534. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  535. }
  536. // MARK: - Noti Actioins
  537. @objc func AIDeviceStatusChangeNotification() {
  538. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  539. self.refreshAIMenuItemInfo()
  540. }
  541. }
  542. @objc func deviceActivateStatusChangeNotification() {
  543. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  544. for item in appMenu!.items {
  545. if item.action == #selector(aiToolsAction) {
  546. if let tManager = VerificationManager.default() {
  547. let status = tManager.status
  548. if status == ActivityStatusNone {
  549. item.isHidden = true
  550. }
  551. }
  552. }
  553. }
  554. initDidFinish()
  555. }
  556. @objc func iapSubscriptionLoadedNotification() {
  557. KMMainThreadExecute {
  558. self.openWindowForIAPSubscriptionLoaded()
  559. }
  560. }
  561. @objc func iapProdcutLoadedNotification() {
  562. KMNewUserGiftManager.default.iapProductLoadProgressState = .success
  563. KMMainThreadExecute {
  564. self.openWindowForIAPSubscriptionLoaded()
  565. }
  566. }
  567. @objc func advertisementDidLoadedNotification() {
  568. KMMainThreadExecute {
  569. self.openWindowForAdvertisementDidLoaded()
  570. }
  571. }
  572. @objc func deviceVerifyFinishNotification() {
  573. KMNewUserGiftManager.default.fetchReceiptProgressState = .success
  574. KMMainThreadExecute {
  575. self.openWindowForIAPSubscriptionLoaded()
  576. }
  577. }
  578. func refreshAIMenuItemInfo() -> Void {
  579. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  580. for item in appMenu!.items {
  581. if item.action == #selector(aiToolsAction) {
  582. item.isHidden = true
  583. }
  584. }
  585. }
  586. //MARK: - iVersion
  587. func initiVersionData() -> Void{
  588. #if VERSION_DMG
  589. #else
  590. let tVersion = iVersion.sharedInstance()
  591. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  592. var tStr = "New Update Available"
  593. tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n"
  594. tVersion?.versionLabelFormat = ""
  595. tVersion?.groupNotesByVersion = true
  596. tVersion?.showOnFirstLaunch = false
  597. tVersion?.delegate = self
  598. tVersion?.checkPeriod = 2
  599. tVersion?.remindPeriod = 5
  600. let infoDictionary = Bundle .main.infoDictionary!
  601. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  602. if appName.count < 1 {
  603. appName = infoDictionary["CFBundleName"] as! String
  604. }
  605. tStr = "The new version of %@ is available now. Go update for new features.";
  606. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  607. tStr = String(format: tStr, appName)
  608. tVersion?.inThisVersionTitle = tStr
  609. tStr = "UPDATE NOW";
  610. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  611. tStr = "LATER";
  612. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  613. tVersion!.ignoreButtonLabel = ""
  614. #endif
  615. }
  616. // MARK: - Menu
  617. func initMainMenu() {
  618. // 处理菜单栏多语
  619. let mainMenu = NSApp.mainMenu
  620. if (mainMenu == nil) {
  621. return
  622. }
  623. for menu in mainMenu!.items {
  624. let subMenu = menu.submenu
  625. for item in subMenu!.items {
  626. item.title = NSLocalizedString(item.title, comment: "")
  627. let itemSubMenu = item.submenu
  628. if (itemSubMenu == nil) {
  629. continue
  630. }
  631. for item in itemSubMenu!.items {
  632. item.title = NSLocalizedString(item.title, comment: "")
  633. let itemSubMenu = item.submenu
  634. if (itemSubMenu == nil) {
  635. continue
  636. }
  637. for item in itemSubMenu!.items {
  638. item.title = NSLocalizedString(item.title, comment: "")
  639. }
  640. }
  641. }
  642. }
  643. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  644. #if VERSION_DMG
  645. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 3)
  646. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4)
  647. // if ([VerificationManager manager].needUpgradeLicense == NO) {
  648. if VerificationManager.default().needUpgradeLicense {
  649. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5)
  650. }
  651. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  652. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  653. #endif
  654. #if !VERSION_DMG
  655. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  656. #endif
  657. if let items = PDFOfficeMenu?.items {
  658. for menu in items {
  659. let ranges = menu.title.ranges(of: "PDF Reader Pro")
  660. if let _range = ranges.range.first {
  661. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  662. }
  663. }
  664. }
  665. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("Volume Discount", comment: "")) {
  666. item.isHidden = true
  667. }
  668. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("One License for Mac and Windows", comment: "")) {
  669. item.isHidden = true
  670. }
  671. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("Education Discount", comment: "")) {
  672. item.isHidden = true
  673. }
  674. let fileMenu = mainMenu?.item(at: 1)?.submenu
  675. var shareItem: NSMenuItem?
  676. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  677. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  678. fileMenu?.insertItem(shareItem!, at: item.index)
  679. fileMenu?.insertItem(.separator(), at: item.index)
  680. } else {
  681. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  682. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  683. }
  684. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  685. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  686. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  687. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  688. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  689. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  690. }
  691. @objc func sharePageItemAction(sender: NSMenuItem) {
  692. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  693. return
  694. }
  695. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  696. let model = windowControler.browser?.tabStripModel
  697. if let cnt = model?.count(), cnt <= 0 {
  698. return
  699. }
  700. if let data = model?.activeTabContents()?.isHome, data {
  701. return
  702. }
  703. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  704. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  705. let represent : NSSharingService = sender.representedObject as! NSSharingService
  706. represent.perform(withItems: [document.fileURL as Any])
  707. return
  708. }
  709. let represent : NSSharingService = sender.representedObject as! NSSharingService
  710. represent.perform(withItems: [document.fileURL as Any])
  711. }
  712. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  713. KMPrint("deviceCameraMenuItemAciton")
  714. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil)
  715. }
  716. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  717. KMPrint("deviceScannerMenuItemAciton")
  718. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil)
  719. }
  720. // MARK: PDF Reader Pro Menu
  721. @IBAction func openPreferenceWindow(_ sender: Any) {
  722. KMPreferenceController.shared.showWindow(self)
  723. }
  724. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  725. if KMLightMemberManager.manager.isLogin() {
  726. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  727. }
  728. }
  729. @IBAction func loginMenuItemAction(_ sender: Any) {
  730. // Login & Logout
  731. if KMLightMemberManager.manager.isLogin() {
  732. } else {
  733. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  734. }
  735. }
  736. @IBAction func logoutMenuItemAction(_ sender: Any) {
  737. // Login & Logout
  738. if KMLightMemberManager.manager.isLogin() {
  739. KMRequestServerManager.manager.logout { success, result in
  740. if success {
  741. KMPrint("登出成功")
  742. }
  743. }
  744. }
  745. }
  746. @IBAction func restoreMenuItemAction(_ sender: Any) {
  747. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  748. if isSuccess {
  749. } else {
  750. if error != .restoreSuccess {
  751. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  752. }
  753. }
  754. }
  755. }
  756. @objc func accountRefreshAction() {
  757. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  758. }
  759. }
  760. @objc func showAccount() {
  761. }
  762. @objc func resumePurchase() {
  763. }
  764. // MARK: help Menu
  765. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  766. KMTools.openQuickStartStudy()
  767. }
  768. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  769. KMTools.openFAQWebsite()
  770. }
  771. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  772. KMTools.openMoreProductWebsite()
  773. }
  774. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  775. KMTools.openFreePDFTemplatesWebsite()
  776. }
  777. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  778. KMEmailSubWindowController().showWindow(nil)
  779. }
  780. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  781. KMTools.openComPDFKitPowerWebsite()
  782. }
  783. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  784. KMTools.proposeNewFeature()
  785. }
  786. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  787. KMTools.rateUs()
  788. }
  789. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  790. // if(KMMemberInfo.shared.isLogin == false) {
  791. // KMLoginWindowsController.shared.showWindow(nil)
  792. // return
  793. // }
  794. #if !VERSION_DMG
  795. KMPrint("restoreSubscriptions ...")
  796. KMProductCompareWC.shared.orientation = false
  797. KMProductCompareWC.shared.showWindowRestore(sender)
  798. #else
  799. var vc: KMToolCompareWindowController? = nil
  800. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  801. vc!.showWindowRestore(sender: (Any).self)
  802. #endif
  803. }
  804. // MARK:- DMG
  805. @objc func checkForUpdates(_ sender: NSMenuItem) {
  806. #if VERSION_DMG
  807. SUUpdater.shared().checkForUpdates(sender)
  808. #endif
  809. }
  810. @objc func enterLicense(_ sender: NSMenuItem) {
  811. #if VERSION_DMG
  812. if let tManager = VerificationManager.default() {
  813. let status = tManager.status
  814. if status == ActivityStatusVerifExpire {
  815. let vc = KMVerificationWindowController.verification(with: .activateExpired)
  816. vc?.showWindow(nil)
  817. } else if status == ActivityStatusVerification {
  818. let vc = KMVerificationWindowController.verification(with: .info)
  819. vc?.showWindow(nil)
  820. } else {
  821. let vc = KMVerificationWindowController.verification(with: .activate)
  822. vc?.showWindow(nil)
  823. }
  824. }
  825. #endif
  826. }
  827. @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) {
  828. #if VERSION_DMG
  829. // var url = URL(string: Store_Link + "?product_code=product_2")
  830. // let tWorkSpace = NSWorkspace.shared
  831. // if tWorkSpace.open(url!) == false {
  832. // tWorkSpace.open(url!)
  833. // }
  834. let embeddedWC = DMGEmbeddedOldWC.currentFirstTrialWC("com.brother.pdfreaderpro.mac.product_2")
  835. embeddedWC.showWindow(nil)
  836. embeddedWC.window?.center()
  837. #endif
  838. }
  839. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  840. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  841. #if VERSION_DMG
  842. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  843. #else
  844. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  845. #endif
  846. guard let url = URL(string: tStrHttpUrl) else {
  847. NSSound.beep()
  848. return
  849. }
  850. let tWorkSpace = NSWorkspace.shared
  851. if tWorkSpace.open(url) == false {
  852. tWorkSpace.open(url)
  853. }
  854. }
  855. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  856. var tStrHttpUrl = CrossPlatform_Link
  857. guard let url = URL(string: tStrHttpUrl) else {
  858. return
  859. }
  860. let tWorkSpace = NSWorkspace.shared
  861. if tWorkSpace.open(url) == false {
  862. tWorkSpace.open(url)
  863. }
  864. #if VERSION_DMG
  865. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  866. #endif
  867. }
  868. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  869. let tStrHttpUrl = Store_Edu_Link
  870. guard let url = URL(string: tStrHttpUrl) else {
  871. return
  872. }
  873. let tWorkSpace = NSWorkspace.shared
  874. if tWorkSpace.open(url) == false {
  875. tWorkSpace.open(url)
  876. }
  877. #if VERSION_DMG
  878. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  879. #endif
  880. }
  881. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  882. #if VERSION_DMG
  883. KMProductCompareWC.shared.orientation = false
  884. KMProductCompareWC.shared.showWindow(nil)
  885. #else
  886. AIPurchaseWindowController.currentWC().showWindow(nil)
  887. #endif
  888. }
  889. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  890. if let win = KMLineInspector.shared.window {
  891. if win.isVisible {
  892. win.orderOut(sender)
  893. } else {
  894. win.orderFront(sender)
  895. }
  896. }
  897. }
  898. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  899. KMPrint("showDownloads ...")
  900. }
  901. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  902. self.reopenDocument(forPaths: [])
  903. }
  904. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  905. KMEmailSubWindowController().showWindow(nil)
  906. }
  907. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  908. KMTools.feekback()
  909. }
  910. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  911. KMTools.reportBug()
  912. }
  913. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  914. KMTools.reportGeneralQuestions()
  915. }
  916. }
  917. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  918. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  919. let action = menuItem.action
  920. if action == #selector(manageAcctounMenuAction) {
  921. self.updateLoginMenuItem()
  922. return KMLightMemberManager.manager.isLogin()
  923. }
  924. if action == #selector(loginMenuItemAction) {
  925. self.updateLoginMenuItem()
  926. return !KMLightMemberManager.manager.isLogin()
  927. }
  928. if action == #selector(pdftoOfficeMenuItemAction) {
  929. if KMMemberInfo.shared.is_advanced_year_subscribe() {
  930. menuItem.isHidden = true
  931. return false;
  932. }
  933. }
  934. if action == #selector(logoutMenuItemAction) {
  935. self.updateLoginMenuItem()
  936. return KMLightMemberManager.manager.isLogin()
  937. }
  938. if (action == #selector(sharePageItemAction)) {
  939. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  940. return false
  941. }
  942. let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  943. return !isHome
  944. }
  945. if action == #selector(closeDocument) {
  946. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  947. if NSApp.mainWindow?.windowController != nil {
  948. return true
  949. }
  950. return false
  951. }
  952. let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false
  953. if isNewTab {
  954. return true
  955. }
  956. // let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  957. // return !isHome
  958. }
  959. return true
  960. }
  961. func updateLoginMenuItem() {
  962. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  963. if firstItem != nil {
  964. let item1 = firstItem?.item(withTag: 11)
  965. let item2 = firstItem?.item(withTag: 12)
  966. let item3 = firstItem?.item(withTag: 13)
  967. let item4 = firstItem?.item(withTag: 14)
  968. // let item5 = firstItem?.item(withTag: 15)
  969. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  970. // if KMLightMemberManager.manager.isLogin() {
  971. // item1?.title = KMLightMemberManager.manager.info.email
  972. // item1?.isHidden = false
  973. // item2?.isHidden = true
  974. // item3?.isHidden = false
  975. // item4?.isHidden = false
  976. //// item5?.isHidden = false
  977. // item6?.isHidden = false
  978. // } else {
  979. // item1?.isHidden = true
  980. // item2?.isHidden = false
  981. // item3?.isHidden = true
  982. // item4?.isHidden = true
  983. //// item5?.isHidden = true
  984. // item6?.isHidden = true
  985. // }
  986. item1?.isHidden = true
  987. item2?.isHidden = true
  988. item3?.isHidden = true
  989. item4?.isHidden = true
  990. // item5?.isHidden = true
  991. item6?.isHidden = true
  992. }
  993. }
  994. @objc func clickOutline(menuItem: NSMenuItem) {
  995. KMPrint("更新菜单栏")
  996. }
  997. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  998. return true
  999. }
  1000. }
  1001. #if VERSION_DMG
  1002. extension AppDelegate : SUUpdaterDelegate {
  1003. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  1004. }
  1005. func feedURLString(for updater: SUUpdater) -> String? {
  1006. var hostURL = "https://www.pdfreaderpro.com/downloads/"
  1007. #if DEBUG
  1008. hostURL = "http://test-pdf-pro.kdan.cn:3021/downloads/"
  1009. #else
  1010. hostURL = "https://www.pdfreaderpro.com/downloads/"
  1011. #endif
  1012. return hostURL+NSLocalizedString("pdfreaderprocast.xml", comment: "")
  1013. }
  1014. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  1015. return false
  1016. }
  1017. func upgradeAPP(with updater: SUUpdater) {
  1018. let string = "macappstore://apps.apple.com/app/id825459243?mt=12"
  1019. let url: URL = URL(string: string)!
  1020. NSWorkspace.shared.open(url)
  1021. }
  1022. func upgradeButtonString(for updater: SUUpdater) -> String {
  1023. return NSLocalizedString("PDF Reader Pro", comment: "")
  1024. }
  1025. }
  1026. #endif
  1027. extension AppDelegate: iVersionDelegate {
  1028. func iVersionShouldCheckForNewVersion() -> Bool {
  1029. #if VERSION_FREE
  1030. if KMNewUserGiftWindowController.shared.needShowForlocalCheck() == false {
  1031. return true
  1032. }
  1033. let appFirstLaunch = KMDataManager.default.appFirstLaunch
  1034. let appFirstLaunchForUpdate = KMDataManager.default.appFirstLaunchForUpdate
  1035. if appFirstLaunch == false && appFirstLaunchForUpdate == false {
  1036. // 不是首次启动 或 不是更新后首次启动
  1037. return true
  1038. }
  1039. if KMNewUserGiftManager.default.progressState == .none {
  1040. return false
  1041. }
  1042. return KMNewUserGiftWindowController.shared.needShow() == false
  1043. #else
  1044. return true
  1045. #endif
  1046. }
  1047. }
  1048. extension AppDelegate {
  1049. // MARK: - Services Support
  1050. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  1051. var error: NSError?
  1052. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  1053. // Document opened successfully
  1054. } else if let error = error {
  1055. errorString = error.localizedDescription
  1056. }
  1057. }
  1058. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  1059. var error: NSError?
  1060. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  1061. // Document opened successfully
  1062. } else if let error = error {
  1063. errorString = error.localizedDescription
  1064. }
  1065. }
  1066. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  1067. var error: NSError?
  1068. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  1069. // Document opened successfully
  1070. } else if let error = error {
  1071. errorString = error.localizedDescription
  1072. }
  1073. }
  1074. }
  1075. extension AppDelegate: UNUserNotificationCenterDelegate {
  1076. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  1077. // 处理用户点击推送通知的操作
  1078. completionHandler()
  1079. }
  1080. }