AppDelegate.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. //
  2. // AppDelegate.swift
  3. // EaseUS PDF Editor
  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("ILzWBz74Au6H6nAgfuLueZgx2sL9fyuofhY/RcyuS101S3lOkN8PcgQ8jhLMYsIlxJ7h0sXKj9DBvNJrUm/edLenMprULIkhS+CDOL1OqLuJzxTkkKvJC0xcFuYjZSFogcRlejcV3HrZMSUaXx1/aVRQ5M+Dgks6pz75ACBV0NGDTRvwg6f5tWxbvvGRNjFXgS9RT6ZTT5GCw0BvT6fVJTfySeUGXvypC9lbS9El/RC9ziF3ILtzaCETPGQpYiToHEeV6qxPKrekymz5TrZP4kmhum8sHq0O9fZlfVUbSfTWUNY+kfxfr2pXmV5OKxTE58BaZwX/e3OgyECTFWip4Gu0lH1oY17eVN2TRW5amzpoR+M3L2G8qcuBkzBxz6n+YqbX2e/YD1yP1NIkUcZYAqt2ZgDmM9pLFD5as/LM2qPlxxK0kU1GqK92dq3mZGyHUrsiLcIQuK5+OCAao0nnpKlpAsBh5HwjJExzJQdpX9LAxHQ2x8CUbJSuOWBQa1HKv5ekO8j2fD1sjavSZ7c9R/kckGDxzwpQWgc/gcyxQrPTnNstgZ/Uomj9dPW6StotG95pqnSVAGJBXa4B+I1KECLwgPKNkxRRURLoa4dQiOMViyeaDhm30O9zdCO/bfxs19kbvik4ENqZozbRflTjYFiP/U+TS74+B5XhMfXL0o0QaFdc8GwIWMK0SYrNIJneJl9iA4wO+hpQJDAjlus1OeKyZU+8bpmzyUc7/iwmb8OOMFYUoX+4NxRn1os+WHoq2Pi85lD6iwVebIjX8woQgMUWq2/oUpUhb+7PiD7wPfl6n9Cax7qLM3rkoH4ITCPk")
  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+BnM11gxblULiTgFkYLZsuBudusbqrM7WktIkcf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6f5tWxbvvGRNjFXgS9RT6ZTT5GCw0BvT6fVJTfySeUGXvypC9lbS9El/RC9ziF3ILtzaCETPGQpYiToHEeV6qxPKrekymz5TrZP4kmhum8sHq0O9fZlfVUbSfTWUNY+kfxfr2pXmV5OKxTE58BaZwX/e3OgyECTFWip4Gu0lH1oY17eVN2TRW5amzpoR+M3L2G8qcuBkzBxz6n+YqbX2e/YD1yP1NIkUcZYAqt2ZgDmM9pLFD5as/LM2qPlxxK0kU1GqK92dq3mZGyHUrsiLcIQuK5+OCAao0nnpKlpAsBh5HwjJExzJQdpX9LAxHQ2x8CUbJSuOWBQa1HKv5ekO8j2fD1sjavSZ7c9R/kckGDxzwpQWgc/gcyxQrPTnNstgZ/Uomj9dPW6StotG95pqnSVAGJBXa4B+I1KECLwgPKNkxRRURLoa4dQiOMViyeaDhm30O9zdCO/bfxs19kbvik4ENqZozbRflTjYFiP/U+TS74+B5XhMfXL0o0QaFdc8GwIWMK0SYrNIJneJl9iA4wO+hpQJDAjlus1OeKyZU+8bpmzyUc7/iwmb8OOMFYUoX+4NxRn1os+WHoq2Pi85lD6iwVebIjX8woQgMUWq2/oUpUhb+7PiD7wPfl6n9Cax7qLM3rkoH4ITCPk")
  25. ComPDFUIConfig.initializeUIConfig()
  26. KMDesignToken.shared.parserExcel(withPath: "")
  27. }
  28. func applicationDidFinishLaunching(_ aNotification: Notification) {
  29. // Insert code here to initialize your application
  30. //通知
  31. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  32. if granted {
  33. KMPrint("User authorized notifications")
  34. } else {
  35. KMPrint("User denied notifications")
  36. }
  37. }
  38. /**本地推送测试
  39. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  40. if granted {
  41. // 创建本地推送通知
  42. let content = UNMutableNotificationContent()
  43. content.title = "Test Notification"
  44. content.body = "This is a test notification!"
  45. // 触发条件,例如延迟 5 秒触发
  46. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  47. // 创建通知请求
  48. let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
  49. // 添加通知请求到用户通知中心
  50. UNUserNotificationCenter.current().add(request) { error in
  51. if let error = error {
  52. print("Error adding notification request: \(error)")
  53. } else {
  54. print("Local notification scheduled")
  55. }
  56. }
  57. } else {
  58. print("User denied notifications")
  59. }
  60. }
  61. **/
  62. DispatchQueue.main.async {
  63. NSApplication.shared.registerForRemoteNotifications()
  64. }
  65. //Firebase RemoteConfig
  66. #if VERSION_FREE
  67. KMKdanRemoteConfig.remoteConfig.fetch { _status, error in
  68. }
  69. #endif
  70. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  71. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  72. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  73. let sud = UserDefaults.standard
  74. if versionString.isEmpty == false {
  75. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  76. }
  77. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  78. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  79. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  80. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  81. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  82. sud.synchronize()
  83. }
  84. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  85. NSApp.servicesProvider = self
  86. KMKdanRemoteConfig.remoteConfig.fetchWithRemoteConfigCompletionHandler { status, error in
  87. }
  88. KMStatusBar.system()
  89. NSApp.appearance = NSAppearance.current
  90. //第一次开启app
  91. let info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount")
  92. var count = 0
  93. if info != nil {
  94. count = info as? Int ?? 0
  95. }
  96. count += 1
  97. UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount")
  98. UserDefaults.standard.synchronize()
  99. self.initMainMenu()
  100. /// pro
  101. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  102. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  103. reopenDocument(forPaths: [])
  104. KMPreference.shared.initDataForAppLaunch()
  105. self.initiRateData()
  106. let appleEventManager = NSAppleEventManager.shared()
  107. appleEventManager.setEventHandler(self,
  108. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  109. forEventClass: AEEventClass(kInternetEventClass),
  110. andEventID: AEEventID(kAEGetURL))
  111. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  112. #if VERSION_DMG
  113. VerificationManager.default()
  114. KMDMGProductsManager.shareInstance.getProductDatas()
  115. #else
  116. self.initiVersionData()
  117. IAPProductsManager.default().initIAP()
  118. #endif
  119. //AI相关
  120. AIInfoManager.default()
  121. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  122. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  123. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  124. var error: Unmanaged<CFError>?
  125. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  126. print("Failed to register font!")
  127. } else {
  128. print("Font registered successfully!")
  129. }
  130. }
  131. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  132. for item in appMenu!.items {
  133. if item.action == #selector(aiToolsAction) {
  134. if let tManager = VerificationManager.default() {
  135. let status = tManager.status
  136. if status == ActivityStatusNone {
  137. item.isHidden = true
  138. }
  139. }
  140. }
  141. }
  142. NotificationCenter.default.addObserver(self, selector: #selector(deviceActivateStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  143. }
  144. func initiRateData() {
  145. iRate.sharedInstance().delegate = self
  146. #if VERSION_FREE
  147. iRate.sharedInstance().appStoreID = 919472673
  148. #else
  149. iRate.sharedInstance().appStoreID = 825459243
  150. #endif
  151. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  152. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  153. }
  154. //MARK: iRateDelegate
  155. func iRateUserDidDeclineToRateApp() {
  156. KMVerificationWindowController.verificationFeedback()
  157. }
  158. func iRateShouldPromptForRating() -> Bool {
  159. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  160. if !notShow {
  161. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  162. UserDefaults.standard.synchronize()
  163. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  164. }
  165. return false
  166. }
  167. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  168. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  169. let url = URL(string: urlString) {
  170. // 在这里处理收到的 URL Scheme
  171. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  172. KMPrint("Path: \(url.path)")
  173. if NSApp.mainWindow == nil {
  174. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  175. launchApp(bundleIdentifier: bundleIdentifier)
  176. }
  177. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  178. #if VERSION_DMG
  179. // 执行相应的操作
  180. if url.scheme == "subscriptiondmgschemes" {
  181. if urlString.contains("open=expired") {
  182. KMPrint("刷新用户信息")
  183. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  184. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  185. } else {
  186. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  187. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  188. }
  189. }
  190. } else if urlString.contains("open=success") {
  191. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  192. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  193. } else {
  194. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  195. if isSuccess {
  196. } else {
  197. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  198. }
  199. }
  200. }
  201. }
  202. }
  203. #endif
  204. #if VERSION_FREE
  205. // 执行相应的操作
  206. if url.scheme == "subscriptionSchemes" {
  207. //刷新用户信息
  208. KMRequestServerManager.manager.getUserInfo { success, data, error, isLocal in
  209. }
  210. if url.path == "/open" {
  211. // 执行打开操作
  212. } else if url.path == "/close" {
  213. // 执行关闭操作
  214. }
  215. }
  216. #endif
  217. }
  218. }
  219. }
  220. func launchApp(bundleIdentifier: String) {
  221. let workspace = NSWorkspace.shared
  222. // Launch the application with the specified bundle identifier
  223. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  224. do {
  225. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  226. } catch {
  227. print("Error launching the application: \(error)")
  228. }
  229. } else {
  230. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  231. }
  232. }
  233. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  234. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  235. print("Device token:", token)
  236. }
  237. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  238. }
  239. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  240. if !flag {
  241. let browser: KMBrowser = KMBrowser.init()
  242. browser.windowController = KMBrowserWindowController.init(browser: browser)
  243. browser.addHomeTabContents()
  244. browser.windowController.showWindow(self)
  245. }
  246. return flag
  247. }
  248. @IBAction func closeDocument(_ sender: Any) {
  249. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  250. guard let windowControler = NSApp.mainWindow?.windowController else {
  251. return
  252. }
  253. windowControler.window?.performClose(nil)
  254. return
  255. }
  256. let windowControler = NSApp.mainWindow?.windowController as? KMBrowserWindowController
  257. if let data = windowControler?.browser, data.tabCount() >= 2 { // 有两个以上的标签
  258. if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应
  259. return
  260. }
  261. }
  262. if let browser = windowControler?.browser {
  263. if browser.tabCount() == 1 {
  264. windowControler?.window?.close()
  265. } else {
  266. if let _ = windowControler?.window?.attachedSheet {
  267. NSSound.beep()
  268. return
  269. }
  270. browser.closeTab()
  271. }
  272. } else {
  273. windowControler?.window?.close()
  274. }
  275. }
  276. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  277. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  278. return false
  279. }
  280. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  281. if (filepaths == nil || filepaths!.count == 0) {
  282. return false
  283. }
  284. DispatchQueue.main.async {
  285. for filepath in filepaths! {
  286. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  287. }
  288. }
  289. }
  290. return false
  291. }
  292. func applicationWillTerminate(_ aNotification: Notification) {
  293. if (NSDocumentController.shared.documents.count > 0) {
  294. var filepaths: [String] = []
  295. for document in NSDocumentController.shared.documents {
  296. // KMPrint(document.fileURL as Any)
  297. if (document.fileURL?.path != nil) {
  298. filepaths.append((document.fileURL?.path)!)
  299. }
  300. }
  301. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  302. } else {
  303. KMPreferenceManager.shared.lastOpenFilepaths = nil
  304. }
  305. }
  306. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  307. return true
  308. }
  309. // MARK: private
  310. func reopenDocument(forPaths paths: [String]) -> Void {
  311. let browser = KMBrowser.init() as KMBrowser
  312. browser.windowController = KMBrowserWindowController.init(browser: browser)
  313. browser.addHomeTabContents()
  314. browser.windowController.showWindow(self)
  315. }
  316. @objc private func _themeChanged(_ sender: Notification) {
  317. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  318. if isDarkModel {
  319. NSApp.appearance = NSAppearance(named: .darkAqua)
  320. } else {
  321. NSApp.appearance = NSAppearance(named: .aqua)
  322. }
  323. // if let data = NSApp.appearance?.name, data == .darkAqua {
  324. // NSApp.appearance = .init(named: .aqua)
  325. // } else {
  326. // NSApp.appearance = .init(named: .darkAqua)
  327. // }
  328. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  329. }
  330. @objc func AIDeviceStatusChangeNotification() {
  331. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  332. self.refreshAIMenuItemInfo()
  333. }
  334. }
  335. @objc func deviceActivateStatusChangeNotification() {
  336. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  337. for item in appMenu!.items {
  338. if item.action == #selector(aiToolsAction) {
  339. if let tManager = VerificationManager.default() {
  340. let status = tManager.status
  341. if status == ActivityStatusNone {
  342. item.isHidden = true
  343. }
  344. }
  345. }
  346. }
  347. }
  348. func refreshAIMenuItemInfo() -> Void {
  349. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  350. for item in appMenu!.items {
  351. if item.action == #selector(aiToolsAction) {
  352. item.isHidden = true
  353. }
  354. }
  355. }
  356. //MARK: - iVersion
  357. func initiVersionData() -> Void{
  358. #if VERSION_DMG
  359. #else
  360. let tVersion = iVersion.sharedInstance()
  361. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  362. var tStr = "New Update Available"
  363. tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n"
  364. tVersion?.versionLabelFormat = ""
  365. tVersion?.groupNotesByVersion = true
  366. tVersion?.showOnFirstLaunch = false
  367. tVersion?.checkPeriod = 2
  368. tVersion?.remindPeriod = 5
  369. let infoDictionary = Bundle .main.infoDictionary!
  370. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  371. if appName.count < 1 {
  372. appName = infoDictionary["CFBundleName"] as! String
  373. }
  374. tStr = "The new version of %@ is available now. Go update for new features.";
  375. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  376. tStr = String(format: tStr, appName)
  377. tVersion?.inThisVersionTitle = tStr
  378. tStr = "UPDATE NOW";
  379. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  380. tStr = "LATER";
  381. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  382. tVersion!.ignoreButtonLabel = ""
  383. #endif
  384. }
  385. // MARK: - Menu
  386. func initMainMenu() {
  387. // 处理菜单栏多语
  388. let mainMenu = NSApp.mainMenu
  389. if (mainMenu == nil) {
  390. return
  391. }
  392. for menu in mainMenu!.items {
  393. let subMenu = menu.submenu
  394. for item in subMenu!.items {
  395. item.title = NSLocalizedString(item.title, comment: "")
  396. let itemSubMenu = item.submenu
  397. if (itemSubMenu == nil) {
  398. continue
  399. }
  400. for item in itemSubMenu!.items {
  401. item.title = NSLocalizedString(item.title, comment: "")
  402. let itemSubMenu = item.submenu
  403. if (itemSubMenu == nil) {
  404. continue
  405. }
  406. for item in itemSubMenu!.items {
  407. item.title = NSLocalizedString(item.title, comment: "")
  408. }
  409. }
  410. }
  411. }
  412. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  413. #if VERSION_DMG
  414. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4)
  415. // if ([VerificationManager manager].needUpgradeLicense == NO) {
  416. if VerificationManager.default().needUpgradeLicense {
  417. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5)
  418. }
  419. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  420. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  421. #endif
  422. #if !VERSION_DMG
  423. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  424. #endif
  425. if let items = PDFOfficeMenu?.items {
  426. for menu in items {
  427. let ranges = menu.title.ranges(of: "EaseUS PDF Editor")
  428. if let _range = ranges.range.first {
  429. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  430. }
  431. }
  432. }
  433. let fileMenu = mainMenu?.item(at: 1)?.submenu
  434. var shareItem: NSMenuItem?
  435. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  436. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  437. fileMenu?.insertItem(shareItem!, at: item.index)
  438. fileMenu?.insertItem(.separator(), at: item.index)
  439. } else {
  440. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  441. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  442. }
  443. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  444. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  445. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  446. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  447. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  448. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  449. }
  450. @objc func sharePageItemAction(sender: NSMenuItem) {
  451. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  452. return
  453. }
  454. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  455. let model = windowControler.browser?.tabStripModel
  456. if let cnt = model?.count(), cnt <= 0 {
  457. return
  458. }
  459. if let data = model?.activeTabContents()?.isHome, data {
  460. return
  461. }
  462. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  463. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  464. let represent : NSSharingService = sender.representedObject as! NSSharingService
  465. represent.perform(withItems: [document.fileURL as Any])
  466. return
  467. }
  468. let represent : NSSharingService = sender.representedObject as! NSSharingService
  469. represent.perform(withItems: [document.fileURL as Any])
  470. }
  471. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  472. KMPrint("deviceCameraMenuItemAciton")
  473. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil)
  474. }
  475. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  476. KMPrint("deviceScannerMenuItemAciton")
  477. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil)
  478. }
  479. // MARK: EaseUS PDF Editor 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. }
  562. @objc func enterLicense(_ sender: NSMenuItem) {
  563. #if VERSION_DMG
  564. if let tManager = VerificationManager.default() {
  565. let status = tManager.status
  566. if status == ActivityStatusVerifExpire {
  567. let vc = KMVerificationWindowController.verification(with: .activateExpired)
  568. vc?.showWindow(nil)
  569. } else if status == ActivityStatusVerification {
  570. let vc = KMVerificationWindowController.verification(with: .info)
  571. vc?.showWindow(nil)
  572. } else {
  573. let vc = KMVerificationWindowController.verification(with: .activate)
  574. vc?.showWindow(nil)
  575. }
  576. }
  577. #endif
  578. }
  579. @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) {
  580. #if VERSION_DMG
  581. // var url = URL(string: Store_Link + "?product_code=product_2")
  582. // let tWorkSpace = NSWorkspace.shared
  583. // if tWorkSpace.open(url!) == false {
  584. // tWorkSpace.open(url!)
  585. // }
  586. var url = URL(string: "https://www.easeus-software.com/pdf-editor/buy-pdf-mac.html")
  587. let tWorkSpace = NSWorkspace.shared
  588. if tWorkSpace.open(url!) == false {
  589. tWorkSpace.open(url!)
  590. }
  591. #endif
  592. }
  593. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  594. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  595. #if VERSION_DMG
  596. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  597. #else
  598. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  599. #endif
  600. guard let url = URL(string: tStrHttpUrl) else {
  601. NSSound.beep()
  602. return
  603. }
  604. let tWorkSpace = NSWorkspace.shared
  605. if tWorkSpace.open(url) == false {
  606. tWorkSpace.open(url)
  607. }
  608. }
  609. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  610. var tStrHttpUrl = CrossPlatform_Link
  611. guard let url = URL(string: tStrHttpUrl) else {
  612. return
  613. }
  614. let tWorkSpace = NSWorkspace.shared
  615. if tWorkSpace.open(url) == false {
  616. tWorkSpace.open(url)
  617. }
  618. }
  619. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  620. let tStrHttpUrl = Store_Edu_Link
  621. guard let url = URL(string: tStrHttpUrl) else {
  622. return
  623. }
  624. let tWorkSpace = NSWorkspace.shared
  625. if tWorkSpace.open(url) == false {
  626. tWorkSpace.open(url)
  627. }
  628. }
  629. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  630. #if VERSION_DMG
  631. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  632. #else
  633. AIPurchaseWindowController.currentWC().showWindow(nil)
  634. #endif
  635. }
  636. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  637. if let win = KMLineInspector.shared.window {
  638. if win.isVisible {
  639. win.orderOut(sender)
  640. } else {
  641. win.orderFront(sender)
  642. }
  643. }
  644. }
  645. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  646. KMPrint("showDownloads ...")
  647. }
  648. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  649. self.reopenDocument(forPaths: [])
  650. }
  651. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  652. KMEmailSubWindowController().showWindow(nil)
  653. }
  654. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  655. KMTools.feekback()
  656. }
  657. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  658. KMTools.reportBug()
  659. }
  660. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  661. KMTools.reportGeneralQuestions()
  662. }
  663. }
  664. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  665. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  666. let action = menuItem.action
  667. if action == #selector(manageAcctounMenuAction) {
  668. self.updateLoginMenuItem()
  669. return KMLightMemberManager.manager.isLogin()
  670. }
  671. if action == #selector(loginMenuItemAction) {
  672. self.updateLoginMenuItem()
  673. return !KMLightMemberManager.manager.isLogin()
  674. }
  675. if action == #selector(logoutMenuItemAction) {
  676. self.updateLoginMenuItem()
  677. return KMLightMemberManager.manager.isLogin()
  678. }
  679. if (action == #selector(sharePageItemAction)) {
  680. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  681. return false
  682. }
  683. let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  684. return !isHome
  685. }
  686. if action == #selector(closeDocument) {
  687. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  688. if NSApp.mainWindow?.windowController != nil {
  689. return true
  690. }
  691. return false
  692. }
  693. let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false
  694. if isNewTab {
  695. return true
  696. }
  697. // let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  698. // return !isHome
  699. }
  700. return true
  701. }
  702. func updateLoginMenuItem() {
  703. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  704. if firstItem != nil {
  705. let item1 = firstItem?.item(withTag: 11)
  706. let item2 = firstItem?.item(withTag: 12)
  707. let item3 = firstItem?.item(withTag: 13)
  708. let item4 = firstItem?.item(withTag: 14)
  709. // let item5 = firstItem?.item(withTag: 15)
  710. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  711. // if KMLightMemberManager.manager.isLogin() {
  712. // item1?.title = KMLightMemberManager.manager.info.email
  713. // item1?.isHidden = false
  714. // item2?.isHidden = true
  715. // item3?.isHidden = false
  716. // item4?.isHidden = false
  717. //// item5?.isHidden = false
  718. // item6?.isHidden = false
  719. // } else {
  720. // item1?.isHidden = true
  721. // item2?.isHidden = false
  722. // item3?.isHidden = true
  723. // item4?.isHidden = true
  724. //// item5?.isHidden = true
  725. // item6?.isHidden = true
  726. // }
  727. item1?.isHidden = true
  728. item2?.isHidden = true
  729. item3?.isHidden = true
  730. item4?.isHidden = true
  731. // item5?.isHidden = true
  732. item6?.isHidden = true
  733. }
  734. }
  735. @objc func clickOutline(menuItem: NSMenuItem) {
  736. KMPrint("更新菜单栏")
  737. }
  738. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  739. return true
  740. }
  741. }
  742. extension AppDelegate {
  743. // MARK: - Services Support
  744. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  745. var error: NSError?
  746. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  747. // Document opened successfully
  748. } else if let error = error {
  749. errorString = error.localizedDescription
  750. }
  751. }
  752. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  753. var error: NSError?
  754. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  755. // Document opened successfully
  756. } else if let error = error {
  757. errorString = error.localizedDescription
  758. }
  759. }
  760. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  761. var error: NSError?
  762. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  763. // Document opened successfully
  764. } else if let error = error {
  765. errorString = error.localizedDescription
  766. }
  767. }
  768. }
  769. extension AppDelegate: UNUserNotificationCenterDelegate {
  770. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  771. // 处理用户点击推送通知的操作
  772. completionHandler()
  773. }
  774. }