KeyboardViewController.swift 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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. self.dismissKeyboard()
  460. responder?.perform(selectorOpenURL, with: url)
  461. }
  462. }
  463. // 不知道为什么无法使用
  464. // self.extensionContext?.open(url, completionHandler: nil)
  465. }
  466. // 选择键盘按钮点击
  467. @objc func changeBtnClickAction() {
  468. clearPopView()
  469. self.exchangeView.keyboardList = self.keyboardList
  470. self.exchangeView.isHidden = false
  471. }
  472. // 选择键盘后返回
  473. func exchangeViewBackClickAction() {
  474. clearPopView()
  475. self.nowShowView?.isHidden = false
  476. }
  477. // 点击保存按钮
  478. func exchangeViewSaveClickAction(keyboardList: [KeyboardModel], success: @escaping (() -> ())) {
  479. var keyboardId = ""
  480. for keyboard in keyboardList {
  481. if keyboard.isChoose == true {
  482. keyboardId = keyboard.id ?? ""
  483. break
  484. }
  485. }
  486. requestChooseKeyboard(keyboardId: keyboardId) {
  487. self.keyboardList = keyboardList
  488. for keyboard in keyboardList {
  489. if keyboard.isChoose == true {
  490. self.chooseKeyboard = keyboard
  491. break
  492. }
  493. }
  494. success()
  495. self.userChangeLabel.text = self.chooseKeyboard?.name
  496. self.clearPopView()
  497. self.nowShowView?.isHidden = false
  498. }
  499. }
  500. }
  501. extension KeyboardViewController: KeyboardHelpViewDelegate, KeyboardTeachViewDelegate, KeyboardPrologueViewDelegate {
  502. // 帮聊点击cell
  503. func helpCollectionViewDidSelectItem(characterId: String, content: String, complete: @escaping ((Bool) -> ())) {
  504. // 判断是否登录
  505. let isLogin = KeyboardSharedDataManager.shared.isLoggedIn()
  506. if !isLogin {
  507. popLoginView()
  508. complete(false)
  509. return
  510. }
  511. self.requestSuperReply(characterId: characterId, content: content) { text in
  512. self.insertText(text)
  513. complete(true)
  514. }
  515. }
  516. // 教你说点击cell
  517. func teachCollectionViewDidSelectItem(characterId: String, content: String, complete: @escaping (([String], Bool, Bool) -> ())) {
  518. // 判断是否登录
  519. let isLogin = KeyboardSharedDataManager.shared.isLoggedIn()
  520. if !isLogin {
  521. popLoginView()
  522. complete([String](), false, false)
  523. return
  524. } else {
  525. complete([String](), true, false)
  526. }
  527. self.requestSuperSpeak(characterId: characterId, content: content) { list in
  528. complete(list, true, true)
  529. }
  530. }
  531. // 教你说点击 TableViewCell
  532. func teachTableViewDidSelectItem(content: String) {
  533. self.insertText(content)
  534. }
  535. // 开场白点击cell
  536. func prologueCollectionViewDidSelectItem(name: String, complete: @escaping (([String], Bool, Bool) -> ())) {
  537. // 判断是否登录
  538. let isLogin = KeyboardSharedDataManager.shared.isLoggedIn()
  539. if !isLogin {
  540. popLoginView()
  541. complete([String](), false, false)
  542. return
  543. } else {
  544. complete([String](), true, false)
  545. }
  546. self.requestSuperPrologue(name: name) { list in
  547. complete(list, true, true)
  548. }
  549. }
  550. // 开场白点击 TableViewCell
  551. func prologueTableViewDidSelectItem(content: String) {
  552. self.insertText(content)
  553. }
  554. // 点击添加人设
  555. func addCharacterJump() {
  556. self.marketBtnClickAction()
  557. }
  558. }
  559. // MARK: - 处理键盘操作
  560. extension KeyboardViewController: KeyboardBaseViewDelegate {
  561. // 插入文字
  562. func insertText(_ text: String) {
  563. self.textDocumentProxy.insertText(text)
  564. }
  565. // 点击粘贴按钮
  566. func pasteBtnClickAction() {
  567. detectPasteboardPermissionAlert { isShowing in
  568. if isShowing {
  569. print("系统正在显示剪贴板权限弹窗")
  570. self.view.toast(text: "请允许访问剪贴板")
  571. self.openPasteTipView()
  572. }
  573. if let content = self.getPasteboardContent() {
  574. print("获取到剪贴板内容: \(content)")
  575. self.view.toast(text: "获取到剪贴板内容")
  576. self.helpView.setPasteStr(content: content)
  577. self.teachView.setPasteStr(content: content)
  578. } else {
  579. print("无法获取剪贴板内容")
  580. self.view.toast(text: "无法获取剪贴板内容")
  581. }
  582. }
  583. }
  584. // 删除按钮
  585. func deleteBtnClickAction() {
  586. self.textDocumentProxy.deleteBackward()
  587. }
  588. // 清除按钮
  589. func clearBtnClickAction() {
  590. // 获取当前文本
  591. let proxy = self.textDocumentProxy
  592. // 清空所有文本
  593. for _ in 0..<100 {
  594. proxy.deleteBackward()
  595. }
  596. }
  597. // 发送按钮
  598. func sendBtnClickAction() {
  599. self.textDocumentProxy.insertText("\n")
  600. }
  601. func deleteBtnLongPressBegin() {
  602. // 停止已有的定时器
  603. stopContinuousDelete()
  604. // 创建新的定时器,初始间隔为0.5秒
  605. deleteTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(continuousDeleteAction), userInfo: nil, repeats: false)
  606. }
  607. func deleteBtnLongPressEnd() {
  608. stopContinuousDelete()
  609. }
  610. // 停止删除
  611. func stopContinuousDelete() {
  612. deleteTimer?.invalidate()
  613. deleteTimer = nil
  614. deleteAcceleration = 0.1 // 重置加速度
  615. }
  616. @objc func continuousDeleteAction() {
  617. // 执行删除操作
  618. self.textDocumentProxy.deleteBackward()
  619. // 停止当前定时器
  620. deleteTimer?.invalidate()
  621. // 加速删除(最快0.05秒一次)
  622. let newInterval = max(0.05, 0.5 - deleteAcceleration)
  623. deleteAcceleration += 0.05 // 每次加速0.05秒
  624. // 创建新的更快的定时器
  625. deleteTimer = Timer.scheduledTimer(timeInterval: newInterval, target: self, selector: #selector(continuousDeleteAction), userInfo: nil, repeats: false)
  626. }
  627. // 监听剪贴板变化
  628. func startMonitoringPasteboard() {
  629. // 记录当前剪贴板变化计数
  630. var initialChangeCount = UIPasteboard.general.changeCount
  631. // 记录上一次的剪贴板内容
  632. var lastPasteboardContent: String? = UIPasteboard.general.string
  633. // 创建定时器定期检查剪贴板变化
  634. Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] timer in
  635. guard let self = self else {
  636. timer.invalidate()
  637. return
  638. }
  639. let currentChangeCount = UIPasteboard.general.changeCount
  640. if currentChangeCount != initialChangeCount {
  641. // 记录访问前的时间
  642. let startTime = Date()
  643. // 剪贴板计数已变化,检查内容是否真的变化
  644. if let copiedString = UIPasteboard.general.string {
  645. // 只有当内容真的不同时才处理
  646. if !copiedString.isEmpty {
  647. print("检测到新复制的内容: \(copiedString)")
  648. // 更新记录的内容和计数
  649. lastPasteboardContent = copiedString
  650. initialChangeCount = currentChangeCount
  651. // 处理复制的内容
  652. self.handleCopiedContent(copiedString)
  653. // 检查访问后的时间延迟
  654. let timeDelay = Date().timeIntervalSince(startTime)
  655. // 如果访问剪贴板的时间超过一定阈值,可能是因为系统弹出了权限弹窗
  656. // 通常正常访问剪贴板的时间应该很短,如果超过100毫秒,可能是弹出了弹窗
  657. if timeDelay > 0.1 {
  658. self.openPasteTipView()
  659. } else {
  660. }
  661. } else {
  662. // 内容相同或为空,只更新计数
  663. initialChangeCount = currentChangeCount
  664. print("剪贴板计数变化但内容未变或为空")
  665. self.openPasteTipView()
  666. }
  667. } else {
  668. // 剪贴板内容为nil,更新计数
  669. initialChangeCount = currentChangeCount
  670. lastPasteboardContent = nil
  671. print("剪贴板内容被清空")
  672. }
  673. }
  674. }
  675. }
  676. // 处理复制的内容
  677. func handleCopiedContent(_ content: String) {
  678. self.helpView.setPasteStr(content: content)
  679. self.teachView.setPasteStr(content: content)
  680. }
  681. // 检查键盘权限
  682. func checkPasteboardPermission() -> Bool {
  683. var hasPasteboardPermission = false
  684. // iOS 14及以上版本需要检查权限
  685. if #available(iOS 14.0, *) {
  686. // 尝试读取剪贴板内容来检查权限
  687. let pasteboard = UIPasteboard.general
  688. if let _ = pasteboard.string {
  689. hasPasteboardPermission = true
  690. print("键盘扩展有剪贴板访问权限")
  691. } else {
  692. hasPasteboardPermission = false
  693. print("键盘扩展没有剪贴板访问权限")
  694. }
  695. } else {
  696. // iOS 14以下版本默认有权限
  697. hasPasteboardPermission = true
  698. }
  699. return hasPasteboardPermission
  700. }
  701. // 检测系统是否弹出剪贴板权限弹窗
  702. func detectPasteboardPermissionAlert(completion: @escaping (Bool) -> Void) {
  703. // 记录访问前的时间
  704. let startTime = Date()
  705. // 尝试访问剪贴板
  706. let _ = UIPasteboard.general.string
  707. // 检查访问后的时间延迟
  708. let timeDelay = Date().timeIntervalSince(startTime)
  709. // 如果访问剪贴板的时间超过一定阈值,可能是因为系统弹出了权限弹窗
  710. // 通常正常访问剪贴板的时间应该很短,如果超过100毫秒,可能是弹出了弹窗
  711. if timeDelay > 0.1 {
  712. completion(true)
  713. } else {
  714. completion(false)
  715. }
  716. }
  717. // 获取剪贴板内容
  718. func getPasteboardContent() -> String? {
  719. let pasteboard = UIPasteboard.general
  720. return pasteboard.string
  721. }
  722. // 允许粘贴跳转至设置页
  723. func jumpToSettings() {
  724. if let url = URL(string: UIApplication.openSettingsURLString) {
  725. self.openURL(url)
  726. }
  727. }
  728. func tipsCloseBtnAction() {
  729. self.helpView.topView.isHidden = true
  730. self.helpView.topView.snp.updateConstraints { make in
  731. make.height.equalTo(0)
  732. }
  733. self.teachView.topView.isHidden = true
  734. self.teachView.topView.snp.updateConstraints { make in
  735. make.height.equalTo(0)
  736. }
  737. self.prologueView.topView.isHidden = true
  738. self.prologueView.topView.snp.updateConstraints { make in
  739. make.height.equalTo(0)
  740. }
  741. }
  742. }
  743. extension KeyboardViewController {
  744. // 打开弹窗
  745. func openPasteTipView() {
  746. self.helpView.topView.isHidden = false
  747. self.helpView.topView.snp.updateConstraints { make in
  748. make.height.equalTo(32)
  749. }
  750. self.teachView.topView.isHidden = false
  751. self.teachView.topView.snp.updateConstraints { make in
  752. make.height.equalTo(32)
  753. }
  754. self.prologueView.topView.isHidden = false
  755. self.prologueView.topView.snp.updateConstraints { make in
  756. make.height.equalTo(32)
  757. }
  758. }
  759. // 检查是否有完全访问权限
  760. func checkFullAccess() {
  761. let isFullAccess = self.hasFullAccess
  762. if !isFullAccess {
  763. let tipView = KeyboardTipsPopView()
  764. tipView.settingBtnClosure = {
  765. if let url = URL(string: UIApplication.openSettingsURLString) {
  766. self.openURL(url)
  767. }
  768. }
  769. self.view.addSubview(tipView)
  770. tipView.snp.makeConstraints { make in
  771. make.left.right.bottom.equalTo(0)
  772. make.top.equalTo(56)
  773. }
  774. }
  775. }
  776. // 跳转登录页
  777. func popLoginView() {
  778. self.clearPopView()
  779. self.loginView.isHidden = false
  780. }
  781. // 弹出vip页面
  782. func popVipView() {
  783. self.clearPopView()
  784. self.vipView.isHidden = false
  785. }
  786. // 关闭其他弹出页
  787. func clearPopView() {
  788. self.vipView.isHidden = true
  789. self.loginView.isHidden = true
  790. self.menuView.isHidden = true
  791. self.exchangeView.isHidden = true
  792. self.helpView.isHidden = true
  793. self.teachView.isHidden = true
  794. self.prologueView.isHidden = true
  795. }
  796. // 更新主要界面
  797. func updateMainViewUI() {
  798. clearPopView()
  799. switch chooseType {
  800. case .help:
  801. // self.helpView.characterList = self.characterList
  802. self.helpView.isHidden = false
  803. self.nowShowView = self.helpView
  804. self.functionLabel.text = "帮聊"
  805. break
  806. case .teach:
  807. // self.teachView.characterList = self.characterList
  808. self.teachView.isHidden = false
  809. self.nowShowView = self.teachView
  810. self.functionLabel.text = "教你说"
  811. break
  812. case .prologue:
  813. self.prologueView.isHidden = false
  814. self.nowShowView = self.prologueView
  815. self.functionLabel.text = "开场白"
  816. break
  817. }
  818. }
  819. // 更新人设列表
  820. func updateCharacterUI() {
  821. self.helpView.characterList = self.characterList
  822. self.teachView.characterList = self.characterList
  823. }
  824. // 更新开场白
  825. func updatePrologueUI() {
  826. self.prologueView.prologueList = self.prologueList
  827. }
  828. // 更新键盘选择按钮
  829. func updateUserChangeBtnUI() {
  830. if self.keyboardList?.count == 1 {
  831. self.keyboardList?[0].isChoose = true
  832. self.chooseKeyboard = self.keyboardList?.first
  833. } else {
  834. if let keyboardList = self.keyboardList {
  835. for keyboard in keyboardList {
  836. if keyboard.isChoose == true {
  837. self.chooseKeyboard = keyboard
  838. }
  839. }
  840. }
  841. }
  842. if let chooseKeyboard = self.chooseKeyboard {
  843. self.userChangeLabel.text = chooseKeyboard.name
  844. self.heartLabel.text = "\(chooseKeyboard.intimacy ?? 0)%"
  845. }
  846. }
  847. func setUI() {
  848. self.view.addSubview(bgImageView)
  849. bgImageView.snp.makeConstraints { make in
  850. make.edges.equalToSuperview()
  851. }
  852. self.view.addSubview(menuBtn)
  853. menuBtn.snp.makeConstraints { make in
  854. make.size.equalTo(CGSize(width: 32, height: 32))
  855. make.left.equalTo(13)
  856. make.top.equalTo(17)
  857. }
  858. self.view.addSubview(heartAnimation)
  859. heartAnimation.snp.makeConstraints { make in
  860. make.size.equalTo(CGSize(width: 35, height: 30))
  861. make.right.equalTo(-10)
  862. make.centerY.equalTo(menuBtn.snp.centerY)
  863. }
  864. heartAnimation.play()
  865. self.view.addSubview(heartLabel)
  866. heartLabel.snp.makeConstraints { make in
  867. make.centerY.equalTo(heartAnimation.snp.centerY).offset(-2)
  868. make.centerX.equalTo(heartAnimation.snp.centerX)
  869. }
  870. self.view.addSubview(exchangeBtn)
  871. exchangeBtn.snp.makeConstraints { make in
  872. make.size.equalTo(CGSize(width: 34, height: 34))
  873. make.right.equalTo(heartAnimation.snp.left).offset(-10)
  874. make.centerY.equalTo(menuBtn.snp.centerY)
  875. }
  876. self.view.addSubview(teachView)
  877. teachView.snp.makeConstraints { make in
  878. make.left.right.bottom.equalTo(0)
  879. make.top.equalTo(60)
  880. }
  881. self.view.addSubview(helpView)
  882. helpView.snp.makeConstraints { make in
  883. make.left.right.bottom.equalTo(0)
  884. make.top.equalTo(60)
  885. }
  886. self.view.addSubview(prologueView)
  887. prologueView.snp.makeConstraints { make in
  888. make.left.right.bottom.equalTo(0)
  889. make.top.equalTo(60)
  890. }
  891. self.view.addSubview(chooseView)
  892. chooseView.snp.makeConstraints { make in
  893. make.width.equalTo(147)
  894. make.height.equalTo(34)
  895. make.left.equalTo(menuBtn.snp.right).offset(9)
  896. make.centerY.equalTo(menuBtn.snp.centerY)
  897. }
  898. self.view.addSubview(exchangeView)
  899. exchangeView.snp.makeConstraints { make in
  900. make.top.equalTo(menuBtn.snp.bottom)
  901. make.left.right.bottom.equalTo(0)
  902. }
  903. self.view.addSubview(menuView)
  904. menuView.snp.makeConstraints { make in
  905. make.left.right.bottom.equalTo(0)
  906. make.top.equalTo(menuBtn.snp.bottom)
  907. }
  908. self.view.addSubview(loginView)
  909. loginView.snp.makeConstraints { make in
  910. make.top.left.right.bottom.equalTo(0)
  911. }
  912. self.view.addSubview(vipView)
  913. vipView.snp.makeConstraints { make in
  914. make.top.left.right.bottom.equalTo(0)
  915. }
  916. chooseView.addSubview(functionView)
  917. functionView.snp.makeConstraints { make in
  918. make.top.left.equalTo(1)
  919. make.bottom.equalTo(-1)
  920. make.width.equalTo(85)
  921. }
  922. functionView.addSubview(functionLabel)
  923. functionLabel.snp.makeConstraints { make in
  924. make.left.equalTo(12)
  925. make.centerY.equalToSuperview()
  926. }
  927. functionView.addSubview(arrowIcon)
  928. arrowIcon.snp.makeConstraints { make in
  929. make.size.equalTo(CGSize(width: 18, height: 18))
  930. make.centerY.equalToSuperview()
  931. make.right.equalTo(-5)
  932. }
  933. chooseView.addSubview(userChangeView)
  934. userChangeView.snp.makeConstraints { make in
  935. make.left.equalTo(functionView.snp.right)
  936. make.right.equalToSuperview()
  937. make.top.bottom.equalTo(0)
  938. }
  939. userChangeView.addSubview(userChangeIcon)
  940. userChangeIcon.snp.makeConstraints { make in
  941. make.size.equalTo(CGSize(width: 12, height: 12))
  942. make.centerY.equalToSuperview()
  943. make.right.equalTo(-8)
  944. }
  945. userChangeView.addSubview(userChangeLabel)
  946. userChangeLabel.snp.makeConstraints { make in
  947. make.right.equalTo(userChangeIcon.snp.left).offset(-4)
  948. make.left.equalTo(4)
  949. make.centerY.equalToSuperview()
  950. }
  951. // chooseView.addSubview(userChangeBtn)
  952. // userChangeBtn.snp.makeConstraints { make in
  953. // make.left.equalTo(functionView.snp.right)
  954. // make.right.equalToSuperview()
  955. // make.top.bottom.equalTo(0)
  956. // }
  957. self.nowShowView = self.helpView
  958. }
  959. }