AppDelegate.swift 44 KB

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