AppDelegate.swift 35 KB

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