// // ZFont.m // FontLabel // // Created by Kevin Ballard on 7/2/09. // Copyright © 2009 Zynga Game Networks // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "ZFont.h" @interface ZFont () @property (nonatomic, readonly) CGFloat ratio; - (NSString *)copyNameTableEntryForID:(UInt16)nameID; @end @implementation ZFont @synthesize cgFont=_cgFont, pointSize=_pointSize, ratio=_ratio; + (ZFont *)fontWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize { return [[[self alloc] initWithCGFont:cgFont size:fontSize] autorelease]; } + (ZFont *)fontWithUIFont:(UIFont *)uiFont { NSParameterAssert(uiFont != nil); CGFontRef cgFont = CGFontCreateWithFontName((CFStringRef)uiFont.fontName); ZFont *zFont = [[self alloc] initWithCGFont:cgFont size:uiFont.pointSize]; CGFontRelease(cgFont); return [zFont autorelease]; } - (id)initWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize { if ((self = [super init])) { _cgFont = CGFontRetain(cgFont); _pointSize = fontSize; _ratio = fontSize/CGFontGetUnitsPerEm(cgFont); } return self; } - (id)init { NSAssert(NO, @"-init is not valid for ZFont"); return nil; } - (CGFloat)ascender { return ceilf(self.ratio * CGFontGetAscent(self.cgFont)); } - (CGFloat)descender { return floorf(self.ratio * CGFontGetDescent(self.cgFont)); } - (CGFloat)leading { return (self.ascender - self.descender); } - (CGFloat)capHeight { return ceilf(self.ratio * CGFontGetCapHeight(self.cgFont)); } - (CGFloat)xHeight { return ceilf(self.ratio * CGFontGetXHeight(self.cgFont)); } - (NSString *)familyName { if (_familyName == nil) { _familyName = [self copyNameTableEntryForID:1]; } return _familyName; } - (NSString *)fontName { if (_fontName == nil) { _fontName = [self copyNameTableEntryForID:4]; } return _fontName; } - (NSString *)postScriptName { if (_postScriptName == nil) { _postScriptName = [self copyNameTableEntryForID:6]; } return _postScriptName; } - (ZFont *)fontWithSize:(CGFloat)fontSize { if (fontSize == self.pointSize) return self; NSParameterAssert(fontSize > 0.0); return [[[ZFont alloc] initWithCGFont:self.cgFont size:fontSize] autorelease]; } - (BOOL)isEqual:(id)object { if (![object isKindOfClass:[ZFont class]]) return NO; ZFont *font = (ZFont *)object; return (font.cgFont == self.cgFont && font.pointSize == self.pointSize); } - (NSString *)copyNameTableEntryForID:(UInt16)aNameID { CFDataRef nameTable = CGFontCopyTableForTag(self.cgFont, 'name'); NSAssert1(nameTable != NULL, @"CGFontCopyTableForTag returned NULL for 'name' tag in font %@", [(id)CFCopyDescription(self.cgFont) autorelease]); const UInt8 * const bytes = CFDataGetBytePtr(nameTable); NSAssert1(OSReadBigInt16(bytes, 0) == 0, @"name table for font %@ has bad version number", [(id)CFCopyDescription(self.cgFont) autorelease]); const UInt16 count = OSReadBigInt16(bytes, 2); const UInt16 stringOffset = OSReadBigInt16(bytes, 4); const UInt8 * const nameRecords = &bytes[6]; UInt16 nameLength = 0; UInt16 nameOffset = 0; NSStringEncoding encoding = 0; for (UInt16 idx = 0; idx < count; idx++) { const uintptr_t recordOffset = 12 * idx; const UInt16 nameID = OSReadBigInt16(nameRecords, recordOffset + 6); if (nameID != aNameID) continue; const UInt16 platformID = OSReadBigInt16(nameRecords, recordOffset + 0); const UInt16 platformSpecificID = OSReadBigInt16(nameRecords, recordOffset + 2); encoding = 0; // for now, we only support a subset of encodings switch (platformID) { case 0: // Unicode encoding = NSUTF16StringEncoding; break; case 1: // Macintosh switch (platformSpecificID) { case 0: encoding = NSMacOSRomanStringEncoding; break; } case 3: // Microsoft switch (platformSpecificID) { case 1: encoding = NSUTF16StringEncoding; break; } } if (encoding == 0) continue; nameLength = OSReadBigInt16(nameRecords, recordOffset + 8); nameOffset = OSReadBigInt16(nameRecords, recordOffset + 10); break; } NSString *result = nil; if (nameOffset > 0) { const UInt8 *nameBytes = &bytes[stringOffset + nameOffset]; result = [[NSString alloc] initWithBytes:nameBytes length:nameLength encoding:encoding]; } CFRelease(nameTable); return result; } - (void)dealloc { CGFontRelease(_cgFont); [_familyName release]; [_fontName release]; [_postScriptName release]; [super dealloc]; } @end ='n42' href='#n42'>42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
//
//  ZAttributedString.m
//  FontLabel
//
//  Created by Kevin Ballard on 9/22/09.
//  Copyright 2009 Zynga Game Networks. All rights reserved.
//

