Keyboard.mm 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. #include "Keyboard.h"
  2. #include "DisplayManager.h"
  3. #include "UnityAppController.h"
  4. #include "UnityForwardDecls.h"
  5. #include <string>
  6. #import <GameController/GameController.h>
  7. #ifndef FILTER_EMOJIS_IOS_KEYBOARD
  8. #define FILTER_EMOJIS_IOS_KEYBOARD 0
  9. #endif
  10. static KeyboardDelegate* _keyboard = nil;
  11. static bool _shouldHideInput = false;
  12. static bool _shouldHideInputChanged = false;
  13. static const unsigned kSingleLineFontSize = 20;
  14. extern "C" void UnityKeyboard_StatusChanged(int status);
  15. extern "C" void UnityKeyboard_TextChanged(NSString* text);
  16. extern "C" void UnityKeyboard_LayoutChanged(NSString* layout);
  17. static unsigned GetToolbarHeight()
  18. {
  19. if (@available(iOS 26, *))
  20. return 48;
  21. return 40;
  22. }
  23. @interface AdjustableWidthTextField : UITextField
  24. @property (nonatomic) CGFloat width;
  25. @end
  26. @implementation AdjustableWidthTextField
  27. - (instancetype)init
  28. {
  29. self = [super initWithFrame:CGRectZero];
  30. self.width = 0;
  31. self.translatesAutoresizingMaskIntoConstraints = NO;
  32. if (@available(iOS 26, *))
  33. self.backgroundColor = UIColor.clearColor;
  34. [NSLayoutConstraint activateConstraints:@[
  35. [self.topAnchor constraintEqualToAnchor:self.topAnchor],
  36. [self.bottomAnchor constraintEqualToAnchor:self.bottomAnchor],
  37. [self.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
  38. [self.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
  39. ]];
  40. return self;
  41. }
  42. - (CGSize)intrinsicContentSize
  43. {
  44. CGSize baseSize = [super intrinsicContentSize];
  45. return CGSizeMake(self.width, baseSize.height);
  46. }
  47. @end
  48. @implementation KeyboardDelegate
  49. {
  50. // UI handling
  51. // in case of single line we use UITextField inside UIToolbar
  52. // in case of multi-line input we use UITextView with UIToolbar as accessory view
  53. // tvOS does not support multiline input thus only UITextField option is implemented
  54. // tvOS does not support UIToolbar so we rely on tvOS default processing
  55. #if PLATFORM_IOS || PLATFORM_VISIONOS
  56. UITextView* textView;
  57. UIToolbar* viewToolbar;
  58. UIToolbar* fieldToolbar;
  59. // toolbar items are kept around to prevent releasing them
  60. UIBarButtonItem *multiLineDone, *multiLineCancel;
  61. UIBarButtonItem *singleLineDone, *singleLineCancel, *singleLineInputField;
  62. CGFloat singleLineSystemButtonsSpace;
  63. #endif
  64. AdjustableWidthTextField* textField;
  65. // inputView is view used for actual input (it will be responder): UITextField [single-line] or UITextView [multi-line]
  66. // editView is the "root" view for keyboard: UIToolbar [single-line] or UITextView [multi-line]
  67. UIView* inputView;
  68. UIView* editView;
  69. // dummy view used for positioning editView when the on-screen keyboard is floating
  70. UIView* dummyAccessoryPositionView;
  71. KeyboardShowParam cachedKeyboardParam;
  72. CGRect _area;
  73. CGRect lastKeyboardRect;
  74. NSString* initialText;
  75. UIKeyboardType keyboardType;
  76. BOOL _multiline;
  77. BOOL _inputHidden;
  78. BOOL _active;
  79. KeyboardStatus _status;
  80. int _characterLimit;
  81. // not pretty but seems like easiest way to keep "we are rotating" status
  82. BOOL _rotating;
  83. NSRange _hiddenSelection;
  84. NSRange _selectionRequest;
  85. // used for < iOS 14 external keyboard
  86. CGFloat _heightOfKeyboard;
  87. }
  88. @synthesize area;
  89. @synthesize active = _active;
  90. @synthesize status = _status;
  91. @synthesize text;
  92. @synthesize selection;
  93. @synthesize hasUsedDictation;
  94. - (void)setPendingSelectionRequest
  95. {
  96. if (_selectionRequest.location != NSNotFound)
  97. {
  98. _keyboard.selection = _selectionRequest;
  99. _selectionRequest.location = NSNotFound;
  100. }
  101. }
  102. - (BOOL)textFieldShouldReturn:(UITextField*)textFieldObj
  103. {
  104. [self textInputDone: nil];
  105. return YES;
  106. }
  107. - (void)textInputDone:(id)sender
  108. {
  109. if (_status == Visible)
  110. {
  111. _status = Done;
  112. UnityKeyboard_StatusChanged(_status);
  113. }
  114. [self hide];
  115. }
  116. - (void)becomeFirstResponder
  117. {
  118. if (_status == Visible)
  119. {
  120. [_keyboard->inputView becomeFirstResponder];
  121. }
  122. }
  123. - (void)textInputCancel:(id)sender
  124. {
  125. _status = Canceled;
  126. UnityKeyboard_StatusChanged(_status);
  127. [self hide];
  128. }
  129. - (void)textInputLostFocus
  130. {
  131. if (_status == Visible)
  132. {
  133. _status = LostFocus;
  134. UnityKeyboard_StatusChanged(_status);
  135. }
  136. [self hide];
  137. }
  138. - (void)textViewDidChange:(UITextView *)textView
  139. {
  140. if (textView.markedTextRange == nil && textView.text.length > _characterLimit && _characterLimit != 0)
  141. {
  142. textView.text = [textView.text substringToIndex: _characterLimit];
  143. }
  144. UnityKeyboard_TextChanged(textView.text);
  145. }
  146. - (void)textFieldDidChange:(UITextField*)textField
  147. {
  148. if (textField.markedTextRange == nil && textField.text.length > _characterLimit && _characterLimit != 0)
  149. {
  150. textField.text = [textField.text substringToIndex: _characterLimit];
  151. }
  152. UnityKeyboard_TextChanged(textField.text);
  153. }
  154. - (BOOL)textViewShouldBeginEditing:(UITextView*)view
  155. {
  156. return YES;
  157. }
  158. #if PLATFORM_IOS || PLATFORM_VISIONOS
  159. - (void)textInputModeDidChange:(NSNotification*)notification
  160. {
  161. [self setPendingSelectionRequest];
  162. // Apple reports back the primary language of the current keyboard text input mode using BCP 47 language code i.e "en-GB"
  163. // but this also (undocumented) will return "dictation" when using voice dictation and "emoji" when using the emoji keyboard.
  164. if ([_keyboard->inputView.textInputMode.primaryLanguage isEqualToString: @"dictation"])
  165. {
  166. hasUsedDictation = YES;
  167. }
  168. }
  169. - (void)keyboardWillShow:(NSNotification *)notification
  170. {
  171. if (notification.userInfo == nil || inputView == nil)
  172. return;
  173. [self setPendingSelectionRequest];
  174. [self positionInput];
  175. auto appController = GetAppController();
  176. if (@available(iOS 16, tvOS 16, *)) {}
  177. else if (!appController.didResignActive) // A workaround for iPadOS 15 to fully animate keyboard after going from detached to docked
  178. [inputView reloadInputViews];
  179. }
  180. - (void)reportLayout:(NSString*)layout
  181. {
  182. // Under some conditions keyboardDidShow is sent multiple times in a row
  183. // only report layout to Unity if it actually changed
  184. // to avoid possibly expensive consequences
  185. static NSString* lastReportedLayout = nil;
  186. if (lastReportedLayout != layout)
  187. {
  188. lastReportedLayout = layout;
  189. UnityKeyboard_LayoutChanged(layout);
  190. }
  191. }
  192. - (void)keyboardDidShow:(NSNotification*)notification
  193. {
  194. _active = YES;
  195. [self reportLayout:textField.textInputMode.primaryLanguage];
  196. }
  197. - (void)keyboardWillHide:(NSNotification*)notification
  198. {
  199. if (_keyboard)
  200. {
  201. // Reset selection to avoid selection graphics staying on the screen
  202. if (_keyboard.selection.length > 0)
  203. {
  204. NSRange range = NSMakeRange(_keyboard.text.length, 0);
  205. _keyboard.selection = range;
  206. }
  207. }
  208. [self reportLayout:nil];
  209. [self systemHideKeyboard];
  210. }
  211. - (void)keyboardDidHide:(NSNotification*)notification
  212. {
  213. // The audio engine starts and restarts by listening to AVAudioSessionInterruptionNotifications, However
  214. // Apple does *not* guarantee that the AVAudioSessionInterruptionTypeEnded will be sent, especially if
  215. // the app is in the foreground - This can happen when using the dictate function on the keyboard
  216. // so we send the notification ourselves to ensure the audio restarts.
  217. if (hasUsedDictation)
  218. {
  219. [[NSNotificationCenter defaultCenter] postNotificationName: AVAudioSessionInterruptionNotification
  220. object: [AVAudioSession sharedInstance]
  221. userInfo: @{AVAudioSessionInterruptionTypeKey: [NSNumber numberWithUnsignedInteger: AVAudioSessionInterruptionTypeEnded]}];
  222. }
  223. }
  224. - (void)keyboardDidChangeFrame:(NSNotification*)notification
  225. {
  226. CGRect srcRect = [[notification.userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue];
  227. CGRect rect = [UnityGetGLView() convertRect: srcRect fromView: nil];
  228. if (!CGRectEqualToRect(lastKeyboardRect, rect))
  229. {
  230. [self positionInput];
  231. }
  232. lastKeyboardRect = rect;
  233. }
  234. - (void)positionInput
  235. {
  236. /*
  237. The logic in this function and everywhere around it is extremely fragile
  238. When changing make sure to test:
  239. - Area API
  240. - Orientation changes
  241. - Size changes in Stage Manager
  242. - Split Screen
  243. - Ducking/Undocking the keyboard
  244. - All the combinations of all of the above
  245. */
  246. if ([self hasExternalKeyboard])
  247. {
  248. [self systemHideKeyboard];
  249. _active = NO;
  250. return;
  251. }
  252. if (!inputView.isFirstResponder)
  253. {
  254. _area = CGRectMake(0, 0, 0, 0);
  255. _active = NO; // in case of floating keyboard this looks to be the only place to detect it closed
  256. return;
  257. }
  258. UIView* unityView = UnityGetGLView();
  259. CGRect unityViewRect = unityView.frame;
  260. CGRect accessoryRect = [dummyAccessoryPositionView.superview convertRect: dummyAccessoryPositionView.frame toView: unityView];
  261. float width = unityViewRect.size.width;
  262. float xPos = accessoryRect.origin.x;
  263. float yPos = accessoryRect.origin.y;
  264. const float safeAreaInsetLeft = [unityView safeAreaInsets].left;
  265. const float safeAreaInsetRight = [unityView safeAreaInsets].right;
  266. const float safeAreaInsetBottom = [unityView safeAreaInsets].bottom;
  267. if (_rotating || yPos == 0)
  268. {
  269. // hacky way to reposition input view just before the screen rotation animation starts
  270. // this way position animates nicely throughout the screen rotation animation
  271. yPos = unityViewRect.size.height - safeAreaInsetBottom;
  272. if (_rotating)
  273. xPos = safeAreaInsetLeft;
  274. }
  275. // Only add safe area offset if the input bar is placed at the bottom of the view
  276. float offsetY = yPos == unityViewRect.size.height ? safeAreaInsetBottom : 0;
  277. const auto kToolBarHeight = GetToolbarHeight();
  278. if (_multiline)
  279. {
  280. // use smaller area for iphones and bigger one for ipads
  281. int height = UnityDeviceDPI() > 300 ? 75 : 100;
  282. editView.frame = CGRectMake(xPos + safeAreaInsetLeft, yPos - kToolBarHeight - height - offsetY, width - safeAreaInsetLeft - safeAreaInsetRight, height);
  283. viewToolbar.frame = CGRectMake(xPos, yPos - kToolBarHeight - offsetY, width, kToolBarHeight);;
  284. }
  285. else
  286. {
  287. // add some space between keyboard and toolbar, which is now transparent
  288. if (@available(iOS 26, *))
  289. offsetY += 10;
  290. editView.frame = CGRectMake(xPos, yPos - kToolBarHeight - offsetY, width, kToolBarHeight);
  291. textField.width = unityViewRect.size.width - safeAreaInsetLeft - safeAreaInsetRight - self->singleLineSystemButtonsSpace;
  292. [textField invalidateIntrinsicContentSize];
  293. }
  294. [self updateInputHidden];
  295. // updating area of the keyboard
  296. _area = CGRectMake(xPos, yPos, width - safeAreaInsetLeft - safeAreaInsetRight, unityViewRect.size.height - yPos);
  297. if (!editView.hidden)
  298. _area = CGRectUnion(_area, editView.frame);
  299. _active = YES; // at this point input field is first responder, so keyboard is active
  300. }
  301. #endif
  302. + (void)Initialize
  303. {
  304. NSAssert(_keyboard == nil, @"[KeyboardDelegate Initialize] called after creating keyboard");
  305. if (!_keyboard)
  306. _keyboard = [[KeyboardDelegate alloc] init];
  307. }
  308. + (KeyboardDelegate*)Instance
  309. {
  310. if (!_keyboard)
  311. _keyboard = [[KeyboardDelegate alloc] init];
  312. return _keyboard;
  313. }
  314. + (void)Destroy
  315. {
  316. _keyboard = nil;
  317. }
  318. #if PLATFORM_IOS || PLATFORM_VISIONOS
  319. - (UIToolbar*)createToolbarWithItems:(NSArray*)items
  320. {
  321. // Default position ensures the input view slides from the bottom of the screen together with the keyboard
  322. CGSize windowSize = [UnityGetGLView() bounds].size;
  323. UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, windowSize.height, windowSize.width, GetToolbarHeight())];
  324. UnitySetViewTouchProcessing(toolbar, touchesIgnored);
  325. toolbar.hidden = NO;
  326. toolbar.items = items;
  327. return toolbar;
  328. }
  329. - (void)createToolbars
  330. {
  331. multiLineDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target: self action: @selector(textInputDone:)];
  332. multiLineCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(textInputCancel:)];
  333. viewToolbar = [self createToolbarWithItems: @[multiLineDone, multiLineCancel]];
  334. singleLineInputField = [[UIBarButtonItem alloc] initWithCustomView: textField];
  335. singleLineDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target: self action: @selector(textInputDone:)];
  336. singleLineCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(textInputCancel:)];
  337. fieldToolbar = [self createToolbarWithItems: @[singleLineInputField, singleLineDone, singleLineCancel]];
  338. // Gather round boys, let's hear the story of apple ingenious api.
  339. // Did you see UIBarButtonItem above? oh the marvel of design
  340. // Maybe you thought it will have some connection to UIView or something?
  341. // Yes, internally, in private members, hidden like dirty laundry in a room of a youngster
  342. // But, you may ask, why do we care? Oh, easy - sometimes you want to use non-english language
  343. // And in these languages, not good enough to be english, done/cancel items can have different sizes
  344. // And we insist on having input field size set because, yes, we cannot quite do a layout inside UIToolbar
  345. // [because there are no views we can actually touch, thanks for asking]
  346. // Obviously, localizing system strings is also well hidden, and what works now might stop working tomorrow
  347. // That's why we keep UIBarButtonSystemItemDone/UIBarButtonSystemItemCancel above
  348. // and try to translate "Done"/"Cancel" in a way that "should" work
  349. // if localization fails we will still have "some" values (coming from english)
  350. UIFont* font = [UIFont systemFontOfSize: kSingleLineFontSize];
  351. NSBundle* uikitBundle = [NSBundle bundleForClass: UIApplication.class];
  352. NSString* doneStr = [uikitBundle localizedStringForKey: @"Done" value: nil table: nil];
  353. NSString* cancelStr = [uikitBundle localizedStringForKey: @"Cancel" value: nil table: nil];
  354. // mind you, all of that is highly empirical.
  355. // we assume space between items to be 18 [both between buttons and on the sides]
  356. // we also assume that button width would be more or less the title width exactly (it should be quite close though)
  357. // some language fonts (i.e korean, vietnamese..) can have non integer width (i.e 34.5999), thus we round up the width to fit the buttons
  358. const CGFloat doneW = ceil([doneStr sizeWithAttributes: @{NSFontAttributeName: font}].width);
  359. const CGFloat cancelW = ceil([cancelStr sizeWithAttributes: @{NSFontAttributeName: font}].width);
  360. singleLineSystemButtonsSpace = doneW + cancelW + 3 * 18;
  361. }
  362. #endif
  363. - (id)init
  364. {
  365. NSAssert(_keyboard == nil, @"You can have only one instance of KeyboardDelegate");
  366. self = [super init];
  367. if (self)
  368. {
  369. #if PLATFORM_IOS || PLATFORM_VISIONOS
  370. // Default position ensures the input view slides from the bottom of the screen together with the keyboard
  371. CGSize windowSize = [UnityGetGLView() bounds].size;
  372. textView = [[UITextView alloc] initWithFrame: CGRectMake(0, windowSize.height, 480, 30)];
  373. textView.delegate = self;
  374. textView.font = [UIFont systemFontOfSize: 18.0];
  375. textView.hidden = YES;
  376. // For some unknown reason, the `textView` has visual issues when
  377. // using Dark Mode (some parts of the view become transparent). See case 1367091.
  378. // However, setting alpha to a value different than 1 fixes the issue.
  379. textView.alpha = 0.99;
  380. dummyAccessoryPositionView = [[UIView alloc] initWithFrame: CGRectMake(0, windowSize.height, 0, 0)];
  381. dummyAccessoryPositionView.backgroundColor = [UIColor clearColor];
  382. dummyAccessoryPositionView.userInteractionEnabled = NO;
  383. dummyAccessoryPositionView.translatesAutoresizingMaskIntoConstraints = NO;
  384. #endif
  385. textField = [[AdjustableWidthTextField alloc] init];
  386. textField.delegate = self;
  387. if (@available(iOS 26, *))
  388. textField.borderStyle = UITextBorderStyleNone;
  389. else
  390. textField.borderStyle = UITextBorderStyleRoundedRect;
  391. textField.font = [UIFont systemFontOfSize: kSingleLineFontSize];
  392. textField.clearButtonMode = UITextFieldViewModeWhileEditing;
  393. textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  394. [textField addTarget: self action: @selector(textFieldDidChange:) forControlEvents: UIControlEventEditingChanged];
  395. #if PLATFORM_IOS || PLATFORM_VISIONOS
  396. [self createToolbars];
  397. #if !PLATFORM_VISIONOS
  398. textView.inputAccessoryView = dummyAccessoryPositionView;
  399. textField.inputAccessoryView = dummyAccessoryPositionView;
  400. #endif
  401. #endif
  402. #if PLATFORM_IOS || PLATFORM_VISIONOS
  403. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object: nil];
  404. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object: nil];
  405. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object: nil];
  406. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidHide:) name: UIKeyboardDidHideNotification object: nil];
  407. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidChangeFrame:) name: UIKeyboardDidChangeFrameNotification object: nil];
  408. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textInputModeDidChange:) name: UITextInputCurrentInputModeDidChangeNotification object: nil];
  409. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyboardDidConnect:) name: GCKeyboardDidConnectNotification object: nil];
  410. #endif
  411. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textInputDone:) name: UITextFieldTextDidEndEditingNotification object: nil];
  412. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textInputDone:) name: UITextViewTextDidEndEditingNotification object: nil];
  413. }
  414. return self;
  415. }
  416. - (void)layoutSubviews
  417. {
  418. #if PLATFORM_IOS
  419. // Needed for updating keyboard when resizing the view in stage manager and orientation change
  420. [_keyboard positionInput];
  421. #endif
  422. }
  423. - (void)keyboardDidConnect:(NSNotification *)notification {
  424. [self systemHideKeyboard];
  425. }
  426. - (void)setTextInputTraits:(id<UITextInputTraits>)traits
  427. withParam:(KeyboardShowParam)param
  428. {
  429. UITextAutocapitalizationType capitalization = [KeyboardDelegate capitalizationForKeyboardParam: param];
  430. if (!_inputHidden)
  431. traits.secureTextEntry = param.secure;
  432. if (param.secure)
  433. {
  434. traits.autocorrectionType = UITextAutocorrectionTypeNo;
  435. traits.spellCheckingType = UITextSpellCheckingTypeNo;
  436. traits.autocapitalizationType = UITextAutocapitalizationTypeNone;
  437. }
  438. else
  439. {
  440. traits.autocorrectionType = param.autocorrectionType;
  441. traits.spellCheckingType = param.spellcheckingType;
  442. traits.autocapitalizationType = capitalization;
  443. }
  444. traits.keyboardType = param.keyboardType;
  445. traits.keyboardAppearance = param.appearance;
  446. }
  447. + (UITextAutocapitalizationType)capitalizationForKeyboardParam:(KeyboardShowParam)param
  448. {
  449. if (param.secure)
  450. return UITextAutocapitalizationTypeNone;
  451. UITextAutocapitalizationType capitalization;
  452. switch (param.keyboardType)
  453. {
  454. case UIKeyboardTypeURL:
  455. case UIKeyboardTypeEmailAddress:
  456. case UIKeyboardTypeWebSearch:
  457. capitalization = UITextAutocapitalizationTypeNone;
  458. break;
  459. default:
  460. capitalization = UITextAutocapitalizationTypeSentences;
  461. }
  462. return capitalization;
  463. }
  464. - (void)setKeyboardParams:(KeyboardShowParam)param
  465. {
  466. #if PLATFORM_IOS
  467. if (@available(iOS 26, *))
  468. {
  469. if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
  470. {
  471. // iOS bug: number/phone pad have special behavior that leads to crash with floating keyboard in windowed mode
  472. // input field activation shows minimalist overlay bubble, tapping ouside which dismissed it
  473. // the keyboard only opens on tapping the input field again,
  474. // but if accessory view is set on field, it crashes inside Apple code
  475. // plus did not find a way to detect when first bubble is dismissed (it's keyboard close from our perspective)
  476. switch (param.keyboardType)
  477. {
  478. case UIKeyboardTypeDecimalPad:
  479. case UIKeyboardTypePhonePad:
  480. case UIKeyboardTypeNumberPad:
  481. param.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  482. break;
  483. default:
  484. break;
  485. }
  486. }
  487. }
  488. #endif
  489. [NSObject cancelPreviousPerformRequestsWithTarget: self];
  490. if (cachedKeyboardParam.multiline != param.multiline ||
  491. cachedKeyboardParam.secure != param.secure ||
  492. cachedKeyboardParam.keyboardType != param.keyboardType ||
  493. cachedKeyboardParam.autocorrectionType != param.autocorrectionType ||
  494. cachedKeyboardParam.appearance != param.appearance)
  495. {
  496. [self hideUIDelayed];
  497. }
  498. cachedKeyboardParam = param;
  499. if (_active)
  500. [self hide];
  501. initialText = param.text ? [[NSString alloc] initWithUTF8String: param.text] : @"";
  502. _characterLimit = param.characterLimit;
  503. #if PLATFORM_IOS || PLATFORM_VISIONOS
  504. _multiline = param.multiline;
  505. if (_multiline)
  506. {
  507. [self setTextInputTraits: textView withParam: param];
  508. }
  509. else
  510. {
  511. if (param.oneTimeCode)
  512. textField.textContentType = UITextContentTypeOneTimeCode;
  513. [self setTextInputTraits: textField withParam: param];
  514. textField.placeholder = [NSString stringWithUTF8String: param.placeholder];
  515. }
  516. inputView = _multiline ? textView : textField;
  517. editView = _multiline ? textView : fieldToolbar;
  518. // Initially hide input fields in case external keyboard is connected.
  519. // This is needed for certain cases where external keyboard is connected
  520. // and soft keyboard is reopened without closing it first.
  521. // If external keyboard does not exist, these values will be updated by keyboardWillShow
  522. editView.hidden = YES;
  523. viewToolbar.hidden = YES;
  524. #else // PLATFORM_TVOS
  525. [self setTextInputTraits: textField withParam: param];
  526. textField.placeholder = [NSString stringWithUTF8String: param.placeholder];
  527. inputView = textField;
  528. editView = textField;
  529. #endif
  530. [self shouldHideInput: _shouldHideInput];
  531. [KeyboardDelegate Instance].text = initialText;
  532. _status = Visible;
  533. UnityKeyboard_StatusChanged(_status);
  534. _active = !self.hasExternalKeyboard;
  535. _selectionRequest.location = NSNotFound;
  536. }
  537. // we need to show/hide keyboard to react to orientation too, so extract we extract UI fiddling
  538. - (void)showUI
  539. {
  540. // if we unhide everything now the input will be shown smaller then needed quickly (and resized later)
  541. // so unhide only when keyboard is actually shown (we will update it when reacting to ios notifications)
  542. [NSObject cancelPreviousPerformRequestsWithTarget: self];
  543. if (!inputView.isFirstResponder)
  544. {
  545. editView.hidden = YES;
  546. UIView* unityView = UnityGetGLView();
  547. [unityView addSubview: editView];
  548. #if PLATFORM_IOS
  549. [unityView addSubview: viewToolbar];
  550. #endif
  551. [inputView becomeFirstResponder];
  552. #if PLATFORM_TVOS
  553. // make keyboard usable via controller by allowing exit to home temporarily
  554. // val 3, as second lowest bit indicates a temporary disable
  555. if (UnityGetAppleTVRemoteAllowExitToMenu() == 0)
  556. UnitySetAppleTVRemoteAllowExitToMenu(3);
  557. #endif
  558. }
  559. // we need to reload input views when switching the keyboard type for already active keyboard
  560. // otherwise the changed traits may not be immediately applied
  561. editView.hidden = self.inputHidden;
  562. [inputView reloadInputViews];
  563. }
  564. - (void)hideUI
  565. {
  566. [NSObject cancelPreviousPerformRequestsWithTarget: self];
  567. [self performSelector: @selector(hideUIDelayed) withObject: nil afterDelay: 0.05]; // to avoid unnecessary hiding
  568. }
  569. - (BOOL)inputHidden
  570. {
  571. if (self.hasExternalKeyboard)
  572. return YES;
  573. return _inputHidden;
  574. }
  575. - (void)hideUIDelayed
  576. {
  577. [inputView resignFirstResponder];
  578. [editView removeFromSuperview];
  579. editView.hidden = YES;
  580. #if PLATFORM_IOS
  581. [viewToolbar removeFromSuperview];
  582. viewToolbar.hidden = YES;
  583. #endif
  584. // Keyboard notifications are not supported on tvOS so keyboardWillHide: will never be called which would set _active to false.
  585. // To work around that limitation we will update _active from here.
  586. #if PLATFORM_TVOS
  587. BOOL wasActive = _active;
  588. _active = editView.isFirstResponder;
  589. // if closing, restore exit value to what it was (getter ignores temp value and returns what it is meant to be)
  590. if (!_active && wasActive)
  591. UnitySetAppleTVRemoteAllowExitToMenu(UnityGetAppleTVRemoteAllowExitToMenu());
  592. #endif
  593. }
  594. - (void)systemHideKeyboard
  595. {
  596. // when we are rotating os will bombard us with keyboardWillHide: and keyboardDidChangeFrame:
  597. // ignore all of them (we do it here only to simplify code: we call systemHideKeyboard only from these notification handlers)
  598. if (_rotating)
  599. return;
  600. _active = editView.isFirstResponder;
  601. editView.hidden = YES;
  602. // Default position ensures the input view slides from the bottom of the screen together with the keyboard
  603. CGSize windowSize = [UnityGetGLView() frame].size;
  604. editView.frame = CGRectMake(0, windowSize.height, editView.frame.size.width, editView.frame.size.height);
  605. #if PLATFORM_IOS || PLATFORM_VISIONOS
  606. viewToolbar.hidden = YES;
  607. #endif
  608. _area = CGRectMake(0, 0, 0, 0);
  609. lastKeyboardRect = CGRectMake(0, 0, 0, 0);
  610. }
  611. - (void)show
  612. {
  613. [self showUI];
  614. }
  615. - (void)hide
  616. {
  617. [self hideUI];
  618. }
  619. - (void)updateInputHidden
  620. {
  621. if (_shouldHideInputChanged)
  622. {
  623. [self shouldHideInput: _shouldHideInput];
  624. _shouldHideInputChanged = false;
  625. }
  626. textField.returnKeyType = _inputHidden ? UIReturnKeyDone : UIReturnKeyDefault;
  627. #if PLATFORM_IOS || PLATFORM_VISIONOS
  628. UIView* unityView = UnityGetGLView();
  629. NSMutableArray<UIAccessibilityElement*>* elements = unityView.accessibilityElements ? [unityView.accessibilityElements mutableCopy] : [NSMutableArray array];
  630. viewToolbar.hidden = !_multiline || self.inputHidden;
  631. [elements removeObject: (UIAccessibilityElement*)viewToolbar];
  632. if (!viewToolbar.hidden)
  633. {
  634. [elements addObject: (UIAccessibilityElement*)viewToolbar];
  635. }
  636. [elements removeObject: (UIAccessibilityElement*)fieldToolbar];
  637. editView.hidden = self.inputHidden;
  638. if (!_multiline && !editView.hidden)
  639. {
  640. [elements addObject: (UIAccessibilityElement*)fieldToolbar];
  641. }
  642. unityView.accessibilityElements = elements;
  643. #else
  644. editView.hidden = self.inputHidden;
  645. #endif
  646. [self setTextInputTraits: textField withParam: cachedKeyboardParam];
  647. }
  648. - (CGRect)queryArea
  649. {
  650. return _area;
  651. }
  652. - (NSRange)querySelection
  653. {
  654. UIView<UITextInput>* textInput;
  655. #if PLATFORM_TVOS
  656. textInput = textField;
  657. #else
  658. textInput = _multiline ? textView : textField;
  659. #endif
  660. UITextPosition* beginning = textInput.beginningOfDocument;
  661. UITextRange* selectedRange = textInput.selectedTextRange;
  662. UITextPosition* selectionStart = selectedRange.start;
  663. UITextPosition* selectionEnd = selectedRange.end;
  664. const NSInteger location = [textInput offsetFromPosition: beginning toPosition: selectionStart];
  665. const NSInteger length = [textInput offsetFromPosition: selectionStart toPosition: selectionEnd];
  666. return NSMakeRange(location, length);
  667. }
  668. - (void)assignSelection:(NSRange)range
  669. {
  670. UIView<UITextInput>* textInput;
  671. #if PLATFORM_TVOS
  672. textInput = textField;
  673. #else
  674. textInput = _multiline ? textView : textField;
  675. #endif
  676. UITextPosition* begin = [textInput beginningOfDocument];
  677. UITextPosition* caret = [textInput positionFromPosition: begin offset: range.location];
  678. UITextPosition* select = [textInput positionFromPosition: caret offset: range.length];
  679. UITextRange* textRange = [textInput textRangeFromPosition: caret toPosition: select];
  680. [textInput setSelectedTextRange: textRange];
  681. if (_inputHidden)
  682. _hiddenSelection = range;
  683. _selectionRequest = range;
  684. }
  685. + (void)StartReorientation
  686. {
  687. if (_keyboard && _keyboard.active)
  688. {
  689. _keyboard->_rotating = YES;
  690. }
  691. }
  692. + (void)FinishReorientation
  693. {
  694. if (_keyboard && _keyboard.active)
  695. {
  696. _keyboard->_rotating = NO;
  697. #if PLATFORM_IOS || PLATFORM_VISIONOS
  698. _keyboard->editView.hidden = _keyboard.inputHidden;
  699. #endif
  700. }
  701. }
  702. - (NSString*)getText
  703. {
  704. if (_status == Canceled)
  705. return initialText;
  706. else
  707. {
  708. #if PLATFORM_TVOS
  709. return [textField text];
  710. #else
  711. return _multiline ? [textView text] : [textField text];
  712. #endif
  713. }
  714. }
  715. - (void)setText:(NSString*)newText
  716. {
  717. #if PLATFORM_IOS || PLATFORM_VISIONOS
  718. if (_multiline)
  719. textView.text = newText;
  720. else
  721. textField.text = newText;
  722. #else
  723. textField.text = newText;
  724. #endif
  725. // for hidden selection place cursor at the end when text changes
  726. _hiddenSelection.location = newText.length;
  727. _hiddenSelection.length = 0;
  728. }
  729. - (void)shouldHideInput:(BOOL)hide
  730. {
  731. if (hide)
  732. {
  733. switch (keyboardType)
  734. {
  735. case UIKeyboardTypeDefault: hide = YES; break;
  736. case UIKeyboardTypeASCIICapable: hide = YES; break;
  737. case UIKeyboardTypeNumbersAndPunctuation: hide = YES; break;
  738. case UIKeyboardTypeURL: hide = YES; break;
  739. case UIKeyboardTypeNumberPad: hide = NO; break;
  740. case UIKeyboardTypePhonePad: hide = NO; break;
  741. case UIKeyboardTypeNamePhonePad: hide = NO; break;
  742. case UIKeyboardTypeEmailAddress: hide = YES; break;
  743. case UIKeyboardTypeTwitter: hide = YES; break;
  744. case UIKeyboardTypeWebSearch: hide = YES; break;
  745. case UIKeyboardTypeDecimalPad: hide = NO; break;
  746. default: hide = NO; break;
  747. }
  748. }
  749. _inputHidden = hide;
  750. }
  751. - (BOOL)hasExternalKeyboard
  752. {
  753. return [GCKeyboard coalescedKeyboard] != nil;
  754. }
  755. - (UITextField*)getTextField
  756. {
  757. return textField;
  758. }
  759. static bool StringContainsEmoji(NSString *string);
  760. - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string_
  761. {
  762. BOOL stringContainsEmoji = NO;
  763. #if FILTER_EMOJIS_IOS_KEYBOARD
  764. stringContainsEmoji = StringContainsEmoji(string_);
  765. #endif
  766. if (range.length + range.location > textField.text.length)
  767. return NO;
  768. return [self currentText: textField.text shouldChangeInRange: range replacementText: string_] && !stringContainsEmoji;
  769. }
  770. - (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text_
  771. {
  772. BOOL stringContainsEmoji = NO;
  773. #if FILTER_EMOJIS_IOS_KEYBOARD
  774. stringContainsEmoji = StringContainsEmoji(text_);
  775. #endif
  776. if (range.length + range.location > textView.text.length)
  777. return NO;
  778. return [self currentText: textView.text shouldChangeInRange: range replacementText: text_] && !stringContainsEmoji;
  779. }
  780. - (BOOL)currentText:(NSString*)currentText shouldChangeInRange:(NSRange)range replacementText:(NSString*)text_
  781. {
  782. NSUInteger newLength = currentText.length + (text_.length - range.length);
  783. if (newLength > _characterLimit && _characterLimit != 0 && newLength >= currentText.length)
  784. {
  785. // If the user inserts any emoji that exceeds the character limit it should quickly reject it, else it'll crash. We need to check regardless of FILTER_EMOJIS_IOS_KEYBOARD status as sometimes this method gets called before we've filtered out an emoji.
  786. if (StringContainsEmoji(text_))
  787. return NO;
  788. NSString* newReplacementText = @"";
  789. if ((currentText.length - range.length) < _characterLimit)
  790. newReplacementText = [text_ substringWithRange: NSMakeRange(0, _characterLimit - (currentText.length - range.length))];
  791. NSString* newText = [currentText stringByReplacingCharactersInRange: range withString: newReplacementText];
  792. #if PLATFORM_IOS || PLATFORM_VISIONOS
  793. if (_multiline)
  794. [textView setText: newText];
  795. else
  796. [textField setText: newText];
  797. #else
  798. [textField setText: newText];
  799. #endif
  800. // If we're trying to exceed the max length of the field BUT the text can merge into
  801. // precomposed characters then we should allow the input.
  802. NSString* precomposedNewText = [currentText precomposedStringWithCompatibilityMapping];
  803. __block int count = 0;
  804. [precomposedNewText enumerateSubstringsInRange: NSMakeRange(0, [precomposedNewText length]) options: NSStringEnumerationByComposedCharacterSequences
  805. usingBlock: ^(NSString *inSubstring, NSRange inSubstringRange, NSRange inEnclosingRange, BOOL *outStop) {
  806. count++;
  807. }];
  808. // count of characters of precomposed string will equal the character limit
  809. // if there has been characters merged bringing us under the limit.
  810. return count <= _characterLimit;
  811. }
  812. else
  813. {
  814. if (_inputHidden && _hiddenSelection.length > 0)
  815. {
  816. NSString* newText = [currentText stringByReplacingCharactersInRange: _hiddenSelection withString: text_];
  817. #if PLATFORM_IOS || PLATFORM_VISIONOS
  818. if (_multiline)
  819. [textView setText: newText];
  820. else
  821. [textField setText: newText];
  822. #else
  823. [textField setText: newText];
  824. #endif
  825. _hiddenSelection.location = _hiddenSelection.location + text_.length;
  826. _hiddenSelection.length = 0;
  827. self.selection = _hiddenSelection;
  828. return NO;
  829. }
  830. _hiddenSelection.location = range.location + text_.length;
  831. _hiddenSelection.length = 0;
  832. return YES;
  833. }
  834. }
  835. @end
  836. //==============================================================================
  837. //
  838. // Unity Interface:
  839. UNITY_EXPORT extern "C" void UnityKeyboard_Create(unsigned keyboardType, int autocorrection, int multiline, int secure, int alert, const char* text, const char* placeholder, int characterLimit)
  840. {
  841. #if PLATFORM_TVOS
  842. // Not supported. The API for showing keyboard for editing multi-line text is not available on tvOS
  843. multiline = false;
  844. #endif
  845. static const UIKeyboardType keyboardTypes[] =
  846. {
  847. UIKeyboardTypeDefault,
  848. UIKeyboardTypeASCIICapable,
  849. UIKeyboardTypeNumbersAndPunctuation,
  850. UIKeyboardTypeURL,
  851. UIKeyboardTypeNumberPad,
  852. UIKeyboardTypePhonePad,
  853. UIKeyboardTypeNamePhonePad,
  854. UIKeyboardTypeEmailAddress,
  855. UIKeyboardTypeDefault, // Default is used in case Wii U specific NintendoNetworkAccount type is selected (indexed at 8 in UnityEngine.TouchScreenKeyboardType)
  856. UIKeyboardTypeTwitter,
  857. UIKeyboardTypeWebSearch,
  858. UIKeyboardTypeDecimalPad,
  859. UIKeyboardTypeNumberPad, // Keyboard type 12, OneTimeCode, does not directly translate to a UIKeyboardType.
  860. };
  861. const auto maxKeyboardType = sizeof(keyboardTypes) / sizeof(UIKeyboardTypeDefault) - 1;
  862. if (keyboardType > maxKeyboardType)
  863. {
  864. assert(false && "Unsupported keyboard type");
  865. keyboardType = 0;
  866. }
  867. // on iOS 15, QuickType bar was decoupled from autocorrection (so it still shows candidates)
  868. // for a principle of "the least surprise" we keep it coupled internally, so autocorrection == spellchecking
  869. // TODO: should we expose the control of it?
  870. static const UITextAutocorrectionType autocorrectionTypes[] =
  871. {
  872. UITextAutocorrectionTypeNo,
  873. UITextAutocorrectionTypeDefault,
  874. };
  875. static const UITextSpellCheckingType spellcheckingTypes[] =
  876. {
  877. UITextSpellCheckingTypeNo,
  878. UITextSpellCheckingTypeDefault,
  879. };
  880. static const UIKeyboardAppearance keyboardAppearances[] =
  881. {
  882. UIKeyboardAppearanceDefault,
  883. UIKeyboardAppearanceAlert,
  884. };
  885. KeyboardShowParam param =
  886. {
  887. text, placeholder,
  888. keyboardTypes[keyboardType],
  889. autocorrectionTypes[autocorrection],
  890. spellcheckingTypes[autocorrection],
  891. keyboardAppearances[alert],
  892. (BOOL)multiline, (BOOL)secure,
  893. characterLimit,
  894. keyboardType == 12
  895. };
  896. [[KeyboardDelegate Instance] setKeyboardParams: param];
  897. }
  898. UNITY_EXPORT extern "C" void UnityKeyboard_Show()
  899. {
  900. // do not send hide if didnt create keyboard
  901. // TODO: probably assert?
  902. if (!_keyboard)
  903. return;
  904. [[KeyboardDelegate Instance] show];
  905. }
  906. UNITY_EXPORT extern "C" void UnityKeyboard_Hide()
  907. {
  908. // do not send hide if didnt create keyboard
  909. // TODO: probably assert?
  910. if (!_keyboard)
  911. return;
  912. [[KeyboardDelegate Instance] textInputLostFocus];
  913. }
  914. UNITY_EXPORT extern "C" void UnityKeyboard_SetText(const char* text)
  915. {
  916. [KeyboardDelegate Instance].text = [NSString stringWithUTF8String: text];
  917. }
  918. UNITY_EXPORT extern "C" NSString* UnityKeyboard_GetText()
  919. {
  920. return [KeyboardDelegate Instance].text;
  921. }
  922. UNITY_EXPORT extern "C" int UnityKeyboard_IsActive()
  923. {
  924. return (_keyboard && _keyboard.active) ? 1 : 0;
  925. }
  926. UNITY_EXPORT extern "C" int UnityKeyboard_Status()
  927. {
  928. return _keyboard ? _keyboard.status : Canceled;
  929. }
  930. UNITY_EXPORT extern "C" void UnityKeyboard_SetInputHidden(int hidden)
  931. {
  932. _shouldHideInput = hidden;
  933. _shouldHideInputChanged = true;
  934. // update hidden status only if keyboard is on screen to avoid showing input view out of nowhere
  935. if (_keyboard && _keyboard.active)
  936. [_keyboard updateInputHidden];
  937. }
  938. UNITY_EXPORT extern "C" int UnityKeyboard_IsInputHidden()
  939. {
  940. return _shouldHideInput ? 1 : 0;
  941. }
  942. UNITY_EXPORT extern "C" void UnityKeyboard_GetRect(float* x, float* y, float* w, float* h)
  943. {
  944. CGRect area = _keyboard ? _keyboard.area : CGRectMake(0, 0, 0, 0);
  945. // convert to unity coord system
  946. float multX = (float)GetMainDisplaySurface()->targetW / UnityGetGLView().bounds.size.width;
  947. float multY = (float)GetMainDisplaySurface()->targetH / UnityGetGLView().bounds.size.height;
  948. *x = 0;
  949. *y = area.origin.y * multY;
  950. *w = area.size.width * multX;
  951. *h = area.size.height * multY;
  952. }
  953. UNITY_EXPORT extern "C" void UnityKeyboard_SetCharacterLimit(unsigned characterLimit)
  954. {
  955. [KeyboardDelegate Instance].characterLimit = characterLimit;
  956. }
  957. UNITY_EXPORT extern "C" int UnityKeyboard_CanGetSelection()
  958. {
  959. return (_keyboard) ? 1 : 0;
  960. }
  961. UNITY_EXPORT extern "C" void UnityKeyboard_GetSelection(int* location, int* length)
  962. {
  963. if (_keyboard)
  964. {
  965. NSRange selection = _keyboard.selection;
  966. *location = (int)selection.location;
  967. *length = (int)selection.length;
  968. }
  969. else
  970. {
  971. *location = 0;
  972. *length = 0;
  973. }
  974. }
  975. UNITY_EXPORT extern "C" int UnityKeyboard_CanSetSelection()
  976. {
  977. return (_keyboard) ? 1 : 0;
  978. }
  979. UNITY_EXPORT extern "C" void UnityKeyboard_SetSelection(int location, int length)
  980. {
  981. if (_keyboard)
  982. {
  983. _keyboard.selection = NSMakeRange(location, length);
  984. }
  985. }
  986. //==============================================================================
  987. //
  988. // Emoji Filtering: unicode magic
  989. static bool StringContainsEmoji(NSString *string)
  990. {
  991. __block BOOL returnValue = NO;
  992. [string enumerateSubstringsInRange: NSMakeRange(0, string.length)
  993. options: NSStringEnumerationByComposedCharacterSequences
  994. usingBlock:^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop)
  995. {
  996. const unichar hs = [substring characterAtIndex: 0];
  997. const unichar ls = substring.length > 1 ? [substring characterAtIndex: 1] : 0;
  998. #define IS_IN(val, min, max) (((val) >= (min)) && ((val) <= (max)))
  999. if (IS_IN(hs, 0xD800, 0xDBFF))
  1000. {
  1001. if (substring.length > 1)
  1002. {
  1003. const int uc = ((hs - 0xD800) * 0x400) + (ls - 0xDC00) + 0x10000;
  1004. // Musical: [U+1D000, U+1D24F]
  1005. // Enclosed Alphanumeric Supplement: [U+1F100, U+1F1FF]
  1006. // Enclosed Ideographic Supplement: [U+1F200, U+1F2FF]
  1007. // Miscellaneous Symbols and Pictographs: [U+1F300, U+1F5FF]
  1008. // Supplemental Symbols and Pictographs: [U+1F900, U+1F9FF]
  1009. // Emoticons: [U+1F600, U+1F64F]
  1010. // Transport and Map Symbols: [U+1F680, U+1F6FF]
  1011. if (IS_IN(uc, 0x1D000, 0x1F9FF))
  1012. returnValue = YES;
  1013. }
  1014. }
  1015. else if (substring.length > 1 && ls == 0x20E3)
  1016. {
  1017. // emojis for numbers: number + modifier ls = U+20E3
  1018. returnValue = YES;
  1019. }
  1020. else
  1021. {
  1022. if ( // Latin-1 Supplement
  1023. hs == 0x00A9 || hs == 0x00AE
  1024. // General Punctuation
  1025. || hs == 0x203C || hs == 0x2049
  1026. // Letterlike Symbols
  1027. || hs == 0x2122 || hs == 0x2139
  1028. // Arrows
  1029. || IS_IN(hs, 0x2194, 0x2199) || IS_IN(hs, 0x21A9, 0x21AA)
  1030. // Miscellaneous Technical
  1031. || IS_IN(hs, 0x231A, 0x231B) || IS_IN(hs, 0x23E9, 0x23F3) || IS_IN(hs, 0x23F8, 0x23FA) || hs == 0x2328 || hs == 0x23CF
  1032. // Geometric Shapes
  1033. || IS_IN(hs, 0x25AA, 0x25AB) || IS_IN(hs, 0x25FB, 0x25FE) || hs == 0x25B6 || hs == 0x25C0
  1034. // Miscellaneous Symbols
  1035. || IS_IN(hs, 0x2600, 0x2604) || IS_IN(hs, 0x2614, 0x2615) || IS_IN(hs, 0x2622, 0x2623) || IS_IN(hs, 0x262E, 0x262F)
  1036. || IS_IN(hs, 0x2638, 0x263A) || IS_IN(hs, 0x2648, 0x2653) || IS_IN(hs, 0x2665, 0x2666) || IS_IN(hs, 0x2692, 0x2694)
  1037. || IS_IN(hs, 0x2696, 0x2697) || IS_IN(hs, 0x269B, 0x269C) || IS_IN(hs, 0x26A0, 0x26A1) || IS_IN(hs, 0x26AA, 0x26AB)
  1038. || IS_IN(hs, 0x26B0, 0x26B1) || IS_IN(hs, 0x26BD, 0x26BE) || IS_IN(hs, 0x26C4, 0x26C5) || IS_IN(hs, 0x26CE, 0x26CF)
  1039. || IS_IN(hs, 0x26D3, 0x26D4) || IS_IN(hs, 0x26D3, 0x26D4) || IS_IN(hs, 0x26E9, 0x26EA) || IS_IN(hs, 0x26F0, 0x26F5)
  1040. || IS_IN(hs, 0x26F7, 0x26FA)
  1041. || hs == 0x260E || hs == 0x2611 || hs == 0x2618 || hs == 0x261D || hs == 0x2620 || hs == 0x2626 || hs == 0x262A
  1042. || hs == 0x2660 || hs == 0x2663 || hs == 0x2668 || hs == 0x267B || hs == 0x267F || hs == 0x2699 || hs == 0x26C8
  1043. || hs == 0x26D1 || hs == 0x26FD
  1044. // Dingbats
  1045. || IS_IN(hs, 0x2708, 0x270D) || IS_IN(hs, 0x2733, 0x2734) || IS_IN(hs, 0x2753, 0x2755)
  1046. || IS_IN(hs, 0x2763, 0x2764) || IS_IN(hs, 0x2795, 0x2797)
  1047. || hs == 0x2702 || hs == 0x2705 || hs == 0x270F || hs == 0x2712 || hs == 0x2714 || hs == 0x2716 || hs == 0x271D
  1048. || hs == 0x2721 || hs == 0x2728 || hs == 0x2744 || hs == 0x2747 || hs == 0x274C || hs == 0x274E || hs == 0x2757
  1049. || hs == 0x27A1 || hs == 0x27B0 || hs == 0x27BF
  1050. // CJK Symbols and Punctuation
  1051. || hs == 0x3030 || hs == 0x303D
  1052. // Enclosed CJK Letters and Months
  1053. || hs == 0x3297 || hs == 0x3299
  1054. // Supplemental Arrows-B
  1055. || IS_IN(hs, 0x2934, 0x2935)
  1056. // Miscellaneous Symbols and Arrows
  1057. || IS_IN(hs, 0x2B05, 0x2B07) || IS_IN(hs, 0x2B1B, 0x2B1C) || hs == 0x2B50 || hs == 0x2B55
  1058. )
  1059. {
  1060. returnValue = YES;
  1061. }
  1062. }
  1063. #undef IS_IN
  1064. }];
  1065. return returnValue;
  1066. }