AppDelegate.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. func applicationWillFinishLaunching(_ notification: Notification) {
  12. #if VERSION_FREE
  13. #if VERSION_DMG
  14. 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==")
  15. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+v5w339rXeJw+v0hhIv5Q4btZUOscw80t3c1bXxpLq3B6fv6psGJP0+FMyQOerBP6u4YYan9tCSe6rawjumJYCQMT5YNHtN/72HTYtc9HAcQzdMudePhw3hYY3747Z6Sq7DCCqgbK+BnM11gxblULiTgFkYLZsuBudusbqrM7WktIkcfpLfh15Y+TZ04iXpI9LWkgKoeYZ1VAJMTcrfwCs63g/8nUiZ59kpdetHbzONEIhsi+Wu0lH1oY17eVN2TRW5amzrZsD0yy20WxEXrssgDJq7xPzi1sOZ56C+jdE/8p9tNUW4KYJ5GoqCVh5w0Ajkc3xRqWrpmJXUollqL+u9K6VDPqy3tmvVGdknJxHlX4q+ufAQa+Tb3qlEJwp14dhrbJERqUs5Gygc6W5Fk18+uJ6IjwvilMe8T8+t3vLDZPlOgVg4lqZaxlBn/t+RvkJ/76CDO1/Byfqmig2vE4qETJmxV+pK4Lftqjsxibe087g3EFlaO/7ZpewBkqMhR1sG/D/3Jjsevjbb32Ut+5f8JWMFL7gFHikJx6PJwxlEEfVHP/dqNkFfBJKTqjjZoj9LNxxkOngdfNDsnWigFkZUSivLNCXAJ+a4C/mHaaRf95ad20LA0NahljpcTQ7x8TR8fuAHZkFK4DnFK+ST8zSP17/yW3x9ACHU6arojAbZ0IAz2pZRRuYYl9YB07NckfhpuE2qQAu+IaHm32opV2P/l/7HZUt7hsw7wAHIKJqnBs4cNag==")
  16. #else
  17. 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==")
  18. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+v5w339rXeJw+v0hhIv5Q4btZUOscw80t3c1bXxpLq3B6fv6psGJP0+FMyQOerBP6u4YYan9tCSe6rawjumJYCQMT5YNHtN/72HTYtc9HAcQzdMudePhw3hYY3747Z6Sq7DCCqgbK+BnM11gxblULiTgFkYLZsuBudusbqrM7WktIkcfpLfh15Y+TZ04iXpI9LWkgKoeYZ1VAJMTcrfwCs63g/8nUiZ59kpdetHbzONEIhsi+Wu0lH1oY17eVN2TRW5amzrZsD0yy20WxEXrssgDJq7xPzi1sOZ56C+jdE/8p9tNUW4KYJ5GoqCVh5w0Ajkc3xRqWrpmJXUollqL+u9K6VDPqy3tmvVGdknJxHlX4q+ufAQa+Tb3qlEJwp14dhrbJERqUs5Gygc6W5Fk18+uJ6IjwvilMe8T8+t3vLDZPlOgVg4lqZaxlBn/t+RvkJ/76CDO1/Byfqmig2vE4qETJmxV+pK4Lftqjsxibe087g3EFlaO/7ZpewBkqMhR1sG/D/3Jjsevjbb32Ut+5f8JWMFL7gFHikJx6PJwxlEEfVHP/dqNkFfBJKTqjjZoj9LNxxkOngdfNDsnWigFkZUSivLNCXAJ+a4C/mHaaRf95ad20LA0NahljpcTQ7x8TR8fuAHZkFK4DnFK+ST8zSP17/yW3x9ACHU6arojAbZ0IAz2pZRRuYYl9YB07NckfhpuE2qQAu+IaHm32opV2P/l/7HZUt7hsw7wAHIKJqnBs4cNag==")
  19. #endif
  20. #else
  21. CPDFKit.setLicenseKey("vEeYzYqkir/aYIfrBDmhQEj2omreQNEjmVvLFlAV82dFc/aIwVlR4TZX9zgHb2zFW9+cK5/DeiisEwS5yrto3CFY2Q9MqLwIATeSF1vlV0bhRLYexOw8Sabyzl9iOYufVyFQz68T7jCZVkXEKukJMi06Zpqwc5F/tGnrnrzkydk=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4rCrm/O2+fI9yUYXNZ/JY1KPbFCeKgG+lEVwrbGHrpAyXATqjrt8ApqRYhafFooQjwAFgayISwZT/pa4NjR459gu4aGVjtYuk+Uxs/kosIBwyxQV1SVCQFsC27oMGz5P/rBQYv0T/D0N0z+Um3U+I+tG7BHAIgXXXaVusko5CeqTkm+stgaO9rjBr8W89IPRRCg5dRM1r/xf9BsO0NNqcqQDBaBDLYysZFZsvpYi1vbvQ==")
  22. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+v5w339rXeJw+v0hhIv5Q4btZUOscw80t3c1bXxpLq3B6fv6psGJP0+FMyQOerBP6u4YYan9tCSe6rawjumJYCQMT5YNHtN/72HTYtc9HAcQzdMudePhw3hYY3747Z6Sq7DCCqgbK+BnM11gxblULiTgFkYLZsuBudusbqrM7WktIkcfpLfh15Y+TZ04iXpI9LWkgKoeYZ1VAJMTcrfwCs63g/8nUiZ59kpdetHbzONEIhsi+Wu0lH1oY17eVN2TRW5amzrZsD0yy20WxEXrssgDJq7xPzi1sOZ56C+jdE/8p9tNUW4KYJ5GoqCVh5w0Ajkc3xRqWrpmJXUollqL+u9K6VDPqy3tmvVGdknJxHlX4q+ufAQa+Tb3qlEJwp14dhrbJERqUs5Gygc6W5Fk18+uJ6IjwvilMe8T8+t3vLDZPlOgVg4lqZaxlBn/t+RvkJ/76CDO1/Byfqmig2vE4qETJmxV+pK4Lftqjsxibe087g3EFlaO/7ZpewBkqMhR1sG/D/3Jjsevjbb32Ut+5f8JWMFL7gFHikJx6PJwxlEEfVHP/dqNkFfBJKTqjjZoj9LNxxkOngdfNDsnWigFkZUSivLNCXAJ+a4C/mHaaRf95ad20LA0NahljpcTQ7x8TR8fuAHZkFK4DnFK+ST8zSP17/yW3x9ACHU6arojAbZ0IAz2pZRRuYYl9YB07NckfhpuE2qQAu+IaHm32opV2P/l/7HZUt7hsw7wAHIKJqnBs4cNag==")
  23. #endif
  24. ComPDFUIConfig.initializeUIConfig()
  25. KMDesignToken.shared.parserExcel(withPath: "")
  26. }
  27. func applicationDidFinishLaunching(_ aNotification: Notification) {
  28. // Insert code here to initialize your application
  29. //通知
  30. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  31. if granted {
  32. print("User authorized notifications")
  33. } else {
  34. print("User denied notifications")
  35. }
  36. }
  37. /**本地推送测试
  38. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  39. if granted {
  40. // 创建本地推送通知
  41. let content = UNMutableNotificationContent()
  42. content.title = "Test Notification"
  43. content.body = "This is a test notification!"
  44. // 触发条件,例如延迟 5 秒触发
  45. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  46. // 创建通知请求
  47. let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
  48. // 添加通知请求到用户通知中心
  49. UNUserNotificationCenter.current().add(request) { error in
  50. if let error = error {
  51. print("Error adding notification request: \(error)")
  52. } else {
  53. print("Local notification scheduled")
  54. }
  55. }
  56. } else {
  57. print("User denied notifications")
  58. }
  59. }
  60. **/
  61. DispatchQueue.main.async {
  62. NSApplication.shared.registerForRemoteNotifications()
  63. }
  64. #if VERSION_DMG
  65. let updater = SUUpdater.shared()
  66. updater?.delegate = self
  67. updater?.automaticallyChecksForUpdates = true
  68. #else
  69. #endif
  70. //Firebase RemoteConfig
  71. #if VERSION_FREE
  72. KMKdanRemoteConfig.remoteConfig().fetch { _status, error in
  73. }
  74. #endif
  75. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  76. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  77. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  78. let sud = UserDefaults.standard
  79. if versionString.isEmpty == false {
  80. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  81. }
  82. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  83. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  84. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  85. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  86. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  87. sud.synchronize()
  88. }
  89. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  90. NSApp.servicesProvider = self
  91. KMKdanRemoteConfig.remoteConfig().fetchWithRemoteConfigCompletionHandler { status, error in
  92. }
  93. KMStatusBar.system()
  94. // MARK: 广告数据初始化
  95. var appName: KMAdvertisementAppNameType = .PDFReaderProMac
  96. #if VERSION_FREE
  97. #if VERSION_DMG
  98. appName = .PDFReaderProMacDMG
  99. #else
  100. #endif
  101. #else
  102. appName = .PDFReaderProMacPro
  103. #endif
  104. KMAdvertisementManager.manager.initConfig(appName: appName,
  105. subscribeType: .unknow,
  106. platform: .Mac)
  107. // 测试模式,默认false
  108. KMAdvertisementManager.manager.debug = true
  109. NSApp.appearance = NSAppearance.current
  110. KMAnalytics.configure()
  111. //第一次开启app
  112. var info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount")
  113. var count = 0
  114. if info != nil {
  115. count = info as? Int ?? 0
  116. }
  117. count += 1
  118. UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount")
  119. UserDefaults.standard.synchronize()
  120. self.initMainMenu()
  121. /// pro
  122. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  123. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  124. reopenDocument(forPaths: [])
  125. KMPreference.shared.initDataForAppLaunch()
  126. self.initiRateData()
  127. let appleEventManager = NSAppleEventManager.shared()
  128. appleEventManager.setEventHandler(self,
  129. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  130. forEventClass: AEEventClass(kInternetEventClass),
  131. andEventID: AEEventID(kAEGetURL))
  132. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  133. #if VERSION_DMG
  134. VerificationManager.default()
  135. #else
  136. self.initiVersionData()
  137. IAPProductsManager.default().initIAP()
  138. #endif
  139. //AI相关
  140. AIInfoManager.default()
  141. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  142. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  143. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  144. var error: Unmanaged<CFError>?
  145. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  146. print("Failed to register font!")
  147. } else {
  148. print("Font registered successfully!")
  149. }
  150. }
  151. }
  152. func initiRateData() {
  153. iRate.sharedInstance().delegate = self
  154. #if VERSION_FREE
  155. iRate.sharedInstance().appStoreID = 919472673
  156. #else
  157. iRate.sharedInstance().appStoreID = 825459243
  158. #endif
  159. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  160. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  161. }
  162. //MARK: iRateDelegate
  163. func iRateUserDidDeclineToRateApp() {
  164. }
  165. func iRateShouldPromptForRating() -> Bool {
  166. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  167. if !notShow {
  168. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  169. UserDefaults.standard.synchronize()
  170. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  171. }
  172. let rate = KMRateWindowController()
  173. let window = NSWindow.currentWindow()
  174. window.km_beginSheet(windowC: rate)
  175. rate.closeBlock = { wc in
  176. window.km_quick_endSheet()
  177. }
  178. return false
  179. }
  180. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  181. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  182. let url = URL(string: urlString) {
  183. // 在这里处理收到的 URL Scheme
  184. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  185. KMPrint("Path: \(url.path)")
  186. if NSApp.mainWindow == nil {
  187. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  188. launchApp(bundleIdentifier: bundleIdentifier)
  189. }
  190. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  191. #if VERSION_DMG
  192. // 执行相应的操作
  193. if url.scheme == "subscriptiondmgschemes" {
  194. if urlString.contains("open=expired") {
  195. KMPrint("刷新用户信息")
  196. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  197. KMLoginWindowController.show(window: NSApp.mainWindow!)
  198. } else {
  199. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  200. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  201. }
  202. }
  203. } else if urlString.contains("open=success") {
  204. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  205. KMLoginWindowController.show(window: NSApp.mainWindow!)
  206. } else {
  207. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  208. if isSuccess {
  209. } else {
  210. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  211. }
  212. }
  213. }
  214. }
  215. }
  216. #endif
  217. #if VERSION_FREE
  218. // 执行相应的操作
  219. if url.scheme == "subscriptionSchemes" {
  220. //刷新用户信息
  221. KMRequestServerManager.manager.getUserInfo { [weak self] success, data, error, isLocal in
  222. }
  223. if url.path == "/open" {
  224. // 执行打开操作
  225. } else if url.path == "/close" {
  226. // 执行关闭操作
  227. }
  228. }
  229. #endif
  230. }
  231. }
  232. }
  233. func launchApp(bundleIdentifier: String) {
  234. let workspace = NSWorkspace.shared
  235. // Launch the application with the specified bundle identifier
  236. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  237. do {
  238. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  239. } catch {
  240. print("Error launching the application: \(error)")
  241. }
  242. } else {
  243. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  244. }
  245. }
  246. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  247. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  248. print("Device token:", token)
  249. }
  250. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  251. }
  252. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  253. if !flag {
  254. let browser: KMBrowser = KMBrowser.init()
  255. browser.windowController = KMBrowserWindowController.init(browser: browser)
  256. browser.addHomeTabContents()
  257. browser.windowController.showWindow(self)
  258. }
  259. return flag
  260. }
  261. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  262. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  263. return false
  264. }
  265. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  266. if (filepaths == nil || filepaths!.count == 0) {
  267. return false
  268. }
  269. DispatchQueue.main.async {
  270. for filepath in filepaths! {
  271. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  272. }
  273. }
  274. }
  275. return false
  276. }
  277. func applicationWillTerminate(_ aNotification: Notification) {
  278. if (NSApp.orderedDocuments.count > 0) {
  279. var filepaths: [String] = []
  280. for document in NSApp.orderedDocuments {
  281. // KMPrint(document.fileURL as Any)
  282. if (document.fileURL?.path != nil) {
  283. filepaths.append((document.fileURL?.path)!)
  284. }
  285. }
  286. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  287. } else {
  288. KMPreferenceManager.shared.lastOpenFilepaths = nil
  289. }
  290. }
  291. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  292. return true
  293. }
  294. // MARK: private
  295. func reopenDocument(forPaths paths: [String]) -> Void {
  296. let browser = KMBrowser.init() as KMBrowser
  297. browser.windowController = KMBrowserWindowController.init(browser: browser)
  298. browser.addHomeTabContents()
  299. browser.windowController.showWindow(self)
  300. }
  301. @objc private func _themeChanged(_ sender: Notification) {
  302. if let data = NSApp.appearance?.name, data == .darkAqua {
  303. NSApp.appearance = .init(named: .aqua)
  304. } else {
  305. NSApp.appearance = .init(named: .darkAqua)
  306. }
  307. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  308. }
  309. @objc func AIDeviceStatusChangeNotification() {
  310. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  311. self.refreshAIMenuItemInfo()
  312. }
  313. }
  314. func refreshAIMenuItemInfo() -> Void {
  315. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  316. for item in appMenu!.items {
  317. if item.action == #selector(aiToolsAction) {
  318. item.isHidden = true
  319. }
  320. }
  321. }
  322. //MARK: - iVersion
  323. func initiVersionData() -> Void{
  324. #if VERSION_DMG
  325. return
  326. #endif
  327. let tVersion = iVersion.sharedInstance()
  328. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  329. var tStr = "New Update Available"
  330. tVersion?.updateAvailableTitle = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  331. tVersion?.versionLabelFormat = ""
  332. tVersion?.groupNotesByVersion = true
  333. tVersion?.showOnFirstLaunch = false
  334. tVersion?.checkPeriod = 2
  335. tVersion?.remindPeriod = 5
  336. let infoDictionary = Bundle .main.infoDictionary!
  337. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  338. if appName.count < 1 {
  339. appName = infoDictionary["CFBundleName"] as! String
  340. }
  341. tStr = "The new version of %@ is available now. Go update for new features.";
  342. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  343. tStr = String(format: tStr, appName)
  344. tVersion?.inThisVersionTitle = "\n" + tStr
  345. tStr = "UPDATE NOW";
  346. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  347. tStr = "LATER";
  348. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  349. tVersion!.ignoreButtonLabel = ""
  350. }
  351. // MARK: - Menu
  352. func initMainMenu() {
  353. // 处理菜单栏多语
  354. let mainMenu = NSApp.mainMenu
  355. if (mainMenu == nil) {
  356. return
  357. }
  358. for menu in mainMenu!.items {
  359. let subMenu = menu.submenu
  360. for item in subMenu!.items {
  361. item.title = NSLocalizedString(item.title, comment: "")
  362. let itemSubMenu = item.submenu
  363. if (itemSubMenu == nil) {
  364. continue
  365. }
  366. for item in itemSubMenu!.items {
  367. item.title = NSLocalizedString(item.title, comment: "")
  368. }
  369. }
  370. }
  371. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  372. #if VERSION_DMG
  373. PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 1)
  374. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  375. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  376. #endif
  377. #if !VERSION_DMG
  378. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  379. #endif
  380. if let items = PDFOfficeMenu?.items {
  381. for menu in items {
  382. let ranges = menu.title.ranges(of: "PDF Reader Pro")
  383. if let _range = ranges.range.first {
  384. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  385. }
  386. }
  387. }
  388. let fileMenu = mainMenu?.item(at: 1)?.submenu
  389. var shareItem: NSMenuItem?
  390. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  391. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  392. fileMenu?.insertItem(shareItem!, at: item.index)
  393. fileMenu?.insertItem(.separator(), at: item.index)
  394. } else {
  395. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  396. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  397. }
  398. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  399. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  400. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  401. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  402. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  403. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  404. let viewMenu = mainMenu?.item(at: 3)?.submenu
  405. var zoomMenu: NSMenu?
  406. for item in viewMenu!.items {
  407. if (item.title == NSLocalizedString("Zoom", comment: "")) {
  408. zoomMenu = item.submenu
  409. break
  410. }
  411. }
  412. if (zoomMenu != nil) {
  413. for item in zoomMenu!.items {
  414. if (item.title == NSLocalizedString("Zoom In", comment: "")) {
  415. item.keyEquivalent = "+"
  416. item.keyEquivalentModifierMask = [.command]
  417. break
  418. }
  419. }
  420. }
  421. }
  422. @objc func sharePageItemAction(sender: NSMenuItem) {
  423. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  424. return
  425. }
  426. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  427. let model: CTTabStripModel = windowControler.browser.tabStripModel
  428. if (model.count() <= 0) {
  429. return
  430. }
  431. if (model.activeTabContents().isHome) {
  432. return
  433. }
  434. let document: KMMainDocument = model.activeTabContents() as! KMMainDocument
  435. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  436. let represent : NSSharingService = sender.representedObject as! NSSharingService
  437. represent.perform(withItems: [document.fileURL as Any])
  438. return
  439. }
  440. // 有使用付费功能
  441. Task { @MainActor in
  442. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  443. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  444. if (isClose) {
  445. return
  446. }
  447. if (isSubscribeSuccess) {
  448. let represent : NSSharingService = sender.representedObject as! NSSharingService
  449. represent.perform(withItems: [document.fileURL as Any])
  450. return
  451. }
  452. if (isWaterMarkExport) {
  453. let doucumentURL = document.fileURL
  454. let docDir = NSTemporaryDirectory()
  455. let documentName : String = doucumentURL!.path.lastPathComponent
  456. let path = docDir.stringByAppendingPathComponent(documentName)
  457. let data = KMTools.saveWatermarkDocument(document: document.mainViewController!.document!, to: URL(fileURLWithPath: path), secureOptions: document.mainViewController!.secureOptions, removePWD: document.mainViewController!.removeSecureFlag)
  458. let writeSuccess = data != nil
  459. if writeSuccess == false {
  460. __NSBeep()
  461. return;
  462. }
  463. let represent : NSSharingService = sender.representedObject as! NSSharingService
  464. represent.perform(withItems: [data as Any])
  465. return
  466. }
  467. }
  468. return
  469. }
  470. let represent : NSSharingService = sender.representedObject as! NSSharingService
  471. represent.perform(withItems: [document.fileURL as Any])
  472. }
  473. }
  474. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  475. KMPrint("deviceCameraMenuItemAciton")
  476. }
  477. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  478. KMPrint("deviceScannerMenuItemAciton")
  479. }
  480. // MARK: PDF Reader Pro Menu
  481. @IBAction func openPreferenceWindow(_ sender: Any) {
  482. KMPreferenceController.shared.showWindow(self)
  483. }
  484. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  485. if KMLightMemberManager.manager.isLogin() {
  486. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  487. }
  488. }
  489. @IBAction func loginMenuItemAction(_ sender: Any) {
  490. // Login & Logout
  491. if KMLightMemberManager.manager.isLogin() {
  492. } else {
  493. KMLoginWindowController.show(window: NSApp.mainWindow!)
  494. }
  495. }
  496. @IBAction func logoutMenuItemAction(_ sender: Any) {
  497. // Login & Logout
  498. if KMLightMemberManager.manager.isLogin() {
  499. KMRequestServerManager.manager.logout { success, result in
  500. if success {
  501. KMPrint("登出成功")
  502. }
  503. }
  504. }
  505. }
  506. @IBAction func restoreMenuItemAction(_ sender: Any) {
  507. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  508. if isSuccess {
  509. } else {
  510. if error != .restoreSuccess {
  511. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  512. }
  513. }
  514. }
  515. }
  516. @objc func accountRefreshAction() {
  517. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  518. }
  519. }
  520. @objc func showAccount() {
  521. }
  522. @objc func resumePurchase() {
  523. }
  524. // MARK: help Menu
  525. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  526. KMTools.openQuickStartStudy()
  527. }
  528. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  529. KMTools.openFAQWebsite()
  530. }
  531. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  532. KMTools.openMoreProductWebsite()
  533. }
  534. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  535. KMTools.openFreePDFTemplatesWebsite()
  536. }
  537. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  538. KMEmailSubWindowController().showWindow(nil)
  539. }
  540. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  541. KMTools.openComPDFKitPowerWebsite()
  542. }
  543. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  544. KMTools.proposeNewFeature()
  545. }
  546. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  547. KMTools.rateUs()
  548. }
  549. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  550. #if VERSION_FREE
  551. KMPrint("restoreSubscriptions ...")
  552. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  553. compareWindowVC.showWindowRestore(nil)
  554. #else
  555. var vc: KMToolCompareWindowController? = nil
  556. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  557. vc!.showWindowRestore(sender: (Any).self)
  558. #endif
  559. }
  560. // MARK:- DMG
  561. @objc func checkForUpdates(_ sender: NSMenuItem) {
  562. #if VERSION_DMG
  563. SUUpdater.shared().checkForUpdates(sender)
  564. #endif
  565. }
  566. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  567. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  568. #if VERSION_DMG
  569. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  570. if SKInspectPublicTool.currentisLanguageHans() {
  571. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp_zh"
  572. }
  573. #else
  574. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  575. if SKInspectPublicTool.currentisLanguageHans() {
  576. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp_zh"
  577. }
  578. #endif
  579. guard let url = URL(string: tStrHttpUrl) else {
  580. NSSound.beep()
  581. return
  582. }
  583. let tWorkSpace = NSWorkspace.shared
  584. if tWorkSpace.open(url) == false {
  585. tWorkSpace.open(url)
  586. }
  587. }
  588. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  589. var tStrHttpUrl = "https://www.pdfreaderpro.com/store/pdf-pro-permanent-cross-platform-package?utm_source=pdf_pro_dmgs&utm_medium=toptbr_help&utm_campaign=cross_platform"
  590. if SKInspectPublicTool.currentisLanguageHans() {
  591. tStrHttpUrl = "https://www.pdfreaderpro.com/zh-cn/store/pdf-pro-permanent-cross-platform-package?utm_source=pdf_pro_dmg&utm_medium=toptbr_help_cn&utm_campaign=cross_platform"
  592. }
  593. guard let url = URL(string: tStrHttpUrl) else {
  594. return
  595. }
  596. let tWorkSpace = NSWorkspace.shared
  597. if tWorkSpace.open(url) == false {
  598. tWorkSpace.open(url)
  599. }
  600. #if VERSION_DMG
  601. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  602. #endif
  603. }
  604. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  605. let tStrHttpUrl = KMLocalizedString("https://www.pdfreaderpro.com/store?mode=edu#utm_source=mac_app&utm_medium=pdf_pro_dmg&utm_content=menu_bar_click", nil)
  606. guard let url = URL(string: tStrHttpUrl) else {
  607. return
  608. }
  609. let tWorkSpace = NSWorkspace.shared
  610. if tWorkSpace.open(url) == false {
  611. tWorkSpace.open(url)
  612. }
  613. #if VERSION_DMG
  614. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  615. #endif
  616. }
  617. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  618. #if VERSION_DMG
  619. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  620. #else
  621. AIPurchaseWindowController.currentWC().showWindow(nil)
  622. #endif
  623. }
  624. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  625. if let win = KMLineInspector.shared.window {
  626. if win.isVisible {
  627. win.orderOut(sender)
  628. } else {
  629. win.orderFront(sender)
  630. }
  631. }
  632. }
  633. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  634. KMPrint("showDownloads ...")
  635. }
  636. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  637. self.reopenDocument(forPaths: [])
  638. }
  639. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  640. KMEmailSubWindowController().showWindow(nil)
  641. }
  642. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  643. KMTools.feekback()
  644. }
  645. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  646. KMTools.reportBug()
  647. }
  648. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  649. KMTools.reportGeneralQuestions()
  650. }
  651. }
  652. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  653. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  654. let action = menuItem.action
  655. if action == #selector(manageAcctounMenuAction) {
  656. self.updateLoginMenuItem()
  657. return KMLightMemberManager.manager.isLogin()
  658. }
  659. if action == #selector(loginMenuItemAction) {
  660. self.updateLoginMenuItem()
  661. return !KMLightMemberManager.manager.isLogin()
  662. }
  663. if action == #selector(logoutMenuItemAction) {
  664. self.updateLoginMenuItem()
  665. return KMLightMemberManager.manager.isLogin()
  666. }
  667. if (action == #selector(sharePageItemAction)) {
  668. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  669. return false
  670. }
  671. return !_windowC.browser.activeTabContents().isHome
  672. }
  673. return true
  674. }
  675. func updateLoginMenuItem() {
  676. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  677. if firstItem != nil {
  678. let item1 = firstItem?.item(withTag: 11)
  679. let item2 = firstItem?.item(withTag: 12)
  680. let item3 = firstItem?.item(withTag: 13)
  681. let item4 = firstItem?.item(withTag: 14)
  682. // let item5 = firstItem?.item(withTag: 15)
  683. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  684. // if KMLightMemberManager.manager.isLogin() {
  685. // item1?.title = KMLightMemberManager.manager.info.email
  686. // item1?.isHidden = false
  687. // item2?.isHidden = true
  688. // item3?.isHidden = false
  689. // item4?.isHidden = false
  690. //// item5?.isHidden = false
  691. // item6?.isHidden = false
  692. // } else {
  693. // item1?.isHidden = true
  694. // item2?.isHidden = false
  695. // item3?.isHidden = true
  696. // item4?.isHidden = true
  697. //// item5?.isHidden = true
  698. // item6?.isHidden = true
  699. // }
  700. item1?.isHidden = true
  701. item2?.isHidden = true
  702. item3?.isHidden = true
  703. item4?.isHidden = true
  704. // item5?.isHidden = true
  705. item6?.isHidden = true
  706. }
  707. }
  708. @objc func clickOutline(menuItem: NSMenuItem) {
  709. KMPrint("更新菜单栏")
  710. }
  711. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  712. return true
  713. }
  714. }
  715. #if VERSION_DMG
  716. extension AppDelegate : SUUpdaterDelegate {
  717. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  718. }
  719. func feedURLString(for updater: SUUpdater) -> String? {
  720. #if DEBUG
  721. return "http://test-pdf-pro.kdan.cn:3021/downloads/pdfmasterprocast.xml"
  722. #else
  723. return "https://www.pdfreaderpro.com/downloads/pdfmasterprocast.xml"
  724. #endif
  725. }
  726. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  727. return false
  728. }
  729. func upgradeAPP(with updater: SUUpdater) {
  730. let string = "macappstore://apps.apple.com/cn/app/pdf-master-ai-pdf/id6446781258?mt=12"
  731. let url: URL = URL(string: string)!
  732. NSWorkspace.shared.open(url)
  733. }
  734. func upgradeButtonString(for updater: SUUpdater) -> String {
  735. return NSLocalizedString("PDF Reader Pro", comment: "")
  736. }
  737. }
  738. #endif
  739. extension AppDelegate {
  740. // MARK: - Services Support
  741. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  742. var error: NSError?
  743. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  744. // Document opened successfully
  745. } else if let error = error {
  746. errorString = error.localizedDescription
  747. }
  748. }
  749. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  750. var error: NSError?
  751. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  752. // Document opened successfully
  753. } else if let error = error {
  754. errorString = error.localizedDescription
  755. }
  756. }
  757. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  758. var error: NSError?
  759. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  760. // Document opened successfully
  761. } else if let error = error {
  762. errorString = error.localizedDescription
  763. }
  764. }
  765. }
  766. extension AppDelegate: UNUserNotificationCenterDelegate {
  767. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  768. // 处理用户点击推送通知的操作
  769. completionHandler()
  770. }
  771. }