#import "ZAttributedString.h"
#import "ZAttributedStringPrivate.h"

@interface ZAttributedString ()
- (NSUInteger)indexOfEffectiveAttributeRunForIndex:(NSUInteger)index;
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange uniquingOnName:(NSString *)attributeName;
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange
							inRange:(NSRange)rangeLimit uniquingOnName:(NSString *)attributeName;
@end

@interface ZAttributedString ()
@property (nonatomic, readonly) NSArray *attributes;
@end

@implementation ZAttributedString
@synthesize string = _buffer;
@synthesize attributes = _attributes;

- (id)initWithAttributedString:(ZAttributedString *)attr {
	NSParameterAssert(attr != nil);
	if ((self = [super init])) {
		_buffer = [attr->_buffer mutableCopy];
		_attributes = [[NSMutableArray alloc] initWithArray:attr->_attributes copyItems:YES];
	}
	return self;
}

- (id)initWithString:(NSString *)str {
	return [self initWithString:str attributes:nil];
}

- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes {
	if ((self = [super init])) {
		_buffer = [str mutableCopy];
		_attributes = [[NSMutableArray alloc] initWithObjects:[ZAttributeRun attributeRunWithIndex:0 attributes:attributes], nil];
	}
	return self;
}

- (id)init {
	return [self initWithString:@"" attributes:nil];
}

- (id)initWithCoder:(NSCoder *)decoder {
	if ((self = [super init])) {
		_buffer = [[decoder decodeObjectForKey:@"buffer"] mutableCopy];
		_attributes = [[decoder decodeObjectForKey:@"attributes"] mutableCopy];
	}
	return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
	[aCoder encodeObject:_buffer forKey:@"buffer"];
	[aCoder encodeObject:_attributes forKey:@"attributes"];
}

- (id)copyWithZone:(NSZone *)zone {
	return [self retain];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
	return [(ZMutableAttributedString *)[ZMutableAttributedString allocWithZone:zone] initWithAttributedString:self];
}

- (NSUInteger)length {
	return [_buffer length];
}

