AppDelegate.swift 36 KB

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