AppDelegate.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. @IBAction func closeDocument(_ sender: Any) {
  262. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  263. guard let windowControler = NSApp.mainWindow?.windowController else {
  264. return
  265. }
  266. windowControler.window?.performClose(nil)
  267. return
  268. }
  269. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  270. windowControler.browser.closeTab()
  271. }
  272. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  273. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  274. return false
  275. }
  276. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  277. if (filepaths == nil || filepaths!.count == 0) {
  278. return false
  279. }
  280. DispatchQueue.main.async {
  281. for filepath in filepaths! {
  282. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  283. }
  284. }
  285. }
  286. return false
  287. }
  288. func applicationWillTerminate(_ aNotification: Notification) {
  289. if (NSApp.orderedDocuments.count > 0) {
  290. var filepaths: [String] = []
  291. for document in NSApp.orderedDocuments {
  292. // KMPrint(document.fileURL as Any)
  293. if (document.fileURL?.path != nil) {
  294. filepaths.append((document.fileURL?.path)!)
  295. }
  296. }
  297. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  298. } else {
  299. KMPreferenceManager.shared.lastOpenFilepaths = nil
  300. }
  301. }
  302. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  303. return true
  304. }
  305. // MARK: private
  306. func reopenDocument(forPaths paths: [String]) -> Void {
  307. let browser = KMBrowser.init() as KMBrowser
  308. browser.windowController = KMBrowserWindowController.init(browser: browser)
  309. browser.addHomeTabContents()
  310. browser.windowController.showWindow(self)
  311. }
  312. @objc private func _themeChanged(_ sender: Notification) {
  313. if let data = NSApp.appearance?.name, data == .darkAqua {
  314. NSApp.appearance = .init(named: .aqua)
  315. } else {
  316. NSApp.appearance = .init(named: .darkAqua)
  317. }
  318. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  319. }
  320. @objc func AIDeviceStatusChangeNotification() {
  321. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  322. self.refreshAIMenuItemInfo()
  323. }
  324. }
  325. func refreshAIMenuItemInfo() -> Void {
  326. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  327. for item in appMenu!.items {
  328. if item.action == #selector(aiToolsAction) {
  329. item.isHidden = true
  330. }
  331. }
  332. }
  333. //MARK: - iVersion
  334. func initiVersionData() -> Void{
  335. #if VERSION_DMG
  336. return
  337. #endif
  338. let tVersion = iVersion.sharedInstance()
  339. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  340. var tStr = "New Update Available"
  341. tVersion?.updateAvailableTitle = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  342. tVersion?.versionLabelFormat = ""
  343. tVersion?.groupNotesByVersion = true
  344. tVersion?.showOnFirstLaunch = false
  345. tVersion?.checkPeriod = 2
  346. tVersion?.remindPeriod = 5
  347. let infoDictionary = Bundle .main.infoDictionary!
  348. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  349. if appName.count < 1 {
  350. appName = infoDictionary["CFBundleName"] as! String
  351. }
  352. tStr = "The new version of %@ is available now. Go update for new features.";
  353. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  354. tStr = String(format: tStr, appName)
  355. tVersion?.inThisVersionTitle = "\n" + tStr
  356. tStr = "UPDATE NOW";
  357. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  358. tStr = "LATER";
  359. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  360. tVersion!.ignoreButtonLabel = ""
  361. }
  362. // MARK: - Menu
  363. func initMainMenu() {
  364. // 处理菜单栏多语
  365. let mainMenu = NSApp.mainMenu
  366. if (mainMenu == nil) {
  367. return
  368. }
  369. for menu in mainMenu!.items {
  370. let subMenu = menu.submenu
  371. for item in subMenu!.items {
  372. item.title = NSLocalizedString(item.title, comment: "")
  373. let itemSubMenu = item.submenu
  374. if (itemSubMenu == nil) {
  375. continue
  376. }
  377. for item in itemSubMenu!.items {
  378. item.title = NSLocalizedString(item.title, comment: "")
  379. }
  380. }
  381. }
  382. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  383. #if VERSION_DMG
  384. PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 1)
  385. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  386. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  387. #endif
  388. #if !VERSION_DMG
  389. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  390. #endif
  391. if let items = PDFOfficeMenu?.items {
  392. for menu in items {
  393. let ranges = menu.title.ranges(of: "PDF Reader Pro")
  394. if let _range = ranges.range.first {
  395. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  396. }
  397. }
  398. }
  399. let fileMenu = mainMenu?.item(at: 1)?.submenu
  400. var shareItem: NSMenuItem?
  401. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  402. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  403. fileMenu?.insertItem(shareItem!, at: item.index)
  404. fileMenu?.insertItem(.separator(), at: item.index)
  405. } else {
  406. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  407. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  408. }
  409. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  410. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  411. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  412. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  413. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  414. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  415. let viewMenu = mainMenu?.item(at: 3)?.submenu
  416. var zoomMenu: NSMenu?
  417. for item in viewMenu!.items {
  418. if (item.title == NSLocalizedString("Zoom", comment: "")) {
  419. zoomMenu = item.submenu
  420. break
  421. }
  422. }
  423. if (zoomMenu != nil) {
  424. for item in zoomMenu!.items {
  425. if (item.title == NSLocalizedString("Zoom In", comment: "")) {
  426. item.keyEquivalent = "+"
  427. item.keyEquivalentModifierMask = [.command]
  428. break
  429. }
  430. }
  431. }
  432. }
  433. @objc func sharePageItemAction(sender: NSMenuItem) {
  434. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  435. return
  436. }
  437. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  438. let model: CTTabStripModel = windowControler.browser.tabStripModel
  439. if (model.count() <= 0) {
  440. return
  441. }
  442. if (model.activeTabContents().isHome) {
  443. return
  444. }
  445. let document: KMMainDocument = model.activeTabContents() as! KMMainDocument
  446. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  447. let represent : NSSharingService = sender.representedObject as! NSSharingService
  448. represent.perform(withItems: [document.fileURL as Any])
  449. return
  450. }
  451. // 有使用付费功能
  452. Task { @MainActor in
  453. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  454. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  455. if (isClose) {
  456. return
  457. }
  458. if (isSubscribeSuccess) {
  459. let represent : NSSharingService = sender.representedObject as! NSSharingService
  460. represent.perform(withItems: [document.fileURL as Any])
  461. return
  462. }
  463. if (isWaterMarkExport) {
  464. let doucumentURL = document.fileURL
  465. let docDir = NSTemporaryDirectory()
  466. let documentName : String = doucumentURL!.path.lastPathComponent
  467. let path = docDir.stringByAppendingPathComponent(documentName)
  468. let data = KMTools.saveWatermarkDocument(document: document.mainViewController!.document!, to: URL(fileURLWithPath: path), secureOptions: document.mainViewController!.secureOptions, removePWD: document.mainViewController!.removeSecureFlag)
  469. let writeSuccess = data != nil
  470. if writeSuccess == false {
  471. __NSBeep()
  472. return;
  473. }
  474. let represent : NSSharingService = sender.representedObject as! NSSharingService
  475. represent.perform(withItems: [data as Any])
  476. return
  477. }
  478. }
  479. return
  480. }
  481. let represent : NSSharingService = sender.representedObject as! NSSharingService
  482. represent.perform(withItems: [document.fileURL as Any])
  483. }
  484. }
  485. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  486. KMPrint("deviceCameraMenuItemAciton")
  487. }
  488. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  489. KMPrint("deviceScannerMenuItemAciton")
  490. }
  491. // MARK: PDF Reader Pro Menu
  492. @IBAction func openPreferenceWindow(_ sender: Any) {
  493. KMPreferenceController.shared.showWindow(self)
  494. }
  495. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  496. if KMLightMemberManager.manager.isLogin() {
  497. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  498. }
  499. }
  500. @IBAction func loginMenuItemAction(_ sender: Any) {
  501. // Login & Logout
  502. if KMLightMemberManager.manager.isLogin() {
  503. } else {
  504. KMLoginWindowController.show(window: NSApp.mainWindow!)
  505. }
  506. }
  507. @IBAction func logoutMenuItemAction(_ sender: Any) {
  508. // Login & Logout
  509. if KMLightMemberManager.manager.isLogin() {
  510. KMRequestServerManager.manager.logout { success, result in
  511. if success {
  512. KMPrint("登出成功")
  513. }
  514. }
  515. }
  516. }
  517. @IBAction func restoreMenuItemAction(_ sender: Any) {
  518. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  519. if isSuccess {
  520. } else {
  521. if error != .restoreSuccess {
  522. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  523. }
  524. }
  525. }
  526. }
  527. @objc func accountRefreshAction() {
  528. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  529. }
  530. }
  531. @objc func showAccount() {
  532. }
  533. @objc func resumePurchase() {
  534. }
  535. // MARK: help Menu
  536. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  537. KMTools.openQuickStartStudy()
  538. }
  539. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  540. KMTools.openFAQWebsite()
  541. }
  542. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  543. KMTools.openMoreProductWebsite()
  544. }
  545. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  546. KMTools.openFreePDFTemplatesWebsite()
  547. }
  548. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  549. KMEmailSubWindowController().showWindow(nil)
  550. }
  551. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  552. KMTools.openComPDFKitPowerWebsite()
  553. }
  554. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  555. KMTools.proposeNewFeature()
  556. }
  557. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  558. KMTools.rateUs()
  559. }
  560. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  561. #if VERSION_FREE
  562. KMPrint("restoreSubscriptions ...")
  563. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  564. compareWindowVC.showWindowRestore(nil)
  565. #else
  566. var vc: KMToolCompareWindowController? = nil
  567. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  568. vc!.showWindowRestore(sender: (Any).self)
  569. #endif
  570. }
  571. // MARK:- DMG
  572. @objc func checkForUpdates(_ sender: NSMenuItem) {
  573. #if VERSION_DMG
  574. SUUpdater.shared().checkForUpdates(sender)
  575. #endif
  576. }
  577. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  578. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  579. #if VERSION_DMG
  580. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  581. if SKInspectPublicTool.currentisLanguageHans() {
  582. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp_zh"
  583. }
  584. #else
  585. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  586. if SKInspectPublicTool.currentisLanguageHans() {
  587. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp_zh"
  588. }
  589. #endif
  590. guard let url = URL(string: tStrHttpUrl) else {
  591. NSSound.beep()
  592. return
  593. }
  594. let tWorkSpace = NSWorkspace.shared
  595. if tWorkSpace.open(url) == false {
  596. tWorkSpace.open(url)
  597. }
  598. }
  599. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  600. 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"
  601. if SKInspectPublicTool.currentisLanguageHans() {
  602. 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"
  603. }
  604. guard let url = URL(string: tStrHttpUrl) else {
  605. return
  606. }
  607. let tWorkSpace = NSWorkspace.shared
  608. if tWorkSpace.open(url) == false {
  609. tWorkSpace.open(url)
  610. }
  611. #if VERSION_DMG
  612. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  613. #endif
  614. }
  615. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  616. 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)
  617. guard let url = URL(string: tStrHttpUrl) else {
  618. return
  619. }
  620. let tWorkSpace = NSWorkspace.shared
  621. if tWorkSpace.open(url) == false {
  622. tWorkSpace.open(url)
  623. }
  624. #if VERSION_DMG
  625. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  626. #endif
  627. }
  628. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  629. #if VERSION_DMG
  630. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  631. #else
  632. AIPurchaseWindowController.currentWC().showWindow(nil)
  633. #endif
  634. }
  635. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  636. if let win = KMLineInspector.shared.window {
  637. if win.isVisible {
  638. win.orderOut(sender)
  639. } else {
  640. win.orderFront(sender)
  641. }
  642. }
  643. }
  644. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  645. KMPrint("showDownloads ...")
  646. }
  647. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  648. self.reopenDocument(forPaths: [])
  649. }
  650. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  651. KMEmailSubWindowController().showWindow(nil)
  652. }
  653. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  654. KMTools.feekback()
  655. }
  656. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  657. KMTools.reportBug()
  658. }
  659. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  660. KMTools.reportGeneralQuestions()
  661. }
  662. }
  663. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  664. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  665. let action = menuItem.action
  666. if action == #selector(manageAcctounMenuAction) {
  667. self.updateLoginMenuItem()
  668. return KMLightMemberManager.manager.isLogin()
  669. }
  670. if action == #selector(loginMenuItemAction) {
  671. self.updateLoginMenuItem()
  672. return !KMLightMemberManager.manager.isLogin()
  673. }
  674. if action == #selector(logoutMenuItemAction) {
  675. self.updateLoginMenuItem()
  676. return KMLightMemberManager.manager.isLogin()
  677. }
  678. if (action == #selector(sharePageItemAction)) {
  679. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  680. return false
  681. }
  682. return !_windowC.browser.activeTabContents().isHome
  683. }
  684. return true
  685. }
  686. func updateLoginMenuItem() {
  687. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  688. if firstItem != nil {
  689. let item1 = firstItem?.item(withTag: 11)
  690. let item2 = firstItem?.item(withTag: 12)
  691. let item3 = firstItem?.item(withTag: 13)
  692. let item4 = firstItem?.item(withTag: 14)
  693. // let item5 = firstItem?.item(withTag: 15)
  694. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  695. // if KMLightMemberManager.manager.isLogin() {
  696. // item1?.title = KMLightMemberManager.manager.info.email
  697. // item1?.isHidden = false
  698. // item2?.isHidden = true
  699. // item3?.isHidden = false
  700. // item4?.isHidden = false
  701. //// item5?.isHidden = false
  702. // item6?.isHidden = false
  703. // } else {
  704. // item1?.isHidden = true
  705. // item2?.isHidden = false
  706. // item3?.isHidden = true
  707. // item4?.isHidden = true
  708. //// item5?.isHidden = true
  709. // item6?.isHidden = true
  710. // }
  711. item1?.isHidden = true
  712. item2?.isHidden = true
  713. item3?.isHidden = true
  714. item4?.isHidden = true
  715. // item5?.isHidden = true
  716. item6?.isHidden = true
  717. }
  718. }
  719. @objc func clickOutline(menuItem: NSMenuItem) {
  720. KMPrint("更新菜单栏")
  721. }
  722. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  723. return true
  724. }
  725. }
  726. #if VERSION_DMG
  727. extension AppDelegate : SUUpdaterDelegate {
  728. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  729. }
  730. func feedURLString(for updater: SUUpdater) -> String? {
  731. #if DEBUG
  732. return "http://test-pdf-pro.kdan.cn:3021/downloads/pdfmasterprocast.xml"
  733. #else
  734. return "https://www.pdfreaderpro.com/downloads/pdfmasterprocast.xml"
  735. #endif
  736. }
  737. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  738. return false
  739. }
  740. func upgradeAPP(with updater: SUUpdater) {
  741. let string = "macappstore://apps.apple.com/cn/app/pdf-master-ai-pdf/id6446781258?mt=12"
  742. let url: URL = URL(string: string)!
  743. NSWorkspace.shared.open(url)
  744. }
  745. func upgradeButtonString(for updater: SUUpdater) -> String {
  746. return NSLocalizedString("PDF Reader Pro", comment: "")
  747. }
  748. }
  749. #endif
  750. extension AppDelegate {
  751. // MARK: - Services Support
  752. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  753. var error: NSError?
  754. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  755. // Document opened successfully
  756. } else if let error = error {
  757. errorString = error.localizedDescription
  758. }
  759. }
  760. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  761. var error: NSError?
  762. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  763. // Document opened successfully
  764. } else if let error = error {
  765. errorString = error.localizedDescription
  766. }
  767. }
  768. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  769. var error: NSError?
  770. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  771. // Document opened successfully
  772. } else if let error = error {
  773. errorString = error.localizedDescription
  774. }
  775. }
  776. }
  777. extension AppDelegate: UNUserNotificationCenterDelegate {
  778. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  779. // 处理用户点击推送通知的操作
  780. completionHandler()
  781. }
  782. }