- (NSString *)description {
	NSMutableArray *components = [NSMutableArray arrayWithCapacity:[_attributes count]*2];
	NSRange range = NSMakeRange(0, 0);
	for (NSUInteger i = 0; i <= [_attributes count]; i++) {
		range.location = NSMaxRange(range);
		ZAttributeRun *run;
		if (i < [_attributes count]) {
			run = [_attributes objectAtIndex:i];
			range.length = run.index - range.location;
		} else {
			run = nil;
			range.length = [_buffer length] - range.location;
		}
		if (range.length > 0) {
			[components addObject:[NSString stringWithFormat:@"\"%@\"", [_buffer substringWithRange:range]]];
		}
		if (run != nil) {
			NSMutableArray *attrDesc = [NSMutableArray arrayWithCapacity:[run.attributes count]];
			for (id key in run.attributes) {
				[attrDesc addObject:[NSString stringWithFormat:@"%@: %@", key, [run.attributes objectForKey:key]]];
			}
			[components addObject:[NSString stringWithFormat:@"{%@}", [attrDesc componentsJoinedByString:@", "]]];
		}
	}
	return [NSString stringWithFormat:@"%@", [components componentsJoinedByString:@" "]];
}

- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange {
	NSParameterAssert(attributeName != nil);
	return [[self attributesAtIndex:index effectiveRange:aRange uniquingOnName:attributeName] objectForKey:attributeName];
}

- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit {
	NSParameterAssert(attributeName != nil);
	return [[self attributesAtIndex:index longestEffectiveRange:aRange inRange:rangeLimit uniquingOnName:attributeName] objectForKey:attributeName];
}

- (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange {
	if (NSMaxRange(aRange) > [_buffer length]) {
		@throw [NSException exceptionWithName:NSRangeException reason:@"range was outisde of the attributed string" userInfo:nil];
	}
	ZMutableAttributedString *newStr = [self mutableCopy];
	if (aRange.location > 0) {
		[newStr deleteCharactersInRange:NSMakeRange(0, aRange.location)];
	}
	if (NSMaxRange(aRange) < [_buffer length]) {
		[newStr deleteCharactersInRange:NSMakeRange(aRange.length, [_buffer length] - NSMaxRange(aRange))];
	}
	return [newStr autorelease];
}

- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange {
	return [NSDictionary dictionaryWithDictionary:[self attributesAtIndex:index effectiveRange:aRange uniquingOnName:nil]];
}

- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit {
	return [NSDictionary dictionaryWithDictionary:[self attributesAtIndex:index longestEffectiveRange:aRange inRange:rangeLimit uniquingOnName:nil]];
}

#if Z_BLOCKS
// Warning: this code has not been tested. The only guarantee is that it compiles.
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts
				usingBlock:(void (^)(id, NSRange, BOOL*))block {
	if (opts & ZAttributedStringEnumerationLongestEffectiveRangeNotRequired) {
		[self enumerateAttributesInRange:enumerationRange options:opts usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
			id value = [attrs objectForKey:attrName];
			if (value != nil) {
				block(value, range, stop);
			}
		}];
	} else {
		__block id oldValue = nil;
		__block NSRange effectiveRange = NSMakeRange(0, 0);
		[self enumerateAttributesInRange:enumerationRange options:opts usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
			id value = [attrs objectForKey:attrName];
			if (oldValue == nil) {
				oldValue = value;
				effectiveRange = range;
			} else if (value != nil && [oldValue isEqual:value]) {
				// combine the attributes
				effectiveRange = NSUnionRange(effectiveRange, range);
			} else {
				BOOL innerStop = NO;
				block(oldValue, effectiveRange, &innerStop);
				if (innerStop) {
					*stop = YES;
					oldValue = nil;
				} else {
					oldValue = value;
				}
			}
		}];
		if (oldValue != nil) {
			BOOL innerStop = NO; // necessary for the block, but unused
			block(oldValue, effectiveRange, &innerStop);
		}
	}
}

- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts
						usingBlock:(void (^)(NSDictionary*, NSRange, BOOL*))block {
	// copy the attributes so we can mutate the string if necessary during enumeration
	// also clip the array during copy to only the subarray of attributes that cover the requested range
	NSArray *attrs;
	if (NSEqualRanges(enumerationRange, NSMakeRange(0, 0))) {
		attrs = [NSArray arrayWithArray:_attributes];
	} else {
		// in this binary search, last is the first run after the range
		NSUInteger first = 0, last = [_attributes count];
		while (last > first+1) {
			NSUInteger pivot = (last + first) / 2;
			ZAttributeRun *run = [_attributes objectAtIndex:pivot];
			if (run.index < enumerationRange.location) {
				first = pivot;
			} else if (run.index >= NSMaxRange(enumerationRange)) {
				last = pivot;
			}
		}
		attrs = [_attributes subarrayWithRange:NSMakeRange(first, last-first)];
	}
	if (opts & ZAttributedStringEnumerationReverse) {
		NSUInteger end = [_buffer length];
		for (ZAttributeRun *run in [attrs reverseObjectEnumerator]) {
			BOOL stop = NO;
			NSUInteger start = run.index;
			// clip to enumerationRange
			start = MAX(start, enumerationRange.location);
			end = MIN(end, NSMaxRange(enumerationRange));
			block(run.attributes, NSMakeRange(start, end - start), &stop);
			if (stop) break;
			end = run.index;
		}
	} else {
		NSUInteger start = 0;
		ZAttributeRun *run = [attrs objectAtIndex:0];
		NSInteger offset = 0;
		NSInteger oldLength = [_buffer length];
		for (NSUInteger i = 1;;i++) {
			NSUInteger end;
			if (i >= [attrs count]) {
				end = oldLength;
			} else {
				end = [[attrs objectAtIndex:i] index];
			}
			BOOL stop = NO;
			NSUInteger clippedStart = MAX(start, enumerationRange.location);
			NSUInteger clippedEnd = MIN(end, NSMaxRange(enumerationRange));
			block(run.attributes, NSMakeRange(clippedStart + offset, clippedEnd - start), &stop);
			if (stop || i >= [attrs count]) break;
			start = end;
			NSUInteger newLength = [_buffer length];
			offset += (newLength - oldLength);
			oldLength = newLength;
		}
	}
}
#endif

