AppDelegate.swift 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. //
  2. // AppDelegate.swift
  3. // Cisdem PDFMaster
  4. //
  5. // Created by Niehaoyu on 2022/9/23.
  6. //
  7. import Cocoa
  8. import UserNotifications
  9. @main
  10. class AppDelegate: NSObject, NSApplicationDelegate, iRateDelegate{
  11. var rateWindowVC: KMRateWindowController!
  12. func applicationWillFinishLaunching(_ notification: Notification) {
  13. CPDFConvertKit.setLicenseKey("pwVjLcp4mqoyeB68e8hB4BCy1zhfR2RqFvw21eWf218waYJGiYoR2mm73mvBP0ctmpm7EReGzsWf3bmMEubpqPoJ6iVcx0hXfwtXT00SWh06HY0BJmZsQjebduOWmtjcwa/CGNKbXj+svb9Rn7rw7JqWRx/EOkzo9MMa7EPGWlwG4U5XphLLZJ+Z3FxKrEEsVt7vwAGPdNcNlJZeSnpGl6ilpwXeS8BiSvZSmWz8dpvoZsb57zHUvi3LAAtZpjSeXZD0A+GSs6jNDCSnILJl+C6zp/i4u8xxdH3Gw954GKkp/Q4qtNWTqlzR0rBzh+CTPSbCeDA/VgE2FLCXVAf/RGu0lH1oY17eVN2TRW5amzpVluIgfBYVaYkjt6T5JApf2W8G9zo4Eul5t/EnjYyQEERxob1ji6eXrknf03eZ1m/mFFcrOzq9/Ltqa8PbtYFfhFxgqpxulvUgzfTz4YWf8l7Zgj+iPhAprovkb/TDTucCJrrnDmMLRuMBf8WWqET2nkyPq2L4nW437NrmAOb+LfJf2nePHR5BmbAag9fpeCW5jQfOfu67I6r3O3SjSoV3N9UzCP3KvfOOVJSPslD9k3G9jXTrgx93Y4E9n7RYZcUo4zepltYWoplfONjTZWqeRoNxe9QHXGWMWBc/Ntne3x/a3ZkL84CZ8pvLNnr4BW02+HQbHqDvewW9B5uWL2gyvgt7IOcj0tNlSxXy6ggcZFNhVfyDa0XRQWQNON6lNB8Y7JZwccJY7iRTxaaGIghi")
  14. CPDFKit.verify(withKey: "xJPiZ17w3Ajomg/CzxCNqeyaLREGKaffkshdgpdB/q75AQGGecd69qZoQdajnWqw5UBu4WhB3kP75FN72SearnLFi/+AejuVqZbRj0QJq/7Nafia7c6mo+wVn2Vx25v96q9FkOiuqxWHFeDw9b/y31wjj7Nezp8Y8l+13e0kuzeEQ+pcsKQ4IGFvdUlGdwjHaiMl/jSUMq7kwvLAF3PU2HtuprqKRhxIlCuad0yK39EH4/u0BniTqBmJXziHi2iVu/pqtA9M/XkqOmJQN93ZYpTMFS7uuEMHZjWPTRTZwlcdcxYkYxIYvKDjp1Lyu0rux0AgDQMpVTu8lC/4+OAuoGu0lH1oY17eVN2TRW5amzpVluIgfBYVaYkjt6T5JApf2W8G9zo4Eul5t/EnjYyQEOxficyjBUvAWG6kCEHmjfU5/e/i8Unc6t8gZECSL24tn8B1XRyEZ7b33a/pIXQOQV7Zgj+iPhAprovkb/TDTucCJrrnDmMLRuMBf8WWqET2nkyPq2L4nW437NrmAOb+LbjGybUYYV+WNFNio9JbzmW5jQfOfu67I6r3O3SjSoV3N9UzCP3KvfOOVJSPslD9k2b3n5dAuRcBWESauhoiQon4P4qY1CDHbtB2RRUlY2QoUFrIA98TzqKs2rjolMvFknnky6b9UGeVlyoDXkNwOYUdZ5/3bRgnu1u9Y/IS7aylB5kDht8xLnlZc44WdwoQICBB+s3jKoshBxf0wGSTEenyRBslb8cexbgw1j1TMBDqjOrEKmnDg0rhLXi76xNpUg==")
  15. ComPDFUIConfig.initializeUIConfig()
  16. KMDesignToken.shared.parserExcel(withPath: "")
  17. }
  18. func applicationDidFinishLaunching(_ aNotification: Notification) {
  19. // Insert code here to initialize your application
  20. //通知
  21. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  22. if granted {
  23. KMPrint("User authorized notifications")
  24. } else {
  25. KMPrint("User denied notifications")
  26. }
  27. }
  28. /**本地推送测试
  29. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  30. if granted {
  31. // 创建本地推送通知
  32. let content = UNMutableNotificationContent()
  33. content.title = "Test Notification"
  34. content.body = "This is a test notification!"
  35. // 触发条件,例如延迟 5 秒触发
  36. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  37. // 创建通知请求
  38. let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
  39. // 添加通知请求到用户通知中心
  40. UNUserNotificationCenter.current().add(request) { error in
  41. if let error = error {
  42. print("Error adding notification request: \(error)")
  43. } else {
  44. print("Local notification scheduled")
  45. }
  46. }
  47. } else {
  48. print("User denied notifications")
  49. }
  50. }
  51. **/
  52. DispatchQueue.main.async {
  53. NSApplication.shared.registerForRemoteNotifications()
  54. }
  55. //Firebase RemoteConfig
  56. #if VERSION_FREE
  57. KMKdanRemoteConfig.remoteConfig.fetch { _status, error in
  58. }
  59. #endif
  60. let versionString = MainBundle.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
  61. let lastVersionString = KMDataManager.ud_string(forKey: SKLastVersionLaunchedKey)
  62. if lastVersionString == nil || SKVersionNumber.compareVersionString(lastVersionString, toVersionString: versionString) == .orderedAscending {
  63. let sud = UserDefaults.standard
  64. if versionString.isEmpty == false {
  65. sud.set(versionString, forKey: SKLastVersionLaunchedKey)
  66. }
  67. // [sud setBool:NO forKey:@"kShowRecentGuideKey"];
  68. // [sud removeObjectForKey:@"kToolbarTipIsShow"];
  69. // [sud removeObjectForKey:@"kShowNoPermissionAlertKey"];
  70. // [sud removeObjectForKey:@"KMTabbingHintShowFlag"];
  71. // [sud removeObjectForKey:@"KMConverthHaveOpenConvertDetails"];
  72. sud.synchronize()
  73. }
  74. UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions" : true])
  75. let oemInstall = UserDefaults.standard.bool(forKey: "KMOEMRequestStateInstall")
  76. if !oemInstall {
  77. KMOEMRequestServerManager.defaultManager.oemRequest(state: .install, regCode: "") { wrapper in
  78. if wrapper.success {
  79. UserDefaults.standard.setValue(true, forKey: "KMOEMRequestStateInstall")
  80. }
  81. }
  82. }
  83. let oemUpdate = UserDefaults.standard.string(forKey: "KMOEMRequestStateUpdate")
  84. if oemUpdate != KMOEMRequestServerManager.defaultManager.version() {
  85. self.checkForUpdates1(NSMenuItem())
  86. }
  87. NSApp.servicesProvider = self
  88. KMStatusBar.system()
  89. // MARK: 广告数据初始化
  90. var appName: KMAdvertisementAppNameType = .PDFReaderProMac
  91. #if VERSION_FREE
  92. #if VERSION_DMG
  93. appName = .PDFReaderProMacDMG
  94. #else
  95. #endif
  96. #else
  97. appName = .PDFReaderProMacPro
  98. #endif
  99. KMAdvertisementManager.manager.initConfig(appName: appName,
  100. subscribeType: .unknow,
  101. platform: .Mac)
  102. // 测试模式,默认false
  103. KMAdvertisementManager.manager.debug = true
  104. NSApp.appearance = NSAppearance.current
  105. KMAnalytics.configure()
  106. //第一次开启app
  107. let info = UserDefaults.standard.value(forKey: "kFirstOpenAppCount")
  108. var count = 0
  109. if info != nil {
  110. count = info as? Int ?? 0
  111. }
  112. count += 1
  113. UserDefaults.standard.set(count, forKey: "kFirstOpenAppCount")
  114. UserDefaults.standard.synchronize()
  115. self.initMainMenu()
  116. /// pro
  117. // [DBClientsManager setupWithAppKeyDesktop:@"amipzwtlg9lrwyl"];
  118. DBClientsManager.setup(withAppKeyDesktop: "jxjlqfm1cfp2mjj")
  119. reopenDocument(forPaths: [])
  120. KMPreference.shared.initDataForAppLaunch()
  121. self.initiRateData()
  122. let appleEventManager = NSAppleEventManager.shared()
  123. appleEventManager.setEventHandler(self,
  124. andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
  125. forEventClass: AEEventClass(kInternetEventClass),
  126. andEventID: AEEventID(kAEGetURL))
  127. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  128. #if VERSION_DMG
  129. VerificationManager.default()
  130. #else
  131. self.initiVersionData()
  132. IAPProductsManager.default().initIAP()
  133. #endif
  134. //AI相关
  135. AIInfoManager.default()
  136. NotificationCenter.default.addObserver(self, selector: #selector(AIDeviceStatusChangeNotification), name: NSNotification.Name(rawValue: "kDeviceAIStatusChangeNotification"), object: nil)
  137. for string in ["Ubuntu-Bold","Ubuntu-Medium"] {
  138. let fontURL = Bundle.main.url(forResource: string, withExtension: "ttf")
  139. var error: Unmanaged<CFError>?
  140. if !CTFontManagerRegisterFontsForURL(fontURL! as CFURL, .process, &error) {
  141. print("Failed to register font!")
  142. } else {
  143. print("Font registered successfully!")
  144. }
  145. }
  146. }
  147. func initiRateData() {
  148. iRate.sharedInstance().delegate = self
  149. #if VERSION_FREE
  150. iRate.sharedInstance().appStoreID = 919472673
  151. #else
  152. iRate.sharedInstance().appStoreID = 825459243
  153. #endif
  154. iRate.sharedInstance().onlyPromptIfLatestVersion = false
  155. iRate.sharedInstance().onlyPromptIfMainWindowIsAvailable = true
  156. }
  157. //MARK: iRateDelegate
  158. func iRateUserDidDeclineToRateApp() {
  159. KMVerificationWindowController.verificationFeedback()
  160. }
  161. func iRateShouldPromptForRating() -> Bool {
  162. let notShow: Bool = UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey")
  163. if !notShow {
  164. UserDefaults.standard.setValue(true, forKey: "kUserHaveClickRateUsKey")
  165. UserDefaults.standard.synchronize()
  166. NotificationCenter.default.post(name: Notification.Name(rawValue: "kUserHaveClickRateUsNotification"), object: self)
  167. }
  168. self.rateWindowVC = KMRateWindowController.init(windowNibName: "KMRateWindowController")
  169. self.rateWindowVC.closeBlock = { wc in
  170. }
  171. self.rateWindowVC.closeBlock = { wc in
  172. }
  173. self.rateWindowVC.showWindow(nil)
  174. return false
  175. }
  176. @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
  177. if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
  178. let url = URL(string: urlString) {
  179. // 在这里处理收到的 URL Scheme
  180. KMPrint("Received URL Scheme: \(url.scheme ?? "")")
  181. KMPrint("Path: \(url.path)")
  182. if NSApp.mainWindow == nil {
  183. let bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
  184. launchApp(bundleIdentifier: bundleIdentifier)
  185. }
  186. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  187. #if VERSION_DMG
  188. // 执行相应的操作
  189. if url.scheme == "subscriptiondmgschemes" {
  190. if urlString.contains("open=expired") {
  191. KMPrint("刷新用户信息")
  192. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  193. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  194. } else {
  195. if NSApp.mainWindow != nil && KMLightMemberManager.manager.isLogin() {
  196. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  197. }
  198. }
  199. } else if urlString.contains("open=success") {
  200. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  201. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  202. } else {
  203. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  204. if isSuccess {
  205. } else {
  206. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  207. }
  208. }
  209. }
  210. }
  211. }
  212. #endif
  213. #if VERSION_FREE
  214. // 执行相应的操作
  215. if url.scheme == "subscriptionSchemes" {
  216. //刷新用户信息
  217. KMRequestServerManager.manager.getUserInfo { success, data, error, isLocal in
  218. }
  219. if url.path == "/open" {
  220. // 执行打开操作
  221. } else if url.path == "/close" {
  222. // 执行关闭操作
  223. }
  224. }
  225. #endif
  226. }
  227. }
  228. }
  229. func launchApp(bundleIdentifier: String) {
  230. let workspace = NSWorkspace.shared
  231. // Launch the application with the specified bundle identifier
  232. if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
  233. do {
  234. try workspace.launchApplication(at: appURL, options: .default, configuration: [:])
  235. } catch {
  236. print("Error launching the application: \(error)")
  237. }
  238. } else {
  239. print("Application with bundle identifier '\(bundleIdentifier)' not found.")
  240. }
  241. }
  242. func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  243. let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  244. print("Device token:", token)
  245. }
  246. func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
  247. }
  248. func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  249. if !flag {
  250. let browser: KMBrowser = KMBrowser.init()
  251. browser.windowController = KMBrowserWindowController.init(browser: browser)
  252. browser.addHomeTabContents()
  253. browser.windowController.showWindow(self)
  254. }
  255. return flag
  256. }
  257. @IBAction func closeDocument(_ sender: Any) {
  258. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  259. guard let windowControler = NSApp.mainWindow?.windowController else {
  260. return
  261. }
  262. windowControler.window?.performClose(nil)
  263. return
  264. }
  265. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  266. if let data = windowControler.browser, data.tabCount() >= 2 { // 有两个以上的标签
  267. if data.activeTabIndex() == 0 { // 主页不允许关闭,暂时处理为无反应
  268. return
  269. }
  270. }
  271. windowControler.browser.closeTab()
  272. }
  273. func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
  274. if (KMPreferenceManager.shared.openLastUnclosedDocumentWhenAppStart == false) {
  275. return false
  276. }
  277. let filepaths = KMPreferenceManager.shared.lastOpenFilepaths
  278. if (filepaths == nil || filepaths!.count == 0) {
  279. return false
  280. }
  281. DispatchQueue.main.async {
  282. for filepath in filepaths! {
  283. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: filepath), display: true) { _, _, _ in
  284. }
  285. }
  286. }
  287. return false
  288. }
  289. func applicationWillTerminate(_ aNotification: Notification) {
  290. if (NSDocumentController.shared.documents.count > 0) {
  291. var filepaths: [String] = []
  292. for document in NSDocumentController.shared.documents {
  293. // KMPrint(document.fileURL as Any)
  294. if (document.fileURL?.path != nil) {
  295. filepaths.append((document.fileURL?.path)!)
  296. }
  297. }
  298. KMPreferenceManager.shared.lastOpenFilepaths = filepaths
  299. } else {
  300. KMPreferenceManager.shared.lastOpenFilepaths = nil
  301. }
  302. }
  303. func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
  304. return true
  305. }
  306. // MARK: private
  307. func reopenDocument(forPaths paths: [String]) -> Void {
  308. let browser = KMBrowser.init() as KMBrowser
  309. browser.windowController = KMBrowserWindowController.init(browser: browser)
  310. browser.addHomeTabContents()
  311. browser.windowController.showWindow(self)
  312. }
  313. @objc private func _themeChanged(_ sender: Notification) {
  314. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  315. if isDarkModel {
  316. NSApp.appearance = .init(named: .darkAqua)
  317. } else {
  318. NSApp.appearance = .init(named: .aqua)
  319. }
  320. // if let data = NSApp.appearance?.name, data == .darkAqua {
  321. // NSApp.appearance = .init(named: .aqua)
  322. // } else {
  323. // NSApp.appearance = .init(named: .darkAqua)
  324. // }
  325. NotificationCenter.default.post(name: Notification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  326. }
  327. @objc func AIDeviceStatusChangeNotification() {
  328. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  329. self.refreshAIMenuItemInfo()
  330. }
  331. }
  332. func refreshAIMenuItemInfo() -> Void {
  333. let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
  334. for item in appMenu!.items {
  335. if item.action == #selector(aiToolsAction) {
  336. item.isHidden = true
  337. }
  338. }
  339. }
  340. //MARK: - iVersion
  341. func initiVersionData() -> Void{
  342. #if VERSION_DMG
  343. #else
  344. let tVersion = iVersion.sharedInstance()
  345. tVersion?.applicationBundleID = Bundle.main.bundleIdentifier
  346. var tStr = "New Update Available"
  347. tVersion?.updateAvailableTitle = (tVersion?.localizedString(forKey: tStr, withDefault: tStr) ?? "") + "\n"
  348. tVersion?.versionLabelFormat = ""
  349. tVersion?.groupNotesByVersion = true
  350. tVersion?.showOnFirstLaunch = false
  351. tVersion?.checkPeriod = 2
  352. tVersion?.remindPeriod = 5
  353. let infoDictionary = Bundle .main.infoDictionary!
  354. var appName: String = infoDictionary["CFBundleDisplayName"] as! String
  355. if appName.count < 1 {
  356. appName = infoDictionary["CFBundleName"] as! String
  357. }
  358. tStr = "The new version of %@ is available now. Go update for new features.";
  359. tStr = (tVersion?.localizedString(forKey: tStr, withDefault: tStr))!
  360. tStr = String(format: tStr, appName)
  361. tVersion?.inThisVersionTitle = tStr
  362. tStr = "UPDATE NOW";
  363. tVersion!.downloadButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  364. tStr = "LATER";
  365. tVersion!.remindButtonLabel = tVersion?.localizedString(forKey: tStr, withDefault: tStr)
  366. tVersion!.ignoreButtonLabel = ""
  367. #endif
  368. }
  369. // MARK: - Menu
  370. func initMainMenu() {
  371. // 处理菜单栏多语
  372. let mainMenu = NSApp.mainMenu
  373. if (mainMenu == nil) {
  374. return
  375. }
  376. for menu in mainMenu!.items {
  377. let subMenu = menu.submenu
  378. for item in subMenu!.items {
  379. item.title = NSLocalizedString(item.title, comment: "")
  380. let itemSubMenu = item.submenu
  381. if (itemSubMenu == nil) {
  382. continue
  383. }
  384. for item in itemSubMenu!.items {
  385. item.title = NSLocalizedString(item.title, comment: "")
  386. }
  387. }
  388. }
  389. let PDFOfficeMenu = mainMenu?.item(at: 0)?.submenu
  390. #if VERSION_DMG
  391. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Check for Updates", comment: ""), action: #selector(checkForUpdates), target: self, at: 3)
  392. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Enter License", comment: ""), action: #selector(enterLicense), target: self, at: 4)
  393. // if ([VerificationManager manager].needUpgradeLicense == NO) {
  394. if VerificationManager.default().needUpgradeLicense {
  395. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("PDF to Office Pack", comment: ""), action: #selector(pdftoOfficeMenuItemAction), target: self, at: 5)
  396. }
  397. let accountRefreshItem = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Account Refresh", comment: ""), action: #selector(accountRefreshAction), target: self, at: 8)
  398. accountRefreshItem?.tag = kKMMainMenuAccountRefreshItemTag
  399. #endif
  400. #if !VERSION_DMG
  401. _ = PDFOfficeMenu?.insertItem(withTitle: NSLocalizedString("Restore Previous Purchase", comment: ""), action: #selector(restoreSubscriptions), target: self, at: 1)
  402. #endif
  403. if let items = PDFOfficeMenu?.items {
  404. for menu in items {
  405. let ranges = menu.title.ranges(of: "Cisdem PDFMaster")
  406. if let _range = ranges.range.first {
  407. menu.title.replaceSubrange(_range, with: KMTools.getAppName())
  408. }
  409. }
  410. }
  411. let fileMenu = mainMenu?.item(at: 1)?.submenu
  412. var shareItem: NSMenuItem?
  413. if let item = fileMenu?.item(withTitle: NSLocalizedString("Save Archive…", comment: "")) {
  414. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  415. fileMenu?.insertItem(shareItem!, at: item.index)
  416. fileMenu?.insertItem(.separator(), at: item.index)
  417. } else {
  418. shareItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: nil)
  419. fileMenu?.insertItem(shareItem!, at: (fileMenu?.items.count)!-1)
  420. }
  421. shareItem?.submenu = NSSharingServicePicker.menu(forSharingItems: [""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  422. let deviceCameraMenuItem = NSMenuItem(title: NSLocalizedString("Import From Camera", comment: ""), action: #selector(deviceCameraMenuItemAciton), target: self)
  423. let deviceScannerMenuItem = NSMenuItem(title: NSLocalizedString("Import From Scanner", comment: ""), action: #selector(deviceScannerMenuItemAciton), target: self)
  424. fileMenu?.insertItem(deviceCameraMenuItem, at: (fileMenu?.items.count)!-1)
  425. fileMenu?.insertItem(deviceScannerMenuItem, at: (fileMenu?.items.count)!-1)
  426. fileMenu?.insertItem(.separator(), at: (fileMenu?.items.count)!-1)
  427. }
  428. @objc func sharePageItemAction(sender: NSMenuItem) {
  429. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  430. return
  431. }
  432. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  433. let model = windowControler.browser?.tabStripModel
  434. if let cnt = model?.count(), cnt <= 0 {
  435. return
  436. }
  437. if let data = model?.activeTabContents()?.isHome, data {
  438. return
  439. }
  440. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  441. if let data = document.mainViewController?.saveWatermarkFlag, !data {
  442. let represent : NSSharingService = sender.representedObject as! NSSharingService
  443. represent.perform(withItems: [document.fileURL as Any])
  444. return
  445. }
  446. let represent : NSSharingService = sender.representedObject as! NSSharingService
  447. represent.perform(withItems: [document.fileURL as Any])
  448. }
  449. @objc func deviceCameraMenuItemAciton(sender: NSMenuItem) {
  450. KMPrint("deviceCameraMenuItemAciton")
  451. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceCameraMenuItemNotification"), object: nil)
  452. }
  453. @objc func deviceScannerMenuItemAciton(sender: NSMenuItem) {
  454. KMPrint("deviceScannerMenuItemAciton")
  455. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kDeviceScannerMenuItemNotification"), object: nil)
  456. }
  457. // MARK: Cisdem PDFMaster Menu
  458. @IBAction func openPreferenceWindow(_ sender: Any) {
  459. KMPreferenceController.shared.showWindow(self)
  460. }
  461. @objc @IBAction func manageAcctounMenuAction(_ sender: Any) {
  462. if KMLightMemberManager.manager.isLogin() {
  463. _ = KMAccountInfoWindowController.show(window: NSApp.mainWindow!)
  464. }
  465. }
  466. @IBAction func loginMenuItemAction(_ sender: Any) {
  467. // Login & Logout
  468. if KMLightMemberManager.manager.isLogin() {
  469. } else {
  470. _ = KMLoginWindowController.show(window: NSApp.mainWindow!)
  471. }
  472. }
  473. @IBAction func logoutMenuItemAction(_ sender: Any) {
  474. // Login & Logout
  475. if KMLightMemberManager.manager.isLogin() {
  476. KMRequestServerManager.manager.logout { success, result in
  477. if success {
  478. KMPrint("登出成功")
  479. }
  480. }
  481. }
  482. }
  483. @IBAction func restoreMenuItemAction(_ sender: Any) {
  484. KMPurchaseManager.manager.restorePurchases { isSuccess, error in
  485. if isSuccess {
  486. } else {
  487. if error != .restoreSuccess {
  488. KMComparativeTableViewController.purchasefailed(view: NSApp.mainWindow?.contentView, state: error)
  489. }
  490. }
  491. }
  492. }
  493. @objc func accountRefreshAction() {
  494. KMLightMemberManager.manager.updateNetworkingUserInfo { isDidLogout in
  495. }
  496. }
  497. @objc func showAccount() {
  498. }
  499. @objc func resumePurchase() {
  500. }
  501. // MARK: help Menu
  502. @IBAction func menuItemAction_quickStudy(_ sender: NSMenuItem) -> Void {
  503. KMTools.openQuickStartStudy()
  504. }
  505. @IBAction func menuItemAction_onlineHelp(_ sender: NSMenuItem) -> Void {
  506. KMTools.openFAQWebsite()
  507. }
  508. @IBAction func menuItemAction_morePudact(_ sender: NSMenuItem) -> Void {
  509. KMTools.openMoreProductWebsite()
  510. }
  511. @IBAction func menuItemAction_freePDFTemplate(_ sender: NSMenuItem) -> Void {
  512. KMTools.openFreePDFTemplatesWebsite()
  513. }
  514. @IBAction func menuItemAction_payEmail(_ sender: NSMenuItem) -> Void {
  515. KMEmailSubWindowController().showWindow(nil)
  516. }
  517. @IBAction func menuItemAction_poweredByComPDFKit(_ sender: NSMenuItem) -> Void {
  518. KMTools.openComPDFKitPowerWebsite()
  519. }
  520. @IBAction func menuItemAction_feekback(_ sender: NSMenuItem) -> Void {
  521. KMTools.proposeNewFeature()
  522. }
  523. @IBAction func menuItemAction_giveFiveStar(_ sender: NSMenuItem) -> Void {
  524. KMTools.rateUs()
  525. }
  526. @objc func restoreSubscriptions(_ sender: NSMenuItem) {
  527. #if VERSION_FREE
  528. KMPrint("restoreSubscriptions ...")
  529. let compareWindowVC: KMPurchaseCompareWindowController = KMPurchaseCompareWindowController.sharedInstance() as! KMPurchaseCompareWindowController
  530. compareWindowVC.showWindowRestore(nil)
  531. #else
  532. var vc: KMToolCompareWindowController? = nil
  533. vc = KMToolCompareWindowController.toolCompare(toolType: .Convert, selectNum: 0)
  534. vc!.showWindowRestore(sender: (Any).self)
  535. #endif
  536. }
  537. // MARK:- DMG
  538. @objc func checkForUpdates1(_ sender: NSMenuItem) {
  539. KMOEMRequestServerManager.defaultManager.oemRequest(state: .update, regCode: "") { wrapper in
  540. if wrapper.success {
  541. if let version = wrapper.data["version"] as? String {
  542. let alert = NSAlert()
  543. alert.alertStyle = .critical
  544. alert.messageText = NSLocalizedString("A new version of Cisdem PDFMaster is available!", comment: "")
  545. alert.informativeText = String(format: NSLocalizedString("Cisdem PDFMaster %@ is now available---you have %@. Would you like to download it now?", comment: ""), version, KMOEMRequestServerManager.defaultManager.version())
  546. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  547. alert.addButton(withTitle: NSLocalizedString("Ignore", comment: ""))
  548. alert.addButton(withTitle: NSLocalizedString("NO", comment: ""))
  549. alert.beginSheetModal(for: NSApplication.shared.keyWindow!) { response in
  550. if response == .alertFirstButtonReturn {
  551. let defs = UserDefaults.standard
  552. if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first {
  553. var tStrUrl = "https://www.cisdem.com/pdfmaster.html"
  554. if preferredLang.hasPrefix("de") {
  555. tStrUrl = "https://www.cisdem.com/de/pdfmaster.html"
  556. } else if preferredLang.hasPrefix("fr") {
  557. tStrUrl = "https://www.cisdem.com/fr/pdfmaster.html"
  558. } else if preferredLang.hasPrefix("it") {
  559. tStrUrl = "https://www.cisdem.com/it/pdfmaster.html"
  560. } else if preferredLang.hasPrefix("es") {
  561. tStrUrl = "https://www.cisdem.com/es/pdfmaster.html"
  562. } else if preferredLang.hasPrefix("pt") {
  563. tStrUrl = "https://www.cisdem.com/pt/pdfmaster.html"
  564. } else if preferredLang.hasPrefix("ja") {
  565. tStrUrl = "https://www.cisdem.com/jp/pdfmaster.html"
  566. }
  567. let tStrHttpUrl = tStrUrl
  568. let tWorkSpace = NSWorkspace.shared
  569. if !tWorkSpace.open(URL(string: tStrUrl)!) {
  570. tWorkSpace.open(URL(string: tStrHttpUrl)!)
  571. }
  572. }
  573. } else if response == .alertSecondButtonReturn {
  574. UserDefaults.standard.setValue(KMOEMRequestServerManager.defaultManager.version(), forKey: "KMOEMRequestStateUpdate")
  575. } else if response == .alertThirdButtonReturn {
  576. // Handle "NO" response if needed
  577. }
  578. }
  579. }
  580. }
  581. }
  582. }
  583. @objc func checkForUpdates(_ sender: NSMenuItem) {
  584. KMOEMRequestServerManager.defaultManager.oemRequest(state: .update, regCode: "") { wrapper in
  585. if wrapper.success {
  586. if let version = wrapper.data["version"] as? String {
  587. let alert = NSAlert()
  588. alert.alertStyle = .critical
  589. alert.messageText = NSLocalizedString("A new version of Cisdem PDFMaster is available!", comment: "")
  590. alert.informativeText = String(format: NSLocalizedString("Cisdem PDFMaster %@ is now available---you have %@. Would you like to download it now?", comment: ""), version, KMOEMRequestServerManager.defaultManager.version())
  591. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  592. alert.addButton(withTitle: NSLocalizedString("Ignore", comment: ""))
  593. alert.addButton(withTitle: NSLocalizedString("NO", comment: ""))
  594. alert.beginSheetModal(for: NSApplication.shared.keyWindow!) { response in
  595. if response == .alertFirstButtonReturn {
  596. let defs = UserDefaults.standard
  597. if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first {
  598. var tStrUrl = "https://www.cisdem.com/pdfmaster.html"
  599. if preferredLang.hasPrefix("de") {
  600. tStrUrl = "https://www.cisdem.com/de/pdfmaster.html"
  601. } else if preferredLang.hasPrefix("fr") {
  602. tStrUrl = "https://www.cisdem.com/fr/pdfmaster.html"
  603. } else if preferredLang.hasPrefix("it") {
  604. tStrUrl = "https://www.cisdem.com/it/pdfmaster.html"
  605. } else if preferredLang.hasPrefix("es") {
  606. tStrUrl = "https://www.cisdem.com/es/pdfmaster.html"
  607. } else if preferredLang.hasPrefix("pt") {
  608. tStrUrl = "https://www.cisdem.com/pt/pdfmaster.html"
  609. } else if preferredLang.hasPrefix("ja") {
  610. tStrUrl = "https://www.cisdem.com/jp/pdfmaster.html"
  611. }
  612. let tStrHttpUrl = tStrUrl
  613. let tWorkSpace = NSWorkspace.shared
  614. if !tWorkSpace.open(URL(string: tStrUrl)!) {
  615. tWorkSpace.open(URL(string: tStrHttpUrl)!)
  616. }
  617. }
  618. } else if response == .alertSecondButtonReturn {
  619. UserDefaults.standard.setValue(KMOEMRequestServerManager.defaultManager.version(), forKey: "KMOEMRequestStateUpdate")
  620. } else if response == .alertThirdButtonReturn {
  621. // Handle "NO" response if needed
  622. }
  623. }
  624. }
  625. } else {
  626. if let code = wrapper.data["code"] as? Int, code == 201 {
  627. let alert = NSAlert()
  628. alert.alertStyle = .informational
  629. alert.messageText = String(format: NSLocalizedString("You're up-to-date! %@ is currently the newest version available.", comment: ""), "Cisdem PDFMaster")
  630. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  631. alert.beginSheetModal(for: NSApplication.shared.keyWindow!) { response in
  632. if response == .alertFirstButtonReturn {
  633. // Handle "Yes" response if needed
  634. }
  635. }
  636. }
  637. }
  638. }
  639. }
  640. @objc func enterLicense(_ sender: NSMenuItem) {
  641. #if VERSION_DMG
  642. if let tManager = VerificationManager.default() {
  643. let status = tManager.status
  644. if status == ActivityStatusVerifExpire {
  645. let vc = KMVerificationWindowController.verification(with: .activateExpired)
  646. vc?.showWindow(nil)
  647. } else if status == ActivityStatusVerification {
  648. let vc = KMVerificationWindowController.verification(with: .info)
  649. vc?.showWindow(nil)
  650. } else {
  651. let vc = KMVerificationWindowController.verification(with: .activate)
  652. vc?.showWindow(nil)
  653. }
  654. }
  655. #endif
  656. }
  657. @objc func pdftoOfficeMenuItemAction(_ sender: NSMenuItem) {
  658. #if VERSION_DMG
  659. var tStrUrl = "https://www.cisdem.com/pdfmaster-mac/buy.html"
  660. let defs = UserDefaults.standard
  661. if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first {
  662. if preferredLang.hasPrefix("de") {
  663. tStrUrl = "https://www.cisdem.com/de/pdfmaster-mac/buy.html"
  664. } else if preferredLang.hasPrefix("fr") {
  665. tStrUrl = "https://www.cisdem.com/fr/pdfmaster-mac/buy.html"
  666. } else if preferredLang.hasPrefix("it") {
  667. tStrUrl = "https://www.cisdem.com/it/pdfmaster-mac/buy.html"
  668. } else if preferredLang.hasPrefix("es") {
  669. tStrUrl = "https://www.cisdem.com/es/pdfmaster-mac/buy.html"
  670. } else if preferredLang.hasPrefix("pt") {
  671. tStrUrl = "https://www.cisdem.com/pt/pdfmaster-mac/buy.html"
  672. } else if preferredLang.hasPrefix("ja") {
  673. tStrUrl = "https://www.cisdem.com/jp/pdfmaster-mac/buy.html"
  674. }
  675. }
  676. guard let url = URL(string: tStrUrl) else {
  677. return
  678. }
  679. let tWorkSpace = NSWorkspace.shared
  680. if tWorkSpace.open(url) == false {
  681. tWorkSpace.open(url)
  682. }
  683. #endif
  684. }
  685. @IBAction func volumeDiscount(_ sender: NSMenuItem) {
  686. var tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program"
  687. #if VERSION_DMG
  688. tStrHttpUrl = "https://www.cisdem.com/volume-license-for-business.html"
  689. if SKInspectPublicTool.currentisLanguageHans() {
  690. tStrHttpUrl = "https://www.cisdem.com/volume-license-for-business.html"
  691. }
  692. #else
  693. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp"
  694. if SKInspectPublicTool.currentisLanguageHans() {
  695. tStrHttpUrl = "https://www.pdfreaderpro.com/vpp-purchase-program?utm_source=pdfmacstore&utm_campaign=menubar_vpp_zh"
  696. }
  697. #endif
  698. guard let url = URL(string: tStrHttpUrl) else {
  699. NSSound.beep()
  700. return
  701. }
  702. let tWorkSpace = NSWorkspace.shared
  703. if tWorkSpace.open(url) == false {
  704. tWorkSpace.open(url)
  705. }
  706. }
  707. @IBAction func crossPlatformAction(_ sender: NSMenuItem) {
  708. var tStrUrl = "https://www.cisdem.com/pdfmaster-mac/buy.html"
  709. let defs = UserDefaults.standard
  710. if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first {
  711. if preferredLang.hasPrefix("de") {
  712. tStrUrl = "https://www.cisdem.com/de/pdfmaster-mac/buy.html"
  713. } else if preferredLang.hasPrefix("fr") {
  714. tStrUrl = "https://www.cisdem.com/fr/pdfmaster-mac/buy.html"
  715. } else if preferredLang.hasPrefix("it") {
  716. tStrUrl = "https://www.cisdem.com/it/pdfmaster-mac/buy.html"
  717. } else if preferredLang.hasPrefix("es") {
  718. tStrUrl = "https://www.cisdem.com/es/pdfmaster-mac/buy.html"
  719. } else if preferredLang.hasPrefix("pt") {
  720. tStrUrl = "https://www.cisdem.com/pt/pdfmaster-mac/buy.html"
  721. } else if preferredLang.hasPrefix("ja") {
  722. tStrUrl = "https://www.cisdem.com/jp/pdfmaster-mac/buy.html"
  723. }
  724. }
  725. guard let url = URL(string: tStrUrl) else {
  726. return
  727. }
  728. let tWorkSpace = NSWorkspace.shared
  729. if tWorkSpace.open(url) == false {
  730. tWorkSpace.open(url)
  731. }
  732. #if VERSION_DMG
  733. FMTrackEventManager.defaultManager.trackEvent(event: "Menubar", withProperties: ["Menubar_Btn" : "Menubar_Btn_Help_CrossPlatform"])
  734. #endif
  735. }
  736. @IBAction func EducationDiscountAction(_ sender: NSMenuItem) {
  737. let (major, minor, bugFix) = KMTools.getSystemVersion()
  738. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  739. let appVersion = KMTools.getAppVersion()
  740. let appName = KMTools.getAppNameForSupportEmail()
  741. let subjects = "\(appName) - \(appVersion);Education Discount;\(versionInfoString)"
  742. let email = "sales@cisdem.com"
  743. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  744. }
  745. @IBAction func aiToolsAction(_ sender: NSMenuItem) {
  746. #if VERSION_DMG
  747. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  748. #else
  749. AIPurchaseWindowController.currentWC().showWindow(nil)
  750. #endif
  751. }
  752. @IBAction func orderFrontLineInspector(_ sender: Any?) {
  753. if let win = KMLineInspector.shared.window {
  754. if win.isVisible {
  755. win.orderOut(sender)
  756. } else {
  757. win.orderFront(sender)
  758. }
  759. }
  760. }
  761. @IBAction func showDownloads(_ sender: NSMenuItem) -> Void {
  762. KMPrint("showDownloads ...")
  763. }
  764. @IBAction func showWelcomeWindow(_ sender: NSMenuItem) -> Void {
  765. self.reopenDocument(forPaths: [])
  766. }
  767. @IBAction func newsletter(_ sender: NSMenuItem) -> Void {
  768. KMEmailSubWindowController().showWindow(nil)
  769. }
  770. @IBAction func feedback(_ sender: NSMenuItem) -> Void {
  771. KMTools.feekback()
  772. }
  773. @IBAction func reportBug(_ sender: NSMenuItem) -> Void {
  774. KMTools.reportBug()
  775. }
  776. @IBAction func reportGeneralQuestions(_ sender: NSMenuItem) -> Void {
  777. KMTools.reportGeneralQuestions()
  778. }
  779. }
  780. extension AppDelegate : NSMenuDelegate,NSMenuItemValidation {
  781. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  782. let action = menuItem.action
  783. if action == #selector(manageAcctounMenuAction) {
  784. self.updateLoginMenuItem()
  785. return KMLightMemberManager.manager.isLogin()
  786. }
  787. if action == #selector(loginMenuItemAction) {
  788. self.updateLoginMenuItem()
  789. return !KMLightMemberManager.manager.isLogin()
  790. }
  791. if action == #selector(logoutMenuItemAction) {
  792. self.updateLoginMenuItem()
  793. return KMLightMemberManager.manager.isLogin()
  794. }
  795. if (action == #selector(sharePageItemAction)) {
  796. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  797. return false
  798. }
  799. let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  800. return !isHome
  801. }
  802. if action == #selector(closeDocument) {
  803. guard let _windowC = NSApp.mainWindow?.windowController as? KMBrowserWindowController else {
  804. if NSApp.mainWindow?.windowController != nil {
  805. return true
  806. }
  807. return false
  808. }
  809. let isNewTab = _windowC.browser?.activeTabContents()?.isNewTab ?? false
  810. if isNewTab {
  811. return true
  812. }
  813. // let isHome = _windowC.browser?.activeTabContents()?.isHome ?? false
  814. // return !isHome
  815. }
  816. return true
  817. }
  818. func updateLoginMenuItem() {
  819. let firstItem = NSApp.mainMenu?.item(at: 0)?.submenu
  820. if firstItem != nil {
  821. let item1 = firstItem?.item(withTag: 11)
  822. let item2 = firstItem?.item(withTag: 12)
  823. let item3 = firstItem?.item(withTag: 13)
  824. let item4 = firstItem?.item(withTag: 14)
  825. // let item5 = firstItem?.item(withTag: 15)
  826. let item6 = firstItem?.item(withTag: kKMMainMenuAccountRefreshItemTag)
  827. // if KMLightMemberManager.manager.isLogin() {
  828. // item1?.title = KMLightMemberManager.manager.info.email
  829. // item1?.isHidden = false
  830. // item2?.isHidden = true
  831. // item3?.isHidden = false
  832. // item4?.isHidden = false
  833. //// item5?.isHidden = false
  834. // item6?.isHidden = false
  835. // } else {
  836. // item1?.isHidden = true
  837. // item2?.isHidden = false
  838. // item3?.isHidden = true
  839. // item4?.isHidden = true
  840. //// item5?.isHidden = true
  841. // item6?.isHidden = true
  842. // }
  843. item1?.isHidden = true
  844. item2?.isHidden = true
  845. item3?.isHidden = true
  846. item4?.isHidden = true
  847. // item5?.isHidden = true
  848. item6?.isHidden = true
  849. }
  850. }
  851. @objc func clickOutline(menuItem: NSMenuItem) {
  852. KMPrint("更新菜单栏")
  853. }
  854. func menu(_ menu: NSMenu, update item: NSMenuItem, at index: Int, shouldCancel: Bool) -> Bool {
  855. return true
  856. }
  857. }
  858. extension AppDelegate {
  859. // MARK: - Services Support
  860. func openDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  861. var error: NSError?
  862. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: false, outError: &error) {
  863. // Document opened successfully
  864. } else if let error = error {
  865. errorString = error.localizedDescription
  866. }
  867. }
  868. func openDocumentFromDataOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  869. var error: NSError?
  870. if let document = NSDocumentController.shared.openDocumentWithImageFromPasteboard(pboard, error: &error) {
  871. // Document opened successfully
  872. } else if let error = error {
  873. errorString = error.localizedDescription
  874. }
  875. }
  876. func openNotesDocumentFromURLOnPboard(_ pboard: NSPasteboard, userData: String?, error errorString: inout String?) {
  877. var error: NSError?
  878. if let document = NSDocumentController.shared.openDocumentWithURLFromPasteboard(pboard, showNotes: true, outError: &error) {
  879. // Document opened successfully
  880. } else if let error = error {
  881. errorString = error.localizedDescription
  882. }
  883. }
  884. }
  885. extension AppDelegate: UNUserNotificationCenterDelegate {
  886. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  887. // 处理用户点击推送通知的操作
  888. completionHandler()
  889. }
  890. }