CYRTextView.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //
  2. // CYRTextView.m
  3. //
  4. // Version 0.2.0
  5. //
  6. // Created by Illya Busigin on 01/05/2014.
  7. // Copyright (c) 2014 Cyrillian, Inc.
  8. // Copyright (c) 2013 Dominik Hauser
  9. // Copyright (c) 2013 Sam Rijs
  10. //
  11. // Distributed under MIT license.
  12. // Get the latest version from here:
  13. //
  14. // https://github.com/illyabusigin/CYRTextView
  15. //
  16. // The MIT License (MIT)
  17. //
  18. // Copyright (c) 2014 Cyrillian, Inc.
  19. //
  20. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  21. // this software and associated documentation files (the "Software"), to deal in
  22. // the Software without restriction, including without limitation the rights to
  23. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  24. // the Software, and to permit persons to whom the Software is furnished to do so,
  25. // subject to the following conditions:
  26. //
  27. // The above copyright notice and this permission notice shall be included in all
  28. // copies or substantial portions of the Software.
  29. //
  30. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  32. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  33. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  34. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  35. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  36. #import "CYRTextView.h"
  37. #import "CYRLayoutManager.h"
  38. #import "CYRTextStorage.h"
  39. #define RGB(r,g,b) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:1.0f]
  40. static void *CYRTextViewContext = &CYRTextViewContext;
  41. static const float kCursorVelocity = 1.0f/8.0f;
  42. @interface CYRTextView ()
  43. @property (nonatomic, strong) CYRLayoutManager *lineNumberLayoutManager;
  44. @property (nonatomic, strong) CYRTextStorage *syntaxTextStorage;
  45. @end
  46. @implementation CYRTextView
  47. {
  48. NSRange startRange;
  49. }
  50. #pragma mark - Initialization & Setup
  51. - (id)initWithFrame:(CGRect)frame
  52. {
  53. CYRTextStorage *textStorage = [CYRTextStorage new];
  54. CYRLayoutManager *layoutManager = [CYRLayoutManager new];
  55. self.lineNumberLayoutManager = layoutManager;
  56. NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)];
  57. // Wrap text to the text view's frame
  58. textContainer.widthTracksTextView = YES;
  59. [layoutManager addTextContainer:textContainer];
  60. [textStorage removeLayoutManager:textStorage.layoutManagers.firstObject];
  61. [textStorage addLayoutManager:layoutManager];
  62. self.syntaxTextStorage = textStorage;
  63. if ((self = [super initWithFrame:frame textContainer:textContainer]))
  64. {
  65. self.contentMode = UIViewContentModeRedraw; // causes drawRect: to be called on frame resizing and device rotation
  66. [self _commonSetup];
  67. }
  68. return self;
  69. }
  70. - (void)_commonSetup
  71. {
  72. // Setup observers
  73. [self addObserver:self forKeyPath:NSStringFromSelector(@selector(font)) options:NSKeyValueObservingOptionNew context:CYRTextViewContext];
  74. [self addObserver:self forKeyPath:NSStringFromSelector(@selector(selectedTextRange)) options:NSKeyValueObservingOptionNew context:CYRTextViewContext];
  75. [self addObserver:self forKeyPath:NSStringFromSelector(@selector(selectedRange)) options:NSKeyValueObservingOptionNew context:CYRTextViewContext];
  76. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextViewDidChangeNotification:) name:UITextViewTextDidChangeNotification object:self];
  77. // Setup defaults
  78. self.font = [UIFont systemFontOfSize:16.0f];
  79. self.autocapitalizationType = UITextAutocapitalizationTypeNone;
  80. self.autocorrectionType = UITextAutocorrectionTypeNo;
  81. self.lineCursorEnabled = YES;
  82. self.gutterBackgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
  83. self.gutterLineColor = [UIColor lightGrayColor];
  84. // Inset the content to make room for line numbers
  85. self.textContainerInset = UIEdgeInsetsMake(8, self.lineNumberLayoutManager.gutterWidth, 8, 0);
  86. // Setup the gesture recognizers
  87. _singleFingerPanRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(singleFingerPanHappend:)];
  88. _singleFingerPanRecognizer.maximumNumberOfTouches = 1;
  89. [self addGestureRecognizer:_singleFingerPanRecognizer];
  90. _doubleFingerPanRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(doubleFingerPanHappend:)];
  91. _doubleFingerPanRecognizer.minimumNumberOfTouches = 2;
  92. [self addGestureRecognizer:_doubleFingerPanRecognizer];
  93. }
  94. #pragma mark - Cleanup
  95. - (void)dealloc
  96. {
  97. [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(font))];
  98. [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(selectedTextRange))];
  99. [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(selectedRange))];
  100. }
  101. #pragma mark - KVO
  102. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  103. {
  104. if ([keyPath isEqualToString:NSStringFromSelector(@selector(font))] && context == CYRTextViewContext)
  105. {
  106. // Whenever the UITextView font is changed we want to keep a reference in the stickyFont ivar. We do this to counteract a bug where the underlying font can be changed without notice and cause undesired behaviour.
  107. self.syntaxTextStorage.defaultFont = self.font;
  108. }
  109. else if (([keyPath isEqualToString:NSStringFromSelector(@selector(selectedTextRange))] ||
  110. [keyPath isEqualToString:NSStringFromSelector(@selector(selectedRange))]) && context == CYRTextViewContext)
  111. {
  112. [self setNeedsDisplay];
  113. }
  114. else
  115. {
  116. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  117. }
  118. }
  119. #pragma mark - Notifications
  120. - (void)handleTextViewDidChangeNotification:(NSNotification *)notification
  121. {
  122. if (notification.object == self)
  123. {
  124. CGRect line = [self caretRectForPosition: self.selectedTextRange.start];
  125. CGFloat overflow = line.origin.y + line.size.height - ( self.contentOffset.y + self.bounds.size.height - self.contentInset.bottom - self.contentInset.top );
  126. if ( overflow > 0 )
  127. {
  128. // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
  129. // Scroll caret to visible area
  130. CGPoint offset = self.contentOffset;
  131. offset.y += overflow + 7; // leave 7 pixels margin
  132. // Cannot animate with setContentOffset:animated: or caret will not appear
  133. // [UIView animateWithDuration:.2 animations:^{
  134. // [self setContentOffset:offset];
  135. // }];
  136. }
  137. }
  138. }
  139. #pragma mark - Overrides
  140. - (void)setTokens:(NSMutableArray *)tokens
  141. {
  142. [self.syntaxTextStorage setTokens:tokens];
  143. }
  144. - (NSArray *)tokens
  145. {
  146. CYRTextStorage *syntaxTextStorage = (CYRTextStorage *)self.textStorage;
  147. return syntaxTextStorage.tokens;
  148. }
  149. - (void)setText:(NSString *)text
  150. {
  151. UITextRange *textRange = [self textRangeFromPosition:self.beginningOfDocument toPosition:self.endOfDocument];
  152. [self replaceRange:textRange withText:text];
  153. }
  154. #pragma mark - Line Drawing
  155. // Original implementation sourced from: https://github.com/alldritt/TextKit_LineNumbers
  156. - (void)drawRect:(CGRect)rect
  157. {
  158. // Drag the line number gutter background. The line numbers them selves are drawn by LineNumberLayoutManager.
  159. CGContextRef context = UIGraphicsGetCurrentContext();
  160. CGRect bounds = self.bounds;
  161. CGFloat height = MAX(CGRectGetHeight(bounds), self.contentSize.height) + 200;
  162. // Set the regular fill
  163. CGContextSetFillColorWithColor(context, self.gutterBackgroundColor.CGColor);
  164. CGContextFillRect(context, CGRectMake(bounds.origin.x, bounds.origin.y, self.lineNumberLayoutManager.gutterWidth, height));
  165. // Draw line
  166. CGContextSetFillColorWithColor(context, self.gutterLineColor.CGColor);
  167. CGContextFillRect(context, CGRectMake(self.lineNumberLayoutManager.gutterWidth, bounds.origin.y, 0.5, height));
  168. if (_lineCursorEnabled)
  169. {
  170. self.lineNumberLayoutManager.selectedRange = self.selectedRange;
  171. NSRange glyphRange = [self.lineNumberLayoutManager.textStorage.string paragraphRangeForRange:self.selectedRange];
  172. glyphRange = [self.lineNumberLayoutManager glyphRangeForCharacterRange:glyphRange actualCharacterRange:NULL];
  173. self.lineNumberLayoutManager.selectedRange = glyphRange;
  174. [self.lineNumberLayoutManager invalidateDisplayForGlyphRange:glyphRange];
  175. }
  176. [super drawRect:rect];
  177. }
  178. #pragma mark - Gestures
  179. // Sourced from: https://github.com/srijs/NLTextView
  180. - (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
  181. {
  182. // Only accept horizontal pans for the code navigation to preserve correct scrolling behaviour.
  183. if (gestureRecognizer == _singleFingerPanRecognizer || gestureRecognizer == _doubleFingerPanRecognizer)
  184. {
  185. CGPoint translation = [gestureRecognizer translationInView:self];
  186. float translationX = (float)translation.x;
  187. float translationY = (float)translation.y;
  188. return fabsf(translationX) > fabsf(translationY);
  189. }
  190. return YES;
  191. }
  192. // Sourced from: https://github.com/srijs/NLTextView
  193. - (void)singleFingerPanHappend:(UIPanGestureRecognizer *)sender
  194. {
  195. if (sender.state == UIGestureRecognizerStateBegan)
  196. {
  197. startRange = self.selectedRange;
  198. }
  199. CGFloat cursorLocation = MAX(startRange.location + [sender translationInView:self].x * kCursorVelocity, 0);
  200. self.selectedRange = NSMakeRange(cursorLocation, 0);
  201. }
  202. // Sourced from: https://github.com/srijs/NLTextView
  203. - (void)doubleFingerPanHappend:(UIPanGestureRecognizer *)sender
  204. {
  205. if (sender.state == UIGestureRecognizerStateBegan)
  206. {
  207. startRange = self.selectedRange;
  208. }
  209. CGFloat cursorLocation = MAX(startRange.location + [sender translationInView:self].x * kCursorVelocity, 0);
  210. float location = startRange.location - cursorLocation;
  211. if (cursorLocation > startRange.location)
  212. {
  213. self.selectedRange = NSMakeRange(startRange.location, fabsf(location));
  214. }
  215. else
  216. {
  217. self.selectedRange = NSMakeRange(cursorLocation, fabsf(location));
  218. }
  219. }
  220. @end