- (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString {
	return ([_buffer isEqualToString:otherString->_buffer] && [_attributes isEqualToArray:otherString->_attributes]);
}

- (BOOL)isEqual:(id)object {
	return [object isKindOfClass:[ZAttributedString class]] && [self isEqualToAttributedString:(ZAttributedString *)object];
}

#pragma mark -

- (NSUInteger)indexOfEffectiveAttributeRunForIndex:(NSUInteger)index {
	NSUInteger first = 0, last = [_attributes count];
	while (last > first + 1) {
		NSUInteger pivot = (last + first) / 2;
		ZAttributeRun *run = [_attributes objectAtIndex:pivot];
		if (run.index > index) {
			last = pivot;
		} else if (run.index < index) {
			first = pivot;
		} else {
			first = pivot;
			break;
		}
	}
	return first;
}

- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange uniquingOnName:(NSString *)attributeName {
	if (index >= [_buffer length]) {
		@throw [NSException exceptionWithName:NSRangeException reason:@"index beyond range of attributed string" userInfo:nil];
	}
	NSUInteger runIndex = [self indexOfEffectiveAttributeRunForIndex:index];
	ZAttributeRun *run = [_attributes objectAtIndex:runIndex];
	if (aRange != NULL) {
		aRange->location = run.index;
		runIndex++;
		if (runIndex < [_attributes count]) {
			aRange->length = [[_attributes objectAtIndex:runIndex] index] - aRange->location;
		} else {
			aRange->length = [_buffer length] - aRange->location;
		}
	}
	return run.attributes;
}
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange
							inRange:(NSRange)rangeLimit uniquingOnName:(NSString *)attributeName {
	if (index >= [_buffer length]) {
		@throw [NSException exceptionWithName:NSRangeException reason:@"index beyond range of attributed string" userInfo:nil];
	} else if (NSMaxRange(rangeLimit) > [_buffer length]) {
		@throw [NSException exceptionWithName:NSRangeException reason:@"rangeLimit beyond range of attributed string" userInfo:nil];
	}
	NSUInteger runIndex = [self indexOfEffectiveAttributeRunForIndex:index];
	ZAttributeRun *run = [_attributes objectAtIndex:runIndex];
	if (aRange != NULL) {
		if (attributeName != nil) {
			id value = [run.attributes objectForKey:attributeName];
			NSUInteger endRunIndex = runIndex+1;
			runIndex--;
			// search backwards
			while (1) {
				if (run.index <= rangeLimit.location) {
					break;
				}
				ZAttributeRun *prevRun = [_attributes objectAtIndex:runIndex];
				id prevValue = [prevRun.attributes objectForKey:attributeName];
				if (prevValue == value || (value != nil && [prevValue isEqual:value])) {
					runIndex--;
					run = prevRun;
				} else {
					break;
				}
			}
			// search forwards
			ZAttributeRun *endRun = nil;
			while (endRunIndex < [_attributes count]) {
				ZAttributeRun *nextRun = [_attributes objectAtIndex:endRunIndex];
				if (nextRun.index >= NSMaxRange(rangeLimit)) {
					endRun = nextRun;
					break;
				}
				id nextValue = [nextRun.attributes objectForKey:attributeName];
				if (nextValue == value || (value != nil && [nextValue isEqual:value])) {
					endRunIndex++;
				} else {
					endRun = nextRun;
					break;
				}
			}
			aRange->location = MAX(run.index, rangeLimit.location);
			aRange->length = MIN((endRun ? endRun.index : [_buffer length]), NSMaxRange(rangeLimit)) - aRange->location;
		} else {
			// with no attribute name, we don't need to do any real searching,
			// as we already guarantee each run has unique attributes.
			// just make sure to clip the range to the rangeLimit
			aRange->location = MAX(run.index, rangeLimit.location);
			ZAttributeRun *endRun = (runIndex+1 < [_attributes count] ? [_attributes objectAtIndex:runIndex+1] : nil);
			aRange->length = MIN((endRun ? endRun.index : [_buffer length]), NSMaxRange(rangeLimit)) - aRange->location;
		}
	}
	return run.attributes;
}

- (void)dealloc {
	[_buffer release];
	[_attributes release];
	[super dealloc];
}
@end

@interface ZMutableAttributedString ()
- (void)cleanupAttributesInRange:(NSRange)range;
- (NSRange)rangeOfAttributeRunsForRange:(NSRange)range;
- (void)offsetRunsInRange:(NSRange )range byOffset:(NSInteger)offset;
@end

@implementation ZMutableAttributedString
- (id)copyWithZone:(NSZone *)zone {
	return [(ZAttributedString *)[ZAttributedString allocWithZone:zone] initWithAttributedString:self];
}

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range {
	range = [self rangeOfAttributeRunsForRange:range];
	for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
		[run.attributes setObject:value forKey:name];
	}
	[self cleanupAttributesInRange:range];
}

- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range {
	range = [self rangeOfAttributeRunsForRange:range];
	for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
		[run.attributes addEntriesFromDictionary:attributes];
	}
	[self cleanupAttributesInRange:range];
}

- (void)appendAttributedString:(ZAttributedString *)str {
	[self insertAttributedString:str atIndex:[_buffer length]];
}

- (void)deleteCharactersInRange:(NSRange)range {
	NSRange runRange = [self rangeOfAttributeRunsForRange:range];
	[_buffer replaceCharactersInRange:range withString:@""];
	[_attributes removeObjectsInRange:runRange];
	for (NSUInteger i = runRange.location; i < [_attributes count]; i++) {
		ZAttributeRun *run = [_attributes objectAtIndex:i];
		ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:(run.index - range.length) attributes:run.attributes];
		[_attributes replaceObjectAtIndex:i withObject:newRun];
		[newRun release];
	}
	[self cleanupAttributesInRange:NSMakeRange(runRange.location, 0)];
}

