RTLabel.m 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. //
  2. // RTLabel.m
  3. // RTLabelProject
  4. //
  5. /**
  6. * Copyright (c) 2010 Muh Hon Cheng
  7. * Created by honcheng on 1/6/11.
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining
  10. * a copy of this software and associated documentation files (the
  11. * "Software"), to deal in the Software without restriction, including
  12. * without limitation the rights to use, copy, modify, merge, publish,
  13. * distribute, sublicense, and/or sell copies of the Software, and to
  14. * permit persons to whom the Software is furnished to do so, subject
  15. * to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be
  18. * included in all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT
  21. * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  22. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. * MERCHANTABILITY, FITNESS FOR A PARTICULAR
  24. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  25. * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  28. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  29. * IN CONNECTION WITH THE SOFTWARE OR
  30. * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. *
  32. * @author Muh Hon Cheng <honcheng@gmail.com>
  33. * @copyright 2011 Muh Hon Cheng
  34. * @version
  35. *
  36. */
  37. #import "RTLabel.h"
  38. @interface RTLabelButton : UIButton
  39. @property (nonatomic, assign) long componentIndex;
  40. @property (nonatomic) NSURL *url;
  41. @end
  42. @implementation RTLabelButton
  43. @end
  44. @implementation RTLabelComponent
  45. - (id)initWithString:(NSString*)aText tag:(NSString*)aTagLabel attributes:(NSMutableDictionary*)theAttributes
  46. {
  47. self = [super init];
  48. if (self) {
  49. _text = aText;
  50. _tagLabel = aTagLabel;
  51. _attributes = theAttributes;
  52. }
  53. return self;
  54. }
  55. + (id)componentWithString:(NSString*)aText tag:(NSString*)aTagLabel attributes:(NSMutableDictionary*)theAttributes
  56. {
  57. return [[self alloc] initWithString:aText tag:aTagLabel attributes:theAttributes];
  58. }
  59. - (id)initWithTag:(NSString*)aTagLabel position:(int)aPosition attributes:(NSMutableDictionary*)theAttributes
  60. {
  61. self = [super init];
  62. if (self) {
  63. _tagLabel = aTagLabel;
  64. _position = aPosition;
  65. _attributes = theAttributes;
  66. }
  67. return self;
  68. }
  69. +(id)componentWithTag:(NSString*)aTagLabel position:(int)aPosition attributes:(NSMutableDictionary*)theAttributes
  70. {
  71. return [[self alloc] initWithTag:aTagLabel position:aPosition attributes:theAttributes];
  72. }
  73. - (NSString*)description
  74. {
  75. NSMutableString *desc = [NSMutableString string];
  76. [desc appendFormat:@"text: %@", self.text];
  77. [desc appendFormat:@", position: %li", self.position];
  78. if (self.tagLabel) [desc appendFormat:@", tag: %@", self.tagLabel];
  79. if (self.attributes) [desc appendFormat:@", attributes: %@", self.attributes];
  80. return desc;
  81. }
  82. @end
  83. @implementation RTLabelExtractedComponent
  84. + (RTLabelExtractedComponent*)rtLabelExtractComponentsWithTextComponent:(NSMutableArray*)textComponents plainText:(NSString*)plainText
  85. {
  86. RTLabelExtractedComponent *component = [[RTLabelExtractedComponent alloc] init];
  87. [component setTextComponents:textComponents];
  88. [component setPlainText:plainText];
  89. return component;
  90. }
  91. @end
  92. @interface RTLabel()
  93. - (CGFloat)frameHeight:(CTFrameRef)frame;
  94. - (NSArray *)components;
  95. - (void)parse:(NSString *)data valid_tags:(NSArray *)valid_tags;
  96. - (NSArray*) colorForHex:(NSString *)hexColor;
  97. - (void)render;
  98. #pragma mark -
  99. #pragma mark styling
  100. - (void)applyItalicStyleToText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  101. - (void)applyBoldStyleToText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  102. - (void)applyBoldItalicStyleToText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  103. - (void)applyColor:(NSString*)value toText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  104. - (void)applySingleUnderlineText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  105. - (void)applyDoubleUnderlineText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  106. - (void)applyUnderlineColor:(NSString*)value toText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  107. - (void)applyFontAttributes:(NSDictionary*)attributes toText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length;
  108. - (void)applyParagraphStyleToText:(CFMutableAttributedStringRef)text attributes:(NSMutableDictionary*)attributes atPosition:(long)position withLength:(long)length;
  109. @end
  110. @implementation RTLabel
  111. - (id)initWithFrame:(CGRect)_frame
  112. {
  113. self = [super initWithFrame:_frame];
  114. if (self)
  115. {
  116. [self initialize];
  117. }
  118. return self;
  119. }
  120. - (id)initWithCoder:(NSCoder *)aDecoder
  121. {
  122. self = [super initWithCoder:aDecoder];
  123. if (self)
  124. {
  125. [self initialize];
  126. }
  127. return self;
  128. }
  129. - (void)initialize
  130. {
  131. [self setBackgroundColor:[UIColor clearColor]];
  132. _font = [UIFont systemFontOfSize:17];
  133. _textColor = [UIColor blackColor];
  134. _text = @"";
  135. _textAlignment = RTTextAlignmentLeft;
  136. _lineBreakMode = RTTextLineBreakModeWordWrapping;
  137. _lineSpacing = 7;
  138. _currentSelectedButtonComponentIndex = -1;
  139. _paragraphReplacement = @"\n";
  140. [self setMultipleTouchEnabled:YES];
  141. }
  142. - (void)setTextAlignment:(RTTextAlignment)textAlignment
  143. {
  144. _textAlignment = textAlignment;
  145. [self setNeedsDisplay];
  146. }
  147. - (void)setLineBreakMode:(RTTextLineBreakMode)lineBreakMode
  148. {
  149. _lineBreakMode = lineBreakMode;
  150. [self setNeedsDisplay];
  151. }
  152. - (void)drawRect:(CGRect)rect
  153. {
  154. [self render];
  155. }
  156. - (void)render
  157. {
  158. if (self.currentSelectedButtonComponentIndex==-1)
  159. {
  160. for (id view in [self subviews])
  161. {
  162. if ([view isKindOfClass:[UIView class]])
  163. {
  164. [view removeFromSuperview];
  165. }
  166. }
  167. }
  168. if (!self.plainText) return;
  169. CGContextRef context = UIGraphicsGetCurrentContext();
  170. if (context != NULL)
  171. {
  172. // Drawing code.
  173. CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  174. CGAffineTransform flipVertical = CGAffineTransformMake(1,0,0,-1,0,self.frame.size.height);
  175. CGContextConcatCTM(context, flipVertical);
  176. }
  177. // Initialize an attributed string.
  178. CFStringRef string = (__bridge CFStringRef)self.plainText;
  179. CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
  180. CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), string);
  181. CFMutableDictionaryRef styleDict1 = ( CFDictionaryCreateMutable( (0), 0, (0), (0) ) );
  182. // Create a color and add it as an attribute to the string.
  183. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
  184. CGColorSpaceRelease(rgbColorSpace);
  185. CFDictionaryAddValue( styleDict1, kCTForegroundColorAttributeName, [self.textColor CGColor] );
  186. CFAttributedStringSetAttributes( attrString, CFRangeMake( 0, CFAttributedStringGetLength(attrString) ), styleDict1, 0 );
  187. CFMutableDictionaryRef styleDict = ( CFDictionaryCreateMutable( (0), 0, (0), (0) ) );
  188. [self applyParagraphStyleToText:attrString attributes:nil atPosition:0 withLength:CFAttributedStringGetLength(attrString)];
  189. CTFontRef thisFont = CTFontCreateWithName ((__bridge CFStringRef)[self.font fontName], [self.font pointSize], NULL);
  190. CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTFontAttributeName, thisFont);
  191. NSMutableArray *links = [NSMutableArray array];
  192. NSMutableArray *textComponents = nil;
  193. if (self.highlighted) textComponents = self.highlightedTextComponents;
  194. else textComponents = self.textComponents;
  195. for (RTLabelComponent *component in textComponents)
  196. {
  197. long index = [textComponents indexOfObject:component];
  198. component.componentIndex = index;
  199. if ([component.tagLabel caseInsensitiveCompare:@"i"] == NSOrderedSame)
  200. {
  201. // make font italic
  202. [self applyItalicStyleToText:attrString atPosition:component.position withLength:[component.text length]];
  203. }
  204. else if ([component.tagLabel caseInsensitiveCompare:@"b"] == NSOrderedSame)
  205. {
  206. // make font bold
  207. [self applyBoldStyleToText:attrString atPosition:component.position withLength:[component.text length]];
  208. }
  209. else if ([component.tagLabel caseInsensitiveCompare:@"bi"] == NSOrderedSame)
  210. {
  211. [self applyBoldItalicStyleToText:attrString atPosition:component.position withLength:[component.text length]];
  212. }
  213. else if ([component.tagLabel caseInsensitiveCompare:@"a"] == NSOrderedSame)
  214. {
  215. if (self.currentSelectedButtonComponentIndex==index)
  216. {
  217. if (self.selectedLinkAttributes)
  218. {
  219. [self applyFontAttributes:self.selectedLinkAttributes toText:attrString atPosition:component.position withLength:[component.text length]];
  220. }
  221. else
  222. {
  223. [self applyBoldStyleToText:attrString atPosition:component.position withLength:[component.text length]];
  224. [self applyColor:@"#FF0000" toText:attrString atPosition:component.position withLength:[component.text length]];
  225. }
  226. }
  227. else
  228. {
  229. if (self.linkAttributes)
  230. {
  231. [self applyFontAttributes:self.linkAttributes toText:attrString atPosition:component.position withLength:[component.text length]];
  232. }
  233. else
  234. {
  235. [self applyBoldStyleToText:attrString atPosition:component.position withLength:[component.text length]];
  236. [self applySingleUnderlineText:attrString atPosition:component.position withLength:[component.text length]];
  237. }
  238. }
  239. NSString *value = [component.attributes objectForKey:@"href"];
  240. value = [value stringByReplacingOccurrencesOfString:@"'" withString:@""];
  241. [component.attributes setObject:value forKey:@"href"];
  242. [links addObject:component];
  243. }
  244. else if ([component.tagLabel caseInsensitiveCompare:@"u"] == NSOrderedSame || [component.tagLabel caseInsensitiveCompare:@"uu"] == NSOrderedSame)
  245. {
  246. // underline
  247. if ([component.tagLabel caseInsensitiveCompare:@"u"] == NSOrderedSame)
  248. {
  249. [self applySingleUnderlineText:attrString atPosition:component.position withLength:[component.text length]];
  250. }
  251. else if ([component.tagLabel caseInsensitiveCompare:@"uu"] == NSOrderedSame)
  252. {
  253. [self applyDoubleUnderlineText:attrString atPosition:component.position withLength:[component.text length]];
  254. }
  255. if ([component.attributes objectForKey:@"color"])
  256. {
  257. NSString *value = [component.attributes objectForKey:@"color"];
  258. [self applyUnderlineColor:value toText:attrString atPosition:component.position withLength:[component.text length]];
  259. }
  260. }
  261. else if ([component.tagLabel caseInsensitiveCompare:@"font"] == NSOrderedSame)
  262. {
  263. [self applyFontAttributes:component.attributes toText:attrString atPosition:component.position withLength:[component.text length]];
  264. }
  265. else if ([component.tagLabel caseInsensitiveCompare:@"p"] == NSOrderedSame)
  266. {
  267. [self applyParagraphStyleToText:attrString attributes:component.attributes atPosition:component.position withLength:[component.text length]];
  268. }
  269. else if ([component.tagLabel caseInsensitiveCompare:@"center"] == NSOrderedSame)
  270. {
  271. [self applyCenterStyleToText:attrString attributes:component.attributes atPosition:component.position withLength:[component.text length]];
  272. }
  273. }
  274. // Create the framesetter with the attributed string.
  275. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
  276. CFRelease(attrString);
  277. // Initialize a rectangular path.
  278. CGMutablePathRef path = CGPathCreateMutable();
  279. CGRect bounds = CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height);
  280. CGPathAddRect(path, NULL, bounds);
  281. // Create the frame and draw it into the graphics context
  282. //CTFrameRef
  283. CTFrameRef frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0), path, NULL);
  284. CFRange range;
  285. CGSize constraint = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
  286. self.optimumSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [self.plainText length]), nil, constraint, &range);
  287. if (self.currentSelectedButtonComponentIndex==-1)
  288. {
  289. // only check for linkable items the first time, not when it's being redrawn on button pressed
  290. for (RTLabelComponent *linkableComponents in links)
  291. {
  292. float height = 0.0;
  293. CFArrayRef frameLines = CTFrameGetLines(frame);
  294. for (CFIndex i=0; i<CFArrayGetCount(frameLines); i++)
  295. {
  296. CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(frameLines, i);
  297. CFRange lineRange = CTLineGetStringRange(line);
  298. CGFloat ascent;
  299. CGFloat descent;
  300. CGFloat leading;
  301. CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
  302. CGPoint origin;
  303. CTFrameGetLineOrigins(frame, CFRangeMake(i, 1), &origin);
  304. if ( (linkableComponents.position<lineRange.location && linkableComponents.position+linkableComponents.text.length>(u_int16_t)(lineRange.location)) || (linkableComponents.position>=lineRange.location && linkableComponents.position<lineRange.location+lineRange.length))
  305. {
  306. CGFloat secondaryOffset;
  307. CGFloat primaryOffset = CTLineGetOffsetForStringIndex(CFArrayGetValueAtIndex(frameLines,i), linkableComponents.position, &secondaryOffset);
  308. CGFloat primaryOffset2 = CTLineGetOffsetForStringIndex(CFArrayGetValueAtIndex(frameLines,i), linkableComponents.position+linkableComponents.text.length, NULL);
  309. CGFloat button_width = primaryOffset2 - primaryOffset;
  310. RTLabelButton *button = [[RTLabelButton alloc] initWithFrame:CGRectMake(primaryOffset+origin.x, height, button_width, ascent+descent)];
  311. [button setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
  312. [button setComponentIndex:linkableComponents.componentIndex];
  313. [button setUrl:[NSURL URLWithString:[linkableComponents.attributes objectForKey:@"href"]]];
  314. [button addTarget:self action:@selector(onButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
  315. [button addTarget:self action:@selector(onButtonTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
  316. [button addTarget:self action:@selector(onButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
  317. [self addSubview:button];
  318. }
  319. origin.y = self.frame.size.height - origin.y;
  320. height = origin.y + descent + _lineSpacing;
  321. }
  322. }
  323. }
  324. self.visibleRange = CTFrameGetVisibleStringRange(frame);
  325. CFRelease(thisFont);
  326. CFRelease(path);
  327. CFRelease(styleDict1);
  328. CFRelease(styleDict);
  329. CFRelease(framesetter);
  330. CTFrameDraw(frame, context);
  331. CFRelease(frame);
  332. }
  333. #pragma mark -
  334. #pragma mark styling
  335. - (void)applyParagraphStyleToText:(CFMutableAttributedStringRef)text attributes:(NSMutableDictionary*)attributes atPosition:(long)position withLength:(long)length
  336. {
  337. CFMutableDictionaryRef styleDict = ( CFDictionaryCreateMutable( (0), 0, (0), (0) ) );
  338. // direction
  339. CTWritingDirection direction = kCTWritingDirectionLeftToRight;
  340. // leading
  341. CGFloat firstLineIndent = 0.0;
  342. CGFloat headIndent = 0.0;
  343. CGFloat tailIndent = 0.0;
  344. CGFloat lineHeightMultiple = 1.0;
  345. CGFloat maxLineHeight = 0;
  346. CGFloat minLineHeight = 0;
  347. CGFloat paragraphSpacing = 0.0;
  348. CGFloat paragraphSpacingBefore = 0.0;
  349. CTTextAlignment textAlignment = (CTTextAlignment)_textAlignment;
  350. CTLineBreakMode lineBreakMode = (CTLineBreakMode)_lineBreakMode;
  351. CGFloat lineSpacing = _lineSpacing;
  352. for (NSUInteger i=0; i<[[attributes allKeys] count]; i++)
  353. {
  354. NSString *key = [[attributes allKeys] objectAtIndex:i];
  355. id value = [attributes objectForKey:key];
  356. if ([key caseInsensitiveCompare:@"align"] == NSOrderedSame)
  357. {
  358. if ([value caseInsensitiveCompare:@"left"] == NSOrderedSame)
  359. {
  360. textAlignment = kCTLeftTextAlignment;
  361. }
  362. else if ([value caseInsensitiveCompare:@"right"] == NSOrderedSame)
  363. {
  364. textAlignment = kCTRightTextAlignment;
  365. }
  366. else if ([value caseInsensitiveCompare:@"justify"] == NSOrderedSame)
  367. {
  368. textAlignment = kCTJustifiedTextAlignment;
  369. }
  370. else if ([value caseInsensitiveCompare:@"center"] == NSOrderedSame)
  371. {
  372. textAlignment = kCTCenterTextAlignment;
  373. }
  374. }
  375. else if ([key caseInsensitiveCompare:@"indent"] == NSOrderedSame)
  376. {
  377. firstLineIndent = [value floatValue];
  378. }
  379. else if ([key caseInsensitiveCompare:@"linebreakmode"] == NSOrderedSame)
  380. {
  381. if ([value caseInsensitiveCompare:@"wordwrap"] == NSOrderedSame)
  382. {
  383. lineBreakMode = kCTLineBreakByWordWrapping;
  384. }
  385. else if ([value caseInsensitiveCompare:@"charwrap"] == NSOrderedSame)
  386. {
  387. lineBreakMode = kCTLineBreakByCharWrapping;
  388. }
  389. else if ([value caseInsensitiveCompare:@"clipping"] == NSOrderedSame)
  390. {
  391. lineBreakMode = kCTLineBreakByClipping;
  392. }
  393. else if ([value caseInsensitiveCompare:@"truncatinghead"] == NSOrderedSame)
  394. {
  395. lineBreakMode = kCTLineBreakByTruncatingHead;
  396. }
  397. else if ([value caseInsensitiveCompare:@"truncatingtail"] == NSOrderedSame)
  398. {
  399. lineBreakMode = kCTLineBreakByTruncatingTail;
  400. }
  401. else if ([value caseInsensitiveCompare:@"truncatingmiddle"] == NSOrderedSame)
  402. {
  403. lineBreakMode = kCTLineBreakByTruncatingMiddle;
  404. }
  405. }
  406. }
  407. CTParagraphStyleSetting theSettings[] =
  408. {
  409. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &textAlignment },
  410. { kCTParagraphStyleSpecifierLineBreakMode, sizeof(CTLineBreakMode), &lineBreakMode },
  411. { kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(CTWritingDirection), &direction },
  412. { kCTParagraphStyleSpecifierMinimumLineSpacing, sizeof(CGFloat), &lineSpacing }, // leading
  413. { kCTParagraphStyleSpecifierMaximumLineSpacing, sizeof(CGFloat), &lineSpacing }, // leading
  414. { kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(CGFloat), &firstLineIndent },
  415. { kCTParagraphStyleSpecifierHeadIndent, sizeof(CGFloat), &headIndent },
  416. { kCTParagraphStyleSpecifierTailIndent, sizeof(CGFloat), &tailIndent },
  417. { kCTParagraphStyleSpecifierLineHeightMultiple, sizeof(CGFloat), &lineHeightMultiple },
  418. { kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(CGFloat), &maxLineHeight },
  419. { kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(CGFloat), &minLineHeight },
  420. { kCTParagraphStyleSpecifierParagraphSpacing, sizeof(CGFloat), &paragraphSpacing },
  421. { kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), &paragraphSpacingBefore }
  422. };
  423. CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, sizeof(theSettings) / sizeof(CTParagraphStyleSetting));
  424. CFDictionaryAddValue( styleDict, kCTParagraphStyleAttributeName, theParagraphRef );
  425. CFAttributedStringSetAttributes( text, CFRangeMake(position, length), styleDict, 0 );
  426. CFRelease(theParagraphRef);
  427. CFRelease(styleDict);
  428. }
  429. - (void)applyCenterStyleToText:(CFMutableAttributedStringRef)text attributes:(NSMutableDictionary*)attributes atPosition:(long)position withLength:(long)length
  430. {
  431. CFMutableDictionaryRef styleDict = ( CFDictionaryCreateMutable( (0), 0, (0), (0) ) );
  432. // direction
  433. CTWritingDirection direction = kCTWritingDirectionLeftToRight;
  434. // leading
  435. CGFloat firstLineIndent = 0.0;
  436. CGFloat headIndent = 0.0;
  437. CGFloat tailIndent = 0.0;
  438. CGFloat lineHeightMultiple = 1.0;
  439. CGFloat maxLineHeight = 0;
  440. CGFloat minLineHeight = 0;
  441. CGFloat paragraphSpacing = 0.0;
  442. CGFloat paragraphSpacingBefore = 0.0;
  443. int textAlignment = _textAlignment;
  444. int lineBreakMode = _lineBreakMode;
  445. int lineSpacing = (int)_lineSpacing;
  446. textAlignment = kCTCenterTextAlignment;
  447. CTParagraphStyleSetting theSettings[] =
  448. {
  449. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &textAlignment },
  450. { kCTParagraphStyleSpecifierLineBreakMode, sizeof(CTLineBreakMode), &lineBreakMode },
  451. { kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(CTWritingDirection), &direction },
  452. { kCTParagraphStyleSpecifierLineSpacing, sizeof(CGFloat), &lineSpacing },
  453. { kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(CGFloat), &firstLineIndent },
  454. { kCTParagraphStyleSpecifierHeadIndent, sizeof(CGFloat), &headIndent },
  455. { kCTParagraphStyleSpecifierTailIndent, sizeof(CGFloat), &tailIndent },
  456. { kCTParagraphStyleSpecifierLineHeightMultiple, sizeof(CGFloat), &lineHeightMultiple },
  457. { kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(CGFloat), &maxLineHeight },
  458. { kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(CGFloat), &minLineHeight },
  459. { kCTParagraphStyleSpecifierParagraphSpacing, sizeof(CGFloat), &paragraphSpacing },
  460. { kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), &paragraphSpacingBefore }
  461. };
  462. CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, sizeof(theSettings) / sizeof(CTParagraphStyleSetting));
  463. CFDictionaryAddValue( styleDict, kCTParagraphStyleAttributeName, theParagraphRef );
  464. CFAttributedStringSetAttributes( text, CFRangeMake(position, length), styleDict, 0 );
  465. CFRelease(theParagraphRef);
  466. CFRelease(styleDict);
  467. }
  468. - (void)applySingleUnderlineText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  469. {
  470. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTUnderlineStyleAttributeName, (__bridge CFNumberRef)[NSNumber numberWithInt:kCTUnderlineStyleSingle]);
  471. }
  472. - (void)applyDoubleUnderlineText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  473. {
  474. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTUnderlineStyleAttributeName, (__bridge CFNumberRef)[NSNumber numberWithInt:kCTUnderlineStyleDouble]);
  475. }
  476. - (void)applyItalicStyleToText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  477. {
  478. CFTypeRef actualFontRef = CFAttributedStringGetAttribute(text, position, kCTFontAttributeName, NULL);
  479. CTFontRef italicFontRef = CTFontCreateCopyWithSymbolicTraits(actualFontRef, 0.0, NULL, kCTFontItalicTrait, kCTFontItalicTrait);
  480. if (!italicFontRef) {
  481. //fallback to system italic font
  482. UIFont *font = [UIFont italicSystemFontOfSize:CTFontGetSize(actualFontRef)];
  483. italicFontRef = CTFontCreateWithName ((__bridge CFStringRef)[font fontName], [font pointSize], NULL);
  484. }
  485. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTFontAttributeName, italicFontRef);
  486. CFRelease(italicFontRef);
  487. }
  488. - (void)applyFontAttributes:(NSDictionary*)attributes toText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  489. {
  490. for (NSString *key in attributes)
  491. {
  492. NSString *value = [attributes objectForKey:key];
  493. value = [value stringByReplacingOccurrencesOfString:@"'" withString:@""];
  494. if ([key caseInsensitiveCompare:@"color"] == NSOrderedSame)
  495. {
  496. [self applyColor:value toText:text atPosition:position withLength:length];
  497. }
  498. else if ([key caseInsensitiveCompare:@"stroke"] == NSOrderedSame)
  499. {
  500. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTStrokeWidthAttributeName, (__bridge CFTypeRef)([NSNumber numberWithFloat:[[attributes objectForKey:@"stroke"] intValue]]));
  501. }
  502. else if ([key caseInsensitiveCompare:@"kern"] == NSOrderedSame)
  503. {
  504. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTKernAttributeName, (__bridge CFTypeRef)([NSNumber numberWithFloat:[[attributes objectForKey:@"kern"] intValue]]));
  505. }
  506. else if ([key caseInsensitiveCompare:@"underline"] == NSOrderedSame)
  507. {
  508. int numberOfLines = [value intValue];
  509. if (numberOfLines==1)
  510. {
  511. [self applySingleUnderlineText:text atPosition:position withLength:length];
  512. }
  513. else if (numberOfLines==2)
  514. {
  515. [self applyDoubleUnderlineText:text atPosition:position withLength:length];
  516. }
  517. }
  518. else if ([key caseInsensitiveCompare:@"style"] == NSOrderedSame)
  519. {
  520. if ([value caseInsensitiveCompare:@"bold"] == NSOrderedSame)
  521. {
  522. [self applyBoldStyleToText:text atPosition:position withLength:length];
  523. }
  524. else if ([value caseInsensitiveCompare:@"italic"] == NSOrderedSame)
  525. {
  526. [self applyItalicStyleToText:text atPosition:position withLength:length];
  527. }
  528. }
  529. }
  530. UIFont *font = nil;
  531. if ([attributes objectForKey:@"face"] && [attributes objectForKey:@"size"])
  532. {
  533. NSString *fontName = [attributes objectForKey:@"face"];
  534. fontName = [fontName stringByReplacingOccurrencesOfString:@"'" withString:@""];
  535. font = [UIFont fontWithName:fontName size:[[attributes objectForKey:@"size"] intValue]];
  536. }
  537. else if ([attributes objectForKey:@"face"] && ![attributes objectForKey:@"size"])
  538. {
  539. NSString *fontName = [attributes objectForKey:@"face"];
  540. fontName = [fontName stringByReplacingOccurrencesOfString:@"'" withString:@""];
  541. font = [UIFont fontWithName:fontName size:self.font.pointSize];
  542. }
  543. else if (![attributes objectForKey:@"face"] && [attributes objectForKey:@"size"])
  544. {
  545. font = [UIFont fontWithName:[self.font fontName] size:[[attributes objectForKey:@"size"] intValue]];
  546. }
  547. if (font)
  548. {
  549. CTFontRef customFont = CTFontCreateWithName ((__bridge CFStringRef)[font fontName], [font pointSize], NULL);
  550. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTFontAttributeName, customFont);
  551. CFRelease(customFont);
  552. }
  553. }
  554. - (void)applyBoldStyleToText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  555. {
  556. CFTypeRef actualFontRef = CFAttributedStringGetAttribute(text, position, kCTFontAttributeName, NULL);
  557. CTFontRef boldFontRef = CTFontCreateCopyWithSymbolicTraits(actualFontRef, 0.0, NULL, kCTFontBoldTrait, kCTFontBoldTrait);
  558. if (!boldFontRef) {
  559. //fallback to system bold font
  560. UIFont *font = [UIFont boldSystemFontOfSize:CTFontGetSize(actualFontRef)];
  561. boldFontRef = CTFontCreateWithName ((__bridge CFStringRef)[font fontName], [font pointSize], NULL);
  562. }
  563. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTFontAttributeName, boldFontRef);
  564. CFRelease(boldFontRef);
  565. }
  566. - (void)applyBoldItalicStyleToText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  567. {
  568. CFTypeRef actualFontRef = CFAttributedStringGetAttribute(text, position, kCTFontAttributeName, NULL);
  569. CTFontRef boldItalicFontRef = CTFontCreateCopyWithSymbolicTraits(actualFontRef, 0.0, NULL, kCTFontBoldTrait | kCTFontItalicTrait , kCTFontBoldTrait | kCTFontItalicTrait);
  570. if (!boldItalicFontRef) {
  571. //try fallback to system boldItalic font
  572. NSString *fontName = [NSString stringWithFormat:@"%@-BoldOblique", self.font.fontName];
  573. boldItalicFontRef = CTFontCreateWithName ((__bridge CFStringRef)fontName, [self.font pointSize], NULL);
  574. }
  575. if (boldItalicFontRef) {
  576. CFAttributedStringSetAttribute(text, CFRangeMake(position, length), kCTFontAttributeName, boldItalicFontRef);
  577. CFRelease(boldItalicFontRef);
  578. }
  579. }
  580. - (void)applyColor:(NSString*)value toText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  581. {
  582. if ([value rangeOfString:@"#"].location==0)
  583. {
  584. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
  585. value = [value stringByReplacingOccurrencesOfString:@"#" withString:@""];
  586. NSArray *colorComponents = [self colorForHex:value];
  587. CGFloat components[] = { [[colorComponents objectAtIndex:0] floatValue] , [[colorComponents objectAtIndex:1] floatValue] , [[colorComponents objectAtIndex:2] floatValue] , [[colorComponents objectAtIndex:3] floatValue] };
  588. CGColorRef color = CGColorCreate(rgbColorSpace, components);
  589. CFAttributedStringSetAttribute(text, CFRangeMake(position, length),kCTForegroundColorAttributeName, color);
  590. CFRelease(color);
  591. CGColorSpaceRelease(rgbColorSpace);
  592. } else {
  593. value = [value stringByAppendingString:@"Color"];
  594. SEL colorSel = NSSelectorFromString(value);
  595. UIColor *_color = nil;
  596. if ([UIColor respondsToSelector:colorSel]) {
  597. _color = [UIColor performSelector:colorSel];
  598. CGColorRef color = [_color CGColor];
  599. CFAttributedStringSetAttribute(text, CFRangeMake(position, length),kCTForegroundColorAttributeName, color);
  600. }
  601. }
  602. }
  603. - (void)applyUnderlineColor:(NSString*)value toText:(CFMutableAttributedStringRef)text atPosition:(long)position withLength:(long)length
  604. {
  605. value = [value stringByReplacingOccurrencesOfString:@"'" withString:@""];
  606. if ([value rangeOfString:@"#"].location==0) {
  607. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
  608. value = [value stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
  609. NSArray *colorComponents = [self colorForHex:value];
  610. CGFloat components[] = { [[colorComponents objectAtIndex:0] floatValue] , [[colorComponents objectAtIndex:1] floatValue] , [[colorComponents objectAtIndex:2] floatValue] , [[colorComponents objectAtIndex:3] floatValue] };
  611. CGColorRef color = CGColorCreate(rgbColorSpace, components);
  612. CFAttributedStringSetAttribute(text, CFRangeMake(position, length),kCTUnderlineColorAttributeName, color);
  613. CGColorRelease(color);
  614. CGColorSpaceRelease(rgbColorSpace);
  615. }
  616. else
  617. {
  618. value = [value stringByAppendingString:@"Color"];
  619. SEL colorSel = NSSelectorFromString(value);
  620. if ([UIColor respondsToSelector:colorSel]) {
  621. UIColor *_color = [UIColor performSelector:colorSel];
  622. CGColorRef color = [_color CGColor];
  623. CFAttributedStringSetAttribute(text, CFRangeMake(position, length),kCTUnderlineColorAttributeName, color);
  624. //CGColorRelease(color);
  625. }
  626. }
  627. }
  628. #pragma mark -
  629. #pragma mark button
  630. - (void)onButtonTouchDown:(id)sender
  631. {
  632. RTLabelButton *button = (RTLabelButton*)sender;
  633. [self setCurrentSelectedButtonComponentIndex:button.componentIndex];
  634. [self setNeedsDisplay];
  635. }
  636. - (void)onButtonTouchUpOutside:(id)sender
  637. {
  638. [self setCurrentSelectedButtonComponentIndex:-1];
  639. [self setNeedsDisplay];
  640. }
  641. - (void)onButtonPressed:(id)sender
  642. {
  643. RTLabelButton *button = (RTLabelButton*)sender;
  644. [self setCurrentSelectedButtonComponentIndex:-1];
  645. [self setNeedsDisplay];
  646. if ([self.delegate respondsToSelector:@selector(rtLabel:didSelectLinkWithURL:)])
  647. {
  648. [self.delegate rtLabel:self didSelectLinkWithURL:button.url];
  649. }
  650. }
  651. - (CGSize)optimumSize
  652. {
  653. [self render];
  654. return _optimumSize;
  655. }
  656. - (void)setLineSpacing:(CGFloat)lineSpacing
  657. {
  658. _lineSpacing = lineSpacing;
  659. [self setNeedsDisplay];
  660. }
  661. - (void)setHighlighted:(BOOL)highlighted
  662. {
  663. if (highlighted!=_highlighted)
  664. {
  665. _highlighted = highlighted;
  666. [self setNeedsDisplay];
  667. }
  668. }
  669. - (void)setHighlightedText:(NSString *)text
  670. {
  671. _highlightedText = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
  672. RTLabelExtractedComponent *component = [RTLabel extractTextStyleFromText:_highlightedText paragraphReplacement:self.paragraphReplacement];
  673. [self setHighlightedTextComponents:component.textComponents];
  674. }
  675. - (void)setText:(NSString *)text
  676. {
  677. _text = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
  678. RTLabelExtractedComponent *component = [RTLabel extractTextStyleFromText:_text paragraphReplacement:self.paragraphReplacement];
  679. [self setTextComponents:component.textComponents];
  680. [self setPlainText:component.plainText];
  681. [self setNeedsDisplay];
  682. }
  683. - (void)setText:(NSString *)text extractedTextComponent:(RTLabelExtractedComponent*)extractedComponent
  684. {
  685. _text = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
  686. [self setTextComponents:extractedComponent.textComponents];
  687. [self setPlainText:extractedComponent.plainText];
  688. [self setNeedsDisplay];
  689. }
  690. - (void)setHighlightedText:(NSString *)text extractedTextComponent:(RTLabelExtractedComponent*)extractedComponent
  691. {
  692. _highlightedText = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
  693. [self setHighlightedTextComponents:extractedComponent.textComponents];
  694. }
  695. // http://forums.macrumors.com/showthread.php?t=925312
  696. // not accurate
  697. - (CGFloat)frameHeight:(CTFrameRef)theFrame
  698. {
  699. CFArrayRef lines = CTFrameGetLines(theFrame);
  700. CGFloat height = 0.0;
  701. CGFloat ascent, descent, leading;
  702. for (CFIndex index = 0; index < CFArrayGetCount(lines); index++) {
  703. CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(lines, index);
  704. CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
  705. height += (ascent + fabs(descent) + leading);
  706. }
  707. return ceilf(height);
  708. }
  709. - (void)dealloc
  710. {
  711. self.delegate = nil;
  712. }
  713. - (NSArray *)components
  714. {
  715. NSScanner *scanner = [NSScanner scannerWithString:self.text];
  716. [scanner setCharactersToBeSkipped:nil];
  717. NSMutableArray *components = [NSMutableArray array];
  718. while (![scanner isAtEnd])
  719. {
  720. NSString *currentComponent;
  721. BOOL foundComponent = [scanner scanUpToString:@"http" intoString:&currentComponent];
  722. if (foundComponent)
  723. {
  724. [components addObject:currentComponent];
  725. NSString *string;
  726. BOOL foundURLComponent = [scanner scanUpToString:@" " intoString:&string];
  727. if (foundURLComponent)
  728. {
  729. // if last character of URL is punctuation, its probably not part of the URL
  730. NSCharacterSet *punctuationSet = [NSCharacterSet punctuationCharacterSet];
  731. NSInteger lastCharacterIndex = string.length - 1;
  732. if ([punctuationSet characterIsMember:[string characterAtIndex:lastCharacterIndex]])
  733. {
  734. // remove the punctuation from the URL string and move the scanner back
  735. string = [string substringToIndex:lastCharacterIndex];
  736. [scanner setScanLocation:scanner.scanLocation - 1];
  737. }
  738. [components addObject:string];
  739. }
  740. }
  741. else
  742. { // first string is a link
  743. NSString *string;
  744. BOOL foundURLComponent = [scanner scanUpToString:@" " intoString:&string];
  745. if (foundURLComponent)
  746. {
  747. [components addObject:string];
  748. }
  749. }
  750. }
  751. return [components copy];
  752. }
  753. + (RTLabelExtractedComponent*)extractTextStyleFromText:(NSString*)data paragraphReplacement:(NSString*)paragraphReplacement
  754. {
  755. NSScanner *scanner = nil;
  756. NSString *text = nil;
  757. NSString *tag = nil;
  758. NSMutableArray *components = [NSMutableArray array];
  759. long last_position = 0;
  760. scanner = [NSScanner scannerWithString:data];
  761. while (![scanner isAtEnd])
  762. {
  763. [scanner scanUpToString:@"<" intoString:NULL];
  764. [scanner scanUpToString:@">" intoString:&text];
  765. NSString *delimiter = [NSString stringWithFormat:@"%@>", text];
  766. NSRange range =[data rangeOfString:delimiter];
  767. NSUInteger position = range.location;
  768. if (position!=NSNotFound)
  769. {
  770. if ([delimiter rangeOfString:@"<p"].location==0)
  771. {
  772. data = [data stringByReplacingOccurrencesOfString:delimiter withString:paragraphReplacement options:NSCaseInsensitiveSearch range:NSMakeRange(last_position, position+delimiter.length-last_position)];
  773. }
  774. else
  775. {
  776. data = [data stringByReplacingOccurrencesOfString:delimiter withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(last_position, position+delimiter.length-last_position)];
  777. }
  778. data = [data stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
  779. data = [data stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
  780. }
  781. if ([text rangeOfString:@"</"].location==0)
  782. {
  783. // end of tag
  784. tag = [text substringFromIndex:2];
  785. if (position!=NSNotFound)
  786. {
  787. for (long i=[components count]-1; i>=0; i--)
  788. {
  789. RTLabelComponent *component = [components objectAtIndex:i];
  790. if (component.text==nil && [component.tagLabel isEqualToString:tag])
  791. {
  792. NSString *text2 = [data substringWithRange:NSMakeRange(component.position, position-component.position)];
  793. component.text = text2;
  794. break;
  795. }
  796. }
  797. }
  798. }
  799. else
  800. {
  801. // start of tag
  802. NSArray *textComponents = [[text substringFromIndex:1] componentsSeparatedByString:@" "];
  803. tag = [textComponents objectAtIndex:0];
  804. NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
  805. for (NSUInteger i=1; i<[textComponents count]; i++)
  806. {
  807. NSArray *pair = [[textComponents objectAtIndex:i] componentsSeparatedByString:@"="];
  808. if ([pair count] > 0) {
  809. NSString *key = [[pair objectAtIndex:0] lowercaseString];
  810. if ([pair count]>=2) {
  811. // Trim " charactere
  812. NSString *value = [[pair subarrayWithRange:NSMakeRange(1, [pair count] - 1)] componentsJoinedByString:@"="];
  813. value = [value stringByReplacingOccurrencesOfString:@"\"" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, 1)];
  814. value = [value stringByReplacingOccurrencesOfString:@"\"" withString:@"" options:NSLiteralSearch range:NSMakeRange([value length]-1, 1)];
  815. [attributes setObject:value forKey:key];
  816. } else if ([pair count]==1) {
  817. [attributes setObject:key forKey:key];
  818. }
  819. }
  820. }
  821. RTLabelComponent *component = [RTLabelComponent componentWithString:nil tag:tag attributes:attributes];
  822. component.position = position;
  823. [components addObject:component];
  824. }
  825. last_position = position;
  826. }
  827. return [RTLabelExtractedComponent rtLabelExtractComponentsWithTextComponent:components plainText:data];
  828. }
  829. - (void)parse:(NSString *)data valid_tags:(NSArray *)valid_tags
  830. {
  831. //use to strip the HTML tags from the data
  832. NSScanner *scanner = nil;
  833. NSString *text = nil;
  834. NSString *tag = nil;
  835. NSMutableArray *components = [NSMutableArray array];
  836. //set up the scanner
  837. scanner = [NSScanner scannerWithString:data];
  838. NSMutableDictionary *lastAttributes = nil;
  839. NSUInteger last_position = 0;
  840. while([scanner isAtEnd] == NO)
  841. {
  842. //find start of tag
  843. [scanner scanUpToString:@"<" intoString:NULL];
  844. //find end of tag
  845. [scanner scanUpToString:@">" intoString:&text];
  846. NSMutableDictionary *attributes = nil;
  847. //get the name of the tag
  848. if([text rangeOfString:@"</"].location != NSNotFound)
  849. tag = [text substringFromIndex:2]; //remove </
  850. else
  851. {
  852. tag = [text substringFromIndex:1]; //remove <
  853. //find out if there is a space in the tag
  854. if([tag rangeOfString:@" "].location != NSNotFound)
  855. {
  856. attributes = [NSMutableDictionary dictionary];
  857. NSArray *rawAttributes = [tag componentsSeparatedByString:@" "];
  858. for (NSUInteger i=1; i<[rawAttributes count]; i++)
  859. {
  860. NSArray *pair = [[rawAttributes objectAtIndex:i] componentsSeparatedByString:@"="];
  861. if ([pair count]==2)
  862. {
  863. [attributes setObject:[pair objectAtIndex:1] forKey:[pair objectAtIndex:0]];
  864. }
  865. }
  866. //remove text after a space
  867. tag = [tag substringToIndex:[tag rangeOfString:@" "].location];
  868. }
  869. }
  870. //if not a valid tag, replace the tag with a space
  871. if([valid_tags containsObject:tag] == NO)
  872. {
  873. NSString *delimiter = [NSString stringWithFormat:@"%@>", text];
  874. NSUInteger position = [data rangeOfString:delimiter].location;
  875. BOOL isEnd = [delimiter rangeOfString:@"</"].location!=NSNotFound;
  876. if (position!=NSNotFound)
  877. {
  878. NSString *text2 = [data substringWithRange:NSMakeRange(last_position, position-last_position)];
  879. if (isEnd)
  880. {
  881. // is inside a tag
  882. [components addObject:[RTLabelComponent componentWithString:text2 tag:tag attributes:lastAttributes]];
  883. }
  884. else
  885. {
  886. // is outside a tag
  887. [components addObject:[RTLabelComponent componentWithString:text2 tag:nil attributes:lastAttributes]];
  888. }
  889. data = [data stringByReplacingOccurrencesOfString:delimiter withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(last_position, position+delimiter.length-last_position)];
  890. last_position = position;
  891. }
  892. else
  893. {
  894. NSString *text2 = [data substringFromIndex:last_position];
  895. // is outside a tag
  896. [components addObject:[RTLabelComponent componentWithString:text2 tag:nil attributes:lastAttributes]];
  897. }
  898. lastAttributes = attributes;
  899. }
  900. }
  901. [self setTextComponents:components];
  902. [self setPlainText:data];
  903. }
  904. - (NSArray*)colorForHex:(NSString *)hexColor
  905. {
  906. hexColor = [[hexColor stringByTrimmingCharactersInSet:
  907. [NSCharacterSet whitespaceAndNewlineCharacterSet]
  908. ] uppercaseString];
  909. NSRange range;
  910. range.location = 0;
  911. range.length = 2;
  912. NSString *rString = [hexColor substringWithRange:range];
  913. range.location = 2;
  914. NSString *gString = [hexColor substringWithRange:range];
  915. range.location = 4;
  916. NSString *bString = [hexColor substringWithRange:range];
  917. // Scan values
  918. unsigned int r, g, b;
  919. [[NSScanner scannerWithString:rString] scanHexInt:&r];
  920. [[NSScanner scannerWithString:gString] scanHexInt:&g];
  921. [[NSScanner scannerWithString:bString] scanHexInt:&b];
  922. NSArray *components = [NSArray arrayWithObjects:[NSNumber numberWithFloat:((float) r / 255.0f)],[NSNumber numberWithFloat:((float) g / 255.0f)],[NSNumber numberWithFloat:((float) b / 255.0f)],[NSNumber numberWithFloat:1.0],nil];
  923. return components;
  924. }
  925. - (NSString*)visibleText
  926. {
  927. [self render];
  928. NSString *text = [self.text substringWithRange:NSMakeRange(self.visibleRange.location, self.visibleRange.length)];
  929. return text;
  930. }
  931. #pragma mark deprecated methods
  932. - (void)setText:(NSString *)text extractedTextStyle:(NSDictionary*)extractTextStyle
  933. {
  934. _text = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
  935. [self setTextComponents:[extractTextStyle objectForKey:@"textComponents"]];
  936. [self setPlainText:[extractTextStyle objectForKey:@"plainText"]];
  937. [self setNeedsDisplay];
  938. }
  939. + (NSDictionary*)preExtractTextStyle:(NSString*)data
  940. {
  941. NSString* paragraphReplacement = @"\n";
  942. RTLabelExtractedComponent *component = [RTLabel extractTextStyleFromText:data paragraphReplacement:paragraphReplacement];
  943. return [NSDictionary dictionaryWithObjectsAndKeys:component.textComponents, @"textComponents", component.plainText, @"plainText", nil];
  944. }
  945. @end