AppDelegate.swift 35 KB

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