- (void)insertAttributedString:(ZAttributedString *)str atIndex:(NSUInteger)idx {
	[self replaceCharactersInRange:NSMakeRange(idx, 0) withAttributedString:str];
}

- (void)removeAttribute:(NSString *)name range:(NSRange)range {
	range = [self rangeOfAttributeRunsForRange:range];
	for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
		[run.attributes removeObjectForKey:name];
	}
	[self cleanupAttributesInRange:range];
}

- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(ZAttributedString *)str {
	NSRange replaceRange = [self rangeOfAttributeRunsForRange:range];
	NSInteger offset = [str->_buffer length] - range.length;
	[_buffer replaceCharactersInRange:range withString:str->_buffer];
	[_attributes replaceObjectsInRange:replaceRange withObjectsFromArray:str->_attributes];
	NSRange newRange = NSMakeRange(replaceRange.location, [str->_attributes count]);
	[self offsetRunsInRange:newRange byOffset:range.location];
	[self offsetRunsInRange:NSMakeRange(NSMaxRange(newRange), [_attributes count] - NSMaxRange(newRange)) byOffset:offset];
	[self cleanupAttributesInRange:NSMakeRange(newRange.location, 0)];
	[self cleanupAttributesInRange:NSMakeRange(NSMaxRange(newRange), 0)];
}

- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str {
	[self replaceCharactersInRange:range withAttributedString:[[[ZAttributedString alloc] initWithString:str] autorelease]];
}

- (void)setAttributedString:(ZAttributedString *)str {
	[_buffer release], _buffer = [str->_buffer mutableCopy];
	[_attributes release], _attributes = [str->_attributes mutableCopy];
}

- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range {
	range = [self rangeOfAttributeRunsForRange:range];
	for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
		[run.attributes setDictionary:attributes];
	}
	[self cleanupAttributesInRange:range];
}

#pragma mark -

// splits the existing runs to provide one or more new runs for the given range
- (NSRange)rangeOfAttributeRunsForRange:(NSRange)range {
	NSParameterAssert(NSMaxRange(range) <= [_buffer length]);
	
	// find (or create) the first run
	NSUInteger first = 0;
	ZAttributeRun *lastRun = nil;
	for (;;first++) {
		if (first >= [_attributes count]) {
			// we didn't find a run
			first = [_attributes count];
			ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:range.location attributes:lastRun.attributes];
			[_attributes addObject:newRun];
			[newRun release];
			break;
		}
		ZAttributeRun *run = [_attributes objectAtIndex:first];
		if (run.index == range.location) {
			break;
		} else if (run.index > range.location) {
			ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:range.location attributes:lastRun.attributes];
			[_attributes insertObject:newRun atIndex:first];
			[newRun release];
			break;
		}
		lastRun = run;
	}
	
	if (((ZAttributeRun *)[_attributes lastObject]).index < NSMaxRange(range)) {
		NSRange subrange = NSMakeRange(first, [_attributes count] - first);
		if (NSMaxRange(range) < [_buffer length]) {
			ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:NSMaxRange(range)
															  attributes:(NSDictionary*)[(ZAttributeRun *)[_attributes lastObject] attributes]];
			[_attributes addObject:newRun];
			[newRun release];
		}
		return subrange;
	} else {
		// find the last run within and the first run after the range
		NSUInteger lastIn = first, firstAfter = [_attributes count]-1;
		while (firstAfter > lastIn + 1) {
			NSUInteger idx = (firstAfter + lastIn) / 2;
			ZAttributeRun *run = [_attributes objectAtIndex:idx];
			if (run.index < range.location) {
				lastIn = idx;
			} else if (run.index > range.location) {
				firstAfter = idx;
			} else {
				// this is definitively the first run after the range
				firstAfter = idx;
				break;
			}
		}
		if ([[_attributes objectAtIndex:firstAfter] index] > NSMaxRange(range)) {
			// the first after is too far after, insert another run!
			ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:NSMaxRange(range)
															  attributes:[(ZAttributeRun *)[_attributes objectAtIndex:firstAfter-1] attributes]];
			[_attributes insertObject:newRun atIndex:firstAfter];
			[newRun release];
		}
		return NSMakeRange(lastIn, firstAfter - lastIn);
	}
}

