AppDelegate.swift 39 KB

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