AppDelegate.swift 35 KB

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