KeyboardViewController.swift 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. //
  2. // KeyboardViewController.swift
  3. // AiKeyboard
  4. //
  5. // Created by Destiny on 2025/4/23.
  6. //
  7. import UIKit
  8. import Lottie
  9. import SnapKit
  10. import MarqueeLabel
  11. enum KeyboardType: Int {
  12. case help = 0 // 帮聊
  13. case teach = 1 // 教你说
  14. case prologue = 2 // 开场白
  15. }
  16. class KeyboardViewController: UIInputViewController {
  17. struct UX {
  18. static let keyboardHeight = 318.0
  19. }
  20. // 选择的键盘类型
  21. var chooseType: KeyboardType = .help {
  22. didSet {
  23. self.updateMainViewUI()
  24. }
  25. }
  26. // 键盘列表
  27. var keyboardList: [KeyboardModel]?
  28. // 选择的键盘
  29. var chooseKeyboard: KeyboardModel?
  30. // 人设列表
  31. var characterList: [CharacterModel]?
  32. // 开场白列表
  33. var prologueList: [PrologueModel]?
  34. // 开始持续删除
  35. private var deleteTimer: Timer?
  36. private var deleteAcceleration: TimeInterval = 0.1
  37. var heightConstriaint: NSLayoutConstraint?
  38. lazy var bgImageView: UIImageView = {
  39. let imageView = UIImageView()
  40. imageView.image = UIImage(named: "keyboard_bg")
  41. return imageView
  42. }()
  43. lazy var menuBtn: UIButton = {
  44. let button = UIButton()
  45. button.setImage(UIImage(named: "keyboard_menu_btn"), for: .normal)
  46. button.addTarget(self, action: #selector(menuBtnClickAction), for: .touchUpInside)
  47. return button
  48. }()
  49. lazy var heartAnimation: LottieAnimationView = {
  50. let animate = LottieAnimationView(name: "heart")
  51. animate.loopMode = .loop
  52. animate.backgroundColor = .clear
  53. animate.isUserInteractionEnabled = true
  54. let tap = UITapGestureRecognizer(target: self, action: #selector(heartBtnClickAction))
  55. animate.addGestureRecognizer(tap)
  56. return animate
  57. }()
  58. lazy var heartLabel: UILabel = {
  59. let label = UILabel()
  60. label.text = "30%"
  61. label.font = .boldSystemFont(ofSize: 10)
  62. label.textColor = .white
  63. label.isUserInteractionEnabled = true
  64. let tap = UITapGestureRecognizer(target: self, action: #selector(heartBtnClickAction))
  65. label.addGestureRecognizer(tap)
  66. return label
  67. }()
  68. lazy var exchangeBtn: UIButton = {
  69. let button = UIButton()
  70. button.setImage(UIImage(named: "keyboard_exchange_btn"), for: .normal)
  71. button.addTarget(self, action: #selector(exchangeBtnClickAction), for: .touchUpInside)
  72. return button
  73. }()
  74. lazy var chooseView: UIView = {
  75. let view = UIView()
  76. view.backgroundColor = .white
  77. view.layer.cornerRadius = 17
  78. return view
  79. }()
  80. lazy var functionView: UIView = {
  81. let view = UIView()
  82. view.backgroundColor = .hexStringColor(hexString: "#DDCFFD")
  83. view.layer.cornerRadius = 16
  84. view.isUserInteractionEnabled = true
  85. let tap = UITapGestureRecognizer(target: self, action: #selector(functionBtnClickAction))
  86. view.addGestureRecognizer(tap)
  87. return view
  88. }()
  89. lazy var functionLabel: UILabel = {
  90. let label = UILabel()
  91. label.text = "帮聊"
  92. label.font = .boldSystemFont(ofSize: 12)
  93. label.textColor = .hexStringColor(hexString: "#000000", alpha: 0.8)
  94. return label
  95. }()
  96. lazy var arrowIcon: UIImageView = {
  97. let imageView = UIImageView()
  98. imageView.image = UIImage(named: "icon_arrow_down")
  99. return imageView
  100. }()
  101. lazy var userChangeBtn: UIButton = {
  102. let btn = UIButton()
  103. btn.setTitle("小蕾", for: .normal)
  104. btn.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium)
  105. btn.setTitleColor(.hexStringColor(hexString: "#000000").withAlphaComponent(0.8), for: .normal)
  106. btn.setImage(UIImage(named: "keyboard_user_change_icon"), for: .normal)
  107. btn.setImageTitleLayout(.imgRight, spacing: 8)
  108. btn.addTarget(self, action: #selector(changeBtnClickAction), for: .touchUpInside)
  109. return btn
  110. }()
  111. lazy var userChangeView: UIView = {
  112. let view = UIView()
  113. let tap = UITapGestureRecognizer(target: self, action: #selector(changeBtnClickAction))
  114. view.addGestureRecognizer(tap)
  115. return view
  116. }()
  117. lazy var userChangeLabel: MarqueeLabel = {
  118. let label = MarqueeLabel(frame: .zero, duration: 3.0, fadeLength: 0)
  119. label.type = .leftRight
  120. label.text = "通用键盘"
  121. label.font = .systemFont(ofSize: 12)
  122. label.textColor = .hexStringColor(hexString: "#000000")
  123. label.textAlignment = .center
  124. return label
  125. }()
  126. lazy var userChangeIcon: UIImageView = {
  127. let icon = UIImageView()
  128. icon.image = UIImage(named: "keyboard_user_change_icon")
  129. return icon
  130. }()
  131. lazy var helpView: KeyboardHelpView = {
  132. let view = KeyboardHelpView()
  133. view.delegate = self
  134. view.helpDelegate = self
  135. return view
  136. }()
  137. lazy var teachView: KeyboardTeachView = {
  138. let view = KeyboardTeachView()
  139. view.delegate = self
  140. view.teachDelegate = self
  141. view.isHidden = true
  142. return view
  143. }()
  144. lazy var prologueView: KeyboardPrologueView = {
  145. let view = KeyboardPrologueView()
  146. view.delegate = self
  147. view.prologueDelegate = self
  148. view.isHidden = true
  149. return view
  150. }()
  151. lazy var exchangeView: KeyboardExchangeView = {
  152. let view = KeyboardExchangeView()
  153. view.isHidden = true
  154. view.delegate = self
  155. return view
  156. }()
  157. lazy var menuView: KeyboardMenuView = {
  158. let view = KeyboardMenuView()
  159. view.isHidden = true
  160. view.delegate = self
  161. return view
  162. }()
  163. lazy var loginView: KeyboardLoginTipView = {
  164. let view = KeyboardLoginTipView()
  165. view.isHidden = true
  166. view.loginBtnClosure = {
  167. self.navigateToLogin()
  168. }
  169. view.backBtnClosure = {
  170. self.clearPopView()
  171. self.loginView.isHidden = true
  172. self.nowShowView?.isHidden = false
  173. }
  174. return view
  175. }()
  176. lazy var vipView: KeyboardVipTipView = {
  177. let view = KeyboardVipTipView()
  178. view.isHidden = true
  179. view.unlockBtnClosure = {
  180. self.navigateToMembership()
  181. }
  182. view.backBtnClosure = {
  183. self.clearPopView()
  184. self.vipView.isHidden = true
  185. self.nowShowView?.isHidden = false
  186. }
  187. return view
  188. }()
  189. var nowShowView: UIView?
  190. // 命令检查定时器
  191. private var guideCheckTimer: Timer?
  192. override func viewWillAppear(_ animated: Bool) {
  193. super.viewWillAppear(animated)
  194. self.prepareHeightConstraint()
  195. }
  196. override func viewDidLoad() {
  197. super.viewDidLoad()
  198. setUI()
  199. checkFullAccess()
  200. KeyboardApi.initParams()
  201. requestKeyboardList()
  202. requestPrologueList()
  203. startMonitoringPasteboard()
  204. startListenGuide()
  205. // self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
  206. // self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
  207. }
  208. override func viewWillDisappear(_ animated: Bool) {
  209. super.viewWillDisappear(animated)
  210. }
  211. override func viewWillLayoutSubviews() {
  212. super.viewWillLayoutSubviews()
  213. }
  214. override func updateViewConstraints() {
  215. super.updateViewConstraints()
  216. if self.view.frame.size.width == 0 && self.view.frame.size.height == 0 {
  217. return
  218. }
  219. self.prepareHeightConstraint()
  220. }
  221. override func textWillChange(_ textInput: UITextInput?) {
  222. // The app is about to change the document's contents. Perform any preparation here.
  223. }
  224. override func textDidChange(_ textInput: UITextInput?) {
  225. // The app has just changed the document's contents, the document context has been updated.
  226. var textColor: UIColor
  227. let proxy = self.textDocumentProxy
  228. if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
  229. textColor = UIColor.white
  230. } else {
  231. textColor = UIColor.black
  232. }
  233. }
  234. func prepareHeightConstraint() {
  235. if self.heightConstriaint == nil {
  236. if let view = self.view {
  237. self.heightConstriaint = NSLayoutConstraint(item: view, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0.0, constant: UX.keyboardHeight)
  238. self.heightConstriaint?.priority = UILayoutPriority(750)
  239. self.view.addConstraint(self.heightConstriaint!)
  240. }
  241. } else {
  242. self.heightConstriaint?.constant = UX.keyboardHeight
  243. }
  244. }
  245. // 开始监听是否需要打开引导页
  246. func startListenGuide() {
  247. // 创建定时器定期检查命令
  248. guideCheckTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
  249. self?.popGuideView()
  250. }
  251. }
  252. func popGuideView() {
  253. let hasFullAccess = self.hasFullAccess
  254. let isNotFirstOpen = UserDefaults.standard.bool(forKey: "isNotFirstOpenKey")
  255. let showGuide = KeyboardSharedDataManager.shared.getIsShowGuide()
  256. if !isNotFirstOpen && hasFullAccess && (showGuide == true) {
  257. let guideView = KeyboardGuideView()
  258. self.view.addSubview(guideView)
  259. guideView.snp.makeConstraints { make in
  260. make.top.left.right.bottom.equalTo(0)
  261. }
  262. UserDefaults.standard.set(true, forKey: "isNotFirstOpenKey")
  263. guideCheckTimer?.invalidate()
  264. guideCheckTimer = nil
  265. }
  266. }
  267. }
  268. // MARK: - 网络请求
  269. extension KeyboardViewController {
  270. // 获取键盘列表
  271. func requestKeyboardList() {
  272. KeyboardNetworkManager.request(.keyboard_list(params: [:])) { response in
  273. if let keyboardInfos = try? response.mapArray(KeyboardModel.self, atKeyPath: "data.keyboardInfos") {
  274. self.keyboardList = keyboardInfos
  275. self.updateUserChangeBtnUI()
  276. self.requestCharacterList()
  277. print("成功解析数组,数量:\(keyboardInfos.count)")
  278. }
  279. } fail: { code, error in
  280. self.view.toast(text: error)
  281. print(error)
  282. }
  283. }
  284. // 获取键盘人设列表
  285. func requestCharacterList() {
  286. var params: [String: Any] = [String: Any]()
  287. if let chooseKeyboard = self.chooseKeyboard {
  288. params = ["keyboardId": chooseKeyboard.id ?? ""]
  289. }
  290. KeyboardNetworkManager.request(.character_list(params: params)) { response in
  291. if let characterInfos = try? response.mapArray(CharacterModel.self, atKeyPath: "data.characterInfos") {
  292. self.characterList = characterInfos
  293. self.updateCharacterUI()
  294. print("成功解析数组,数量:\(characterInfos.count)")
  295. }
  296. } fail: { code, error in
  297. self.view.toast(text: error)
  298. print(error)
  299. }
  300. }
  301. // 获取键盘开场白列表
  302. func requestPrologueList() {
  303. KeyboardNetworkManager.request(.prologue_list(params: [:])) { response in
  304. if let prologueList = try? response.mapArray(PrologueModel.self, atKeyPath: "data.prologues") {
  305. self.prologueList = prologueList
  306. self.updatePrologueUI()
  307. }
  308. } fail: { code, error in
  309. self.view.toast(text: error)
  310. print(error)
  311. }
  312. }
  313. // 选择键盘
  314. func requestChooseKeyboard(keyboardId: String, success: @escaping (() -> Void)) {
  315. var params: [String: Any] = [String: Any]()
  316. params = ["keyboardId": keyboardId]
  317. KeyboardNetworkManager.request(.keyboard_choose(params: params)) { response in
  318. self.view.toast(text: "保存成功")
  319. success()
  320. } fail: { code, error in
  321. self.view.toast(text: error)
  322. print(error)
  323. }
  324. }
  325. // 请求获取超会回
  326. func requestSuperReply(characterId: String, content: String, complete: @escaping ((String) -> ())) {
  327. var params: [String: Any] = [String: Any]()
  328. params = ["keyboardId": self.chooseKeyboard?.id ?? "",
  329. "characterId": characterId,
  330. "content": content]
  331. KeyboardNetworkManager.request(.chat_super_reply(params: params)) { response in
  332. if let contentModel = try? response.mapObject(ReplyModel.self, atKeyPath: "data") {
  333. complete(contentModel.content ?? "")
  334. } else {
  335. complete("")
  336. }
  337. } fail: { code, error in
  338. self.view.toast(text: error)
  339. print(error)
  340. complete("")
  341. if code == 1006 {
  342. // 弹出登录页
  343. self.popLoginView()
  344. } else if code == 1008 {
  345. // 弹出会员页
  346. self.popVipView()
  347. }
  348. }
  349. }
  350. // 请求获取超会说
  351. func requestSuperSpeak(characterId: String, content: String, complete: @escaping (([String]) -> ())) {
  352. var params: [String: Any] = [String: Any]()
  353. params = ["keyboardId": self.chooseKeyboard?.id ?? "",
  354. "characterId": characterId,
  355. "content": content]
  356. KeyboardNetworkManager.request(.chat_super_speak(params: params)) { response in
  357. if let contentModel = try? response.mapObject(SpeakModel.self, atKeyPath: "data"), let list = contentModel.list {
  358. complete(list)
  359. } else {
  360. complete([String]())
  361. }
  362. } fail: { code, error in
  363. self.view.toast(text: error)
  364. print(error)
  365. complete([String]())
  366. if code == 1006 {
  367. // 弹出登录页
  368. self.popLoginView()
  369. } else if code == 1008 {
  370. // 弹出会员页
  371. self.popVipView()
  372. }
  373. }
  374. }
  375. // 请求获取超会说
  376. func requestSuperPrologue(name: String, complete: @escaping (([String]) -> ())) {
  377. var params: [String: Any] = [String: Any]()
  378. params = ["name": name]
  379. KeyboardNetworkManager.request(.chat_super_prologue(params: params)) { response in
  380. if let contentModel = try? response.mapObject(SpeakModel.self, atKeyPath: "data"), let list = contentModel.list {
  381. complete(list)
  382. } else {
  383. complete([String]())
  384. }
  385. } fail: { code, error in
  386. self.view.toast(text: error)
  387. print(error)
  388. complete([String]())
  389. if code == 1006 {
  390. // 弹出登录页
  391. self.popLoginView()
  392. } else if code == 1008 {
  393. // 弹出会员页
  394. self.popVipView()
  395. }
  396. }
  397. }
  398. }
  399. // MARK: - 点击事件
  400. extension KeyboardViewController: KeyboardMenuViewDelegate, KeyboardExchangeViewDelegate {
  401. // 亲密度按钮点击
  402. @objc func heartBtnClickAction() {
  403. let url = URL(string: "com.qihuan.zhuiaijianpan:///intimacy")!
  404. openURL(url)
  405. }
  406. // 切换系统键盘
  407. @objc func exchangeBtnClickAction() {
  408. self.advanceToNextInputMode()
  409. }
  410. // 功能按钮选择点击
  411. @objc func functionBtnClickAction() {
  412. KeyboardFunctionPopView.show(view: self.view, selectType: self.chooseType) { type in
  413. self.chooseType = type
  414. }
  415. }
  416. // 菜单按钮点击
  417. @objc func menuBtnClickAction() {
  418. clearPopView()
  419. self.menuView.isHidden = false
  420. }
  421. // 菜单按钮返回
  422. func menuBackBtnClickAction() {
  423. clearPopView()
  424. self.nowShowView?.isHidden = false
  425. }
  426. // 会员按钮点击
  427. func vipBtnClickAction() {
  428. navigateToMembership()
  429. }
  430. // 定制人设
  431. func diyBtnClickAction() {
  432. let url = URL(string: "com.qihuan.zhuiaijianpan:///character/custom")!
  433. openURL(url)
  434. }
  435. // 人设市场
  436. func marketBtnClickAction() {
  437. let url = URL(string: "com.qihuan.zhuiaijianpan:///character/market")!
  438. openURL(url)
  439. }
  440. // 跳转到主应用的登录页面
  441. @objc func navigateToLogin() {
  442. let url = URL(string: "com.qihuan.zhuiaijianpan:///login")!
  443. openURL(url)
  444. }
  445. // 跳转到主应用的会员页面
  446. @objc func navigateToMembership() {
  447. let url = URL(string: "com.qihuan.zhuiaijianpan:///member")!
  448. openURL(url)
  449. }
  450. // 通用的打开URL方法
  451. private func openURL(_ url: URL) {
  452. var responder = self as UIResponder?
  453. while (responder != nil && !(responder is UIApplication)) {
  454. responder = responder?.next
  455. }
  456. if responder != nil {
  457. let selectorOpenURL = sel_registerName("openURL:")
  458. if responder!.responds(to: selectorOpenURL) {
  459. responder?.perform(selectorOpenURL, with: url)
  460. }
  461. }
  462. // 不知道为什么无法使用
  463. // self.extensionContext?.open(url, completionHandler: nil)
  464. }
  465. // 选择键盘按钮点击
  466. @objc func changeBtnClickAction() {
  467. clearPopView()
  468. self.exchangeView.keyboardList = self.keyboardList
  469. self.exchangeView.isHidden = false
  470. }
  471. // 选择键盘后返回
  472. func exchangeViewBackClickAction() {
  473. clearPopView()
  474. self.nowShowView?.isHidden = false
  475. }
  476. // 点击保存按钮
  477. func exchangeViewSaveClickAction(keyboardList: [KeyboardModel], success: @escaping (() -> ())) {
  478. var keyboardId = ""
  479. for keyboard in keyboardList {
  480. if keyboard.isChoose == true {
  481. keyboardId = keyboard.id ?? ""
  482. break
  483. }
  484. }
  485. requestChooseKeyboard(keyboardId: keyboardId) {
  486. self.keyboardList = keyboardList
  487. for keyboard in keyboardList {
  488. if keyboard.isChoose == true {
  489. self.chooseKeyboard = keyboard
  490. break
  491. }
  492. }
  493. success()
  494. self.userChangeLabel.text = self.chooseKeyboard?.name
  495. self.clearPopView()
  496. self.nowShowView?.isHidden = false
  497. }
  498. }
  499. }
  500. extension KeyboardViewController: KeyboardHelpViewDelegate, KeyboardTeachViewDelegate, KeyboardPrologueViewDelegate {
  501. // 帮聊点击cell
  502. func helpCollectionViewDidSelectItem(characterId: String, content: String, complete: @escaping ((Bool) -> ())) {
  503. // 判断是否登录
  504. let isLogin = KeyboardSharedDataManager.shared.isLoggedIn()
  505. if !isLogin {
  506. popLoginView()
  507. complete(false)
  508. return
  509. }
  510. self.requestSuperReply(characterId: characterId, content: content) { text in
  511. self.insertText(text)
  512. complete(true)
  513. }
  514. }
  515. // 教你说点击cell
  516. func teachCollectionViewDidSelectItem(characterId: String, content: String, complete: @escaping (([String], Bool, Bool) -> ())) {
  517. // 判断是否登录
  518. let isLogin = KeyboardSharedDataManager.shared.isLoggedIn()
  519. if !isLogin {
  520. popLoginView()
  521. complete([String](), false, false)
  522. return
  523. } else {
  524. complete([String](), true, false)
  525. }
  526. self.requestSuperSpeak(characterId: characterId, content: content) { list in
  527. complete(list, true, true)
  528. }
  529. }
  530. // 教你说点击 TableViewCell
  531. func teachTableViewDidSelectItem(content: String) {
  532. self.insertText(content)
  533. }
  534. // 开场白点击cell
  535. func prologueCollectionViewDidSelectItem(name: String, complete: @escaping (([String], Bool, Bool) -> ())) {
  536. // 判断是否登录
  537. let isLogin = KeyboardSharedDataManager.shared.isLoggedIn()
  538. if !isLogin {
  539. popLoginView()
  540. complete([String](), false, false)
  541. return
  542. } else {
  543. complete([String](), true, false)
  544. }
  545. self.requestSuperPrologue(name: name) { list in
  546. complete(list, true, true)
  547. }
  548. }
  549. // 开场白点击 TableViewCell
  550. func prologueTableViewDidSelectItem(content: String) {
  551. self.insertText(content)
  552. }
  553. // 点击添加人设
  554. func addCharacterJump() {
  555. self.marketBtnClickAction()
  556. }
  557. }
  558. // MARK: - 处理键盘操作
  559. extension KeyboardViewController: KeyboardBaseViewDelegate {
  560. // 插入文字
  561. func insertText(_ text: String) {
  562. self.textDocumentProxy.insertText(text)
  563. }
  564. // 点击粘贴按钮
  565. func pasteBtnClickAction() {
  566. detectPasteboardPermissionAlert { isShowing in
  567. if isShowing {
  568. print("系统正在显示剪贴板权限弹窗")
  569. self.view.toast(text: "请允许访问剪贴板")
  570. self.openPasteTipView()
  571. }
  572. if let content = self.getPasteboardContent() {
  573. print("获取到剪贴板内容: \(content)")
  574. self.view.toast(text: "获取到剪贴板内容")
  575. self.helpView.setPasteStr(content: content)
  576. self.teachView.setPasteStr(content: content)
  577. } else {
  578. print("无法获取剪贴板内容")
  579. self.view.toast(text: "无法获取剪贴板内容")
  580. }
  581. }
  582. }
  583. // 删除按钮
  584. func deleteBtnClickAction() {
  585. self.textDocumentProxy.deleteBackward()
  586. }
  587. // 清除按钮
  588. func clearBtnClickAction() {
  589. // 获取当前文本
  590. let proxy = self.textDocumentProxy
  591. // 清空所有文本
  592. for _ in 0..<100 {
  593. proxy.deleteBackward()
  594. }
  595. }
  596. // 发送按钮
  597. func sendBtnClickAction() {
  598. self.textDocumentProxy.insertText("\n")
  599. }
  600. func deleteBtnLongPressBegin() {
  601. // 停止已有的定时器
  602. stopContinuousDelete()
  603. // 创建新的定时器,初始间隔为0.5秒
  604. deleteTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(continuousDeleteAction), userInfo: nil, repeats: false)
  605. }
  606. func deleteBtnLongPressEnd() {
  607. stopContinuousDelete()
  608. }
  609. // 停止删除
  610. func stopContinuousDelete() {
  611. deleteTimer?.invalidate()
  612. deleteTimer = nil
  613. deleteAcceleration = 0.1 // 重置加速度
  614. }
  615. @objc func continuousDeleteAction() {
  616. // 执行删除操作
  617. self.textDocumentProxy.deleteBackward()
  618. // 停止当前定时器
  619. deleteTimer?.invalidate()
  620. // 加速删除(最快0.05秒一次)
  621. let newInterval = max(0.05, 0.5 - deleteAcceleration)
  622. deleteAcceleration += 0.05 // 每次加速0.05秒
  623. // 创建新的更快的定时器
  624. deleteTimer = Timer.scheduledTimer(timeInterval: newInterval, target: self, selector: #selector(continuousDeleteAction), userInfo: nil, repeats: false)
  625. }
  626. // 监听剪贴板变化
  627. func startMonitoringPasteboard() {
  628. // 记录当前剪贴板变化计数
  629. var initialChangeCount = UIPasteboard.general.changeCount
  630. // 记录上一次的剪贴板内容
  631. var lastPasteboardContent: String? = UIPasteboard.general.string
  632. // 创建定时器定期检查剪贴板变化
  633. Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] timer in
  634. guard let self = self else {
  635. timer.invalidate()
  636. return
  637. }
  638. let currentChangeCount = UIPasteboard.general.changeCount
  639. if currentChangeCount != initialChangeCount {
  640. // 记录访问前的时间
  641. let startTime = Date()
  642. // 剪贴板计数已变化,检查内容是否真的变化
  643. if let copiedString = UIPasteboard.general.string {
  644. // 只有当内容真的不同时才处理
  645. if !copiedString.isEmpty {
  646. print("检测到新复制的内容: \(copiedString)")
  647. // 更新记录的内容和计数
  648. lastPasteboardContent = copiedString
  649. initialChangeCount = currentChangeCount
  650. // 处理复制的内容
  651. self.handleCopiedContent(copiedString)
  652. // 检查访问后的时间延迟
  653. let timeDelay = Date().timeIntervalSince(startTime)
  654. // 如果访问剪贴板的时间超过一定阈值,可能是因为系统弹出了权限弹窗
  655. // 通常正常访问剪贴板的时间应该很短,如果超过100毫秒,可能是弹出了弹窗
  656. if timeDelay > 0.1 {
  657. self.openPasteTipView()
  658. } else {
  659. }
  660. } else {
  661. // 内容相同或为空,只更新计数
  662. initialChangeCount = currentChangeCount
  663. print("剪贴板计数变化但内容未变或为空")
  664. self.openPasteTipView()
  665. }
  666. } else {
  667. // 剪贴板内容为nil,更新计数
  668. initialChangeCount = currentChangeCount
  669. lastPasteboardContent = nil
  670. print("剪贴板内容被清空")
  671. }
  672. }
  673. }
  674. }
  675. // 处理复制的内容
  676. func handleCopiedContent(_ content: String) {
  677. self.helpView.setPasteStr(content: content)
  678. self.teachView.setPasteStr(content: content)
  679. }
  680. // 检查键盘权限
  681. func checkPasteboardPermission() -> Bool {
  682. var hasPasteboardPermission = false
  683. // iOS 14及以上版本需要检查权限
  684. if #available(iOS 14.0, *) {
  685. // 尝试读取剪贴板内容来检查权限
  686. let pasteboard = UIPasteboard.general
  687. if let _ = pasteboard.string {
  688. hasPasteboardPermission = true
  689. print("键盘扩展有剪贴板访问权限")
  690. } else {
  691. hasPasteboardPermission = false
  692. print("键盘扩展没有剪贴板访问权限")
  693. }
  694. } else {
  695. // iOS 14以下版本默认有权限
  696. hasPasteboardPermission = true
  697. }
  698. return hasPasteboardPermission
  699. }
  700. // 检测系统是否弹出剪贴板权限弹窗
  701. func detectPasteboardPermissionAlert(completion: @escaping (Bool) -> Void) {
  702. // 记录访问前的时间
  703. let startTime = Date()
  704. // 尝试访问剪贴板
  705. let _ = UIPasteboard.general.string
  706. // 检查访问后的时间延迟
  707. let timeDelay = Date().timeIntervalSince(startTime)
  708. // 如果访问剪贴板的时间超过一定阈值,可能是因为系统弹出了权限弹窗
  709. // 通常正常访问剪贴板的时间应该很短,如果超过100毫秒,可能是弹出了弹窗
  710. if timeDelay > 0.1 {
  711. completion(true)
  712. } else {
  713. completion(false)
  714. }
  715. }
  716. // 获取剪贴板内容
  717. func getPasteboardContent() -> String? {
  718. let pasteboard = UIPasteboard.general
  719. return pasteboard.string
  720. }
  721. // 允许粘贴跳转至设置页
  722. func jumpToSettings() {
  723. if let url = URL(string: UIApplication.openSettingsURLString) {
  724. self.openURL(url)
  725. }
  726. }
  727. func tipsCloseBtnAction() {
  728. self.helpView.topView.isHidden = true
  729. self.helpView.topView.snp.updateConstraints { make in
  730. make.height.equalTo(0)
  731. }
  732. self.teachView.topView.isHidden = true
  733. self.teachView.topView.snp.updateConstraints { make in
  734. make.height.equalTo(0)
  735. }
  736. self.prologueView.topView.isHidden = true
  737. self.prologueView.topView.snp.updateConstraints { make in
  738. make.height.equalTo(0)
  739. }
  740. }
  741. }
  742. extension KeyboardViewController {
  743. // 打开弹窗
  744. func openPasteTipView() {
  745. self.helpView.topView.isHidden = false
  746. self.helpView.topView.snp.updateConstraints { make in
  747. make.height.equalTo(32)
  748. }
  749. self.teachView.topView.isHidden = false
  750. self.teachView.topView.snp.updateConstraints { make in
  751. make.height.equalTo(32)
  752. }
  753. self.prologueView.topView.isHidden = false
  754. self.prologueView.topView.snp.updateConstraints { make in
  755. make.height.equalTo(32)
  756. }
  757. }
  758. // 检查是否有完全访问权限
  759. func checkFullAccess() {
  760. let isFullAccess = self.hasFullAccess
  761. if !isFullAccess {
  762. let tipView = KeyboardTipsPopView()
  763. tipView.settingBtnClosure = {
  764. if let url = URL(string: UIApplication.openSettingsURLString) {
  765. self.openURL(url)
  766. }
  767. }
  768. self.view.addSubview(tipView)
  769. tipView.snp.makeConstraints { make in
  770. make.left.right.bottom.equalTo(0)
  771. make.top.equalTo(56)
  772. }
  773. }
  774. }
  775. // 跳转登录页
  776. func popLoginView() {
  777. self.clearPopView()
  778. self.loginView.isHidden = false
  779. }
  780. // 弹出vip页面
  781. func popVipView() {
  782. self.clearPopView()
  783. self.vipView.isHidden = false
  784. }
  785. // 关闭其他弹出页
  786. func clearPopView() {
  787. self.vipView.isHidden = true
  788. self.loginView.isHidden = true
  789. self.menuView.isHidden = true
  790. self.exchangeView.isHidden = true
  791. self.helpView.isHidden = true
  792. self.teachView.isHidden = true
  793. self.prologueView.isHidden = true
  794. }
  795. // 更新主要界面
  796. func updateMainViewUI() {
  797. clearPopView()
  798. switch chooseType {
  799. case .help:
  800. // self.helpView.characterList = self.characterList
  801. self.helpView.isHidden = false
  802. self.nowShowView = self.helpView
  803. self.functionLabel.text = "帮聊"
  804. break
  805. case .teach:
  806. // self.teachView.characterList = self.characterList
  807. self.teachView.isHidden = false
  808. self.nowShowView = self.teachView
  809. self.functionLabel.text = "教你说"
  810. break
  811. case .prologue:
  812. self.prologueView.isHidden = false
  813. self.nowShowView = self.prologueView
  814. self.functionLabel.text = "开场白"
  815. break
  816. }
  817. }
  818. // 更新人设列表
  819. func updateCharacterUI() {
  820. self.helpView.characterList = self.characterList
  821. self.teachView.characterList = self.characterList
  822. }
  823. // 更新开场白
  824. func updatePrologueUI() {
  825. self.prologueView.prologueList = self.prologueList
  826. }
  827. // 更新键盘选择按钮
  828. func updateUserChangeBtnUI() {
  829. if self.keyboardList?.count == 1 {
  830. self.keyboardList?[0].isChoose = true
  831. self.chooseKeyboard = self.keyboardList?.first
  832. } else {
  833. if let keyboardList = self.keyboardList {
  834. for keyboard in keyboardList {
  835. if keyboard.isChoose == true {
  836. self.chooseKeyboard = keyboard
  837. }
  838. }
  839. }
  840. }
  841. if let chooseKeyboard = self.chooseKeyboard {
  842. self.userChangeLabel.text = chooseKeyboard.name
  843. self.heartLabel.text = "\(chooseKeyboard.intimacy ?? 0)%"
  844. }
  845. }
  846. func setUI() {
  847. self.view.addSubview(bgImageView)
  848. bgImageView.snp.makeConstraints { make in
  849. make.edges.equalToSuperview()
  850. }
  851. self.view.addSubview(menuBtn)
  852. menuBtn.snp.makeConstraints { make in
  853. make.size.equalTo(CGSize(width: 32, height: 32))
  854. make.left.equalTo(13)
  855. make.top.equalTo(17)
  856. }
  857. self.view.addSubview(heartAnimation)
  858. heartAnimation.snp.makeConstraints { make in
  859. make.size.equalTo(CGSize(width: 35, height: 30))
  860. make.right.equalTo(-10)
  861. make.centerY.equalTo(menuBtn.snp.centerY)
  862. }
  863. heartAnimation.play()
  864. self.view.addSubview(heartLabel)
  865. heartLabel.snp.makeConstraints { make in
  866. make.centerY.equalTo(heartAnimation.snp.centerY).offset(-2)
  867. make.centerX.equalTo(heartAnimation.snp.centerX)
  868. }
  869. self.view.addSubview(exchangeBtn)
  870. exchangeBtn.snp.makeConstraints { make in
  871. make.size.equalTo(CGSize(width: 34, height: 34))
  872. make.right.equalTo(heartAnimation.snp.left).offset(-10)
  873. make.centerY.equalTo(menuBtn.snp.centerY)
  874. }
  875. self.view.addSubview(teachView)
  876. teachView.snp.makeConstraints { make in
  877. make.left.right.bottom.equalTo(0)
  878. make.top.equalTo(60)
  879. }
  880. self.view.addSubview(helpView)
  881. helpView.snp.makeConstraints { make in
  882. make.left.right.bottom.equalTo(0)
  883. make.top.equalTo(60)
  884. }
  885. self.view.addSubview(prologueView)
  886. prologueView.snp.makeConstraints { make in
  887. make.left.right.bottom.equalTo(0)
  888. make.top.equalTo(60)
  889. }
  890. self.view.addSubview(chooseView)
  891. chooseView.snp.makeConstraints { make in
  892. make.width.equalTo(147)
  893. make.height.equalTo(34)
  894. make.left.equalTo(menuBtn.snp.right).offset(9)
  895. make.centerY.equalTo(menuBtn.snp.centerY)
  896. }
  897. self.view.addSubview(exchangeView)
  898. exchangeView.snp.makeConstraints { make in
  899. make.top.equalTo(menuBtn.snp.bottom)
  900. make.left.right.bottom.equalTo(0)
  901. }
  902. self.view.addSubview(menuView)
  903. menuView.snp.makeConstraints { make in
  904. make.left.right.bottom.equalTo(0)
  905. make.top.equalTo(menuBtn.snp.bottom)
  906. }
  907. self.view.addSubview(loginView)
  908. loginView.snp.makeConstraints { make in
  909. make.top.left.right.bottom.equalTo(0)
  910. }
  911. self.view.addSubview(vipView)
  912. vipView.snp.makeConstraints { make in
  913. make.top.left.right.bottom.equalTo(0)
  914. }
  915. chooseView.addSubview(functionView)
  916. functionView.snp.makeConstraints { make in
  917. make.top.left.equalTo(1)
  918. make.bottom.equalTo(-1)
  919. make.width.equalTo(85)
  920. }
  921. functionView.addSubview(functionLabel)
  922. functionLabel.snp.makeConstraints { make in
  923. make.left.equalTo(12)
  924. make.centerY.equalToSuperview()
  925. }
  926. functionView.addSubview(arrowIcon)
  927. arrowIcon.snp.makeConstraints { make in
  928. make.size.equalTo(CGSize(width: 18, height: 18))
  929. make.centerY.equalToSuperview()
  930. make.right.equalTo(-5)
  931. }
  932. chooseView.addSubview(userChangeView)
  933. userChangeView.snp.makeConstraints { make in
  934. make.left.equalTo(functionView.snp.right)
  935. make.right.equalToSuperview()
  936. make.top.bottom.equalTo(0)
  937. }
  938. userChangeView.addSubview(userChangeIcon)
  939. userChangeIcon.snp.makeConstraints { make in
  940. make.size.equalTo(CGSize(width: 12, height: 12))
  941. make.centerY.equalToSuperview()
  942. make.right.equalTo(-8)
  943. }
  944. userChangeView.addSubview(userChangeLabel)
  945. userChangeLabel.snp.makeConstraints { make in
  946. make.right.equalTo(userChangeIcon.snp.left).offset(-4)
  947. make.left.equalTo(4)
  948. make.centerY.equalToSuperview()
  949. }
  950. // chooseView.addSubview(userChangeBtn)
  951. // userChangeBtn.snp.makeConstraints { make in
  952. // make.left.equalTo(functionView.snp.right)
  953. // make.right.equalToSuperview()
  954. // make.top.bottom.equalTo(0)
  955. // }
  956. self.nowShowView = self.helpView
  957. }
  958. }