AppDelegate.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. //
  2. // AppDelegate.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2022/9/23.
  6. //
  7. import Cocoa
  8. import UserNotifications
  9. import KMComponentLibrary
  10. @main
  11. class AppDelegate: NSObject, NSApplicationDelegate, iRateDelegate{
  12. var rateWindowVC: KMRateWindowController!
  13. func applicationWillFinishLaunching(_ notification: Notification) {
  14. #if VERSION_FREE
  15. #if VERSION_DMG
  16. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/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==")
  17. #else
  18. CPDFConvertKit.setLicenseKey("6zZWsJZxS0gKqledWY3Wo8AC+0IQ0EU1u9Wp7IVHvMsHpPe/0IPk9aNAbMUZwpTHMicme3hvjORzGJYnpBvb3/Z82a1GikkQmNZd+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n37TM/hBROJ3ufWlCiyNQy5AlRqzN1AAIKVmJzmOQCOcohtAQS/ULdkM2FO7GcxWLAf1YhWUmCAiDfm1c1lrdjqG0V0XpnGga69npgRspIG1y9kaZz89k1E7lWRj5bPVsGo+cInV8gEE9jyu1d/w+z+IoMv/64lho9GX2iJoq9a2ZlLQs3Nchtt3ztkLOIrL83eqpD+OFl7xBMsabCVNViM2vieVHPpj+ryaMGUv809szrKYrmDEsg4RKbxuXysKB3jpAHRMF+rSFAwQSTXQlmZfbxpitFoKX83UBkha60z3+yyZvjzxnVmPLWTnX0u13CDIXEvC3V6mR2aaKvVJnE5h5fVw9F2s3H5Q55YkTYg==")
  24. ComPDFUIConfig.initializeUIConfig()
  25. KMDesignToken.shared.parserExcel(withPath: "")
  26. ComponentLibrary.shared.parserExcel(withPath: "")
  27. }
  28. func applicationDidFinishLaunching(_ aNotification: Notification) {
  29. // Insert code here to initialize your application
  30. KMNThumbnailManager.clearCacheThumImage() //清除页面缩图缓存
  31. //通知
  32. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  33. if granted {
  34. KMPrint("User authorized notifications")
  35. } else {
  36. KMPrint("User denied notifications")
  37. }
  38. }
  39. DispatchQueue.main.async {
  40. NSApplication.shared.registerForRemoteNotifications()
  41. }
  42. #if VERSION_DMG
  43. let updater = SUUpdater.shared()
  44. updater?.delegate = self
  45. updater?.automaticallyChecksForUpdates = true
  46. #else
  47. #endif
  48. //Firebase RemoteConfig
  49. #if VERSION_FREE
  50. KMKdanRemoteConfig.remoteConfig.fetch { _status, error in
  51. }
  52. #endif
  53. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  54. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  55. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  56. let sud = UserDefaults.standard
  57. if versionString.isEmpty == false {
  58. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  59. }
  60. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  61. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  62. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  63. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  64. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  65. sud.synchronize()
  66. }
  67. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  68. NSApp.servicesProvider = self
  69. KMStatusBar.system()
  70. // MARK: 广告数据初始化
  71. var appName: KMAdvertisementAppNameType = .PDFReaderProMac
  72. #if VERSION_FREE
  73. #if VERSION_DMG
  74. appName = .PDFReaderProMacDMG
  75. #else
  76. #endif
  77. #else
  78. appName = .PDFReaderProMacPro
  79. #endif
  80. KMAdvertisementManager.manager.initConfig(appName: appName,
  81. subscribeType: .unknow,
  82. platform: .Mac)
  83. // 测试模式,默认false
  84. KMAdvertisementManager.manager.debug = true
  85. NSApp.appearance = NSAppearance.current
  86. KMAnalytics.configure()
  87. //第一次开启app
  88. let info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount")
  89. var count = 0
  90. if info != nil {
  91. count = info as? Int ?? 0
  92. }
  93. count += 1
  94. UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount")
  95. UserDefaults.standard.synchronize()
  96. self.initMainMenu()
  97. /// pro
  98. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  99. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  100. reopenDocument(forPaths: [])
  101. KMPreference.shared.initDataForAppLaunch()
  102. self.initiRateData()
  103. let appleEventManager = NSAppleEventManager.shared()
  104. appleEventManager.setEventHandler(self,
  105. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  106. forEventClass: AEEventClass(kInternetEventClass),
  107. andEventID: AEEventID(kAEGetURL))
  108. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  109. #if VERSION_DMG
  110. VerificationManager.default()
  111. KMDMGProductsManager.shareInstance.getProductDatas()
  112. #else
  113. self.initiVersionData()
  114. IAPProductsManager.default().initIAP()
  115. #endif
  116. //AI相关
  117. AIInfoManager.default()
  118. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  119. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  120. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  121. var error: Unmanaged<CFError>?
  122. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  123. print("Failed to register font!")
  124. } else {
  125. print("Font registered successfully!")
  126. }
  127. }
  128. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  129. for item in appMenu!.items {
  130. if item.action == #selector(aiToolsAction) {
  131. if let tManager = VerificationManager.default() {
  132. let status = tManager.status
  133. if status == ActivityStatusNone {
  134. item.isHidden = true
  135. }
  136. }
  137. }
  138. }
  139. NotificationCenter.default.addObserver(self, selector: #selector(deviceActivateStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  140. }
  141. func initiRateData() {
  142. iRate.sharedInstance().delegate = self
  143. #if VERSION_FREE
  144. iRate.sharedInstance().appStoreID = 919472673
  145. #else
  146. iRate.sharedInstance().appStoreID = 825459243
  147. #endif
  148. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  149. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  150. }
  151. //MARK: iRateDelegate
  152. func iRateUserDidDeclineToRateApp() {
  153. KMVerificationWindowController.verificationFeedback()
  154. }
  155. func iRateShouldPromptForRating() -> Bool {
  156. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  157. if !notShow {
  158. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  159. UserDefaults.standard.synchronize()
  160. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  161. }
  162. self.rateWindowVC = KMRateWindowController.init(windowNibName: "KMRateWindowController")
  163. self.rateWindowVC.closeBlock = { wc in
  164. }
  165. self.rateWindowVC.closeBlock = { wc in
  166. }
  167. self.rateWindowVC.showWindow(nil)
  168. return false
  169. }
  170. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  171. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  172. let url = URL(string: urlString) {
  173. // 在这里处理收到的 URL Scheme
  174. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  175. KMPrint("Path: \(url.path)")
  176. if NSApp.mainWindow == nil {
  177. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  178. launchApp(bundleIdentifier: bundleIdentifier)
  179. }
  180. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  181. #if VERSION_DMG
  182. // 执行相应的操作
  183. if url.scheme == "subscriptiondmgschemes" {
  184. }
  185. #endif
  186. #if VERSION_FREE
  187. // 执行相应的操作
  188. if url.scheme == "subscriptionSchemes" {
  189. if url.path == "/open" {
  190. // 执行打开操作
  191. } else if url.path == "/close" {
  192. // 执行关闭操作
  193. }
  194. }
  195. #endif
  196. }
  197. }
  198. }
  199. func launchApp(bundleIdentifier: String) {
  200. let workspace = NSWorkspace.shared
  201. // Launch the application with the specified bundle identifier
  202. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  203. do {
  204. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  205. } catch {
  206. print("Error launching the application: \(error)")
  207. }
  208. } else {
  209. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  210. }
  211. }
  212. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  213. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  214. print("Device token:", token)
  215. }
  216. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  217. }
  218. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  219. if !flag {
  220. let browser: KMBrowser = KMBrowser.init()
  221. browser.windowController = KMBrowserWindowController.init(browser: browser)
  222. browser.addHomeTabContents()
  223. browser.windowController.window?.center()
  224. browser.windowController.showWindow(self)
  225. }
  226. return flag
  227. }
  228. @IBAction func closeDocument(_ sender: Any) {
  229. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  230. guard let windowControler = NSApp.mainWindow?.windowController else {
  231. return
  232. }
  233. windowControler.window?.performClose(nil)
  234. return
  235. }
  236. let windowControler = NSApp.mainWindow?.windowController as? KMBrowserWindowController
  237. if let data = windowControler?.browser, data.tabCount() >= 2 { // 有两个以上的标签
  238. if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应
  239. return
  240. }
  241. }
  242. if let browser = windowControler?.browser {
  243. if browser.tabCount() == 1 {
  244. windowControler?.window?.close()
  245. } else {
  246. if let _ = windowControler?.window?.attachedSheet {
  247. NSSound.beep()
  248. return
  249. }
  250. browser.closeTab()
  251. }
  252. } else {
  253. windowControler?.window?.close()
  254. }
  255. }
  256. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  257. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  258. return false
  259. }
  260. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  261. if (filepaths == nil || filepaths!.count == 0) {
  262. return false
  263. }
  264. DispatchQueue.main.async {
  265. for filepath in filepaths! {
  266. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  267. }
  268. }
  269. }
  270. return false
  271. }
  272. func applicationWillTerminate(_ aNotification: Notification) {
  273. if (NSDocumentController.shared.documents.count > 0) {
  274. var filepaths: [String] = []
  275. for document in NSDocumentController.shared.documents {
  276. // KMPrint(document.fileURL as Any)
  277. if (document.fileURL?.path != nil) {
  278. filepaths.append((document.fileURL?.path)!)
  279. }
  280. }
  281. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  282. } else {
  283. KMPreferenceManager.shared.lastOpenFilepaths = nil
  284. }
  285. }
  286. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  287. return true
  288. }
  289. // MARK: private
  290. func reopenDocument(forPaths paths: [String]) -> Void {
  291. let browser = KMBrowser.init() as KMBrowser
  292. browser.windowController = KMBrowserWindowController.init(browser: browser)
  293. browser.addHomeTabContents()
  294. browser.windowController.showWindow(self)
  295. }
  296. @objc private func _themeChanged(_ sender: Notification) {
  297. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  298. if isDarkModel {
  299. NSApp.appearance = NSAppearance(named: .darkAqua)
  300. } else {
  301. NSApp.appearance = NSAppearance(named: .aqua)
  302. }
  303. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  304. }
  305. @objc func AIDeviceStatusChangeNotification() {
  306. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  307. self.refreshAIMenuItemInfo()
  308. }
  309. }
  310. @objc func deviceActivateStatusChangeNotification() {
  311. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  312. for item in appMenu!.items {
  313. if item.action == #selector(aiToolsAction) {
  314. if let tManager = VerificationManager.default() {
  315. let status = tManager.status
  316. if status == ActivityStatusNone {
  317. item.isHidden = true
  318. }
  319. }
  320. }
  321. }
  322. }
  323. func refreshAIMenuItemInfo() -> Void {
  324. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  325. for item in appMenu!.items {
  326. if item.action == #selector(aiToolsAction) {
  327. item.isHidden = true
  328. }
  329. }
  330. }
  331. //MARK: - iVersion
  332. func initiVersionData() -> Void{
  333. #if VERSION_DMG
  334. #else
  335. let tVersion = iVersion.sharedInstance()
  336. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  337. var tStr = "New Update Available"
  338. tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n"
  339. tVersion?.versionLabelFormat = ""
  340. tVersion?.groupNotesByVersion = true
  341. tVersion?.showOnFirstLaunch = false
  342. tVersion?.checkPeriod = 2
  343. tVersion?.remindPeriod = 5
  344. let infoDictionary = Bundle .main.infoDictionary!
  345. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  346. if appName.count < 1 {
  347. appName = infoDictionary["CFBundleName"] as! String
  348. }
  349. tStr = "The new version of %@ is available now. Go update for new features.";
  350. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  351. tStr = String(format: tStr, appName)
  352. tVersion?.inThisVersionTitle = tStr
  353. tStr = "UPDATE NOW";
  354. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  355. tStr = "LATER";
  356. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  357. tVersion!.ignoreButtonLabel = ""
  358. #endif
  359. }
  360. // MARK: - Menu
  361. func initMainMenu() {
  362. // 处理菜单栏多语
  363. let mainMenu = NSApp.mainMenu
  364. if (mainMenu == nil) {
  365. return
  366. }
  367. for menu in mainMenu!.items {
  368. let subMenu = menu.submenu
  369. for item in subMenu!.items {
  370. item.title = NSLocalizedString(item.title, comment: "")
  371. let itemSubMenu = item.submenu
  372. if (itemSubMenu == nil) {
  373. continue
  374. }
  375. for item in itemSubMenu!.items {
  376. item.title = NSLocalizedString(item.title, comment: "")
  377. let itemSubMenu = item.submenu
  378. if (itemSubMenu == nil) {
  379. continue
  380. }
  381. for item in itemSubMenu!.items {
  382. item.title = NSLocalizedString(item.title, comment: "")
  383. }
  384. }
  385. }
  386. }
  387. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  388. #if VERSION_DMG
  389. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 3)
  390. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4)
  391. if VerificationManager.default().needUpgradeLicense {
  392. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5)
  393. }
  394. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  395. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  396. #endif
  397. #if !VERSION_DMG
  398. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  399. #endif
  400. if let items = PDFOfficeMenu?.items {
  401. for menu in items {
  402. }
  403. }
  404. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("Volume Discount", comment: "")) {
  405. item.isHidden = true
  406. }
  407. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("One License for Mac and Windows", comment: "")) {
  408. item.isHidden = true
  409. }
  410. if let item = PDFOfficeMenu?.item(withTitle: NSLocalizedString("Education Discount", comment: "")) {
  411. item.isHidden = true
  412. }
  413. let fileMenu = mainMenu?.item(at: 1)?.submenu
  414. var shareItem: NSMenuItem?
  415. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  416. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  417. fileMenu?.insertItem(shareItem!, at: item.index)
  418. fileMenu?.insertItem(.separator(), at: item.index)
  419. } else {
  420. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  421. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  422. }
  423. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  424. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  425. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  426. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  427. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  428. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  429. }
  430. @objc func sharePageItemAction(sender: NSMenuItem) {
  431. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  432. return
  433. }
  434. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  435. let model = windowControler.browser?.tabStripModel
  436. if let cnt = model?.count(), cnt <= 0 {
  437. return
  438. }
  439. if let data = model?.activeTabContents()?.isHome, data {
  440. return
  441. }
  442. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  443. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  444. let represent : NSSharingService = sender.representedObject as! NSSharingService
  445. represent.perform(withItems: [document.fileURL as Any])
  446. return
  447. }
  448. let represent : NSSharingService = sender.representedObject as! NSSharingService
  449. represent.perform(withItems: [document.fileURL as Any])
  450. }
  451. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  452. KMPrint("deviceCameraMenuItemAciton")
  453. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil)
  454. }
  455. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  456. KMPrint("deviceScannerMenuItemAciton")
  457. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil)
  458. }
  459. // MARK: PDF Reader Pro Menu
  460. @IBAction func openPreferenceWindow(_ sender: Any) {
  461. KMPreferenceController.shared.showWindow(self)
  462. }
  463. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  464. }
  465. @IBAction func loginMenuItemAction(_ sender: Any) {
  466. }
  467. @IBAction func logoutMenuItemAction(_ sender: Any) {
  468. }
  469. @IBAction func restoreMenuItemAction(_ sender: Any) {
  470. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  471. if isSuccess {
  472. } else {
  473. if error != .restoreSuccess {
  474. }
  475. }
  476. }
  477. }
  478. @objc func accountRefreshAction() {
  479. }
  480. @objc func showAccount() {
  481. }
  482. @objc func resumePurchase() {
  483. }
  484. // MARK: help Menu
  485. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  486. KMTools.openQuickStartStudy()
  487. }
  488. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  489. KMTools.openFAQWebsite()
  490. }
  491. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  492. KMTools.openMoreProductWebsite()
  493. }
  494. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  495. KMTools.openFreePDFTemplatesWebsite()
  496. }
  497. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  498. KMEmailSubWindowController().showWindow(nil)
  499. }
  500. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  501. KMTools.openComPDFKitPowerWebsite()
  502. }
  503. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  504. KMTools.proposeNewFeature()
  505. }
  506. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  507. KMTools.rateUs()
  508. }
  509. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  510. #if VERSION_FREE
  511. KMPrint("restoreSubscriptions ...")
  512. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  513. compareWindowVC.showWindowRestore(nil)
  514. #else
  515. var vc: KMToolCompareWindowController? = nil
  516. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  517. vc!.showWindowRestore(sender: (Any).self)
  518. #endif
  519. }
  520. // MARK:- DMG
  521. @objc func checkForUpdates(_ sender: NSMenuItem) {
  522. #if VERSION_DMG
  523. SUUpdater.shared().checkForUpdates(sender)
  524. #endif
  525. }
  526. @objc func enterLicense(_ sender: NSMenuItem) {
  527. #if VERSION_DMG
  528. if let tManager = VerificationManager.default() {
  529. let status = tManager.status
  530. if status == ActivityStatusVerifExpire {
  531. let vc = KMVerificationWindowController.verification(with: .activateExpired)
  532. vc?.showWindow(nil)
  533. } else if status == ActivityStatusVerification {
  534. let vc = KMVerificationWindowController.verification(with: .info)
  535. vc?.showWindow(nil)
  536. } else {
  537. let vc = KMVerificationWindowController.verification(with: .activate)
  538. vc?.showWindow(nil)
  539. }
  540. }
  541. #endif
  542. }
  543. @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) {
  544. #if VERSION_DMG
  545. let embeddedWC = KMPurchaseEmbeddedWindowController.currentFirstTrialWC("com.brother.pdfreaderpro.mac.product_2")
  546. embeddedWC.showWindow(nil)
  547. embeddedWC.window?.center()
  548. #endif
  549. }
  550. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  551. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  552. #if VERSION_DMG
  553. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfdmg&utm_campaign=menubar_vpp"
  554. #else
  555. tStrHttpUrl = APPMain_Link + "/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  556. #endif
  557. guard let url = URL(string: tStrHttpUrl) else {
  558. NSSound.beep()
  559. return
  560. }
  561. let tWorkSpace = NSWorkspace.shared
  562. if tWorkSpace.open(url) == false {
  563. tWorkSpace.open(url)
  564. }
  565. }
  566. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  567. var tStrHttpUrl = CrossPlatform_Link
  568. guard let url = URL(string: tStrHttpUrl) else {
  569. return
  570. }
  571. let tWorkSpace = NSWorkspace.shared
  572. if tWorkSpace.open(url) == false {
  573. tWorkSpace.open(url)
  574. }
  575. #if VERSION_DMG
  576. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  577. #endif
  578. }
  579. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  580. let tStrHttpUrl = KMLocalizedString("https://www.pdfreaderpro.com/store?mode=edu#utm_source=mac_app&utm_medium=pdf_pro_dmg&utm_content=menu_bar_click")
  581. // let tStrHttpUrl = Store_Edu_Link
  582. guard let url = URL(string: tStrHttpUrl) else {
  583. return
  584. }
  585. let tWorkSpace = NSWorkspace.shared
  586. if tWorkSpace.open(url) == false {
  587. tWorkSpace.open(url)
  588. }
  589. #if VERSION_DMG
  590. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_EduDiscount"])
  591. #endif
  592. }
  593. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  594. #if VERSION_DMG
  595. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  596. #else
  597. AIPurchaseWindowController.currentWC().showWindow(nil)
  598. #endif
  599. }
  600. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  601. if let win = KMLineInspector.shared.window {
  602. if win.isVisible {
  603. win.orderOut(sender)
  604. } else {
  605. win.orderFront(sender)
  606. }
  607. }
  608. }
  609. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  610. KMPrint("showDownloads ...")
  611. }
  612. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  613. self.reopenDocument(forPaths: [])
  614. }
  615. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  616. KMEmailSubWindowController().showWindow(nil)
  617. }
  618. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  619. KMTools.feekback()
  620. }
  621. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  622. KMTools.reportBug()
  623. }
  624. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  625. KMTools.reportGeneralQuestions()
  626. }
  627. }
  628. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  629. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  630. let action = menuItem.action
  631. if (action == #selector(sharePageItemAction)) {
  632. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  633. return false
  634. }
  635. let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  636. return !isHome
  637. }
  638. if action == #selector(closeDocument) {
  639. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  640. if NSApp.mainWindow?.windowController != nil {
  641. return true
  642. }
  643. return false
  644. }
  645. let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false
  646. if isNewTab {
  647. return true
  648. }
  649. }
  650. return true
  651. }
  652. func updateLoginMenuItem() {
  653. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  654. if firstItem != nil {
  655. let item1 = firstItem?.item(withTag: 11)
  656. let item2 = firstItem?.item(withTag: 12)
  657. let item3 = firstItem?.item(withTag: 13)
  658. let item4 = firstItem?.item(withTag: 14)
  659. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  660. item1?.isHidden = true
  661. item2?.isHidden = true
  662. item3?.isHidden = true
  663. item4?.isHidden = true
  664. item6?.isHidden = true
  665. }
  666. }
  667. @objc func clickOutline(menuItem: NSMenuItem) {
  668. KMPrint("更新菜单栏")
  669. }
  670. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  671. return true
  672. }
  673. }
  674. #if VERSION_DMG
  675. extension AppDelegate : SUUpdaterDelegate {
  676. func updaterWillRelaunchApplication(_ updater: SUUpdater) {
  677. }
  678. func feedURLString(for updater: SUUpdater) -> String? {
  679. var hostURL = "https://www.pdfreaderpro.com/downloads/"
  680. #if DEBUG
  681. hostURL = "http://test-pdf-pro.kdan.cn:3021/downloads/"
  682. #else
  683. hostURL = "https://www.pdfreaderpro.com/downloads/"
  684. #endif
  685. return hostURL+NSLocalizedString("pdfreaderprocast.xml", comment: "")
  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/app/id825459243?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. }
  727. extension AppDelegate: UNUserNotificationCenterDelegate {
  728. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  729. // 处理用户点击推送通知的操作
  730. completionHandler()
  731. }
  732. }