ASEditableTextNode.mm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. //
  2. // ASEditableTextNode.mm
  3. // AsyncDisplayKit
  4. //
  5. // Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  6. // This source code is licensed under the BSD-style license found in the
  7. // LICENSE file in the root directory of this source tree. An additional grant
  8. // of patent rights can be found in the PATENTS file in the same directory.
  9. //
  10. #import "ASEditableTextNode.h"
  11. #import <objc/message.h>
  12. #import <tgmath.h>
  13. #import "ASDisplayNode+Subclasses.h"
  14. #import "ASEqualityHelpers.h"
  15. #import "ASTextNodeWordKerner.h"
  16. /**
  17. @abstract Object to hold UITextView's pending UITextInputTraits
  18. **/
  19. @interface _ASTextInputTraitsPendingState : NSObject
  20. @property (nonatomic, readwrite, assign) UITextAutocapitalizationType autocapitalizationType;
  21. @property (nonatomic, readwrite, assign) UITextAutocorrectionType autocorrectionType;
  22. @property (nonatomic, readwrite, assign) UITextSpellCheckingType spellCheckingType;
  23. @property (nonatomic, readwrite, assign) UIKeyboardAppearance keyboardAppearance;
  24. @property (nonatomic, readwrite, assign) UIKeyboardType keyboardType;
  25. @property (nonatomic, readwrite, assign) UIReturnKeyType returnKeyType;
  26. @property (nonatomic, readwrite, assign) BOOL enablesReturnKeyAutomatically;
  27. @property (nonatomic, readwrite, assign, getter=isSecureTextEntry) BOOL secureTextEntry;
  28. @end
  29. @implementation _ASTextInputTraitsPendingState
  30. - (instancetype)init
  31. {
  32. if (!(self = [super init]))
  33. return nil;
  34. // set default values, as defined in Apple's comments in UITextInputTraits.h
  35. _autocapitalizationType = UITextAutocapitalizationTypeSentences;
  36. _autocorrectionType = UITextAutocorrectionTypeDefault;
  37. _spellCheckingType = UITextSpellCheckingTypeDefault;
  38. _keyboardAppearance = UIKeyboardAppearanceDefault;
  39. _keyboardType = UIKeyboardTypeDefault;
  40. _returnKeyType = UIReturnKeyDefault;
  41. return self;
  42. }
  43. @end
  44. /**
  45. @abstract As originally reported in rdar://14729288, when scrollEnabled = NO,
  46. UITextView does not calculate its contentSize. This makes it difficult
  47. for a client to embed a UITextView inside a different scroll view with
  48. other content (setting scrollEnabled = NO on the UITextView itself,
  49. because the containing scroll view will handle the gesture)...
  50. because accessing contentSize is typically necessary to perform layout.
  51. Apple later closed the issue as expected behavior. This works around
  52. the issue by ensuring that contentSize is always calculated, while
  53. still providing control over the UITextView's scrolling.
  54. See issue: https://github.com/facebook/AsyncDisplayKit/issues/1063
  55. */
  56. @interface ASPanningOverriddenUITextView : UITextView
  57. {
  58. BOOL _shouldBlockPanGesture;
  59. }
  60. @end
  61. @implementation ASPanningOverriddenUITextView
  62. #if TARGET_OS_IOS
  63. // tvOS doesn't support self.scrollsToTop
  64. - (BOOL)scrollEnabled
  65. {
  66. return _shouldBlockPanGesture;
  67. }
  68. - (void)setScrollEnabled:(BOOL)scrollEnabled
  69. {
  70. _shouldBlockPanGesture = !scrollEnabled;
  71. self.scrollsToTop = scrollEnabled;
  72. [super setScrollEnabled:YES];
  73. }
  74. #endif
  75. - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
  76. {
  77. // Never allow our pans to begin when _shouldBlockPanGesture is true.
  78. if (_shouldBlockPanGesture && gestureRecognizer == self.panGestureRecognizer)
  79. return NO;
  80. // Otherwise, proceed as usual.
  81. if ([UITextView instancesRespondToSelector:_cmd])
  82. return [super gestureRecognizerShouldBegin:gestureRecognizer];
  83. return YES;
  84. }
  85. @end
  86. #pragma mark -
  87. @interface ASEditableTextNode () <UITextViewDelegate, NSLayoutManagerDelegate>
  88. {
  89. @private
  90. // Configuration.
  91. NSDictionary *_typingAttributes;
  92. // Core.
  93. id <ASEditableTextNodeDelegate> __weak _delegate;
  94. BOOL _delegateDidUpdateEnqueued;
  95. // TextKit.
  96. ASDN::RecursiveMutex _textKitLock;
  97. ASTextKitComponents *_textKitComponents;
  98. ASTextKitComponents *_placeholderTextKitComponents;
  99. // Forwards NSLayoutManagerDelegate methods related to word kerning
  100. ASTextNodeWordKerner *_wordKerner;
  101. // UITextInputTraits
  102. ASDN::RecursiveMutex _textInputTraitsLock;
  103. _ASTextInputTraitsPendingState *_textInputTraits;
  104. // Misc. State.
  105. BOOL _displayingPlaceholder; // Defaults to YES.
  106. BOOL _isPreservingSelection;
  107. BOOL _selectionChangedForEditedText;
  108. NSRange _previousSelectedRange;
  109. }
  110. @property (nonatomic, strong, readonly) _ASTextInputTraitsPendingState *textInputTraits;
  111. @end
  112. @implementation ASEditableTextNode
  113. #pragma mark - NSObject Overrides
  114. - (instancetype)init
  115. {
  116. return [self initWithTextKitComponents:[ASTextKitComponents componentsWithAttributedSeedString:nil textContainerSize:CGSizeZero]
  117. placeholderTextKitComponents:[ASTextKitComponents componentsWithAttributedSeedString:nil textContainerSize:CGSizeZero]];
  118. }
  119. - (instancetype)initWithTextKitComponents:(ASTextKitComponents *)textKitComponents
  120. placeholderTextKitComponents:(ASTextKitComponents *)placeholderTextKitComponents
  121. {
  122. if (!(self = [super init]))
  123. return nil;
  124. _displayingPlaceholder = YES;
  125. _scrollEnabled = YES;
  126. // Create the scaffolding for the text view.
  127. _textKitComponents = textKitComponents;
  128. _textKitComponents.layoutManager.delegate = self;
  129. _wordKerner = [[ASTextNodeWordKerner alloc] init];
  130. _textContainerInset = UIEdgeInsetsZero;
  131. // Create the placeholder scaffolding.
  132. _placeholderTextKitComponents = placeholderTextKitComponents;
  133. _placeholderTextKitComponents.layoutManager.delegate = self;
  134. return self;
  135. }
  136. - (void)dealloc
  137. {
  138. _textKitComponents.textView.delegate = nil;
  139. _textKitComponents.layoutManager.delegate = nil;
  140. _placeholderTextKitComponents.layoutManager.delegate = nil;
  141. }
  142. #pragma mark - ASDisplayNode Overrides
  143. - (void)didLoad
  144. {
  145. [super didLoad];
  146. void (^configureTextView)(UITextView *) = ^(UITextView *textView) {
  147. if (!_displayingPlaceholder || textView != _textKitComponents.textView) {
  148. // If showing the placeholder, don't propagate backgroundColor/opaque to the editable textView. It is positioned over the placeholder to accept taps to begin editing, and if it's opaque/colored then it'll obscure the placeholder.
  149. textView.backgroundColor = self.backgroundColor;
  150. textView.opaque = self.opaque;
  151. } else if (_displayingPlaceholder && textView == _textKitComponents.textView) {
  152. // The default backgroundColor for a textView is white. Due to the reason described above, make sure the editable textView starts out transparent.
  153. textView.backgroundColor = nil;
  154. textView.opaque = NO;
  155. }
  156. textView.textContainerInset = self.textContainerInset;
  157. // Configure textView with UITextInputTraits
  158. {
  159. ASDN::MutexLocker l(_textInputTraitsLock);
  160. if (_textInputTraits) {
  161. textView.autocapitalizationType = _textInputTraits.autocapitalizationType;
  162. textView.autocorrectionType = _textInputTraits.autocorrectionType;
  163. textView.spellCheckingType = _textInputTraits.spellCheckingType;
  164. textView.keyboardType = _textInputTraits.keyboardType;
  165. textView.keyboardAppearance = _textInputTraits.keyboardAppearance;
  166. textView.returnKeyType = _textInputTraits.returnKeyType;
  167. textView.enablesReturnKeyAutomatically = _textInputTraits.enablesReturnKeyAutomatically;
  168. textView.secureTextEntry = _textInputTraits.isSecureTextEntry;
  169. }
  170. }
  171. [self.view addSubview:textView];
  172. };
  173. ASDN::MutexLocker l(_textKitLock);
  174. // Create and configure the placeholder text view.
  175. _placeholderTextKitComponents.textView = [[UITextView alloc] initWithFrame:CGRectZero textContainer:_placeholderTextKitComponents.textContainer];
  176. _placeholderTextKitComponents.textView.userInteractionEnabled = NO;
  177. _placeholderTextKitComponents.textView.accessibilityElementsHidden = YES;
  178. configureTextView(_placeholderTextKitComponents.textView);
  179. // Create and configure our text view.
  180. _textKitComponents.textView = [[ASPanningOverriddenUITextView alloc] initWithFrame:CGRectZero textContainer:_textKitComponents.textContainer];
  181. _textKitComponents.textView.scrollEnabled = _scrollEnabled;
  182. _textKitComponents.textView.delegate = self;
  183. #if TARGET_OS_IOS
  184. _textKitComponents.textView.editable = YES;
  185. #endif
  186. _textKitComponents.textView.typingAttributes = _typingAttributes;
  187. _textKitComponents.textView.accessibilityHint = _placeholderTextKitComponents.textStorage.string;
  188. configureTextView(_textKitComponents.textView);
  189. [self _updateDisplayingPlaceholder];
  190. // once view is loaded, setters set directly on view
  191. _textInputTraits = nil;
  192. }
  193. - (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
  194. {
  195. ASTextKitComponents *displayedComponents = [self isDisplayingPlaceholder] ? _placeholderTextKitComponents : _textKitComponents;
  196. CGSize textSize;
  197. if (_maximumLinesToDisplay > 0) {
  198. textSize = [displayedComponents sizeForConstrainedWidth:constrainedSize.width
  199. forMaxNumberOfLines: _maximumLinesToDisplay];
  200. } else {
  201. textSize = [displayedComponents sizeForConstrainedWidth:constrainedSize.width];
  202. }
  203. CGFloat width = std::ceil(textSize.width + _textContainerInset.left + _textContainerInset.right);
  204. CGFloat height = std::ceil(textSize.height + _textContainerInset.top + _textContainerInset.bottom);
  205. return CGSizeMake(std::fmin(width, constrainedSize.width), std::fmin(height, constrainedSize.height));
  206. }
  207. - (void)layout
  208. {
  209. ASDisplayNodeAssertMainThread();
  210. [super layout];
  211. [self _layoutTextView];
  212. }
  213. - (void)setBackgroundColor:(UIColor *)backgroundColor
  214. {
  215. [super setBackgroundColor:backgroundColor];
  216. ASDN::MutexLocker l(_textKitLock);
  217. // If showing the placeholder, don't propagate backgroundColor/opaque to the editable textView. It is positioned over the placeholder to accept taps to begin editing, and if it's opaque/colored then it'll obscure the placeholder.
  218. // The backgroundColor/opaque will be propagated to the editable textView when editing begins.
  219. if (!_displayingPlaceholder) {
  220. _textKitComponents.textView.backgroundColor = backgroundColor;
  221. }
  222. _placeholderTextKitComponents.textView.backgroundColor = backgroundColor;
  223. }
  224. - (void)setTextContainerInset:(UIEdgeInsets)textContainerInset
  225. {
  226. ASDN::MutexLocker l(_textKitLock);
  227. _textContainerInset = textContainerInset;
  228. _textKitComponents.textView.textContainerInset = textContainerInset;
  229. _placeholderTextKitComponents.textView.textContainerInset = textContainerInset;
  230. }
  231. - (void)setOpaque:(BOOL)opaque
  232. {
  233. [super setOpaque:opaque];
  234. ASDN::MutexLocker l(_textKitLock);
  235. // If showing the placeholder, don't propagate backgroundColor/opaque to the editable textView. It is positioned over the placeholder to accept taps to begin editing, and if it's opaque/colored then it'll obscure the placeholder.
  236. // The backgroundColor/opaque will be propagated to the editable textView when editing begins.
  237. if (!_displayingPlaceholder) {
  238. _textKitComponents.textView.opaque = opaque;
  239. }
  240. _placeholderTextKitComponents.textView.opaque = opaque;
  241. }
  242. - (void)setLayerBacked:(BOOL)layerBacked
  243. {
  244. ASDisplayNodeAssert(!layerBacked, @"Cannot set layerBacked to YES on ASEditableTextNode – instances must be view-backed in order to ensure touch events can be passed to the internal UITextView during editing.");
  245. [super setLayerBacked:layerBacked];
  246. }
  247. #pragma mark - Configuration
  248. @synthesize delegate = _delegate;
  249. - (void)setScrollEnabled:(BOOL)scrollEnabled
  250. {
  251. ASDN::MutexLocker l(_textKitLock);
  252. _scrollEnabled = scrollEnabled;
  253. [_textKitComponents.textView setScrollEnabled:_scrollEnabled];
  254. }
  255. - (UITextView *)textView
  256. {
  257. ASDisplayNodeAssertMainThread();
  258. [self view];
  259. ASDisplayNodeAssert(_textKitComponents.textView != nil, @"UITextView must be created in -[ASEditableTextNode didLoad]");
  260. return _textKitComponents.textView;
  261. }
  262. - (void)setMaximumLinesToDisplay:(NSUInteger)maximumLines
  263. {
  264. _maximumLinesToDisplay = maximumLines;
  265. [self setNeedsLayout];
  266. }
  267. #pragma mark -
  268. @dynamic typingAttributes;
  269. - (NSDictionary *)typingAttributes
  270. {
  271. return _typingAttributes;
  272. }
  273. - (void)setTypingAttributes:(NSDictionary *)typingAttributes
  274. {
  275. if (ASObjectIsEqual(typingAttributes, _typingAttributes))
  276. return;
  277. _typingAttributes = [typingAttributes copy];
  278. ASDN::MutexLocker l(_textKitLock);
  279. _textKitComponents.textView.typingAttributes = _typingAttributes;
  280. }
  281. #pragma mark -
  282. @dynamic selectedRange;
  283. - (NSRange)selectedRange
  284. {
  285. ASDN::MutexLocker l(_textKitLock);
  286. return _textKitComponents.textView.selectedRange;
  287. }
  288. - (void)setSelectedRange:(NSRange)selectedRange
  289. {
  290. ASDN::MutexLocker l(_textKitLock);
  291. _textKitComponents.textView.selectedRange = selectedRange;
  292. }
  293. #pragma mark - Placeholder
  294. - (BOOL)isDisplayingPlaceholder
  295. {
  296. return _displayingPlaceholder;
  297. }
  298. #pragma mark -
  299. @dynamic attributedPlaceholderText;
  300. - (NSAttributedString *)attributedPlaceholderText
  301. {
  302. ASDN::MutexLocker l(_textKitLock);
  303. return [_placeholderTextKitComponents.textStorage copy];
  304. }
  305. - (void)setAttributedPlaceholderText:(NSAttributedString *)attributedPlaceholderText
  306. {
  307. ASDN::MutexLocker l(_textKitLock);
  308. if (ASObjectIsEqual(_placeholderTextKitComponents.textStorage, attributedPlaceholderText))
  309. return;
  310. [_placeholderTextKitComponents.textStorage setAttributedString:attributedPlaceholderText ? : [[NSAttributedString alloc] initWithString:@""]];
  311. _textKitComponents.textView.accessibilityHint = attributedPlaceholderText.string;
  312. }
  313. #pragma mark - Modifying User Text
  314. @dynamic attributedText;
  315. - (NSAttributedString *)attributedText
  316. {
  317. // Per contract in our header, this value is nil when the placeholder is displayed.
  318. if ([self isDisplayingPlaceholder])
  319. return nil;
  320. ASDN::MutexLocker l(_textKitLock);
  321. return [_textKitComponents.textStorage copy];
  322. }
  323. - (void)setAttributedText:(NSAttributedString *)attributedText
  324. {
  325. ASDN::MutexLocker l(_textKitLock);
  326. // If we (_cmd) are called while the text view itself is updating (-textViewDidUpdate:), you cannot update the text storage and expect perfect propagation to the text view.
  327. // Thus, we always update the textview directly if it's been created already.
  328. if (ASObjectIsEqual((_textKitComponents.textView.attributedText ? : _textKitComponents.textStorage), attributedText))
  329. return;
  330. // If the cursor isn't at the end of the text, we need to preserve the selected range to avoid moving the cursor.
  331. NSRange selectedRange = _textKitComponents.textView.selectedRange;
  332. BOOL preserveSelectedRange = (selectedRange.location != _textKitComponents.textStorage.length);
  333. NSAttributedString *attributedStringToDisplay = nil;
  334. if (attributedText)
  335. attributedStringToDisplay = attributedText;
  336. // Otherwise, note that we don't simply nil out attributed text. Because the insertion point is guided by the attributes at index 0, we need to attribute an empty string to ensure the insert point obeys our typing attributes.
  337. else
  338. attributedStringToDisplay = [[NSAttributedString alloc] initWithString:@"" attributes:self.typingAttributes];
  339. // Always prefer updating the text view directly if it's been created (see above).
  340. if (_textKitComponents.textView)
  341. [_textKitComponents.textView setAttributedText:attributedStringToDisplay];
  342. else
  343. [_textKitComponents.textStorage setAttributedString:attributedStringToDisplay];
  344. // Calculated size depends on the seeded text.
  345. [self setNeedsLayout];
  346. // Update if placeholder is shown.
  347. [self _updateDisplayingPlaceholder];
  348. // Preserve cursor range, if necessary.
  349. if (preserveSelectedRange) {
  350. _isPreservingSelection = YES; // Used in -textViewDidChangeSelection: to avoid informing our delegate about our preservation.
  351. [_textKitComponents.textView setSelectedRange:selectedRange];
  352. _isPreservingSelection = NO;
  353. }
  354. }
  355. #pragma mark - Core
  356. - (void)_updateDisplayingPlaceholder
  357. {
  358. ASDN::MutexLocker l(_textKitLock);
  359. // Show the placeholder if necessary.
  360. _displayingPlaceholder = (_textKitComponents.textStorage.length == 0);
  361. _placeholderTextKitComponents.textView.hidden = !_displayingPlaceholder;
  362. // If hiding the placeholder, propagate backgroundColor/opaque to the editable textView. It is positioned over the placeholder to accept taps to begin editing, and was kept transparent so it doesn't obscure the placeholder text. Now that we're editing it and the placeholder is hidden, we can make it opaque to avoid unnecessary blending.
  363. if (!_displayingPlaceholder) {
  364. _textKitComponents.textView.opaque = self.isOpaque;
  365. _textKitComponents.textView.backgroundColor = self.backgroundColor;
  366. } else {
  367. _textKitComponents.textView.opaque = NO;
  368. _textKitComponents.textView.backgroundColor = nil;
  369. }
  370. }
  371. - (void)_layoutTextView
  372. {
  373. ASDN::MutexLocker l(_textKitLock);
  374. // Layout filling our bounds.
  375. _textKitComponents.textView.frame = self.bounds;
  376. _placeholderTextKitComponents.textView.frame = self.bounds;
  377. // Note that both of these won't be necessary once we can disable scrolling, pending rdar://14729288
  378. // When we resize to fit (above) the prior layout becomes invalid. For whatever reason, UITextView doesn't invalidate its layout when its frame changes on its own, so we have to do so ourselves.
  379. [_textKitComponents.layoutManager invalidateLayoutForCharacterRange:NSMakeRange(0, [_textKitComponents.textStorage length]) actualCharacterRange:NULL];
  380. // When you type beyond UITextView's bounds it scrolls you down a line. We need to remain at the top.
  381. [_textKitComponents.textView setContentOffset:CGPointZero animated:NO];
  382. }
  383. #pragma mark - Keyboard
  384. @dynamic textInputMode;
  385. - (UITextInputMode *)textInputMode
  386. {
  387. ASDN::MutexLocker l(_textKitLock);
  388. return [_textKitComponents.textView textInputMode];
  389. }
  390. - (BOOL)isFirstResponder
  391. {
  392. ASDN::MutexLocker l(_textKitLock);
  393. return [_textKitComponents.textView isFirstResponder];
  394. }
  395. - (BOOL)canBecomeFirstResponder {
  396. ASDN::MutexLocker l(_textKitLock);
  397. return [_textKitComponents.textView canBecomeFirstResponder];
  398. }
  399. - (BOOL)becomeFirstResponder
  400. {
  401. ASDN::MutexLocker l(_textKitLock);
  402. return [_textKitComponents.textView becomeFirstResponder];
  403. }
  404. - (BOOL)canResignFirstResponder {
  405. ASDN::MutexLocker l(_textKitLock);
  406. return [_textKitComponents.textView canResignFirstResponder];
  407. }
  408. - (BOOL)resignFirstResponder
  409. {
  410. ASDN::MutexLocker l(_textKitLock);
  411. return [_textKitComponents.textView resignFirstResponder];
  412. }
  413. #pragma mark - UITextInputTraits
  414. - (_ASTextInputTraitsPendingState *)textInputTraits
  415. {
  416. if (!_textInputTraits) {
  417. _textInputTraits = [[_ASTextInputTraitsPendingState alloc] init];
  418. }
  419. return _textInputTraits;
  420. }
  421. - (void)setAutocapitalizationType:(UITextAutocapitalizationType)autocapitalizationType
  422. {
  423. ASDN::MutexLocker l(_textInputTraitsLock);
  424. if (self.isNodeLoaded) {
  425. [self.textView setAutocapitalizationType:autocapitalizationType];
  426. } else {
  427. [self.textInputTraits setAutocapitalizationType:autocapitalizationType];
  428. }
  429. }
  430. - (UITextAutocapitalizationType)autocapitalizationType
  431. {
  432. ASDN::MutexLocker l(_textInputTraitsLock);
  433. if (self.isNodeLoaded) {
  434. return [self.textView autocapitalizationType];
  435. } else {
  436. return [self.textInputTraits autocapitalizationType];
  437. }
  438. }
  439. - (void)setAutocorrectionType:(UITextAutocorrectionType)autocorrectionType
  440. {
  441. ASDN::MutexLocker l(_textInputTraitsLock);
  442. if (self.isNodeLoaded) {
  443. [self.textView setAutocorrectionType:autocorrectionType];
  444. } else {
  445. [self.textInputTraits setAutocorrectionType:autocorrectionType];
  446. }
  447. }
  448. - (UITextAutocorrectionType)autocorrectionType
  449. {
  450. ASDN::MutexLocker l(_textInputTraitsLock);
  451. if (self.isNodeLoaded) {
  452. return [self.textView autocorrectionType];
  453. } else {
  454. return [self.textInputTraits autocorrectionType];
  455. }
  456. }
  457. - (void)setSpellCheckingType:(UITextSpellCheckingType)spellCheckingType
  458. {
  459. ASDN::MutexLocker l(_textInputTraitsLock);
  460. if (self.isNodeLoaded) {
  461. [self.textView setSpellCheckingType:spellCheckingType];
  462. } else {
  463. [self.textInputTraits setSpellCheckingType:spellCheckingType];
  464. }
  465. }
  466. - (UITextSpellCheckingType)spellCheckingType
  467. {
  468. ASDN::MutexLocker l(_textInputTraitsLock);
  469. if (self.isNodeLoaded) {
  470. return [self.textView spellCheckingType];
  471. } else {
  472. return [self.textInputTraits spellCheckingType];
  473. }
  474. }
  475. - (void)setEnablesReturnKeyAutomatically:(BOOL)enablesReturnKeyAutomatically
  476. {
  477. ASDN::MutexLocker l(_textInputTraitsLock);
  478. if (self.isNodeLoaded) {
  479. [self.textView setEnablesReturnKeyAutomatically:enablesReturnKeyAutomatically];
  480. } else {
  481. [self.textInputTraits setEnablesReturnKeyAutomatically:enablesReturnKeyAutomatically];
  482. }
  483. }
  484. - (BOOL)enablesReturnKeyAutomatically
  485. {
  486. ASDN::MutexLocker l(_textInputTraitsLock);
  487. if (self.isNodeLoaded) {
  488. return [self.textView enablesReturnKeyAutomatically];
  489. } else {
  490. return [self.textInputTraits enablesReturnKeyAutomatically];
  491. }
  492. }
  493. - (void)setKeyboardAppearance:(UIKeyboardAppearance)setKeyboardAppearance
  494. {
  495. ASDN::MutexLocker l(_textInputTraitsLock);
  496. if (self.isNodeLoaded) {
  497. [self.textView setKeyboardAppearance:setKeyboardAppearance];
  498. } else {
  499. [self.textInputTraits setKeyboardAppearance:setKeyboardAppearance];
  500. }
  501. }
  502. - (UIKeyboardAppearance)keyboardAppearance
  503. {
  504. ASDN::MutexLocker l(_textInputTraitsLock);
  505. if (self.isNodeLoaded) {
  506. return [self.textView keyboardAppearance];
  507. } else {
  508. return [self.textInputTraits keyboardAppearance];
  509. }
  510. }
  511. - (void)setKeyboardType:(UIKeyboardType)keyboardType
  512. {
  513. ASDN::MutexLocker l(_textInputTraitsLock);
  514. if (self.isNodeLoaded) {
  515. [self.textView setKeyboardType:keyboardType];
  516. } else {
  517. [self.textInputTraits setKeyboardType:keyboardType];
  518. }
  519. }
  520. - (UIKeyboardType)keyboardType
  521. {
  522. ASDN::MutexLocker l(_textInputTraitsLock);
  523. if (self.isNodeLoaded) {
  524. return [self.textView keyboardType];
  525. } else {
  526. return [self.textInputTraits keyboardType];
  527. }
  528. }
  529. - (void)setReturnKeyType:(UIReturnKeyType)returnKeyType
  530. {
  531. ASDN::MutexLocker l(_textInputTraitsLock);
  532. if (self.isNodeLoaded) {
  533. [self.textView setReturnKeyType:returnKeyType];
  534. } else {
  535. [self.textInputTraits setReturnKeyType:returnKeyType];
  536. }
  537. }
  538. - (UIReturnKeyType)returnKeyType
  539. {
  540. ASDN::MutexLocker l(_textInputTraitsLock);
  541. if (self.isNodeLoaded) {
  542. return [self.textView returnKeyType];
  543. } else {
  544. return [self.textInputTraits returnKeyType];
  545. }
  546. }
  547. - (void)setSecureTextEntry:(BOOL)secureTextEntry
  548. {
  549. ASDN::MutexLocker l(_textInputTraitsLock);
  550. if (self.isNodeLoaded) {
  551. [self.textView setSecureTextEntry:secureTextEntry];
  552. } else {
  553. [self.textInputTraits setSecureTextEntry:secureTextEntry];
  554. }
  555. }
  556. - (BOOL)isSecureTextEntry
  557. {
  558. ASDN::MutexLocker l(_textInputTraitsLock);
  559. if (self.isNodeLoaded) {
  560. return [self.textView isSecureTextEntry];
  561. } else {
  562. return [self.textInputTraits isSecureTextEntry];
  563. }
  564. }
  565. #pragma mark - UITextView Delegate
  566. - (void)textViewDidBeginEditing:(UITextView *)textView
  567. {
  568. // Delegateify.
  569. [self _delegateDidBeginEditing];
  570. }
  571. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  572. {
  573. // Delegateify.
  574. return [self _delegateShouldChangeTextInRange:range replacementText:text];
  575. }
  576. - (void)textViewDidChange:(UITextView *)textView
  577. {
  578. ASDN::MutexLocker l(_textKitLock);
  579. // Note we received a text changed event.
  580. // This is used by _delegateDidChangeSelectionFromSelectedRange:toSelectedRange: to distinguish between selection changes that happen because of editing or pure selection changes.
  581. _selectionChangedForEditedText = YES;
  582. // Update if the placeholder is visible.
  583. [self _updateDisplayingPlaceholder];
  584. // Invalidate, as our calculated size depends on the textview's seeded text.
  585. [self invalidateCalculatedLayout];
  586. // Delegateify.
  587. [self _delegateDidUpdateText];
  588. }
  589. - (void)textViewDidChangeSelection:(UITextView *)textView
  590. {
  591. // Typing attributes get reset when selection changes. Reapply them so they actually obey our header.
  592. _textKitComponents.textView.typingAttributes = _typingAttributes;
  593. // If we're only changing selection to preserve it, don't notify about anything.
  594. if (_isPreservingSelection)
  595. return;
  596. // Note if we receive a -textDidChange: between now and when we delegatify.
  597. // This is used by _delegateDidChangeSelectionFromSelectedRange:toSelectedRange: to distinguish between selection changes that happen because of editing or pure selection changes.
  598. _selectionChangedForEditedText = NO;
  599. NSRange fromSelectedRange = _previousSelectedRange;
  600. NSRange toSelectedRange = self.selectedRange;
  601. _previousSelectedRange = toSelectedRange;
  602. // Delegateify.
  603. [self _delegateDidChangeSelectionFromSelectedRange:fromSelectedRange toSelectedRange:toSelectedRange];
  604. }
  605. - (void)textViewDidEndEditing:(UITextView *)textView
  606. {
  607. // Delegateify.
  608. [self _delegateDidFinishEditing];
  609. }
  610. #pragma mark - NSLayoutManager Delegate
  611. - (NSUInteger)layoutManager:(NSLayoutManager *)layoutManager shouldGenerateGlyphs:(const CGGlyph *)glyphs properties:(const NSGlyphProperty *)properties characterIndexes:(const NSUInteger *)characterIndexes font:(UIFont *)aFont forGlyphRange:(NSRange)glyphRange
  612. {
  613. return [_wordKerner layoutManager:layoutManager shouldGenerateGlyphs:glyphs properties:properties characterIndexes:characterIndexes font:aFont forGlyphRange:glyphRange];
  614. }
  615. - (NSControlCharacterAction)layoutManager:(NSLayoutManager *)layoutManager shouldUseAction:(NSControlCharacterAction)defaultAction forControlCharacterAtIndex:(NSUInteger)characterIndex
  616. {
  617. return [_wordKerner layoutManager:layoutManager shouldUseAction:defaultAction forControlCharacterAtIndex:characterIndex];
  618. }
  619. - (CGRect)layoutManager:(NSLayoutManager *)layoutManager boundingBoxForControlGlyphAtIndex:(NSUInteger)glyphIndex forTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)proposedRect glyphPosition:(CGPoint)glyphPosition characterIndex:(NSUInteger)characterIndex
  620. {
  621. return [_wordKerner layoutManager:layoutManager boundingBoxForControlGlyphAtIndex:glyphIndex forTextContainer:textContainer proposedLineFragment:proposedRect glyphPosition:glyphPosition characterIndex:characterIndex];
  622. }
  623. #pragma mark - Geometry
  624. - (CGRect)frameForTextRange:(NSRange)textRange
  625. {
  626. ASDN::MutexLocker l(_textKitLock);
  627. // Bail on invalid range.
  628. if (NSMaxRange(textRange) > [_textKitComponents.textStorage length]) {
  629. ASDisplayNodeAssert(NO, @"Invalid range");
  630. return CGRectZero;
  631. }
  632. // Force glyph generation and layout.
  633. [_textKitComponents.layoutManager ensureLayoutForTextContainer:_textKitComponents.textContainer];
  634. NSRange glyphRange = [_textKitComponents.layoutManager glyphRangeForCharacterRange:textRange actualCharacterRange:NULL];
  635. CGRect textRect = [_textKitComponents.layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:_textKitComponents.textContainer];
  636. return [_textKitComponents.textView convertRect:textRect toView:self.view];
  637. }
  638. #pragma mark -
  639. - (void)_delegateDidBeginEditing
  640. {
  641. if ([_delegate respondsToSelector:@selector(editableTextNodeDidBeginEditing:)])
  642. [_delegate editableTextNodeDidBeginEditing:self];
  643. }
  644. - (BOOL)_delegateShouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  645. {
  646. if ([_delegate respondsToSelector:@selector(editableTextNode:shouldChangeTextInRange:replacementText:)]) {
  647. return [_delegate editableTextNode:self shouldChangeTextInRange:range replacementText:text];
  648. }
  649. return YES;
  650. }
  651. - (void)_delegateDidChangeSelectionFromSelectedRange:(NSRange)fromSelectedRange toSelectedRange:(NSRange)toSelectedRange
  652. {
  653. // There are two reasons we're invoking the delegate on the next run of the runloop.
  654. // 1. UITextView invokes its delegate methods when it's in the middle of text-processing. For example, -textViewDidChange: is invoked before you can truly rely on the changes being propagated throughout the Text Kit hierarchy.
  655. // 2. This delegate method (-textViewDidChangeSelection:) is called both before -textViewDidChange: and before the layout manager/etc. has necessarily generated+laid out its glyphs. Because of the former, we need to wait until -textViewDidChange: has had an opportunity to be called so can accurately determine whether this selection change is due to editing (_selectionChangedForEditedText).
  656. // Thus, to avoid calling out to client code in the middle of UITextView's processing, we call the delegate on the next run of the runloop, when all such internal processing is surely done.
  657. dispatch_async(dispatch_get_main_queue(), ^{
  658. if ([_delegate respondsToSelector:@selector(editableTextNodeDidChangeSelection:fromSelectedRange:toSelectedRange:dueToEditing:)])
  659. [_delegate editableTextNodeDidChangeSelection:self fromSelectedRange:fromSelectedRange toSelectedRange:toSelectedRange dueToEditing:_selectionChangedForEditedText];
  660. });
  661. }
  662. - (void)_delegateDidUpdateText
  663. {
  664. // Note that because -editableTextNodeDidUpdateText: passes no state, the current state of the receiver will be accessed. Thus, it's not useful to enqueue a second delegation call if the first hasn't happened yet -- doing so will result in the delegate receiving -editableTextNodeDidUpdateText: when the "updated text" has already been processed. This may sound innocuous, but because our delegation may cause additional updates to the textview's string, and because such updates discard spelling suggestions and autocompletions (like double-space to `.`), it can actually be quite dangerous!
  665. if (_delegateDidUpdateEnqueued)
  666. return;
  667. _delegateDidUpdateEnqueued = YES;
  668. // UITextView invokes its delegate methods when it's in the middle of text-processing. For example, -textViewDidChange: is invoked before you can truly rely on the changes being propagated throughout the Text Kit hierarchy.
  669. // Thus, to avoid calling out to client code in the middle of UITextView's processing, we call the delegate on the next run of the runloop, when all such internal processing is surely done.
  670. dispatch_async(dispatch_get_main_queue(), ^{
  671. _delegateDidUpdateEnqueued = NO;
  672. if ([_delegate respondsToSelector:@selector(editableTextNodeDidUpdateText:)])
  673. [_delegate editableTextNodeDidUpdateText:self];
  674. });
  675. }
  676. - (void)_delegateDidFinishEditing
  677. {
  678. if ([_delegate respondsToSelector:@selector(editableTextNodeDidFinishEditing:)])
  679. [_delegate editableTextNodeDidFinishEditing:self];
  680. }
  681. @end