AppDelegate.swift 36 KB

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