AppDelegate.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. //
  2. // AppDelegate.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2022/9/23.
  6. //
  7. import Cocoa
  8. @main
  9. class AppDelegate: NSObject, NSApplicationDelegate, iRateDelegate{
  10. func applicationWillFinishLaunching(_ notification: Notification) {
  11. #if VERSION_FREE
  12. #if VERSION_DMG
  13. CPD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FlaO/7ZpewBkqMhR1sG/D/3Jjsevjbb32Ut+5f8JWMFL7gFHikJx6PJwxlEEfVHP/dqNkFfBJKTqjjZoj9LNxxkOngdfNDsnWigFkZUSivLNCXAJ+a4C/mHaaRf95ad20LA0NahljpcTQ7x8TR8fuAHZkFK4DnFK+ST8zSP17/yW3x9ACHU6arojAbZ0IAz2pZRRuYYl9YB07NckfhpuE2qQAu+IaHm32opV2P/l/7HZUt7hsw7wAHIKJqnBs4cNag==")
  15. #else
  16. CPDFKit.setLicenseKey("1vz4jXcu5aWfQMr627tGjHjWHG+72WKPzgwSoeGqDlRtLAxe4CTHas7qUep1D46CjreeqLWWV06cFepolm8wCBlZscJaV9/dCyDMi/zMTh47O+sIky0oYdusH/8+jyGruF4pgtinJ/oZg/P95jw4/E0HpoZ9AH9eGpD2XRy8mHk=", secret: "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4rCrm/O2+fI9yUYXNZ/JY1KPbFCeKgG+lEVwrbGHrpAyXATqjrt8ApqRYhafFooQjwAFgayISwZT/pa4NjR459gu4aGVjtYuk+Uxs/kosIBwyxQV1SVCQFsC27oMGz5P/rBQYv0T/D0N0z+Um3U+I+tG7BHAIgXXXaVusko5CeqTvQgas5D7/+aJEhkQvgEI0O+1BYV01oFLnRch1j6tFihDymhFKcLuOq5fKgsuDdHcA==")
  17. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+v5w339rXeJw+v0hhIv5Q4btZUOscw80t3c1bXxpLq3B6fv6psGJP0+FMyQOerBP6u4YYan9tCSe6rawjumJYCQMT5YNHtN/72HTYtc9HAcQzdMudePhw3hYY3747Z6Sq7DCCqgbK+BnM11gxblULiTgFkYLZsuBudusbqrM7WktIkcfpLfh15Y+TZ04iXpI9LWkgKoeYZ1VAJMTcrfwCs63g/8nUiZ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EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+v5w339rXeJw+v0hhIv5Q4btZUOscw80t3c1bXxpLq3B6fv6psGJP0+FMyQOerBP6u4YYan9tCSe6rawjumJYCQMT5YNHtN/72HTYtc9HAcQzdMudePhw3hYY3747Z6Sq7DCCqgbK+BnM11gxblULiTgFkYLZsuBudusbqrM7WktIkcfpLfh15Y+TZ04iXpI9LWkgKoeYZ1VAJMTcrfwCs63g/8nUiZ59kpdetHbzONEIhsi+Wu0lH1oY17eVN2TRW5amzrZsD0yy20WxEXrssgDJq7xPzi1sOZ56C+jdE/8p9tNUW4KYJ5GoqCVh5w0Ajkc3xRqWrpmJXUollqL+u9K6VDPqy3tmvVGdknJxHlX4q+ufAQa+Tb3qlEJwp14dhrbJERqUs5Gygc6W5Fk18+uJ6IjwvilMe8T8+t3vLDZPlOgVg4lqZaxlBn/t+RvkJ/76CDO1/Byfqmig2vE4qETJmxV+pK4Lftqjsxibe087g3EFlaO/7ZpewBkqMhR1sG/D/3Jjsevjbb32Ut+5f8JWMFL7gFHikJx6PJwxlEEfVHP/dqNkFfBJKTqjjZoj9LNxxkOngdfNDsnWigFkZUSivLNCXAJ+a4C/mHaaRf95ad20LA0NahljpcTQ7x8TR8fuAHZkFK4DnFK+ST8zSP17/yW3x9ACHU6arojAbZ0IAz2pZRRuYYl9YB07NckfhpuE2qQAu+IaHm32opV2P/l/7HZUt7hsw7wAHIKJqnBs4cNag==")
  22. #endif
  23. ComPDFUIConfig.initializeUIConfig()
  24. KMDesignToken.shared.parserExcel(withPath: "")
  25. }
  26. func applicationDidFinishLaunching(_ aNotification: Notification) {
  27. // Insert code here to initialize your application
  28. #if VERSION_DMG
  29. let updater = SUUpdater.shared()
  30. updater?.delegate = self
  31. updater?.automaticallyChecksForUpdates = true
  32. #else
  33. #endif
  34. //Firebase RemoteConfig
  35. #if VERSION_FREE
  36. KMKdanRemoteConfig.remoteConfig().fetch { _status, error in
  37. }
  38. #endif
  39. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  40. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  41. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  42. let sud = UserDefaults.standard
  43. if versionString.isEmpty == false {
  44. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  45. }
  46. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  47. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  48. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  49. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  50. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  51. sud.synchronize()
  52. }
  53. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  54. NSApp.servicesProvider = self
  55. KMKdanRemoteConfig.remoteConfig().fetchWithRemoteConfigCompletionHandler { status, error in
  56. }
  57. KMStatusBar.system()
  58. // MARK: 广告数据初始化
  59. var appName: KMAdvertisementAppNameType = .PDFReaderProMac
  60. #if VERSION_FREE
  61. #if VERSION_DMG
  62. appName = .PDFReaderProMacDMG
  63. #else
  64. #endif
  65. #else
  66. appName = .PDFReaderProMacPro
  67. #endif
  68. KMAdvertisementManager.manager.initConfig(appName: appName,
  69. subscribeType: .unknow,
  70. platform: .Mac)
  71. // 测试模式,默认false
  72. KMAdvertisementManager.manager.debug = true
  73. NSApp.appearance = NSAppearance.current
  74. KMAnalytics.configure()
  75. //第一次开启app
  76. var info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount")
  77. var count = 0
  78. if info != nil {
  79. count = info as? Int ?? 0
  80. }
  81. count += 1
  82. UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount")
  83. UserDefaults.standard.synchronize()
  84. self.initMainMenu()
  85. /// pro
  86. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  87. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  88. reopenDocument(forPaths: [])
  89. KMPreference.shared.initDataForAppLaunch()
  90. self.initiRateData()
  91. let appleEventManager = NSAppleEventManager.shared()
  92. appleEventManager.setEventHandler(self,
  93. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  94. forEventClass: AEEventClass(kInternetEventClass),
  95. andEventID: AEEventID(kAEGetURL))
  96. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  97. #if VERSION_DMG
  98. VerificationManager.default()
  99. #else
  100. self.initiVersionData()
  101. #endif
  102. //AI相关
  103. AIInfoManager.default()
  104. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  105. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  106. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  107. var error: Unmanaged<CFError>?
  108. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  109. print("Failed to register font!")
  110. } else {
  111. print("Font registered successfully!")
  112. }
  113. }
  114. }
  115. func initiRateData() {
  116. iRate.sharedInstance().delegate = self
  117. #if VERSION_FREE
  118. iRate.sharedInstance().appStoreID = 919472673
  119. #else
  120. iRate.sharedInstance().appStoreID = 825459243
  121. #endif
  122. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  123. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  124. }
  125. //MARK: iRateDelegate
  126. func iRateUserDidDeclineToRateApp() {
  127. }
  128. func iRateShouldPromptForRating() -> Bool {
  129. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  130. if !notShow {
  131. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  132. UserDefaults.standard.synchronize()
  133. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  134. }
  135. let rate = KMRateWindowController()
  136. let window = NSWindow.currentWindow()
  137. window.km_beginSheet(windowC: rate)
  138. rate.closeBlock = { wc in
  139. window.km_quick_endSheet()
  140. }
  141. return false
  142. }
  143. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  144. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  145. let url = URL(string: urlString) {
  146. // 在这里处理收到的 URL Scheme
  147. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  148. KMPrint("Path: \(url.path)")
  149. if NSApp.mainWindow == nil {
  150. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  151. launchApp(bundleIdentifier: bundleIdentifier)
  152. }
  153. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  154. #if VERSION_DMG
  155. // 执行相应的操作
  156. if url.scheme == "subscriptiondmgschemes" {
  157. if urlString.contains("open=expired") {
  158. KMPrint("刷新用户信息")
  159. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  160. KMLoginWindowController.show(window: NSApp.mainWindow!)
  161. } else {
  162. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  163. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  164. }
  165. }
  166. } else if urlString.contains("open=success") {
  167. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  168. KMLoginWindowController.show(window: NSApp.mainWindow!)
  169. } else {
  170. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  171. if isSuccess {
  172. } else {
  173. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  174. }
  175. }
  176. }
  177. }
  178. }
  179. #endif
  180. #if VERSION_FREE
  181. // 执行相应的操作
  182. if url.scheme == "subscriptionSchemes" {
  183. //刷新用户信息
  184. KMRequestServerManager.manager.getUserInfo { [weak self] success, data, error, isLocal in
  185. }
  186. if url.path == "/open" {
  187. // 执行打开操作
  188. } else if url.path == "/close" {
  189. // 执行关闭操作
  190. }
  191. }
  192. #endif
  193. }
  194. }
  195. }
  196. func launchApp(bundleIdentifier: String) {
  197. let workspace = NSWorkspace.shared
  198. // Launch the application with the specified bundle identifier
  199. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  200. do {
  201. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  202. } catch {
  203. print("Error launching the application: \(error)")
  204. }
  205. } else {
  206. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  207. }
  208. }
  209. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  210. }
  211. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  212. }
  213. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  214. if !flag {
  215. let browser: KMBrowser = KMBrowser.init()
  216. browser.windowController = KMBrowserWindowController.init(browser: browser)
  217. browser.addHomeTabContents()
  218. browser.windowController.showWindow(self)
  219. }
  220. return flag
  221. }
  222. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  223. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  224. return false
  225. }
  226. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  227. if (filepaths == nil || filepaths!.count == 0) {
  228. return false
  229. }
  230. DispatchQueue.main.async {
  231. for filepath in filepaths! {
  232. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  233. }
  234. }
  235. }
  236. return false
  237. }
  238. func applicationWillTerminate(_ aNotification: Notification) {
  239. if (NSApp.orderedDocuments.count > 0) {
  240. var filepaths: [String] = []
  241. for document in NSApp.orderedDocuments {
  242. // KMPrint(document.fileURL as Any)
  243. if (document.fileURL?.path != nil) {
  244. filepaths.append((document.fileURL?.path)!)
  245. }
  246. }
  247. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  248. } else {
  249. KMPreferenceManager.shared.lastOpenFilepaths = nil
  250. }
  251. }
  252. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  253. return true
  254. }
  255. // MARK: private
  256. func reopenDocument(forPaths paths: [String]) -> Void {
  257. let browser = KMBrowser.init() as KMBrowser
  258. browser.windowController = KMBrowserWindowController.init(browser: browser)
  259. browser.addHomeTabContents()
  260. browser.windowController.showWindow(self)
  261. }
  262. @objc private func _themeChanged(_ sender: Notification) {
  263. if let data = NSApp.appearance?.name, data == .darkAqua {
  264. NSApp.appearance = .init(named: .aqua)
  265. } else {
  266. NSApp.appearance = .init(named: .darkAqua)
  267. }
  268. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  269. }
  270. @objc func AIDeviceStatusChangeNotification() {
  271. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  272. self.refreshAIMenuItemInfo()
  273. }
  274. }
  275. func refreshAIMenuItemInfo() -> Void {
  276. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  277. for item in appMenu!.items {
  278. if item.action == #selector(aiToolsAction) {
  279. item.isHidden = true
  280. }
  281. }
  282. }
  283. //MARK: - iVersion
  284. func initiVersionData() -> Void{
  285. #if VERSION_DMG
  286. return
  287. #endif
  288. let tVersion = iVersion.sharedInstance()
  289. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  290. var tStr = "New Update Available"
  291. tVersion?.updateAvailableTitle = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  292. tVersion?.versionLabelFormat = ""
  293. tVersion?.groupNotesByVersion = true
  294. tVersion?.showOnFirstLaunch = false
  295. tVersion?.checkPeriod = 2
  296. tVersion?.remindPeriod = 5
  297. let infoDictionary = Bundle .main.infoDictionary!
  298. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  299. if appName.count < 1 {
  300. appName = infoDictionary["CFBundleName"] as! String
  301. }
  302. tStr = "The new version of %@ is available now. Go update for new features.";
  303. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  304. tStr = String(format: tStr, appName)
  305. tVersion?.inThisVersionTitle = "\n" + tStr
  306. tStr = "UPDATE NOW";
  307. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  308. tStr = "LATER";
  309. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  310. tVersion!.ignoreButtonLabel = ""
  311. }
  312. // MARK: - Menu
  313. func initMainMenu() {
  314. // 处理菜单栏多语
  315. let mainMenu = NSApp.mainMenu
  316. if (mainMenu == nil) {
  317. return
  318. }
  319. for menu in mainMenu!.items {
  320. let subMenu = menu.submenu
  321. for item in subMenu!.items {
  322. item.title = NSLocalizedString(item.title, comment: "")
  323. let itemSubMenu = item.submenu
  324. if (itemSubMenu == nil) {
  325. continue
  326. }
  327. for item in itemSubMenu!.items {
  328. item.title = NSLocalizedString(item.title, comment: "")
  329. }
  330. }
  331. }
  332. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  333. #if VERSION_DMG
  334. PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 1)
  335. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  336. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  337. #endif
  338. #if !VERSION_DMG
  339. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  340. #endif
  341. if let items = PDFOfficeMenu?.items {
  342. for menu in items {
  343. let ranges = menu.title.ranges(of: "PDF Reader Pro")
  344. if let _range = ranges.range.first {
  345. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  346. }
  347. }
  348. }
  349. let fileMenu = mainMenu?.item(at: 1)?.submenu
  350. var shareItem: NSMenuItem?
  351. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  352. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  353. fileMenu?.insertItem(shareItem!, at: item.index)
  354. fileMenu?.insertItem(.separator(), at: item.index)
  355. } else {
  356. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  357. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  358. }
  359. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  360. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  361. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  362. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  363. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  364. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  365. let viewMenu = mainMenu?.item(at: 3)?.submenu
  366. var zoomMenu: NSMenu?
  367. for item in viewMenu!.items {
  368. if (item.title == NSLocalizedString("Zoom", comment: "")) {
  369. zoomMenu = item.submenu
  370. break
  371. }
  372. }
  373. if (zoomMenu != nil) {
  374. for item in zoomMenu!.items {
  375. if (item.title == NSLocalizedString("Zoom In", comment: "")) {
  376. item.keyEquivalent = "+"
  377. item.keyEquivalentModifierMask = [.command]
  378. break
  379. }
  380. }
  381. }
  382. }
  383. @objc func sharePageItemAction(sender: NSMenuItem) {
  384. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  385. return
  386. }
  387. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  388. let model: CTTabStripModel = windowControler.browser.tabStripModel
  389. if (model.count() <= 0) {
  390. return
  391. }
  392. if (model.activeTabContents().isHome) {
  393. return
  394. }
  395. let document: KMMainDocument = model.activeTabContents() as! KMMainDocument
  396. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  397. let represent : NSSharingService = sender.representedObject as! NSSharingService
  398. represent.perform(withItems: [document.fileURL as Any])
  399. return
  400. }
  401. // 有使用付费功能
  402. Task { @MainActor in
  403. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  404. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  405. if (isClose) {
  406. return
  407. }
  408. if (isSubscribeSuccess) {
  409. let represent : NSSharingService = sender.representedObject as! NSSharingService
  410. represent.perform(withItems: [document.fileURL as Any])
  411. return
  412. }
  413. if (isWaterMarkExport) {
  414. let doucumentURL = document.fileURL
  415. let docDir = NSTemporaryDirectory()
  416. let documentName : String = doucumentURL!.path.lastPathComponent
  417. let path = docDir.stringByAppendingPathComponent(documentName)
  418. let data = KMTools.saveWatermarkDocument(document: document.mainViewController!.document!, to: URL(fileURLWithPath: path), secureOptions: document.mainViewController!.secureOptions, removePWD: document.mainViewController!.removeSecureFlag)
  419. let writeSuccess = data != nil
  420. if writeSuccess == false {
  421. __NSBeep()
  422. return;
  423. }
  424. let represent : NSSharingService = sender.representedObject as! NSSharingService
  425. represent.perform(withItems: [data as Any])
  426. return
  427. }
  428. }
  429. return
  430. }
  431. let represent : NSSharingService = sender.representedObject as! NSSharingService
  432. represent.perform(withItems: [document.fileURL as Any])
  433. }
  434. }
  435. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  436. KMPrint("deviceCameraMenuItemAciton")
  437. }
  438. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  439. KMPrint("deviceScannerMenuItemAciton")
  440. }
  441. // MARK: PDF Reader Pro Menu
  442. @IBAction func openPreferenceWindow(_ sender: Any) {
  443. KMPreferenceController.shared.showWindow(self)
  444. }
  445. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  446. if KMLightMemberManager.manager.isLogin() {
  447. KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  448. }
  449. }
  450. @IBAction func loginMenuItemAction(_ sender: Any) {
  451. // Login & Logout
  452. if KMLightMemberManager.manager.isLogin() {
  453. } else {
  454. KMLoginWindowController.show(window: NSApp.mainWindow!)
  455. }
  456. }
  457. @IBAction func logoutMenuItemAction(_ sender: Any) {
  458. // Login & Logout
  459. if KMLightMemberManager.manager.isLogin() {
  460. KMRequestServerManager.manager.logout { success, result in
  461. if success {
  462. KMPrint("登出成功")
  463. }
  464. }
  465. }
  466. }
  467. @IBAction func restoreMenuItemAction(_ sender: Any) {
  468. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  469. if isSuccess {
  470. } else {
  471. if error != .restoreSuccess {
  472. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  473. }
  474. }
  475. }
  476. }
  477. @objc func accountRefreshAction() {
  478. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  479. }
  480. }
  481. @objc func showAccount() {
  482. }
  483. @objc func resumePurchase() {
  484. }
  485. // MARK: help Menu
  486. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  487. KMTools.openQuickStartStudy()
  488. }
  489. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  490. KMTools.openFAQWebsite()
  491. }
  492. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  493. KMTools.openMoreProductWebsite()
  494. }
  495. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  496. KMTools.openFreePDFTemplatesWebsite()
  497. }
  498. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  499. KMEmailSubWindowController().showWindow(nil)
  500. }
  501. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  502. KMTools.openComPDFKitPowerWebsite()
  503. }
  504. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  505. KMTools.proposeNewFeature()
  506. }
  507. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  508. KMTools.rateUs()
  509. }
  510. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  511. #if VERSION_FREE
  512. KMPrint("restoreSubscriptions ...")
  513. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  514. compareWindowVC.showWindowRestore(nil)
  515. #else
  516. var vc: KMToolCompareWindowController? = nil
  517. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  518. vc!.showWindowRestore(sender: (Any).self)
  519. #endif
  520. }
  521. // MARK:- DMG
  522. @objc func checkForUpdates(_ sender: NSMenuItem) {
  523. #if VERSION_DMG
  524. SUUpdater.shared().checkForUpdates(sender)
  525. #endif
  526. }
  527. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  528. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  529. #if VERSION_DMG
  530. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  531. if SKInspectPublicTool.currentisLanguageHans() {
  532. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp_zh"
  533. }
  534. #else
  535. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  536. if SKInspectPublicTool.currentisLanguageHans() {
  537. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp_zh"
  538. }
  539. #endif
  540. guard let url = URL(string: tStrHttpUrl) else {
  541. NSSound.beep()
  542. return
  543. }
  544. let tWorkSpace = NSWorkspace.shared
  545. if tWorkSpace.open(url) == false {
  546. tWorkSpace.open(url)
  547. }
  548. }
  549. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  550. var tStrHttpUrl = "https://www.pdfreaderpro.com/store/pdf-pro-permanent-cross-platform-package?utm_source=pdf_pro_dmgs&utm_medium=toptbr_help&utm_campaign=cross_platform"
  551. if SKInspectPublicTool.currentisLanguageHans() {
  552. tStrHttpUrl = "https://www.pdfreaderpro.com/zh-cn/store/pdf-pro-permanent-cross-platform-package?utm_source=pdf_pro_dmg&utm_medium=toptbr_help_cn&utm_campaign=cross_platform"
  553. }
  554. guard let url = URL(string: tStrHttpUrl) else {
  555. return
  556. }
  557. let tWorkSpace = NSWorkspace.shared
  558. if tWorkSpace.open(url) == false {
  559. tWorkSpace.open(url)
  560. }
  561. #if VERSION_DMG
  562. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  563. #endif
  564. }
  565. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  566. let tStrHttpUrl = KMLocalizedString("https://www.pdfreaderpro.com/store?mode=edu#utm_source=mac_app&utm_medium=pdf_pro_dmg&utm_content=menu_bar_click", nil)
  567. guard let url = URL(string: tStrHttpUrl) else {
  568. return
  569. }
  570. let tWorkSpace = NSWorkspace.shared
  571. if tWorkSpace.open(url) == false {
  572. tWorkSpace.open(url)
  573. }
  574. #if VERSION_DMG
  575. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  576. #endif
  577. }
  578. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  579. #if VERSION_DMG
  580. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  581. #else
  582. AIPurchaseWindowController.currentWC().showWindow(nil)
  583. #endif
  584. }
  585. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  586. if let win = KMLineInspector.shared.window {
  587. if win.isVisible {
  588. win.orderOut(sender)
  589. } else {
  590. win.orderFront(sender)
  591. }
  592. }
  593. }
  594. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  595. KMPrint("showDownloads ...")
  596. }
  597. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  598. self.reopenDocument(forPaths: [])
  599. }
  600. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  601. KMEmailSubWindowController().showWindow(nil)
  602. }
  603. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  604. KMTools.feekback()
  605. }
  606. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  607. KMTools.reportBug()
  608. }
  609. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  610. KMTools.reportGeneralQuestions()
  611. }
  612. }
  613. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  614. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  615. let action = menuItem.action
  616. if action == #selector(manageAcctounMenuAction) {
  617. self.updateLoginMenuItem()
  618. return KMLightMemberManager.manager.isLogin()
  619. }
  620. if action == #selector(loginMenuItemAction) {
  621. self.updateLoginMenuItem()
  622. return !KMLightMemberManager.manager.isLogin()
  623. }
  624. if action == #selector(logoutMenuItemAction) {
  625. self.updateLoginMenuItem()
  626. return KMLightMemberManager.manager.isLogin()
  627. }
  628. if (action == #selector(sharePageItemAction)) {
  629. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  630. return false
  631. }
  632. return !_windowC.browser.activeTabContents().isHome
  633. }
  634. return true
  635. }
  636. func updateLoginMenuItem() {
  637. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  638. if firstItem != nil {
  639. let item1 = firstItem?.item(withTag: 11)
  640. let item2 = firstItem?.item(withTag: 12)
  641. let item3 = firstItem?.item(withTag: 13)
  642. let item4 = firstItem?.item(withTag: 14)
  643. // let item5 = firstItem?.item(withTag: 15)
  644. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  645. // if KMLightMemberManager.manager.isLogin() {
  646. // item1?.title = KMLightMemberManager.manager.info.email
  647. // item1?.isHidden = false
  648. // item2?.isHidden = true
  649. // item3?.isHidden = false
  650. // item4?.isHidden = false
  651. //// item5?.isHidden = false
  652. // item6?.isHidden = false
  653. // } else {
  654. // item1?.isHidden = true
  655. // item2?.isHidden = false
  656. // item3?.isHidden = true
  657. // item4?.isHidden = true
  658. //// item5?.isHidden = true
  659. // item6?.isHidden = true
  660. // }
  661. item1?.isHidden = true
  662. item2?.isHidden = true
  663. item3?.isHidden = true
  664. item4?.isHidden = true
  665. // item5?.isHidden = true
  666. item6?.isHidden = true
  667. }
  668. }
  669. @objc func clickOutline(menuItem: NSMenuItem) {
  670. KMPrint("更新菜单栏")
  671. }
  672. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  673. return true
  674. }
  675. }
  676. #if VERSION_DMG
  677. extension AppDelegate : SUUpdaterDelegate {
  678. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  679. }
  680. func feedURLString(for updater: SUUpdater) -> String? {
  681. #if DEBUG
  682. return "http://test-pdf-pro.kdan.cn:3021/downloads/pdfmasterprocast.xml"
  683. #else
  684. return "https://www.pdfreaderpro.com/downloads/pdfmasterprocast.xml"
  685. #endif
  686. }
  687. func updaterShouldPromptForPermissionToCheck(forUpdates updater: SUUpdater) -> Bool {
  688. return false
  689. }
  690. func upgradeAPP(with updater: SUUpdater) {
  691. let string = "macappstore://apps.apple.com/cn/app/pdf-master-ai-pdf/id6446781258?mt=12"
  692. let url: URL = URL(string: string)!
  693. NSWorkspace.shared.open(url)
  694. }
  695. func upgradeButtonString(for updater: SUUpdater) -> String {
  696. return NSLocalizedString("PDF Reader Pro", comment: "")
  697. }
  698. }
  699. #endif
  700. extension AppDelegate {
  701. // MARK: - Services Support
  702. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  703. var error: NSError?
  704. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  705. // Document opened successfully
  706. } else if let error = error {
  707. errorString = error.localizedDescription
  708. }
  709. }
  710. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  711. var error: NSError?
  712. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  713. // Document opened successfully
  714. } else if let error = error {
  715. errorString = error.localizedDescription
  716. }
  717. }
  718. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  719. var error: NSError?
  720. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  721. // Document opened successfully
  722. } else if let error = error {
  723. errorString = error.localizedDescription
  724. }
  725. }
  726. }