Plugins/WebKit Message View/AIWebkitMessageViewStyle.m
author Zachary West <zacw@adium.im>
Sat Oct 31 22:35:08 2009 -0400 (2009-10-31)
changeset 2718 dce9e8066777
parent 2679 ad119ec778fc
child 2756 fee14660b29e
permissions -rw-r--r--
Only add color tags if a style supports colors. Fixes #13286.
     1 /* 
     2  * Adium is the legal property of its developers, whose names are listed in the copyright file included
     3  * with this source distribution.
     4  * 
     5  * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
     6  * General Public License as published by the Free Software Foundation; either version 2 of the License,
     7  * or (at your option) any later version.
     8  * 
     9  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
    10  * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    11  * Public License for more details.
    12  * 
    13  * You should have received a copy of the GNU General Public License along with this program; if not,
    14  * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    15  */
    16 
    17 #import "AIWebkitMessageViewStyle.h"
    18 #import <AIUtilities/AIColorAdditions.h>
    19 #import <AIUtilities/AIStringAdditions.h>
    20 #import <AIUtilities/AIDateFormatterAdditions.h>
    21 #import <AIUtilities/AIMutableStringAdditions.h>
    22 #import <Adium/AIAccount.h>
    23 #import <Adium/AIChat.h>
    24 #import <Adium/AIContentTopic.h>
    25 #import <Adium/AIContentContext.h>
    26 #import <Adium/AIContentMessage.h>
    27 #import <Adium/AIContentNotification.h>
    28 #import <Adium/AIContentObject.h>
    29 #import <Adium/AIContentStatus.h>
    30 #import <Adium/AIHTMLDecoder.h>
    31 #import <Adium/AIListObject.h>
    32 #import <Adium/AIListContact.h>
    33 #import <Adium/AIService.h>
    34 #import <Adium/ESFileTransfer.h>
    35 #import <Adium/AIServiceIcons.h>
    36 #import <Adium/AIContentControllerProtocol.h>
    37 #import <Adium/AIStatusIcons.h>
    38 
    39 //
    40 #define LEGACY_VERSION_THRESHOLD		3	//Styles older than this version are considered legacy
    41 
    42 //
    43 #define KEY_WEBKIT_VERSION				@"MessageViewVersion"
    44 
    45 //BOM scripts for appending content.
    46 #define APPEND_MESSAGE_WITH_SCROLL		@"checkIfScrollToBottomIsNeeded(); appendMessage(\"%@\"); scrollToBottomIfNeeded();"
    47 #define APPEND_NEXT_MESSAGE_WITH_SCROLL	@"checkIfScrollToBottomIsNeeded(); appendNextMessage(\"%@\"); scrollToBottomIfNeeded();"
    48 #define APPEND_MESSAGE					@"appendMessage(\"%@\");"
    49 #define APPEND_NEXT_MESSAGE				@"appendNextMessage(\"%@\");"
    50 #define APPEND_MESSAGE_NO_SCROLL		@"appendMessageNoScroll(\"%@\");"
    51 #define	APPEND_NEXT_MESSAGE_NO_SCROLL	@"appendNextMessageNoScroll(\"%@\");"
    52 #define REPLACE_LAST_MESSAGE			@"replaceLastMessage(\"%@\");"
    53 
    54 #define TOPIC_MAIN_DIV					@"<div id=\"topic\"></div>"
    55 // We set back, when the user finishes editing, the correct topic, which wipes out the existance of the span before. We don't need to undo the dbl click action.
    56 #define TOPIC_INDIVIDUAL_WRAPPER		@"<span id=\"topicEdit\" ondblclick=\"this.setAttribute('contentEditable', true); this.focus();\">%@</span>"
    57 
    58 @interface NSMutableString (AIKeywordReplacementAdditions)
    59 - (void) replaceKeyword:(NSString *)word withString:(NSString *)newWord;
    60 - (void) safeReplaceCharactersInRange:(NSRange)range withString:(NSString *)newWord;
    61 @end
    62 
    63 @implementation NSMutableString (AIKeywordReplacementAdditions)
    64 - (void) replaceKeyword:(NSString *)keyWord withString:(NSString *)newWord
    65 {
    66 	if(!keyWord) return;
    67 	if(!newWord) newWord = @"";
    68 	[self replaceOccurrencesOfString:keyWord
    69 						  withString:newWord
    70 							 options:NSLiteralSearch
    71 							   range:NSMakeRange(0.0, [self length])];
    72 }
    73 
    74 - (void) safeReplaceCharactersInRange:(NSRange)range withString:(NSString *)newWord
    75 {
    76 	if (range.location == NSNotFound || range.length == 0) return;
    77 	if (!newWord) [self deleteCharactersInRange:range];
    78 	else [self replaceCharactersInRange:range withString:newWord];
    79 }
    80 @end
    81 
    82 //The old code built the paths itself, which follows the filesystem's case sensitivity, so some noobs named stuff wrong. 
    83 //NSBundle is always case sensitive, so those styles broke (they were already broken on case sensitive hfsx)
    84 //These methods only check for the all-lowercase variant, so are not suitable for general purpose use.
    85 @interface NSBundle (StupidCompatibilityHack)
    86 - (NSString *)semiCaseInsensitivePathForResource:(NSString *)res ofType:(NSString *)type;
    87 - (NSString *)semiCaseInsensitivePathForResource:(NSString *)res ofType:(NSString *)type inDirectory:(NSString *)dirpath;
    88 @end
    89 
    90 @implementation NSBundle (StupidCompatibilityHack)
    91 - (NSString *)semiCaseInsensitivePathForResource:(NSString *)res ofType:(NSString *)type
    92 {
    93 	NSString *path = [self pathForResource:res ofType:type];
    94 	if(!path)
    95 		path = [self pathForResource:[res lowercaseString] ofType:type];
    96 	return path;
    97 }
    98 
    99 - (NSString *)semiCaseInsensitivePathForResource:(NSString *)res ofType:(NSString *)type inDirectory:(NSString *)dirpath
   100 {
   101 	NSString *path = [self pathForResource:res ofType:type inDirectory:dirpath];
   102 	if(!path)
   103 		path = [self pathForResource:[res lowercaseString] ofType:type inDirectory:dirpath];
   104 	return path;
   105 }
   106 
   107 @end
   108 
   109 @interface AIWebkitMessageViewStyle ()
   110 - (id)initWithBundle:(NSBundle *)inBundle;
   111 - (void)_loadTemplates;
   112 - (void)releaseResources;
   113 - (NSMutableString *)_escapeStringForPassingToScript:(NSMutableString *)inString;
   114 - (NSString *)noVariantName;
   115 - (NSString *)iconPathForFileTransfer:(ESFileTransfer *)inObject;
   116 - (NSString *)statusIconPathForListObject:(AIListObject *)inObject;
   117 @end
   118 
   119 @implementation AIWebkitMessageViewStyle
   120 
   121 + (id)messageViewStyleFromBundle:(NSBundle *)inBundle
   122 {
   123 	return [[[self alloc] initWithBundle:inBundle] autorelease];
   124 }
   125 
   126 + (id)messageViewStyleFromPath:(NSString *)path
   127 {
   128 	NSBundle *styleBundle = [NSBundle bundleWithPath:path];
   129 	if(styleBundle)
   130 		return [[[self alloc] initWithBundle:styleBundle] autorelease];
   131 	return nil;
   132 }
   133 
   134 /*!
   135  *	@brief Initialize
   136  */
   137 - (id)initWithBundle:(NSBundle *)inBundle
   138 {
   139 	if ((self = [super init])) {
   140 		styleBundle = [inBundle retain];
   141 		stylePath = [[styleBundle resourcePath] retain];
   142 		[self reloadStyle];
   143 	}
   144 
   145 	return self;
   146 }
   147 
   148 - (void) reloadStyle
   149 {
   150 	[self releaseResources];
   151 	
   152 	//Default behavior
   153 	allowTextBackgrounds = YES;
   154 	
   155 	/* Our styles are versioned so we can change how they work without breaking compatibility.
   156 	 *
   157 	 * Version 0: Initial Webkit Version
   158 	 * Version 1: Template.html now handles all scroll-to-bottom functionality.  It is no longer required to call the
   159 	 *            scrollToBottom functions when inserting content.
   160 	 * Version 2: No significant changes
   161 	 * Version 3: main.css is no longer a separate style, it now serves as the base stylesheet and is imported by default.
   162 	 *            The default variant is now a separate file in /variants like all other variants.
   163 	 *			  Template.html now includes appendMessageNoScroll() and appendNextMessageNoScroll() which behave
   164 	 *				the same as appendMessage() and appendNextMessage() in Versions 1 and 2 but without scrolling.
   165 	 * Version 4: Template.html now includes replaceLastMessage()
   166 	 *            Template.html now defines actionMessageUserName and actionMessageBody for display of /me (actions).
   167 	 *				 If the style provides a custom Template.html, these classes must be defined.
   168 	 *				 CSS can be used to customize the appearance of actions.
   169 	 *			  HTML filters in are now supported in Adium's content filter system; filters can assume Version 4 or later.
   170 	 */
   171 	styleVersion = [[styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_VERSION] integerValue];
   172 	
   173 	//Pre-fetch our templates
   174 	[self _loadTemplates];
   175 	
   176 	//Style flags
   177 	allowsCustomBackground = ![[styleBundle objectForInfoDictionaryKey:@"DisableCustomBackground"] boolValue];
   178 	transparentDefaultBackground = [[styleBundle objectForInfoDictionaryKey:@"DefaultBackgroundIsTransparent"] boolValue];
   179 	
   180 	combineConsecutive = ![[styleBundle objectForInfoDictionaryKey:@"DisableCombineConsecutive"] boolValue];
   181 	
   182 	NSNumber *tmpNum = [styleBundle objectForInfoDictionaryKey:@"ShowsUserIcons"];
   183 	allowsUserIcons = (tmpNum ? [tmpNum boolValue] : YES);
   184 	
   185 	//User icon masking
   186 	NSString *tmpName = [styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_USER_ICON_MASK];
   187 	if (tmpName) userIconMask = [[NSImage alloc] initWithContentsOfFile:[stylePath stringByAppendingPathComponent:tmpName]];
   188 	
   189 	NSNumber *allowsColorsNumber = [styleBundle objectForInfoDictionaryKey:@"AllowTextColors"];
   190 	allowsColors = (allowsColorsNumber ? [allowsColorsNumber boolValue] : YES);
   191 }
   192 
   193 /*!
   194  *  @brief release everything we loaded from the style bundle
   195  */
   196 - (void)releaseResources
   197 {
   198 	//Templates
   199 	[headerHTML release];
   200 	[footerHTML release];
   201 	[baseHTML release];
   202 	[contentHTML release];
   203 	[contentInHTML release];
   204 	[nextContentInHTML release];
   205 	[contextInHTML release];
   206 	[nextContextInHTML release];
   207 	[contentOutHTML release];
   208 	[nextContentOutHTML release];
   209 	[contextOutHTML release];
   210 	[nextContextOutHTML release];
   211 	[statusHTML release];	
   212 	[fileTransferHTML release];
   213 	[topicHTML release];
   214 		
   215 	[customBackgroundPath release];
   216 	[customBackgroundColor release];
   217 	
   218 	[userIconMask release];
   219 }
   220 
   221 /*!
   222  *	@brief Deallocate
   223  */
   224 - (void)dealloc
   225 {	
   226 	[styleBundle release];
   227 	[stylePath release];
   228 
   229 	[self releaseResources];
   230 	[timeStampFormatter release];
   231 	
   232 	[statusIconPathCache release];
   233 	
   234 	[super dealloc];
   235 }
   236 
   237 @synthesize bundle = styleBundle;
   238 
   239 - (BOOL)isLegacy
   240 {
   241 	return styleVersion < LEGACY_VERSION_THRESHOLD;
   242 }
   243 
   244 #pragma mark Settings
   245 
   246 @synthesize allowsCustomBackground, allowsUserIcons, allowsColors, userIconMask;
   247 
   248 - (NSArray *)validSenderColors
   249 {
   250 	if(!checkedSenderColors) {
   251 		NSURL *url = [NSURL fileURLWithPath:[stylePath stringByAppendingPathComponent:@"Incoming/SenderColors.txt"]];
   252 		NSString *senderColorsFile = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
   253 		
   254 		if(senderColorsFile)
   255 			validSenderColors = [[senderColorsFile componentsSeparatedByString:@":"] retain];
   256 		
   257 		checkedSenderColors = YES;
   258 	}
   259 	
   260 	return validSenderColors;
   261 }
   262 
   263 - (BOOL)isBackgroundTransparent
   264 {
   265 	//Our custom background is only transparent if the user has set a custom color with an alpha component less than 1.0
   266 	return ((!customBackgroundColor && transparentDefaultBackground) ||
   267 		   (customBackgroundColor && [customBackgroundColor alphaComponent] < 0.99));
   268 }
   269 
   270 - (NSString *)defaultFontFamily
   271 {
   272 	NSString *defaultFontFamily = [styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_DEFAULT_FONT_FAMILY];
   273 	if (!defaultFontFamily) defaultFontFamily = [[NSFont systemFontOfSize:0] familyName];
   274 	
   275 	return defaultFontFamily;
   276 }
   277 
   278 - (NSNumber *)defaultFontSize
   279 {
   280 	NSNumber *defaultFontSize = [styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_DEFAULT_FONT_SIZE];
   281 
   282 	if (!defaultFontSize) defaultFontSize = [NSNumber numberWithInteger:[[NSFont systemFontOfSize:0] pointSize]];
   283 	
   284 	return defaultFontSize;
   285 }
   286 
   287 - (BOOL)hasHeader
   288 {
   289 	return headerHTML && [headerHTML length];
   290 }
   291 
   292 - (BOOL)hasTopic
   293 {
   294 	return topicHTML && [topicHTML length];
   295 }
   296 
   297 #pragma mark Behavior
   298 
   299 - (void)setDateFormat:(NSString *)format
   300 {
   301 	if (!format || [format length] == 0) {
   302 		format = [NSDateFormatter localizedDateFormatStringShowingSeconds:NO showingAMorPM:NO];
   303 	}
   304 
   305 	[timeStampFormatter release];
   306 
   307 	if ([format rangeOfString:@"%"].location != NSNotFound) {
   308 		/* Support strftime-style format strings, which old message styles may use */
   309 		timeStampFormatter = [[NSDateFormatter alloc] initWithDateFormat:format allowNaturalLanguage:NO];
   310 	} else {
   311 		timeStampFormatter = [[NSDateFormatter alloc] init];
   312 		[timeStampFormatter	setFormatterBehavior:NSDateFormatterBehavior10_4];
   313 		[timeStampFormatter setDateFormat:format];
   314 	}
   315 }
   316 
   317 @synthesize allowTextBackgrounds, customBackgroundType, customBackgroundColor, showIncomingMessageColors=showIncomingColors, showIncomingMessageFonts=showIncomingFonts, customBackgroundPath, nameFormat, useCustomNameFormat, showHeader, showUserIcons;
   318 
   319 //Templates ------------------------------------------------------------------------------------------------------------
   320 #pragma mark Templates
   321 - (NSString *)baseTemplateWithVariant:(NSString *)variant chat:(AIChat *)chat
   322 {
   323 	NSMutableString	*templateHTML;
   324 
   325 	// If this is a group chat, we want to include a topic.
   326 	// Otherwise, if the header is shown, use it.
   327 	NSString *headerContent = @"";
   328 	if (showHeader) {
   329 		if (chat.isGroupChat) {
   330 			headerContent = (chat.supportsTopic ? TOPIC_MAIN_DIV : @"");
   331 		} else if (headerHTML) {
   332 			headerContent = headerHTML;
   333 		}
   334 	}
   335 	
   336 	//Old styles may be using an old custom 4 parameter baseHTML.  Styles version 3 and higher should
   337 	//be using the bundled (or a custom) 5 parameter baseHTML.
   338 	if ((styleVersion < 3) && usingCustomTemplateHTML) {
   339 		templateHTML = [NSMutableString stringWithFormat:baseHTML,						//Template
   340 			[[NSURL fileURLWithPath:stylePath] absoluteString],							//Base path
   341 			[self pathForVariant:variant],												//Variant path
   342 			headerContent,
   343 			(footerHTML ? footerHTML : @"")];
   344 	} else {		
   345 		templateHTML = [NSMutableString stringWithFormat:baseHTML,						//Template
   346 			[[NSURL fileURLWithPath:stylePath] absoluteString],							//Base path
   347 			styleVersion < 3 ? @"" : @"@import url( \"main.css\" );",					//Import main.css for new enough styles
   348 			[self pathForVariant:variant],												//Variant path
   349 			headerContent,
   350 			(footerHTML ? footerHTML : @"")];
   351 	}
   352 
   353 	return [self fillKeywordsForBaseTemplate:templateHTML chat:chat];
   354 }
   355 
   356 - (NSString *)templateForContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar
   357 {
   358 	NSString	*template;
   359 	
   360 	//Get the correct template for what we're inserting
   361 	if ([[content type] isEqualToString:CONTENT_MESSAGE_TYPE]) {
   362 		if ([content isOutgoing]) {
   363 			template = (contentIsSimilar ? nextContentOutHTML : contentOutHTML);
   364 		} else {
   365 			template = (contentIsSimilar ? nextContentInHTML : contentInHTML);
   366 		}
   367 	
   368 	} else if ([[content type] isEqualToString:CONTENT_CONTEXT_TYPE]) {
   369 		if ([content isOutgoing]) {
   370 			template = (contentIsSimilar ? nextContextOutHTML : contextOutHTML);
   371 		} else {
   372 			template = (contentIsSimilar ? nextContextInHTML : contextInHTML);
   373 		}
   374 
   375 	} else if([[content type] isEqualToString:CONTENT_FILE_TRANSFER_TYPE]) {
   376 		template = [[fileTransferHTML mutableCopy] autorelease];
   377 	} else if ([[content type] isEqualToString:CONTENT_TOPIC_TYPE]) {
   378 		template = topicHTML;
   379 	}
   380 	else {
   381 		template = statusHTML;
   382 	}
   383 	
   384 	return template;
   385 }
   386 
   387 - (NSString *)completedTemplateForContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar
   388 {
   389 	NSMutableString *mutableTemplate = [[self templateForContent:content similar:contentIsSimilar] mutableCopy];
   390 	
   391 	if (mutableTemplate) {
   392 		mutableTemplate = [self fillKeywords:mutableTemplate forContent:content similar:contentIsSimilar];
   393 	}
   394 	
   395 	return [mutableTemplate autorelease];
   396 }
   397 
   398 /*!
   399  *	@brief Pre-fetch all the style templates
   400  *
   401  *	This needs to be called before either baseTemplate or templateForContent is called
   402  */
   403 - (void)_loadTemplates
   404 {		
   405 	//Load the style's templates
   406 	//We can't use NSString's initWithContentsOfFile here.  HTML files are interpreted in the defaultCEncoding
   407 	//(which varies by system) when read that way.  We want to always interpret the files as UTF8.
   408 	headerHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Header" ofType:@"html"]] retain];
   409 	footerHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Footer" ofType:@"html"]] retain];
   410 	topicHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Topic" ofType:@"html"]] retain];
   411 	baseHTML = [NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Template" ofType:@"html"]];
   412 	
   413 	//Starting with version 1, styles can choose to not include template.html.  If the template is not included 
   414 	//Adium's default will be used.  This is preferred since any future template updates will apply to the style
   415 	if ((!baseHTML || [baseHTML length] == 0) && styleVersion >= 1) {		
   416 		baseHTML = [NSString stringWithContentsOfUTF8File:[[NSBundle bundleForClass:[self class]] semiCaseInsensitivePathForResource:@"Template" ofType:@"html"]];
   417 		usingCustomTemplateHTML = NO;
   418 	} else {
   419 		usingCustomTemplateHTML = YES;
   420 		
   421 		if ([baseHTML rangeOfString:@"function imageCheck()" options:NSLiteralSearch].location != NSNotFound) {
   422 			/* This doesn't quite fix image swapping on styles with broken image swapping due to custom HTML templates,
   423 			 * but it improves it. For some reason, the result of using our normal template.html functions is that 
   424 			 * clicking works once, then the text doesn't allow a return click. This is an improvement compared
   425 			 * to fully broken behavior in which the return click shows a missing-image placeholder.
   426 			 */
   427 			NSMutableString *imageSwapFixedBaseHTML = [[baseHTML mutableCopy] autorelease];
   428 			[imageSwapFixedBaseHTML replaceOccurrencesOfString:
   429 			 @"		function imageCheck() {\n"
   430 			 "			node = event.target;\n"
   431 			 "			if(node.tagName == 'IMG' && node.alt) {\n"
   432 			 "				a = document.createElement('a');\n"
   433 			 "				a.setAttribute('onclick', 'imageSwap(this)');\n"
   434 			 "				a.setAttribute('src', node.src);\n"
   435 			 "				text = document.createTextNode(node.alt);\n"
   436 			 "				a.appendChild(text);\n"
   437 			 "				node.parentNode.replaceChild(a, node);\n"
   438 			 "			}\n"
   439 			 "		}"
   440 													withString:
   441 			 @"		function imageCheck() {\n"
   442 			 "			var node = event.target;\n"
   443 			 "			if(node.tagName.toLowerCase() == 'img' && !client.zoomImage(node) && node.alt) {\n"
   444 			 "				var a = document.createElement('a');\n"
   445 			 "				a.setAttribute('onclick', 'imageSwap(this)');\n"
   446 			 "				a.setAttribute('src', node.getAttribute('src'));\n"
   447 			 "				a.className = node.className;\n"
   448 			 "				var text = document.createTextNode(node.alt);\n"
   449 			 "				a.appendChild(text);\n"
   450 			 "				node.parentNode.replaceChild(a, node);\n"
   451 			 "			}\n"
   452 			 "		}"
   453 													   options:NSLiteralSearch];
   454 			[imageSwapFixedBaseHTML replaceOccurrencesOfString:
   455 			 @"		function imageSwap(node) {\n"
   456 			 "			img = document.createElement('img');\n"
   457 			 "			img.setAttribute('src', node.src);\n"
   458 			 "			img.setAttribute('alt', node.firstChild.nodeValue);\n"
   459 			 "			node.parentNode.replaceChild(img, node);\n"
   460 			 "			alignChat();\n"
   461 			 "		}"
   462 													withString:
   463 			 @"		function imageSwap(node) {\n"
   464 			 "			var shouldScroll = nearBottom();\n"
   465 			 "			//Swap the image/text\n"
   466 			 "			var img = document.createElement('img');\n"
   467 			 "			img.setAttribute('src', node.getAttribute('src'));\n"
   468 			 "			img.setAttribute('alt', node.firstChild.nodeValue);\n"
   469 			 "			img.className = node.className;\n"
   470 			 "			node.parentNode.replaceChild(img, node);\n"
   471 			 "			\n"
   472 			 "			alignChat(shouldScroll);\n"
   473 			 "		}"
   474 													   options:NSLiteralSearch];
   475 			/* Now for ones which don't call alignChat() */
   476 			[imageSwapFixedBaseHTML replaceOccurrencesOfString:
   477 			 @"		function imageSwap(node) {\n"
   478 			 "			img = document.createElement('img');\n"
   479 			 "			img.setAttribute('src', node.src);\n"
   480 			 "			img.setAttribute('alt', node.firstChild.nodeValue);\n"
   481 			 "			node.parentNode.replaceChild(img, node);\n"
   482 			 "		}"
   483 													withString:
   484 			 @"		function imageSwap(node) {\n"
   485 			 "			var shouldScroll = nearBottom();\n"
   486 			 "			//Swap the image/text\n"
   487 			 "			var img = document.createElement('img');\n"
   488 			 "			img.setAttribute('src', node.getAttribute('src'));\n"
   489 			 "			img.setAttribute('alt', node.firstChild.nodeValue);\n"
   490 			 "			img.className = node.className;\n"
   491 			 "			node.parentNode.replaceChild(img, node);\n"
   492 			 "		}"
   493 													   options:NSLiteralSearch];
   494 			baseHTML = imageSwapFixedBaseHTML;
   495 		}
   496 		
   497 	}
   498 	[baseHTML retain];
   499 	
   500 	//Content Templates
   501 	contentHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Content" ofType:@"html"]] retain];
   502 	contentInHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Content" ofType:@"html" inDirectory:@"Incoming"]] retain];
   503 	nextContentInHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"NextContent" ofType:@"html" inDirectory:@"Incoming"]] retain];
   504 	contentOutHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Content" ofType:@"html" inDirectory:@"Outgoing"]] retain];
   505 	nextContentOutHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"NextContent" ofType:@"html" inDirectory:@"Outgoing"]] retain];
   506 	
   507 	//Message history
   508 	contextInHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Context" ofType:@"html" inDirectory:@"Incoming"]] retain];
   509 	nextContextInHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"NextContext" ofType:@"html" inDirectory:@"Incoming"]] retain];
   510 	contextOutHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Context" ofType:@"html" inDirectory:@"Outgoing"]] retain];
   511 	nextContextOutHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"NextContext" ofType:@"html" inDirectory:@"Outgoing"]] retain];
   512 	
   513 	//Fall back to Resources/Content.html if Incoming isn't present
   514 	if (!contentInHTML) contentInHTML = [contentHTML retain];
   515 	
   516 	//Fall back to Content if NextContent doesn't need to use different HTML
   517 	if (!nextContentInHTML) nextContentInHTML = [contentInHTML retain];
   518 	
   519 	//Fall back to Content if Context isn't present
   520 	if (!nextContextInHTML) nextContextInHTML = [nextContentInHTML retain];
   521 	if (!contextInHTML) contextInHTML = [contentInHTML retain];
   522 	
   523 	//Fall back to Content if Context isn't present
   524 	if (!nextContextOutHTML && nextContentOutHTML) nextContextOutHTML = [nextContentOutHTML retain];
   525 	if (!contextOutHTML && contentOutHTML) contextOutHTML = [contentOutHTML retain];
   526 	
   527 	//Fall back to Content if Context isn't present
   528 	if (!nextContextOutHTML) nextContextOutHTML = [nextContextInHTML retain];
   529 	if (!contextOutHTML) contextOutHTML = [contextInHTML retain];
   530 	
   531 	//Fall back to Incoming if Outgoing doesn't need to be different
   532 	if (!contentOutHTML) contentOutHTML = [contentInHTML retain];
   533 	if (!nextContentOutHTML) nextContentOutHTML = [nextContentInHTML retain];
   534 	
   535 	//Status
   536 	statusHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Status" ofType:@"html"]] retain];
   537 	
   538 	//Fall back to Resources/Incoming/Content.html if Status isn't present
   539 	if (!statusHTML) statusHTML = [contentInHTML retain];
   540 	
   541 	//TODO: make a generic Request message, rather than having this ft specific one
   542 	NSMutableString *fileTransferHTMLTemplate;
   543 	fileTransferHTMLTemplate = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"FileTransferRequest" ofType:@"html"]] mutableCopy];
   544 	if(!fileTransferHTMLTemplate) {
   545 		fileTransferHTMLTemplate = [contentInHTML mutableCopy];
   546 		[fileTransferHTMLTemplate replaceKeyword:@"%message%"
   547 									  withString:@"<p><img src=\"%fileIconPath%\" style=\"width:32px; height:32px; vertical-align:middle;\"></img><input type=\"button\" onclick=\"%saveFileAsHandler%\" value=\"Download %fileName%\"></p>"];
   548 	}
   549 	[fileTransferHTMLTemplate replaceKeyword:@"Download %fileName%"
   550 						  withString:[NSString stringWithFormat:AILocalizedString(@"Download %@", "%@ will be a file name"), @"%fileName%"]];
   551 	fileTransferHTML = fileTransferHTMLTemplate;
   552 }
   553 
   554 #pragma mark Scripts
   555 - (NSString *)scriptForAppendingContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar willAddMoreContentObjects:(BOOL)willAddMoreContentObjects replaceLastContent:(BOOL)replaceLastContent
   556 {
   557 	NSMutableString	*newHTML;
   558 	NSString		*script;
   559 	
   560 	//If combining of consecutive messages has been disabled, we treat all content as non-similar
   561 	if (!combineConsecutive) contentIsSimilar = NO;
   562 	
   563 	//Fetch the correct template and substitute keywords for the passed content
   564 	newHTML = [[[self completedTemplateForContent:content similar:contentIsSimilar] mutableCopy] autorelease];
   565 	
   566 	//BOM scripts vary by style version
   567 	if (!usingCustomTemplateHTML && styleVersion >= 4) {
   568 		/* If we're using the built-in template HTML, we know that it supports our most modern scripts */
   569 		if (replaceLastContent)
   570 			script = REPLACE_LAST_MESSAGE;
   571 		else if (willAddMoreContentObjects) {
   572 			script = (contentIsSimilar ? APPEND_NEXT_MESSAGE_NO_SCROLL : APPEND_MESSAGE_NO_SCROLL);
   573 		} else {
   574 			script = (contentIsSimilar ? APPEND_NEXT_MESSAGE : APPEND_MESSAGE);
   575 		}
   576 		
   577 	} else  if (styleVersion >= 3) {
   578 		if (willAddMoreContentObjects) {
   579 			script = (contentIsSimilar ? APPEND_NEXT_MESSAGE_NO_SCROLL : APPEND_MESSAGE_NO_SCROLL);
   580 		} else {
   581 			script = (contentIsSimilar ? APPEND_NEXT_MESSAGE : APPEND_MESSAGE);
   582 		}
   583 	} else if (styleVersion >= 1) {
   584 		script = (contentIsSimilar ? APPEND_NEXT_MESSAGE : APPEND_MESSAGE);
   585 		
   586 	} else {
   587 		if (usingCustomTemplateHTML && [content isKindOfClass:[AIContentStatus class]]) {
   588 			/* Old styles with a custom template.html had Status.html files without 'insert' divs coupled 
   589 			 * with a APPEND_NEXT_MESSAGE_WITH_SCROLL script which assumes one exists.
   590 			 */
   591 			script = APPEND_MESSAGE_WITH_SCROLL;
   592 		} else {
   593 			script = (contentIsSimilar ? APPEND_NEXT_MESSAGE_WITH_SCROLL : APPEND_MESSAGE_WITH_SCROLL);
   594 		}
   595 	}
   596 	
   597 	return [NSString stringWithFormat:script, [self _escapeStringForPassingToScript:newHTML]]; 
   598 }
   599 
   600 - (NSString *)scriptForChangingVariant:(NSString *)variant
   601 {
   602 	AILogWithSignature(@"%@",[NSString stringWithFormat:@"setStylesheet(\"mainStyle\",\"%@\");",[self pathForVariant:variant]]);
   603 
   604 	return [NSString stringWithFormat:@"setStylesheet(\"mainStyle\",\"%@\");",[self pathForVariant:variant]];
   605 }
   606 
   607 - (NSString *)scriptForScrollingAfterAddingMultipleContentObjects
   608 {
   609 	if ((styleVersion >= 3) || !usingCustomTemplateHTML) {
   610 		return @"alignChat(true);";
   611 	}
   612 
   613 	return nil;
   614 }
   615 
   616 /*!
   617  *	@brief Escape a string for passing to our BOM scripts
   618  */
   619 - (NSMutableString *)_escapeStringForPassingToScript:(NSMutableString *)inString
   620 {	
   621 	//We need to escape a few things to get our string to the javascript without trouble
   622 	[inString replaceOccurrencesOfString:@"\\" 
   623 							  withString:@"\\\\" 
   624 								 options:NSLiteralSearch];
   625 	
   626 	[inString replaceOccurrencesOfString:@"\"" 
   627 							  withString:@"\\\"" 
   628 								 options:NSLiteralSearch];
   629 		
   630 	[inString replaceOccurrencesOfString:@"\n" 
   631 							  withString:@"" 
   632 								 options:NSLiteralSearch];
   633 
   634 	[inString replaceOccurrencesOfString:@"\r" 
   635 							  withString:@"<br>" 
   636 								 options:NSLiteralSearch];
   637 
   638 	return inString;
   639 }
   640 
   641 #pragma mark Variants
   642 
   643 - (NSArray *)availableVariants
   644 {
   645 	NSMutableArray	*availableVariants = [NSMutableArray array];
   646 	
   647 	//Build an array of all variant names
   648 	for (NSString *path in [styleBundle pathsForResourcesOfType:@"css" inDirectory:@"Variants"]) {
   649 		[availableVariants addObject:[[path lastPathComponent] stringByDeletingPathExtension]];
   650 	}
   651 
   652 	//Style versions before 3 stored the default variant in a separate location.  They also allowed for this
   653 	//varient name to not be specified, and would substitute a localized string in its place.
   654 	if (styleVersion < 3) {
   655 		[availableVariants addObject:[self noVariantName]];
   656 	}
   657 	
   658 	//Alphabetize the variants
   659 	[availableVariants sortUsingSelector:@selector(compare:)];
   660 	
   661 	return availableVariants;
   662 }
   663 
   664 - (NSString *)pathForVariant:(NSString *)variant
   665 {
   666 	//Styles before version 3 stored the default variant in main.css, and not in the variants folder.
   667 	if (styleVersion < 3 && [variant isEqualToString:[self noVariantName]]) {
   668 		return @"main.css";
   669 	} else {
   670 		return [NSString stringWithFormat:@"Variants/%@.css",variant];
   671 	}
   672 }
   673 
   674 /*!
   675  *	@brief Base variant name for styles before version 2
   676  */
   677 - (NSString *)noVariantName
   678 {
   679 	NSString	*noVariantName = [styleBundle objectForInfoDictionaryKey:@"DisplayNameForNoVariant"];
   680 	return noVariantName ? noVariantName : AILocalizedString(@"Normal","Normal style variant menu item");
   681 }
   682 
   683 + (NSString *)noVariantNameForBundle:(NSBundle *)inBundle
   684 {
   685 	NSString	*noVariantName = [inBundle objectForInfoDictionaryKey:@"DisplayNameForNoVariant"];
   686 	return noVariantName ? noVariantName : AILocalizedString(@"Normal","Normal style variant menu item");	
   687 }
   688 
   689 - (NSString *)defaultVariant
   690 {
   691 	return styleVersion < 3 ? [self noVariantName] : [styleBundle objectForInfoDictionaryKey:@"DefaultVariant"];
   692 }
   693 
   694 + (NSString *)defaultVariantForBundle:(NSBundle *)inBundle
   695 {
   696 	return [[inBundle objectForInfoDictionaryKey:KEY_WEBKIT_VERSION] integerValue] < 3 ? 
   697 		   [self noVariantNameForBundle:inBundle] : 
   698 		   [inBundle objectForInfoDictionaryKey:@"DefaultVariant"];
   699 }
   700 
   701 #pragma mark Keyword replacement
   702 
   703 - (NSMutableString *)fillKeywords:(NSMutableString *)inString forContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar
   704 {
   705 	NSDate			*date = nil;
   706 	NSRange			range;
   707 	AIListObject	*contentSource = [content source];
   708 	AIListObject	*theSource = ([contentSource isKindOfClass:[AIListContact class]] ?
   709 								  [(AIListContact *)contentSource parentContact] :
   710 								  contentSource);
   711 
   712 	/*
   713 		htmlEncodedMessage is only encoded correctly for AIContentMessages
   714 		but we do it up here so that we can check for RTL/LTR text below without
   715 		having to encode the message twice. This is less than ideal 
   716 	 */
   717 	NSString		*htmlEncodedMessage = [AIHTMLDecoder encodeHTML:[content message]
   718 															headers:NO 
   719 														   fontTags:showIncomingFonts
   720 												 includingColorTags:(allowsColors && showIncomingColors)
   721 													  closeFontTags:YES
   722 														  styleTags:YES
   723 										 closeStyleTagsOnFontChange:YES
   724 													 encodeNonASCII:YES
   725 													   encodeSpaces:YES
   726 														 imagesPath:NSTemporaryDirectory()
   727 												  attachmentsAsText:NO
   728 										  onlyIncludeOutgoingImages:NO
   729 													 simpleTagsOnly:NO
   730 													 bodyBackground:NO
   731 										        allowJavascriptURLs:NO];
   732 	
   733 	if (styleVersion >= 4)
   734 		htmlEncodedMessage = [adium.contentController filterHTMLString:htmlEncodedMessage
   735 															   direction:[content isOutgoing] ? AIFilterOutgoing : AIFilterIncoming
   736 																 content:content];
   737 
   738 	//date
   739 	if ([content respondsToSelector:@selector(date)])
   740 		date = [(AIContentMessage *)content date];
   741 	
   742 	//Replacements applicable to any AIContentObject
   743 	[inString replaceKeyword:@"%time%" 
   744 				  withString:(date ? [timeStampFormatter stringFromDate:date] : @"")];
   745 
   746 	NSString *shortTimeString = (date ? [[NSDateFormatter localizedDateFormatterShowingSeconds:NO showingAMorPM:NO] stringFromDate:date] : @"");
   747 	[inString replaceKeyword:@"%shortTime%"
   748 				  withString:shortTimeString];
   749 
   750 	if ([inString rangeOfString:@"%senderStatusIcon%"].location != NSNotFound) {
   751 		//Only cache the status icon to disk if the message style will actually use it
   752 		[inString replaceKeyword:@"%senderStatusIcon%"
   753 					  withString:[self statusIconPathForListObject:theSource]];
   754 	}
   755 	
   756 	//Replaces %localized{x}% with a a localized version of x, searching the style's localizations, and then Adium's localizations
   757 	do{
   758 		range = [inString rangeOfString:@"%localized{"];
   759 		if (range.location != NSNotFound) {
   760 			NSRange endRange;
   761 			endRange = [inString rangeOfString:@"}%" options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), [inString length] - NSMaxRange(range))];
   762 			if (endRange.location != NSNotFound && endRange.location > NSMaxRange(range)) {
   763 				NSString *untranslated = [inString substringWithRange:NSMakeRange(NSMaxRange(range), (endRange.location - NSMaxRange(range)))];
   764 				
   765 				NSString *translated = [styleBundle localizedStringForKey:untranslated
   766 																	value:untranslated
   767 																	table:nil];
   768 				if (!translated || [translated length] == 0) {
   769 					translated = [[NSBundle bundleForClass:[self class]] localizedStringForKey:untranslated
   770 																						 value:untranslated
   771 																						 table:nil];
   772 					if (!translated || [translated length] == 0) {
   773 						translated = [[NSBundle mainBundle] localizedStringForKey:untranslated
   774 																			value:untranslated
   775 																			table:nil];
   776 					}
   777 				}
   778 				
   779 				
   780 				[inString safeReplaceCharactersInRange:NSUnionRange(range, endRange) 
   781 											withString:translated];
   782 			}
   783 		}
   784 	} while (range.location != NSNotFound);
   785 
   786 	[inString replaceKeyword:@"%userIcons%"
   787 				  withString:(showUserIcons ? @"showIcons" : @"hideIcons")];
   788 
   789 	[inString replaceKeyword:@"%messageClasses%"
   790 				  withString:[(contentIsSimilar ? @"consecutive " : @"") stringByAppendingString:[[content displayClasses] componentsJoinedByString:@" "]]];
   791 	
   792 	[inString replaceKeyword:@"%senderColor%"
   793 				  withString:[NSColor representedColorForObject:contentSource.UID withValidColors:self.validSenderColors]];
   794 	
   795 	//HAX. The odd conditional here detects the rtl html that our html parser spits out.
   796 	[inString replaceKeyword:@"%messageDirection%"
   797 				  withString:(([inString rangeOfString:@"<DIV dir=\"rtl\">"].location != NSNotFound) ? @"rtl" : @"ltr")];
   798 	
   799 	//Replaces %time{x}% with a timestamp formatted like x (using NSDateFormatter)
   800 	do{
   801 		range = [inString rangeOfString:@"%time{"];
   802 		if (range.location != NSNotFound) {
   803 			NSRange endRange;
   804 			endRange = [inString rangeOfString:@"}%" options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), [inString length] - NSMaxRange(range))];
   805 			if (endRange.location != NSNotFound && endRange.location > NSMaxRange(range)) {
   806 				if (date) {
   807 					NSString *timeFormat = [inString substringWithRange:NSMakeRange(NSMaxRange(range), (endRange.location - NSMaxRange(range)))];
   808 					
   809 					NSDateFormatter *dateFormatter;
   810 					if ([timeFormat rangeOfString:@"%"].location != NSNotFound) {
   811 						/* Support strftime-style format strings, which old message styles may use */
   812 						dateFormatter = [[NSDateFormatter alloc] initWithDateFormat:timeFormat allowNaturalLanguage:NO];
   813 					} else {
   814 						dateFormatter = [[NSDateFormatter alloc] init];
   815 						[dateFormatter	setFormatterBehavior:NSDateFormatterBehavior10_4];
   816 						[dateFormatter setDateFormat:timeFormat];
   817 					}
   818 					
   819 					[inString safeReplaceCharactersInRange:NSUnionRange(range, endRange) 
   820 												withString:[dateFormatter stringFromDate:date]];
   821 					
   822 					[dateFormatter release];
   823 					
   824 				} else
   825 					[inString deleteCharactersInRange:NSUnionRange(range, endRange)];
   826 				
   827 			}
   828 		}
   829 	} while (range.location != NSNotFound);
   830 	
   831 	do{
   832 		range = [inString rangeOfString:@"%userIconPath%"];
   833 		if (range.location != NSNotFound) {
   834 			NSString    *userIconPath;
   835 			NSString	*replacementString;
   836 			
   837 			userIconPath = [theSource valueForProperty:KEY_WEBKIT_USER_ICON];
   838 			if (!userIconPath) {
   839 				userIconPath = [theSource valueForProperty:@"UserIconPath"];
   840 			}
   841 			
   842 			if (showUserIcons && userIconPath) {
   843 				replacementString = [NSString stringWithFormat:@"file://%@", userIconPath];
   844 				
   845 			} else {
   846 				replacementString = ([content isOutgoing]
   847 									 ? @"Outgoing/buddy_icon.png" 
   848 									 : @"Incoming/buddy_icon.png");
   849 			}
   850 			
   851 			[inString safeReplaceCharactersInRange:range withString:replacementString];
   852 		}
   853 	} while (range.location != NSNotFound);
   854 	
   855 	[inString replaceKeyword:@"%service%" 
   856 				  withString:[content.chat.account.service shortDescription]];
   857 	
   858 	[inString replaceKeyword:@"%serviceIconPath%"
   859 				  withString:[AIServiceIcons pathForServiceIconForServiceID:content.chat.account.service.serviceID
   860 																	   type:AIServiceIconLarge]];
   861 	
   862 	//message stuff
   863 	if ([content isKindOfClass:[AIContentMessage class]]) {
   864 		
   865 		//Use [content source] directly rather than the potentially-metaContact theSource
   866 		NSString *formattedUID = nil;
   867 		if ([content.chat aliasForContact:contentSource]) {
   868 			formattedUID = [content.chat aliasForContact:contentSource];
   869 		} else {
   870 			formattedUID = contentSource.formattedUID;
   871 		}
   872 
   873 		NSString *displayName = [content.chat displayNameForContact:contentSource];
   874 		
   875 		[inString replaceKeyword:@"%status%"
   876 					  withString:@""];
   877 
   878 		[inString replaceKeyword:@"%senderScreenName%" 
   879 					  withString:[(formattedUID ?
   880 								   formattedUID :
   881 								   displayName) stringByEscapingForXMLWithEntities:nil]];
   882 		 
   883         
   884 		[inString replaceKeyword:@"%senderPrefix%"
   885 					  withString:((AIContentMessage *)content).senderPrefix];
   886 		
   887 		do{
   888 			range = [inString rangeOfString:@"%sender%"];
   889 			if (range.location != NSNotFound) {
   890 				NSString		*senderDisplay = nil;
   891 				if (useCustomNameFormat) {
   892 			 		if (formattedUID && ![displayName isEqualToString:formattedUID]) {
   893 						switch (nameFormat) {
   894 							case AIDefaultName:
   895 								break;
   896 
   897 							case AIDisplayName:
   898 								senderDisplay = displayName;
   899 								break;
   900 
   901 							case AIDisplayName_ScreenName:
   902 								senderDisplay = [NSString stringWithFormat:@"%@ (%@)",displayName,formattedUID];
   903 								break;
   904 
   905 							case AIScreenName_DisplayName:
   906 								senderDisplay = [NSString stringWithFormat:@"%@ (%@)",formattedUID,displayName];
   907 								break;
   908 
   909 							case AIScreenName:
   910 								senderDisplay = formattedUID;
   911 								break;
   912 						}
   913 					}
   914 
   915 					//Test both displayName and formattedUID for nil-ness. If they're both nil, the assertion will trip.
   916 					if (!senderDisplay) {
   917 						senderDisplay = displayName;
   918 						if (!senderDisplay) {
   919 							senderDisplay = formattedUID;
   920 							if (!senderDisplay) {
   921 								AILog(@"wtf. we don't have a sender for %@ (%@)", content, [content message]);
   922 								NSAssert1(senderDisplay, @"Sender has no known display name that we can use! displayName and formattedUID were both nil for sender %@", contentSource);
   923 							}
   924 						}
   925 					}
   926 				} else {
   927 					senderDisplay = displayName;
   928 				}
   929 				
   930 				if ([(AIContentMessage *)content isAutoreply]) {
   931 					senderDisplay = [NSString stringWithFormat:@"%@ %@",senderDisplay,AILocalizedString(@"(Autoreply)","Short word inserted after the sender's name when displaying a message which was an autoresponse")];
   932 				}
   933 					
   934 				[inString safeReplaceCharactersInRange:range withString:[senderDisplay stringByEscapingForXMLWithEntities:nil]];
   935 			}
   936 		} while (range.location != NSNotFound);
   937         
   938 		do {
   939 			range = [inString rangeOfString:@"%senderDisplayName%"];
   940 			if (range.location != NSNotFound) {
   941 				NSString *serversideDisplayName = ([theSource isKindOfClass:[AIListContact class]] ?
   942 												   [(AIListContact *)theSource serversideDisplayName] :
   943 												   nil);
   944 				if (!serversideDisplayName) {
   945 					serversideDisplayName = theSource.displayName;
   946 				}
   947 				
   948 				[inString safeReplaceCharactersInRange:range
   949 											withString:[serversideDisplayName stringByEscapingForXMLWithEntities:nil]];
   950 			}
   951 		} while (range.location != NSNotFound);
   952 
   953 		//Blatantly stealing the date code for the background color script.
   954 		do{
   955 			range = [inString rangeOfString:@"%textbackgroundcolor{"];
   956 			if (range.location != NSNotFound) {
   957 				NSRange endRange;
   958 				endRange = [inString rangeOfString:@"}%" options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), [inString length] - NSMaxRange(range))];
   959 				if (endRange.location != NSNotFound && endRange.location > NSMaxRange(range)) {
   960 					NSString *transparency = [inString substringWithRange:NSMakeRange(NSMaxRange(range),
   961 																					  (endRange.location - NSMaxRange(range)))];
   962 					
   963 					if (allowTextBackgrounds && showIncomingColors) {
   964 						NSString *thisIsATemporaryString;
   965 						unsigned rgb = 0, red, green, blue;
   966 						NSScanner *hexcode;
   967 						thisIsATemporaryString = [AIHTMLDecoder encodeHTML:[content message] headers:NO 
   968 																  fontTags:NO
   969 														includingColorTags:NO
   970 															 closeFontTags:NO
   971 																 styleTags:NO
   972 												closeStyleTagsOnFontChange:NO
   973 															encodeNonASCII:NO
   974 															  encodeSpaces:NO
   975 																imagesPath:NSTemporaryDirectory()
   976 														 attachmentsAsText:NO
   977 												 onlyIncludeOutgoingImages:NO
   978 															simpleTagsOnly:NO
   979 															bodyBackground:YES
   980 													   allowJavascriptURLs:NO];
   981 						hexcode = [NSScanner scannerWithString:thisIsATemporaryString];
   982 						[hexcode scanHexInt:&rgb];
   983 						if (![thisIsATemporaryString length] && rgb == 0) {
   984 							[inString deleteCharactersInRange:NSUnionRange(range, endRange)];
   985 						} else {
   986 							red = (rgb & 0xff0000) >> 16;
   987 							green = (rgb & 0x00ff00) >> 8;
   988 							blue = rgb & 0x0000ff;
   989 							[inString safeReplaceCharactersInRange:NSUnionRange(range, endRange)
   990 														withString:[NSString stringWithFormat:@"rgba(%d, %d, %d, %@)", red, green, blue, transparency]];
   991 						}
   992 					} else {
   993 						[inString deleteCharactersInRange:NSUnionRange(range, endRange)];
   994 					}
   995 				} else if (endRange.location == NSMaxRange(range)) {
   996 					if (allowTextBackgrounds && showIncomingColors) {
   997 						NSString *thisIsATemporaryString;
   998 						
   999 						thisIsATemporaryString = [AIHTMLDecoder encodeHTML:[content message] headers:NO 
  1000 																  fontTags:NO
  1001 														includingColorTags:NO
  1002 															 closeFontTags:NO
  1003 																 styleTags:NO
  1004 												closeStyleTagsOnFontChange:NO
  1005 															encodeNonASCII:NO
  1006 															  encodeSpaces:NO
  1007 																imagesPath:NSTemporaryDirectory()
  1008 														 attachmentsAsText:NO
  1009 												 onlyIncludeOutgoingImages:NO
  1010 															simpleTagsOnly:NO
  1011 															bodyBackground:YES
  1012 													   allowJavascriptURLs:NO];
  1013 						[inString safeReplaceCharactersInRange:NSUnionRange(range, endRange) 
  1014 													withString:[NSString stringWithFormat:@"#%@", thisIsATemporaryString]];
  1015 					} else {
  1016 						[inString deleteCharactersInRange:NSUnionRange(range, endRange)];
  1017 					}	
  1018 				}
  1019 			}
  1020 		} while (range.location != NSNotFound);
  1021 
  1022 		if ([content isKindOfClass:[ESFileTransfer class]]) { //file transfers are an AIContentMessage subclass
  1023 		
  1024 			ESFileTransfer *transfer = (ESFileTransfer *)content;
  1025 			NSString *fileName = [[transfer remoteFilename] stringByEscapingForXMLWithEntities:nil];
  1026 			NSString *fileTransferID = [[transfer uniqueID] stringByEscapingForXMLWithEntities:nil];
  1027 
  1028 			range = [inString rangeOfString:@"%fileIconPath%"];
  1029 			if (range.location != NSNotFound) {
  1030 				NSString *iconPath = [self iconPathForFileTransfer:transfer];
  1031 				NSImage *icon = [transfer iconImage];
  1032 				do{
  1033 					[[icon TIFFRepresentation] writeToFile:iconPath atomically:YES];
  1034 					[inString safeReplaceCharactersInRange:range withString:iconPath];
  1035 					range = [inString rangeOfString:@"%fileIconPath%"];
  1036 				} while (range.location != NSNotFound);
  1037 			}
  1038 
  1039 			[inString replaceKeyword:@"%fileName%"
  1040 						  withString:fileName];
  1041 			
  1042 			[inString replaceKeyword:@"%saveFileHandler%"
  1043 						  withString:[NSString stringWithFormat:@"client.handleFileTransfer('Save', '%@')", fileTransferID]];
  1044 			
  1045 			[inString replaceKeyword:@"%saveFileAsHandler%"
  1046 						  withString:[NSString stringWithFormat:@"client.handleFileTransfer('SaveAs', '%@')", fileTransferID]];
  1047 			
  1048 			[inString replaceKeyword:@"%cancelRequestHandler%"
  1049 						  withString:[NSString stringWithFormat:@"client.handleFileTransfer('Cancel', '%@')", fileTransferID]];
  1050 		}
  1051 
  1052 		//Message (must do last)
  1053 		range = [inString rangeOfString:@"%message%"];
  1054 		while(range.location != NSNotFound) {
  1055 			[inString safeReplaceCharactersInRange:range withString:htmlEncodedMessage];
  1056 			range = [inString rangeOfString:@"%message%"
  1057 									options:NSLiteralSearch
  1058 									  range:NSMakeRange(range.location + htmlEncodedMessage.length,
  1059 														inString.length - range.location - htmlEncodedMessage.length)];
  1060 		} 
  1061 		
  1062 		// Topic replacement (if applicable)
  1063 		if ([content isKindOfClass:[AIContentTopic class]]) {
  1064 			range = [inString rangeOfString:@"%topic%"];
  1065 			
  1066 			if (range.location != NSNotFound) {
  1067 				[inString safeReplaceCharactersInRange:range withString:[NSString stringWithFormat:TOPIC_INDIVIDUAL_WRAPPER, htmlEncodedMessage]];
  1068 			}
  1069 		}		
  1070 	} else if ([content isKindOfClass:[AIContentStatus class]]) {
  1071 		NSString	*statusPhrase;
  1072 		BOOL		replacedStatusPhrase = NO;
  1073 		
  1074 		[inString replaceKeyword:@"%status%" 
  1075 				  withString:[[(AIContentStatus *)content status] stringByEscapingForXMLWithEntities:nil]];
  1076 		
  1077 		[inString replaceKeyword:@"%statusSender%" 
  1078 				  withString:[theSource.displayName stringByEscapingForXMLWithEntities:nil]];
  1079 
  1080 		[inString replaceKeyword:@"%senderScreenName%"
  1081 				  withString:@""];
  1082 
  1083 		[inString replaceKeyword:@"%senderPrefix%"
  1084 				  withString:@""];
  1085 
  1086 		[inString replaceKeyword:@"%sender%"
  1087 				  withString:@""];
  1088 
  1089 		if ((statusPhrase = [[content userInfo] objectForKey:@"Status Phrase"])) {
  1090 			do{
  1091 				range = [inString rangeOfString:@"%statusPhrase%"];
  1092 				if (range.location != NSNotFound) {
  1093 					[inString safeReplaceCharactersInRange:range 
  1094 												withString:[statusPhrase stringByEscapingForXMLWithEntities:nil]];
  1095 					replacedStatusPhrase = YES;
  1096 				}
  1097 			} while (range.location != NSNotFound);
  1098 		}
  1099 		
  1100 		//Message (must do last)
  1101 		range = [inString rangeOfString:@"%message%"];
  1102 		if (range.location != NSNotFound) {
  1103 			NSString	*messageString;
  1104 
  1105 			if (replacedStatusPhrase) {
  1106 				//If the status phrase was used, clear the message tag
  1107 				messageString = @"";
  1108 			} else {
  1109 				messageString = [AIHTMLDecoder encodeHTML:[content message]
  1110 												  headers:NO 
  1111 												 fontTags:NO
  1112 									   includingColorTags:NO
  1113 											closeFontTags:YES
  1114 												styleTags:NO
  1115 							   closeStyleTagsOnFontChange:YES
  1116 										   encodeNonASCII:YES
  1117 											 encodeSpaces:YES
  1118 											   imagesPath:NSTemporaryDirectory()
  1119 										attachmentsAsText:NO
  1120 								onlyIncludeOutgoingImages:NO
  1121 										   simpleTagsOnly:NO
  1122 										   bodyBackground:NO
  1123 									  allowJavascriptURLs:NO];
  1124 			}
  1125 			
  1126 			[inString safeReplaceCharactersInRange:range withString:messageString];
  1127 		}
  1128 	}
  1129 
  1130 	return inString;
  1131 }
  1132 
  1133 - (NSMutableString *)fillKeywordsForBaseTemplate:(NSMutableString *)inString chat:(AIChat *)chat
  1134 {
  1135 	NSRange	range;
  1136 	
  1137 	[inString replaceKeyword:@"%chatName%"
  1138 				  withString:[chat.displayName stringByEscapingForXMLWithEntities:nil]];
  1139 
  1140 	NSString * sourceName = [chat.account.displayName stringByEscapingForXMLWithEntities:nil];
  1141 	if(!sourceName) sourceName = @" ";
  1142 	[inString replaceKeyword:@"%sourceName%"
  1143 				  withString:sourceName];
  1144 	
  1145 	NSString *destinationName = chat.listObject.displayName;
  1146 	if (!destinationName) destinationName = chat.displayName;
  1147 	[inString replaceKeyword:@"%destinationName%"
  1148 				  withString:destinationName];
  1149 	
  1150 	NSString *serversideDisplayName = chat.listObject.serversideDisplayName;
  1151 	if (!serversideDisplayName) serversideDisplayName = chat.displayName;
  1152 	[inString replaceKeyword:@"%destinationDisplayName%"
  1153 				  withString:[serversideDisplayName stringByEscapingForXMLWithEntities:nil]];
  1154 		
  1155 	AIListContact	*listObject = chat.listObject;
  1156 	NSString		*iconPath = nil;
  1157 	
  1158 	[inString replaceKeyword:@"%incomingColor%"
  1159 				  withString:[NSColor representedColorForObject:listObject.UID withValidColors:self.validSenderColors]];
  1160 	
  1161 	[inString replaceKeyword:@"%outgoingColor%"
  1162 				  withString:[NSColor representedColorForObject:chat.account.UID withValidColors:self.validSenderColors]];
  1163 	
  1164 	if (listObject) {
  1165 		iconPath = [listObject valueForProperty:KEY_WEBKIT_USER_ICON];
  1166 		if (!iconPath) {
  1167 			iconPath = [listObject valueForProperty:@"UserIconPath"];
  1168 		}
  1169 	}
  1170 	[inString replaceKeyword:@"%incomingIconPath%"
  1171 				  withString:(iconPath ? iconPath : @"incoming_icon.png")];
  1172 	
  1173 	AIListObject	*account = chat.account;
  1174 	iconPath = nil;
  1175 	
  1176 	if (account) {
  1177 		iconPath = [account valueForProperty:KEY_WEBKIT_USER_ICON];
  1178 		if (!iconPath) {
  1179 			iconPath = [account valueForProperty:@"UserIconPath"];
  1180 		}
  1181 	}
  1182 	[inString replaceKeyword:@"%outgoingIconPath%"
  1183 				  withString:(iconPath ? iconPath : @"outgoing_icon.png")];
  1184 	
  1185 	NSString *serviceIconPath = [AIServiceIcons pathForServiceIconForServiceID:account.service.serviceID
  1186 																		  type:AIServiceIconLarge];
  1187 	
  1188 	NSString *serviceIconTag = [NSString stringWithFormat:@"<img class=\"serviceIcon\" src=\"%@\" alt=\"%@\" title=\"%@\">", serviceIconPath ? serviceIconPath : @"outgoing_icon.png", [account.service shortDescription], [account.service shortDescription]];
  1189 	
  1190 	[inString replaceKeyword:@"%serviceIconImg%"
  1191 				  withString:serviceIconTag];
  1192 	
  1193 	[inString replaceKeyword:@"%serviceIconPath%"
  1194 				  withString:serviceIconPath];
  1195 	
  1196 	[inString replaceKeyword:@"%timeOpened%"
  1197 				  withString:[timeStampFormatter stringFromDate:[chat dateOpened]]];
  1198 	
  1199 	//Replaces %time{x}% with a timestamp formatted like x (using NSDateFormatter)
  1200 	do{
  1201 		range = [inString rangeOfString:@"%timeOpened{"];
  1202 		if (range.location != NSNotFound) {
  1203 			NSRange endRange;
  1204 			endRange = [inString rangeOfString:@"}%" options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), [inString length] - NSMaxRange(range))];
  1205 
  1206 			if (endRange.location != NSNotFound && endRange.location > NSMaxRange(range)) {				
  1207 				NSString		*timeFormat = [inString substringWithRange:NSMakeRange(NSMaxRange(range), (endRange.location - NSMaxRange(range)))];
  1208 				
  1209 				NSDateFormatter *dateFormatter;
  1210 				if ([timeFormat rangeOfString:@"%"].location != NSNotFound) {
  1211 					/* Support strftime-style format strings, which old message styles may use */
  1212 					dateFormatter = [[NSDateFormatter alloc] initWithDateFormat:timeFormat allowNaturalLanguage:NO];
  1213 				} else {
  1214 					dateFormatter = [[NSDateFormatter alloc] init];
  1215 					[dateFormatter	setFormatterBehavior:NSDateFormatterBehavior10_4];
  1216 					[dateFormatter setDateFormat:timeFormat];
  1217 				}
  1218 				
  1219 				[inString safeReplaceCharactersInRange:NSUnionRange(range, endRange) 
  1220 												withString:[dateFormatter stringFromDate:[chat dateOpened]]];
  1221 				[dateFormatter release];
  1222 				
  1223 			}
  1224 		}
  1225 	} while (range.location != NSNotFound);
  1226 	
  1227 	[inString replaceKeyword:@"%dateOpened%"
  1228 				  withString:[[NSDateFormatter localizedDateFormatter] stringFromDate:[chat dateOpened]]];
  1229 	
  1230 	//Background
  1231 	{
  1232 		range = [inString rangeOfString:@"==bodyBackground=="];
  1233 		
  1234 		if (range.location != NSNotFound) { //a backgroundImage tag is not required
  1235 			NSMutableString *bodyTag = nil;
  1236 
  1237 			if (allowsCustomBackground && (customBackgroundPath || customBackgroundColor)) {				
  1238 				bodyTag = [[[NSMutableString alloc] init] autorelease];
  1239 				
  1240 				if (customBackgroundPath) {
  1241 					if ([customBackgroundPath length]) {
  1242 						switch (customBackgroundType) {
  1243 							case BackgroundNormal:
  1244 								[bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-repeat: no-repeat; background-attachment:fixed;", customBackgroundPath]];
  1245 							break;
  1246 							case BackgroundCenter:
  1247 								[bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-position: center; background-repeat: no-repeat; background-attachment:fixed;", customBackgroundPath]];
  1248 							break;
  1249 							case BackgroundTile:
  1250 								[bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-repeat: repeat;", customBackgroundPath]];
  1251 							break;
  1252 							case BackgroundTileCenter:
  1253 								[bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-repeat: repeat; background-position: center;", customBackgroundPath]];
  1254 							break;
  1255 							case BackgroundScale:
  1256 								[bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); -webkit-background-size: 100%% 100%%; background-size: 100%% 100%%; background-attachment: fixed;", customBackgroundPath]];
  1257 							break;
  1258 						}
  1259 					} else {
  1260 						[bodyTag appendString:@"background-image: none; "];
  1261 					}
  1262 				}
  1263 				if (customBackgroundColor) {
  1264 					CGFloat red, green, blue, alpha;
  1265 					[customBackgroundColor getRed:&red green:&green blue:&blue alpha:&alpha];
  1266 					[bodyTag appendString:[NSString stringWithFormat:@"background-color: rgba(%ld, %ld, %ld, %f); ", (NSInteger)(red * 255.0), (NSInteger)(green * 255.0), (NSInteger)(blue * 255.0), alpha]];
  1267 				}
  1268  			}
  1269 			
  1270 			//Replace the body background tag
  1271  			[inString safeReplaceCharactersInRange:range withString:(bodyTag ? (NSString *)bodyTag : @"")];
  1272  		}
  1273  	}
  1274 
  1275 	return inString;
  1276 }
  1277 
  1278 #pragma mark Icons
  1279 
  1280 - (NSString *)iconPathForFileTransfer:(ESFileTransfer *)inObject
  1281 {
  1282 	NSString	*filename = [NSString stringWithFormat:@"TEMP-%@%@.tiff", [inObject remoteFilename], [NSString randomStringOfLength:5]];
  1283 	return [[adium cachesPath] stringByAppendingPathComponent:filename];
  1284 }
  1285 
  1286 - (NSString *)statusIconPathForListObject:(AIListObject *)inObject
  1287 {
  1288 	if(!statusIconPathCache) statusIconPathCache = [[NSMutableDictionary alloc] init];
  1289 	NSImage *icon = [AIStatusIcons statusIconForListObject:inObject
  1290 													  type:AIStatusIconTab
  1291 												 direction:AIIconNormal];
  1292 	NSString *statusName = [AIStatusIcons statusNameForListObject:inObject];
  1293 	if(!statusName)
  1294 		statusName = @"UnknownStatus";
  1295 	NSString *path = [statusIconPathCache objectForKey:statusName];
  1296 	if(!path)
  1297 	{
  1298 		path = [[adium cachesPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"TEMP-%@%@.tiff", statusName, [NSString randomStringOfLength:5]]];
  1299 		[[icon TIFFRepresentation] writeToFile:path atomically:YES];
  1300 		[statusIconPathCache setObject:path forKey:statusName];
  1301 	}
  1302 
  1303 	return path;
  1304 }
  1305 
  1306 @end