AppDelegate.swift 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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+0IQ0EU1u9Wp7IVHvMsHpPe/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mZfbxpitFoKX83UBkha60z3+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. }
  247. }
  248. #endif
  249. #endif
  250. }
  251. // 退订挽回窗口
  252. KMCheckInManager.default.fetchCancelSubscribe(callback: nil)
  253. // 签到
  254. KMCheckInManager.default.checkIn(refreshData: true, callback: nil)
  255. }
  256. func openWindowForIAPSubscriptionLoaded() {
  257. // 新手礼窗口
  258. if KMNewUserGiftWindowController.shared.needShow() {
  259. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  260. KMNewUserGiftWindowController.shared.openWindow()
  261. }
  262. } else {
  263. #if VERSION_DMG
  264. #else
  265. #if VERSION_FREE
  266. let iVersion = iVersion.sharedInstance()
  267. if iVersion?.shouldCheckForNewVersion() == true {
  268. iVersion?.checkForNewVersion()
  269. } else {
  270. if KMWinBackWindowController.shared.needShow() {
  271. KMWinBackWindowController.shared.openWindow()
  272. }
  273. }
  274. if KMCheckInManager.default.advancedYearSubscribeTrailCancelForLocal() {
  275. KMCheckInManager.default.openCancelSubscribeWindow()
  276. }
  277. if KMNewUserGiftManager.default.loginProgressState != .none && KMMemberInfo.shared.isLogin == false {
  278. let cnt = KMCancelSubscribeSuccessWindowController.shared.couponsShowCount()
  279. if cnt == 1 { // 有显示过
  280. if KMCancelSubscribeSuccessWindowController.shared.appLaunchCountOfCoupons() == 3 {
  281. KMCancelSubscribeSuccessWindowController.shared.openCouponsWindow()
  282. }
  283. }
  284. }
  285. #endif
  286. #endif
  287. }
  288. }
  289. func openWindowForAdvertisementDidLoaded() {
  290. // 新手礼窗口
  291. if KMNewUserGiftWindowController.shared.needShow() {
  292. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  293. KMNewUserGiftWindowController.shared.openWindow()
  294. }
  295. } else {
  296. #if VERSION_DMG
  297. #else
  298. #if VERSION_FREE
  299. let iVersion = iVersion.sharedInstance()
  300. if iVersion?.shouldCheckForNewVersion() == true {
  301. iVersion?.checkForNewVersion()
  302. }
  303. #endif
  304. #endif
  305. }
  306. }
  307. func initDidFinish() {
  308. #if VERSION_DMG
  309. // DispatchQueue.main.async {
  310. //// DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
  311. // let memberInfo: KMMemberInfo = KMMemberInfo.shared
  312. // if KMMemberInfo.shared.isMemberAllFunction == false && memberInfo.isLogin == false {
  313. // self.checkLoginAndPrompt()
  314. // }
  315. // }
  316. #endif
  317. }
  318. func checkLoginAndPrompt() {
  319. let lastPromptDateKey = "kUserfreehaveDMGAIlastPromptDate"
  320. let userDefaults = UserDefaults.standard
  321. let lastPromptDate = userDefaults.object(forKey: lastPromptDateKey) as? Date
  322. if let lastDate = lastPromptDate {
  323. // 如果距离上次提示超过7天,则再次提示
  324. if Calendar.current.date(byAdding: .day, value: 7, to: lastDate)! <= Date() {
  325. KMOpenDMGPopupBootWC.shared.showWindow(nil)
  326. userDefaults.set(Date(), forKey: lastPromptDateKey) // 更新提示日期
  327. }
  328. } else {
  329. // 如果没有记录,则显示提示
  330. KMOpenDMGPopupBootWC.shared.showWindow(nil)
  331. userDefaults.set(Date(), forKey: lastPromptDateKey) // 保存提示日期
  332. }
  333. }
  334. func initiRateData() {
  335. iRate.sharedInstance().delegate = self
  336. #if VERSION_FREE
  337. iRate.sharedInstance().appStoreID = 919472673
  338. #else
  339. iRate.sharedInstance().appStoreID = 825459243
  340. #endif
  341. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  342. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  343. }
  344. //MARK: iRateDelegate
  345. func iRateUserDidDeclineToRateApp() {
  346. KMVerificationWindowController.verificationFeedback()
  347. }
  348. func iRateShouldPromptForRating() -> Bool {
  349. // let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  350. // if !notShow {
  351. // UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  352. // UserDefaults.standard.synchronize()
  353. // NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  354. // }
  355. //
  356. // self.rateWindowVC = KMRateWindowController.init(windowNibName: "KMRateWindowController")
  357. //
  358. // self.rateWindowVC.closeBlock = { wc in
  359. //
  360. // }
  361. // self.rateWindowVC.closeBlock = { wc in
  362. //
  363. // }
  364. // self.rateWindowVC.showWindow(nil)
  365. return false
  366. }
  367. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  368. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  369. let url = URL(string: urlString) {
  370. // 在这里处理收到的 URL Scheme
  371. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  372. KMPrint("Path: \(url.path)")
  373. if NSApp.mainWindow == nil {
  374. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  375. launchApp(bundleIdentifier: bundleIdentifier)
  376. }
  377. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  378. #if VERSION_DMG
  379. // 执行相应的操作
  380. if url.scheme == "subscriptiondmgschemes" {
  381. if urlString.contains("open=expired") {
  382. KMPrint("刷新用户信息")
  383. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  384. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  385. } else {
  386. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  387. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  388. }
  389. }
  390. } else if urlString.contains("open=success") {
  391. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  392. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  393. } else {
  394. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  395. if isSuccess {
  396. } else {
  397. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  398. }
  399. }
  400. }
  401. }
  402. }
  403. #endif
  404. #if VERSION_FREE
  405. // 执行相应的操作
  406. if url.scheme == "subscriptionSchemes" {
  407. //刷新用户信息
  408. KMRequestServerManager.manager.getUserInfo { success, data, error, isLocal in
  409. }
  410. if url.path == "/open" {
  411. // 执行打开操作
  412. } else if url.path == "/close" {
  413. // 执行关闭操作
  414. }
  415. }
  416. #endif
  417. }
  418. }
  419. }
  420. func launchApp(bundleIdentifier: String) {
  421. let workspace = NSWorkspace.shared
  422. // Launch the application with the specified bundle identifier
  423. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  424. do {
  425. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  426. } catch {
  427. print("Error launching the application: \(error)")
  428. }
  429. } else {
  430. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  431. }
  432. }
  433. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  434. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  435. print("Device token:", token)
  436. }
  437. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  438. }
  439. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  440. if !flag {
  441. let browser: KMBrowser = KMBrowser.init()
  442. browser.windowController = KMBrowserWindowController.init(browser: browser)
  443. browser.addHomeTabContents()
  444. browser.windowController.showWindow(self)
  445. }
  446. return flag
  447. }
  448. @IBAction func closeDocument(_ sender: Any) {
  449. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  450. guard let windowControler = NSApp.mainWindow?.windowController else {
  451. return
  452. }
  453. windowControler.window?.performClose(nil)
  454. return
  455. }
  456. let windowControler = NSApp.mainWindow?.windowController as? KMBrowserWindowController
  457. if let data = windowControler?.browser, data.tabCount() >= 2 { // 有两个以上的标签
  458. if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应
  459. return
  460. }
  461. }
  462. if let browser = windowControler?.browser {
  463. if browser.tabCount() == 1 {
  464. windowControler?.window?.close()
  465. if KMAdvertisementManager.manager.appClosedCount == 0 {
  466. KMAdvertisementManager.manager.appClosedCount = 1
  467. }
  468. } else {
  469. if let _ = windowControler?.window?.attachedSheet {
  470. NSSound.beep()
  471. return
  472. }
  473. browser.closeTab()
  474. }
  475. } else {
  476. windowControler?.window?.close()
  477. }
  478. }
  479. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  480. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  481. return false
  482. }
  483. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  484. if (filepaths == nil || filepaths!.count == 0) {
  485. return false
  486. }
  487. DispatchQueue.main.async {
  488. for filepath in filepaths! {
  489. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  490. }
  491. }
  492. }
  493. return false
  494. }
  495. func applicationWillTerminate(_ aNotification: Notification) {
  496. if (NSDocumentController.shared.documents.count > 0) {
  497. var filepaths: [String] = []
  498. for document in NSDocumentController.shared.documents {
  499. // KMPrint(document.fileURL as Any)
  500. if (document.fileURL?.path != nil) {
  501. filepaths.append((document.fileURL?.path)!)
  502. }
  503. }
  504. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  505. } else {
  506. KMPreferenceManager.shared.lastOpenFilepaths = nil
  507. }
  508. }
  509. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  510. return true
  511. }
  512. // MARK: private
  513. func reopenDocument(forPaths paths: [String]) -> Void {
  514. let browser = KMBrowser.init() as KMBrowser
  515. browser.windowController = KMBrowserWindowController.init(browser: browser)
  516. browser.addHomeTabContents()
  517. browser.windowController.showWindow(self)
  518. }
  519. @objc private func _themeChanged(_ sender: Notification) {
  520. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  521. if isDarkModel {
  522. NSApp.appearance = NSAppearance(named: .darkAqua)
  523. } else {
  524. NSApp.appearance = NSAppearance(named: .aqua)
  525. }
  526. // if let data = NSApp.appearance?.name, data == .darkAqua {
  527. // NSApp.appearance = .init(named: .aqua)
  528. // } else {
  529. // NSApp.appearance = .init(named: .darkAqua)
  530. // }
  531. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  532. }
  533. // MARK: - Noti Actioins
  534. @objc func AIDeviceStatusChangeNotification() {
  535. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  536. self.refreshAIMenuItemInfo()
  537. }
  538. }
  539. @objc func deviceActivateStatusChangeNotification() {
  540. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  541. for item in appMenu!.items {
  542. if item.action == #selector(aiToolsAction) {
  543. if let tManager = VerificationManager.default() {
  544. let status = tManager.status
  545. if status == ActivityStatusNone {
  546. item.isHidden = true
  547. }
  548. }
  549. }
  550. }
  551. initDidFinish()
  552. }
  553. @objc func iapSubscriptionLoadedNotification() {
  554. KMMainThreadExecute {
  555. self.openWindowForIAPSubscriptionLoaded()
  556. }
  557. }
  558. @objc func iapProdcutLoadedNotification() {
  559. KMNewUserGiftManager.default.iapProductLoadProgressState = .success
  560. KMMainThreadExecute {
  561. self.openWindowForIAPSubscriptionLoaded()
  562. }
  563. }
  564. @objc func advertisementDidLoadedNotification() {
  565. KMMainThreadExecute {
  566. self.openWindowForAdvertisementDidLoaded()
  567. }
  568. }
  569. @objc func deviceVerifyFinishNotification() {
  570. KMNewUserGiftManager.default.fetchReceiptProgressState = .success
  571. KMMainThreadExecute {
  572. self.openWindowForIAPSubscriptionLoaded()
  573. }
  574. }
  575. func refreshAIMenuItemInfo() -> Void {
  576. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  577. for item in appMenu!.items {
  578. if item.action == #selector(aiToolsAction) {
  579. item.isHidden = true
  580. }
  581. }
  582. }
  583. //MARK: - iVersion
  584. func initiVersionData() -> Void{
  585. #if VERSION_DMG
  586. #else
  587. let tVersion = iVersion.sharedInstance()
  588. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  589. var tStr = "New Update Available"
  590. tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n"
  591. tVersion?.versionLabelFormat = ""
  592. tVersion?.groupNotesByVersion = true
  593. tVersion?.showOnFirstLaunch = false
  594. tVersion?.delegate = self
  595. tVersion?.checkPeriod = 2
  596. tVersion?.remindPeriod = 5
  597. let infoDictionary = Bundle .main.infoDictionary!
  598. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  599. if appName.count < 1 {
  600. appName = infoDictionary["CFBundleName"] as! String
  601. }
  602. tStr = "The new version of %@ is available now. Go update for new features.";
  603. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  604. tStr = String(format: tStr, appName)
  605. tVersion?.inThisVersionTitle = tStr
  606. tStr = "UPDATE NOW";
  607. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  608. tStr = "LATER";
  609. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  610. tVersion!.ignoreButtonLabel = ""
  611. #endif
  612. }
  613. // MARK: - Menu
  614. func initMainMenu() {
  615. // 处理菜单栏多语
  616. let mainMenu = NSApp.mainMenu
  617. if (mainMenu == nil) {
  618. return
  619. }
  620. for menu in mainMenu!.items {
  621. let subMenu = menu.submenu
  622. for item in subMenu!.items {
  623. item.title = NSLocalizedString(item.title, comment: "")
  624. let itemSubMenu = item.submenu
  625. if (itemSubMenu == nil) {
  626. continue
  627. }
  628. for item in itemSubMenu!.items {
  629. item.title = NSLocalizedString(item.title, comment: "")
  630. let itemSubMenu = item.submenu
  631. if (itemSubMenu == nil) {
  632. continue
  633. }
  634. for item in itemSubMenu!.items {
  635. item.title = NSLocalizedString(item.title, comment: "")
  636. }
  637. }
  638. }
  639. }
  640. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  641. #if VERSION_DMG
  642. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 3)
  643. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4)
  644. // if ([VerificationManager manager].needUpgradeLicense == NO) {
  645. if VerificationManager.default().needUpgradeLicense {
  646. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5)
  647. }
  648. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  649. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  650. #endif
  651. #if !VERSION_DMG
  652. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  653. #endif
  654. if let items = PDFOfficeMenu?.items {
  655. for menu in items {
  656. let ranges = menu.title.ranges(of: "PDF Reader Pro")
  657. if let _range = ranges.range.first {
  658. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  659. }
  660. }
  661. }
  662. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("Volume Discount", comment: "")) {
  663. item.isHidden = true
  664. }
  665. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("One License for Mac and Windows", comment: "")) {
  666. item.isHidden = true
  667. }
  668. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("Education Discount", comment: "")) {
  669. item.isHidden = true
  670. }
  671. let fileMenu = mainMenu?.item(at: 1)?.submenu
  672. var shareItem: NSMenuItem?
  673. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  674. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  675. fileMenu?.insertItem(shareItem!, at: item.index)
  676. fileMenu?.insertItem(.separator(), at: item.index)
  677. } else {
  678. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  679. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  680. }
  681. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  682. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  683. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  684. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  685. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  686. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  687. }
  688. @objc func sharePageItemAction(sender: NSMenuItem) {
  689. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  690. return
  691. }
  692. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  693. let model = windowControler.browser?.tabStripModel
  694. if let cnt = model?.count(), cnt <= 0 {
  695. return
  696. }
  697. if let data = model?.activeTabContents()?.isHome, data {
  698. return
  699. }
  700. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  701. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  702. let represent : NSSharingService = sender.representedObject as! NSSharingService
  703. represent.perform(withItems: [document.fileURL as Any])
  704. return
  705. }
  706. let represent : NSSharingService = sender.representedObject as! NSSharingService
  707. represent.perform(withItems: [document.fileURL as Any])
  708. }
  709. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  710. KMPrint("deviceCameraMenuItemAciton")
  711. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil)
  712. }
  713. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  714. KMPrint("deviceScannerMenuItemAciton")
  715. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil)
  716. }
  717. // MARK: PDF Reader Pro Menu
  718. @IBAction func openPreferenceWindow(_ sender: Any) {
  719. KMPreferenceController.shared.showWindow(self)
  720. }
  721. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  722. if KMLightMemberManager.manager.isLogin() {
  723. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  724. }
  725. }
  726. @IBAction func loginMenuItemAction(_ sender: Any) {
  727. // Login & Logout
  728. if KMLightMemberManager.manager.isLogin() {
  729. } else {
  730. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  731. }
  732. }
  733. @IBAction func logoutMenuItemAction(_ sender: Any) {
  734. // Login & Logout
  735. if KMLightMemberManager.manager.isLogin() {
  736. KMRequestServerManager.manager.logout { success, result in
  737. if success {
  738. KMPrint("登出成功")
  739. }
  740. }
  741. }
  742. }
  743. @IBAction func restoreMenuItemAction(_ sender: Any) {
  744. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  745. if isSuccess {
  746. } else {
  747. if error != .restoreSuccess {
  748. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  749. }
  750. }
  751. }
  752. }
  753. @objc func accountRefreshAction() {
  754. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  755. }
  756. }
  757. @objc func showAccount() {
  758. }
  759. @objc func resumePurchase() {
  760. }
  761. // MARK: help Menu
  762. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  763. KMTools.openQuickStartStudy()
  764. }
  765. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  766. KMTools.openFAQWebsite()
  767. }
  768. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  769. KMTools.openMoreProductWebsite()
  770. }
  771. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  772. KMTools.openFreePDFTemplatesWebsite()
  773. }
  774. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  775. KMEmailSubWindowController().showWindow(nil)
  776. }
  777. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  778. KMTools.openComPDFKitPowerWebsite()
  779. }
  780. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  781. KMTools.proposeNewFeature()
  782. }
  783. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  784. KMTools.rateUs()
  785. }
  786. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  787. // if(KMMemberInfo.shared.isLogin == false) {
  788. // KMLoginWindowsController.shared.showWindow(nil)
  789. // return
  790. // }
  791. #if !VERSION_DMG
  792. KMPrint("restoreSubscriptions ...")
  793. KMProductCompareWC.shared.orientation = false
  794. KMProductCompareWC.shared.showWindowRestore(sender)
  795. #else
  796. var vc: KMToolCompareWindowController? = nil
  797. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  798. vc!.showWindowRestore(sender: (Any).self)
  799. #endif
  800. }
  801. // MARK:- DMG
  802. @objc func checkForUpdates(_ sender: NSMenuItem) {
  803. #if VERSION_DMG
  804. SUUpdater.shared().checkForUpdates(sender)
  805. #endif
  806. }
  807. @objc func enterLicense(_ sender: NSMenuItem) {
  808. #if VERSION_DMG
  809. if let tManager = VerificationManager.default() {
  810. let status = tManager.status
  811. if status == ActivityStatusVerifExpire {
  812. let vc = KMVerificationWindowController.verification(with: .activateExpired)
  813. vc?.showWindow(nil)
  814. } else if status == ActivityStatusVerification {
  815. let vc = KMVerificationWindowController.verification(with: .info)
  816. vc?.showWindow(nil)
  817. } else {
  818. let vc = KMVerificationWindowController.verification(with: .activate)
  819. vc?.showWindow(nil)
  820. }
  821. }
  822. #endif
  823. }
  824. @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) {
  825. #if VERSION_DMG
  826. // var url = URL(string: Store_Link + "?product_code=product_2")
  827. // let tWorkSpace = NSWorkspace.shared
  828. // if tWorkSpace.open(url!) == false {
  829. // tWorkSpace.open(url!)
  830. // }
  831. let embeddedWC = DMGEmbeddedOldWC.currentFirstTrialWC("com.brother.pdfreaderpro.mac.product_2")
  832. embeddedWC.showWindow(nil)
  833. embeddedWC.window?.center()
  834. #endif
  835. }
  836. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  837. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  838. #if VERSION_DMG
  839. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  840. #else
  841. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  842. #endif
  843. guard let url = URL(string: tStrHttpUrl) else {
  844. NSSound.beep()
  845. return
  846. }
  847. let tWorkSpace = NSWorkspace.shared
  848. if tWorkSpace.open(url) == false {
  849. tWorkSpace.open(url)
  850. }
  851. }
  852. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  853. var tStrHttpUrl = CrossPlatform_Link
  854. guard let url = URL(string: tStrHttpUrl) else {
  855. return
  856. }
  857. let tWorkSpace = NSWorkspace.shared
  858. if tWorkSpace.open(url) == false {
  859. tWorkSpace.open(url)
  860. }
  861. #if VERSION_DMG
  862. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  863. #endif
  864. }
  865. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  866. let tStrHttpUrl = Store_Edu_Link
  867. guard let url = URL(string: tStrHttpUrl) else {
  868. return
  869. }
  870. let tWorkSpace = NSWorkspace.shared
  871. if tWorkSpace.open(url) == false {
  872. tWorkSpace.open(url)
  873. }
  874. #if VERSION_DMG
  875. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  876. #endif
  877. }
  878. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  879. #if VERSION_DMG
  880. KMProductCompareWC.shared.orientation = false
  881. KMProductCompareWC.shared.showWindow(nil)
  882. #else
  883. AIPurchaseWindowController.currentWC().showWindow(nil)
  884. #endif
  885. }
  886. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  887. if let win = KMLineInspector.shared.window {
  888. if win.isVisible {
  889. win.orderOut(sender)
  890. } else {
  891. win.orderFront(sender)
  892. }
  893. }
  894. }
  895. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  896. KMPrint("showDownloads ...")
  897. }
  898. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  899. self.reopenDocument(forPaths: [])
  900. }
  901. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  902. KMEmailSubWindowController().showWindow(nil)
  903. }
  904. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  905. KMTools.feekback()
  906. }
  907. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  908. KMTools.reportBug()
  909. }
  910. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  911. KMTools.reportGeneralQuestions()
  912. }
  913. }
  914. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  915. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  916. let action = menuItem.action
  917. if action == #selector(manageAcctounMenuAction) {
  918. self.updateLoginMenuItem()
  919. return KMLightMemberManager.manager.isLogin()
  920. }
  921. if action == #selector(loginMenuItemAction) {
  922. self.updateLoginMenuItem()
  923. return !KMLightMemberManager.manager.isLogin()
  924. }
  925. if action == #selector(pdftoOfficeMenuItemAction) {
  926. if KMMemberInfo.shared.is_advanced_year_subscribe() {
  927. menuItem.isHidden = true
  928. return false;
  929. }
  930. }
  931. if action == #selector(logoutMenuItemAction) {
  932. self.updateLoginMenuItem()
  933. return KMLightMemberManager.manager.isLogin()
  934. }
  935. if (action == #selector(sharePageItemAction)) {
  936. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  937. return false
  938. }
  939. let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  940. return !isHome
  941. }
  942. if action == #selector(closeDocument) {
  943. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  944. if NSApp.mainWindow?.windowController != nil {
  945. return true
  946. }
  947. return false
  948. }
  949. let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false
  950. if isNewTab {
  951. return true
  952. }
  953. // let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  954. // return !isHome
  955. }
  956. return true
  957. }
  958. func updateLoginMenuItem() {
  959. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  960. if firstItem != nil {
  961. let item1 = firstItem?.item(withTag: 11)
  962. let item2 = firstItem?.item(withTag: 12)
  963. let item3 = firstItem?.item(withTag: 13)
  964. let item4 = firstItem?.item(withTag: 14)
  965. // let item5 = firstItem?.item(withTag: 15)
  966. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  967. // if KMLightMemberManager.manager.isLogin() {
  968. // item1?.title = KMLightMemberManager.manager.info.email
  969. // item1?.isHidden = false
  970. // item2?.isHidden = true
  971. // item3?.isHidden = false
  972. // item4?.isHidden = false
  973. //// item5?.isHidden = false
  974. // item6?.isHidden = false
  975. // } else {
  976. // item1?.isHidden = true
  977. // item2?.isHidden = false
  978. // item3?.isHidden = true
  979. // item4?.isHidden = true
  980. //// item5?.isHidden = true
  981. // item6?.isHidden = true
  982. // }
  983. item1?.isHidden = true
  984. item2?.isHidden = true
  985. item3?.isHidden = true
  986. item4?.isHidden = true
  987. // item5?.isHidden = true
  988. item6?.isHidden = true
  989. }
  990. }
  991. @objc func clickOutline(menuItem: NSMenuItem) {
  992. KMPrint("更新菜单栏")
  993. }
  994. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  995. return true
  996. }
  997. }
  998. #if VERSION_DMG
  999. extension AppDelegate : SUUpdaterDelegate {
  1000. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  1001. }
  1002. func feedURLString(for updater: SUUpdater) -> String? {
  1003. var hostURL = "https://www.pdfreaderpro.com/downloads/"
  1004. #if DEBUG
  1005. hostURL = "http://test-pdf-pro.kdan.cn:3021/downloads/"
  1006. #else
  1007. hostURL = "https://www.pdfreaderpro.com/downloads/"
  1008. #endif
  1009. return hostURL+NSLocalizedString("pdfreaderprocast.xml", comment: "")
  1010. }
  1011. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  1012. return false
  1013. }
  1014. func upgradeAPP(with updater: SUUpdater) {
  1015. let string = "macappstore://apps.apple.com/app/id825459243?mt=12"
  1016. let url: URL = URL(string: string)!
  1017. NSWorkspace.shared.open(url)
  1018. }
  1019. func upgradeButtonString(for updater: SUUpdater) -> String {
  1020. return NSLocalizedString("PDF Reader Pro", comment: "")
  1021. }
  1022. }
  1023. #endif
  1024. extension AppDelegate: iVersionDelegate {
  1025. func iVersionShouldCheckForNewVersion() -> Bool {
  1026. #if VERSION_FREE
  1027. if KMNewUserGiftWindowController.shared.needShowForlocalCheck() == false {
  1028. return true
  1029. }
  1030. let appFirstLaunch = KMDataManager.default.appFirstLaunch
  1031. let appFirstLaunchForUpdate = KMDataManager.default.appFirstLaunchForUpdate
  1032. if appFirstLaunch == false && appFirstLaunchForUpdate == false {
  1033. // 不是首次启动 或 不是更新后首次启动
  1034. return true
  1035. }
  1036. if KMNewUserGiftManager.default.progressState == .none {
  1037. return false
  1038. }
  1039. return KMNewUserGiftWindowController.shared.needShow() == false
  1040. #else
  1041. return true
  1042. #endif
  1043. }
  1044. }
  1045. extension AppDelegate {
  1046. // MARK: - Services Support
  1047. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  1048. var error: NSError?
  1049. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  1050. // Document opened successfully
  1051. } else if let error = error {
  1052. errorString = error.localizedDescription
  1053. }
  1054. }
  1055. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  1056. var error: NSError?
  1057. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  1058. // Document opened successfully
  1059. } else if let error = error {
  1060. errorString = error.localizedDescription
  1061. }
  1062. }
  1063. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  1064. var error: NSError?
  1065. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  1066. // Document opened successfully
  1067. } else if let error = error {
  1068. errorString = error.localizedDescription
  1069. }
  1070. }
  1071. }
  1072. extension AppDelegate: UNUserNotificationCenterDelegate {
  1073. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  1074. // 处理用户点击推送通知的操作
  1075. completionHandler()
  1076. }
  1077. }