- (void)cleanupAttributesInRange:(NSRange)range {
	// expand the range to include one surrounding attribute on each side
	if (range.location > 0) {
		range.location -= 1;
		range.length += 1;
	}
	if (NSMaxRange(range) < [_attributes count]) {
		range.length += 1;
	} else {
		// make sure the range is capped to the attributes count
		range.length = [_attributes count] - range.location;
	}
	if (range.length == 0) return;
	ZAttributeRun *lastRun = [_attributes objectAtIndex:range.location];
	for (NSUInteger i = range.location+1; i < NSMaxRange(range);) {
		ZAttributeRun *run = [_attributes objectAtIndex:i];
		if ([lastRun.attributes isEqualToDictionary:run.attributes]) {
			[_attributes removeObjectAtIndex:i];
			range.length -= 1;
		} else {
			lastRun = run;
			i++;
		}
	}
}

- (void)offsetRunsInRange:(NSRange)range byOffset:(NSInteger)offset {
	for (NSUInteger i = range.location; i < NSMaxRange(range); i++) {
		ZAttributeRun *run = [_attributes objectAtIndex:i];
		ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:run.index + offset attributes:run.attributes];
		[_attributes replaceObjectAtIndex:i withObject:newRun];
		[newRun release];
	}
}
@end

@implementation ZAttributeRun
@synthesize index = _index;
@synthesize attributes = _attributes;

+ (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs {
	return [[[self alloc] initWithIndex:idx attributes:attrs] autorelease];
}

- (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs {
	NSParameterAssert(idx >= 0);
	if ((self = [super init])) {
		_index = idx;
		if (attrs == nil) {
			_attributes = [[NSMutableDictionary alloc] init];
		} else {
			_attributes = [attrs mutableCopy];
		}
	}
	return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
	if ((self = [super init])) {
		_index = [[decoder decodeObjectForKey:@"index"] unsignedIntegerValue];
		_attributes = [[decoder decodeObjectForKey:@"attributes"] mutableCopy];
	}
	return self;
}

- (id)init {
	return [self initWithIndex:0 attributes:[NSDictionary dictionary]];
}

- (id)copyWithZone:(NSZone *)zone {
	return [[ZAttributeRun allocWithZone:zone] initWithIndex:_index attributes:_attributes];
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
	[aCoder encodeObject:[NSNumber numberWithUnsignedInteger:_index] forKey:@"index"];
	[aCoder encodeObject:_attributes forKey:@"attributes"];
}

- (NSString *)description {
	NSMutableArray *components = [NSMutableArray arrayWithCapacity:[_attributes count]];
	for (id key in _attributes) {
		[components addObject:[NSString stringWithFormat:@"%@=%@", key, [_attributes objectForKey:key]]];
	}
	return [NSString stringWithFormat:@"<%@: %p index=%lu attributes={%@}>",
			NSStringFromClass([self class]), self, (unsigned long)_index, [components componentsJoinedByString:@" "]];
}

- (BOOL)isEqual:(id)object {
	if (![object isKindOfClass:[ZAttributeRun class]]) return NO;
	ZAttributeRun *other = (ZAttributeRun *)object;
	return _index == other->_index && [_attributes isEqualToDictionary:other->_attributes];
}

- (void)dealloc {
	[_attributes release];
	[super dealloc];
}
@end

NSString * const ZFontAttributeName = @"ZFontAttributeName";
NSString * const ZForegroundColorAttributeName = @"ZForegroundColorAttributeName";
NSString * const ZBackgroundColorAttributeName = @"ZBackgroundColorAttributeName";
NSString * const ZUnderlineStyleAttributeName = @"ZUnderlineStyleAttributeName";