AppDelegate.swift 49 KB

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