AppDelegate.swift 45 KB

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