AppDelegate.swift 40 KB

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