AppDelegate.swift 52 KB

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