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. #endif
  138. //AI相关
  139. AIInfoManager.default()
  140. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  141. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  142. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  143. var error: Unmanaged<CFError>?
  144. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  145. print("Failed to register font!")
  146. } else {
  147. print("Font registered successfully!")
  148. }
  149. }
  150. }
  151. func initiRateData() {
  152. iRate.sharedInstance().delegate = self
  153. #if VERSION_FREE
  154. iRate.sharedInstance().appStoreID = 919472673
  155. #else
  156. iRate.sharedInstance().appStoreID = 825459243
  157. #endif
  158. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  159. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  160. }
  161. //MARK: iRateDelegate
  162. func iRateUserDidDeclineToRateApp() {
  163. }
  164. func iRateShouldPromptForRating() -> Bool {
  165. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  166. if !notShow {
  167. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  168. UserDefaults.standard.synchronize()
  169. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  170. }
  171. let rate = KMRateWindowController()
  172. let window = NSWindow.currentWindow()
  173. window.km_beginSheet(windowC: rate)
  174. rate.closeBlock = { wc in
  175. window.km_quick_endSheet()
  176. }
  177. return false
  178. }
  179. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  180. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  181. let url = URL(string: urlString) {
  182. // 在这里处理收到的 URL Scheme
  183. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  184. KMPrint("Path: \(url.path)")
  185. if NSApp.mainWindow == nil {
  186. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  187. launchApp(bundleIdentifier: bundleIdentifier)
  188. }
  189. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  190. #if VERSION_DMG
  191. // 执行相应的操作
  192. if url.scheme == "subscriptiondmgschemes" {
  193. if urlString.contains("open=expired") {
  194. KMPrint("刷新用户信息")
  195. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  196. KMLoginWindowController.show(window: NSApp.mainWindow!)
  197. } else {
  198. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  199. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  200. }
  201. }
  202. } else if urlString.contains("open=success") {
  203. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  204. KMLoginWindowController.show(window: NSApp.mainWindow!)
  205. } else {
  206. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  207. if isSuccess {
  208. } else {
  209. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  210. }
  211. }
  212. }
  213. }
  214. }
  215. #endif
  216. #if VERSION_FREE
  217. // 执行相应的操作
  218. if url.scheme == "subscriptionSchemes" {
  219. //刷新用户信息
  220. KMRequestServerManager.manager.getUserInfo { [weak self] success, data, error, isLocal in
  221. }
  222. if url.path == "/open" {
  223. // 执行打开操作
  224. } else if url.path == "/close" {
  225. // 执行关闭操作
  226. }
  227. }
  228. #endif
  229. }
  230. }
  231. }
  232. func launchApp(bundleIdentifier: String) {
  233. let workspace = NSWorkspace.shared
  234. // Launch the application with the specified bundle identifier
  235. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  236. do {
  237. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  238. } catch {
  239. print("Error launching the application: \(error)")
  240. }
  241. } else {
  242. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  243. }
  244. }
  245. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  246. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  247. print("Device token:", token)
  248. }
  249. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  250. }
  251. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  252. if !flag {
  253. let browser: KMBrowser = KMBrowser.init()
  254. browser.windowController = KMBrowserWindowController.init(browser: browser)
  255. browser.addHomeTabContents()
  256. browser.windowController.showWindow(self)
  257. }
  258. return flag
  259. }
  260. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  261. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  262. return false
  263. }
  264. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  265. if (filepaths == nil || filepaths!.count == 0) {
  266. return false
  267. }
  268. DispatchQueue.main.async {
  269. for filepath in filepaths! {
  270. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  271. }
  272. }
  273. }
  274. return false
  275. }
  276. func applicationWillTerminate(_ aNotification: Notification) {
  277. if (NSApp.orderedDocuments.count > 0) {
  278. var filepaths: [String] = []
  279. for document in NSApp.orderedDocuments {
  280. // KMPrint(document.fileURL as Any)
  281. if (document.fileURL?.path != nil) {
  282. filepaths.append((document.fileURL?.path)!)
  283. }
  284. }
  285. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  286. } else {
  287. KMPreferenceManager.shared.lastOpenFilepaths = nil
  288. }
  289. }
  290. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  291. return true
  292. }
  293. // MARK: private
  294. func reopenDocument(forPaths paths: [String]) -> Void {
  295. let browser = KMBrowser.init() as KMBrowser
  296. browser.windowController = KMBrowserWindowController.init(browser: browser)
  297. browser.addHomeTabContents()
  298. browser.windowController.showWindow(self)
  299. }
  300. @objc private func _themeChanged(_ sender: Notification) {
  301. if let data = NSApp.appearance?.name, data == .darkAqua {
  302. NSApp.appearance = .init(named: .aqua)
  303. } else {
  304. NSApp.appearance = .init(named: .darkAqua)
  305. }
  306. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  307. }
  308. @objc func AIDeviceStatusChangeNotification() {
  309. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  310. self.refreshAIMenuItemInfo()
  311. }
  312. }
  313. func refreshAIMenuItemInfo() -> Void {
  314. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  315. for item in appMenu!.items {
  316. if item.action == #selector(aiToolsAction) {
  317. item.isHidden = true
  318. }
  319. }
  320. }
  321. //MARK: - iVersion
  322. func initiVersionData() -> Void{
  323. #if VERSION_DMG
  324. return
  325. #endif
  326. let tVersion = iVersion.sharedInstance()
  327. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  328. var tStr = "New Update Available"
  329. tVersion?.updateAvailableTitle = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  330. tVersion?.versionLabelFormat = ""
  331. tVersion?.groupNotesByVersion = true
  332. tVersion?.showOnFirstLaunch = false
  333. tVersion?.checkPeriod = 2
  334. tVersion?.remindPeriod = 5
  335. let infoDictionary = Bundle .main.infoDictionary!
  336. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  337. if appName.count < 1 {
  338. appName = infoDictionary["CFBundleName"] as! String
  339. }
  340. tStr = "The new version of %@ is available now. Go update for new features.";
  341. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  342. tStr = String(format: tStr, appName)
  343. tVersion?.inThisVersionTitle = "\n" + tStr
  344. tStr = "UPDATE NOW";
  345. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  346. tStr = "LATER";
  347. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  348. tVersion!.ignoreButtonLabel = ""
  349. }
  350. // MARK: - Menu
  351. func initMainMenu() {
  352. // 处理菜单栏多语
  353. let mainMenu = NSApp.mainMenu
  354. if (mainMenu == nil) {
  355. return
  356. }
  357. for menu in mainMenu!.items {
  358. let subMenu = menu.submenu
  359. for item in subMenu!.items {
  360. item.title = NSLocalizedString(item.title, comment: "")
  361. let itemSubMenu = item.submenu
  362. if (itemSubMenu == nil) {
  363. continue
  364. }
  365. for item in itemSubMenu!.items {
  366. item.title = NSLocalizedString(item.title, comment: "")
  367. }
  368. }
  369. }
  370. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  371. #if VERSION_DMG
  372. PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 1)
  373. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  374. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  375. #endif
  376. #if !VERSION_DMG
  377. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  378. #endif
  379. if let items = PDFOfficeMenu?.items {
  380. for menu in items {
  381. let ranges = menu.title.ranges(of: "PDF Reader Pro")
  382. if let _range = ranges.range.first {
  383. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  384. }
  385. }
  386. }
  387. let fileMenu = mainMenu?.item(at: 1)?.submenu
  388. var shareItem: NSMenuItem?
  389. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  390. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  391. fileMenu?.insertItem(shareItem!, at: item.index)
  392. fileMenu?.insertItem(.separator(), at: item.index)
  393. } else {
  394. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  395. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  396. }
  397. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  398. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  399. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  400. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  401. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  402. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  403. let viewMenu = mainMenu?.item(at: 3)?.submenu
  404. var zoomMenu: NSMenu?
  405. for item in viewMenu!.items {
  406. if (item.title == NSLocalizedString("Zoom", comment: "")) {
  407. zoomMenu = item.submenu
  408. break
  409. }
  410. }
  411. if (zoomMenu != nil) {
  412. for item in zoomMenu!.items {
  413. if (item.title == NSLocalizedString("Zoom In", comment: "")) {
  414. item.keyEquivalent = "+"
  415. item.keyEquivalentModifierMask = [.command]
  416. break
  417. }
  418. }
  419. }
  420. }
  421. @objc func sharePageItemAction(sender: NSMenuItem) {
  422. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  423. return
  424. }
  425. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  426. let model: CTTabStripModel = windowControler.browser.tabStripModel
  427. if (model.count() <= 0) {
  428. return
  429. }
  430. if (model.activeTabContents().isHome) {
  431. return
  432. }
  433. let document: KMMainDocument = model.activeTabContents() as! KMMainDocument
  434. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  435. let represent : NSSharingService = sender.representedObject as! NSSharingService
  436. represent.perform(withItems: [document.fileURL as Any])
  437. return
  438. }
  439. // 有使用付费功能
  440. Task { @MainActor in
  441. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  442. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  443. if (isClose) {
  444. return
  445. }
  446. if (isSubscribeSuccess) {
  447. let represent : NSSharingService = sender.representedObject as! NSSharingService
  448. represent.perform(withItems: [document.fileURL as Any])
  449. return
  450. }
  451. if (isWaterMarkExport) {
  452. let doucumentURL = document.fileURL
  453. let docDir = NSTemporaryDirectory()
  454. let documentName : String = doucumentURL!.path.lastPathComponent
  455. let path = docDir.stringByAppendingPathComponent(documentName)
  456. let data = KMTools.saveWatermarkDocument(document: document.mainViewController!.document!, to: URL(fileURLWithPath: path), secureOptions: document.mainViewController!.secureOptions, removePWD: document.mainViewController!.removeSecureFlag)
  457. let writeSuccess = data != nil
  458. if writeSuccess == false {
  459. __NSBeep()
  460. return;
  461. }
  462. let represent : NSSharingService = sender.representedObject as! NSSharingService
  463. represent.perform(withItems: [data as Any])
  464. return
  465. }
  466. }
  467. return
  468. }
  469. let represent : NSSharingService = sender.representedObject as! NSSharingService
  470. represent.perform(withItems: [document.fileURL as Any])
  471. }
  472. }
  473. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  474. KMPrint("deviceCameraMenuItemAciton")
  475. }
  476. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  477. KMPrint("deviceScannerMenuItemAciton")
  478. }
  479. // MARK: PDF Reader Pro Menu
  480. @IBAction func openPreferenceWindow(_ sender: Any) {
  481. KMPreferenceController.shared.showWindow(self)
  482. }
  483. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  484. if KMLightMemberManager.manager.isLogin() {
  485. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  486. }
  487. }
  488. @IBAction func loginMenuItemAction(_ sender: Any) {
  489. // Login & Logout
  490. if KMLightMemberManager.manager.isLogin() {
  491. } else {
  492. KMLoginWindowController.show(window: NSApp.mainWindow!)
  493. }
  494. }
  495. @IBAction func logoutMenuItemAction(_ sender: Any) {
  496. // Login & Logout
  497. if KMLightMemberManager.manager.isLogin() {
  498. KMRequestServerManager.manager.logout { success, result in
  499. if success {
  500. KMPrint("登出成功")
  501. }
  502. }
  503. }
  504. }
  505. @IBAction func restoreMenuItemAction(_ sender: Any) {
  506. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  507. if isSuccess {
  508. } else {
  509. if error != .restoreSuccess {
  510. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  511. }
  512. }
  513. }
  514. }
  515. @objc func accountRefreshAction() {
  516. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  517. }
  518. }
  519. @objc func showAccount() {
  520. }
  521. @objc func resumePurchase() {
  522. }
  523. // MARK: help Menu
  524. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  525. KMTools.openQuickStartStudy()
  526. }
  527. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  528. KMTools.openFAQWebsite()
  529. }
  530. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  531. KMTools.openMoreProductWebsite()
  532. }
  533. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  534. KMTools.openFreePDFTemplatesWebsite()
  535. }
  536. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  537. KMEmailSubWindowController().showWindow(nil)
  538. }
  539. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  540. KMTools.openComPDFKitPowerWebsite()
  541. }
  542. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  543. KMTools.proposeNewFeature()
  544. }
  545. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  546. KMTools.rateUs()
  547. }
  548. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  549. #if VERSION_FREE
  550. KMPrint("restoreSubscriptions ...")
  551. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  552. compareWindowVC.showWindowRestore(nil)
  553. #else
  554. var vc: KMToolCompareWindowController? = nil
  555. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  556. vc!.showWindowRestore(sender: (Any).self)
  557. #endif
  558. }
  559. // MARK:- DMG
  560. @objc func checkForUpdates(_ sender: NSMenuItem) {
  561. #if VERSION_DMG
  562. SUUpdater.shared().checkForUpdates(sender)
  563. #endif
  564. }
  565. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  566. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  567. #if VERSION_DMG
  568. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  569. if SKInspectPublicTool.currentisLanguageHans() {
  570. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp_zh"
  571. }
  572. #else
  573. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  574. if SKInspectPublicTool.currentisLanguageHans() {
  575. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp_zh"
  576. }
  577. #endif
  578. guard let url = URL(string: tStrHttpUrl) else {
  579. NSSound.beep()
  580. return
  581. }
  582. let tWorkSpace = NSWorkspace.shared
  583. if tWorkSpace.open(url) == false {
  584. tWorkSpace.open(url)
  585. }
  586. }
  587. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  588. 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"
  589. if SKInspectPublicTool.currentisLanguageHans() {
  590. 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"
  591. }
  592. guard let url = URL(string: tStrHttpUrl) else {
  593. return
  594. }
  595. let tWorkSpace = NSWorkspace.shared
  596. if tWorkSpace.open(url) == false {
  597. tWorkSpace.open(url)
  598. }
  599. #if VERSION_DMG
  600. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  601. #endif
  602. }
  603. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  604. 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)
  605. guard let url = URL(string: tStrHttpUrl) else {
  606. return
  607. }
  608. let tWorkSpace = NSWorkspace.shared
  609. if tWorkSpace.open(url) == false {
  610. tWorkSpace.open(url)
  611. }
  612. #if VERSION_DMG
  613. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  614. #endif
  615. }
  616. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  617. #if VERSION_DMG
  618. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  619. #else
  620. AIPurchaseWindowController.currentWC().showWindow(nil)
  621. #endif
  622. }
  623. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  624. if let win = KMLineInspector.shared.window {
  625. if win.isVisible {
  626. win.orderOut(sender)
  627. } else {
  628. win.orderFront(sender)
  629. }
  630. }
  631. }
  632. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  633. KMPrint("showDownloads ...")
  634. }
  635. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  636. self.reopenDocument(forPaths: [])
  637. }
  638. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  639. KMEmailSubWindowController().showWindow(nil)
  640. }
  641. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  642. KMTools.feekback()
  643. }
  644. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  645. KMTools.reportBug()
  646. }
  647. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  648. KMTools.reportGeneralQuestions()
  649. }
  650. }
  651. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  652. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  653. let action = menuItem.action
  654. if action == #selector(manageAcctounMenuAction) {
  655. self.updateLoginMenuItem()
  656. return KMLightMemberManager.manager.isLogin()
  657. }
  658. if action == #selector(loginMenuItemAction) {
  659. self.updateLoginMenuItem()
  660. return !KMLightMemberManager.manager.isLogin()
  661. }
  662. if action == #selector(logoutMenuItemAction) {
  663. self.updateLoginMenuItem()
  664. return KMLightMemberManager.manager.isLogin()
  665. }
  666. if (action == #selector(sharePageItemAction)) {
  667. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  668. return false
  669. }
  670. return !_windowC.browser.activeTabContents().isHome
  671. }
  672. return true
  673. }
  674. func updateLoginMenuItem() {
  675. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  676. if firstItem != nil {
  677. let item1 = firstItem?.item(withTag: 11)
  678. let item2 = firstItem?.item(withTag: 12)
  679. let item3 = firstItem?.item(withTag: 13)
  680. let item4 = firstItem?.item(withTag: 14)
  681. // let item5 = firstItem?.item(withTag: 15)
  682. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  683. // if KMLightMemberManager.manager.isLogin() {
  684. // item1?.title = KMLightMemberManager.manager.info.email
  685. // item1?.isHidden = false
  686. // item2?.isHidden = true
  687. // item3?.isHidden = false
  688. // item4?.isHidden = false
  689. //// item5?.isHidden = false
  690. // item6?.isHidden = false
  691. // } else {
  692. // item1?.isHidden = true
  693. // item2?.isHidden = false
  694. // item3?.isHidden = true
  695. // item4?.isHidden = true
  696. //// item5?.isHidden = true
  697. // item6?.isHidden = true
  698. // }
  699. item1?.isHidden = true
  700. item2?.isHidden = true
  701. item3?.isHidden = true
  702. item4?.isHidden = true
  703. // item5?.isHidden = true
  704. item6?.isHidden = true
  705. }
  706. }
  707. @objc func clickOutline(menuItem: NSMenuItem) {
  708. KMPrint("更新菜单栏")
  709. }
  710. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  711. return true
  712. }
  713. }
  714. #if VERSION_DMG
  715. extension AppDelegate : SUUpdaterDelegate {
  716. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  717. }
  718. func feedURLString(for updater: SUUpdater) -> String? {
  719. #if DEBUG
  720. return "http://test-pdf-pro.kdan.cn:3021/downloads/pdfmasterprocast.xml"
  721. #else
  722. return "https://www.pdfreaderpro.com/downloads/pdfmasterprocast.xml"
  723. #endif
  724. }
  725. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  726. return false
  727. }
  728. func upgradeAPP(with updater: SUUpdater) {
  729. let string = "macappstore://apps.apple.com/cn/app/pdf-master-ai-pdf/id6446781258?mt=12"
  730. let url: URL = URL(string: string)!
  731. NSWorkspace.shared.open(url)
  732. }
  733. func upgradeButtonString(for updater: SUUpdater) -> String {
  734. return NSLocalizedString("PDF Reader Pro", comment: "")
  735. }
  736. }
  737. #endif
  738. extension AppDelegate {
  739. // MARK: - Services Support
  740. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  741. var error: NSError?
  742. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  743. // Document opened successfully
  744. } else if let error = error {
  745. errorString = error.localizedDescription
  746. }
  747. }
  748. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  749. var error: NSError?
  750. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  751. // Document opened successfully
  752. } else if let error = error {
  753. errorString = error.localizedDescription
  754. }
  755. }
  756. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  757. var error: NSError?
  758. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  759. // Document opened successfully
  760. } else if let error = error {
  761. errorString = error.localizedDescription
  762. }
  763. }
  764. }
  765. extension AppDelegate: UNUserNotificationCenterDelegate {
  766. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  767. // 处理用户点击推送通知的操作
  768. completionHandler()
  769. }
  770. }