Only add color tags if a style supports colors. Fixes #13286.
2 * Adium is the legal property of its developers, whose names are listed in the copyright file included
3 * with this source distribution.
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.
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.
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.
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>
40 #define LEGACY_VERSION_THRESHOLD 3 //Styles older than this version are considered legacy
43 #define KEY_WEBKIT_VERSION @"MessageViewVersion"
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(\"%@\");"
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>"
58 @interface NSMutableString (AIKeywordReplacementAdditions)
59 - (void) replaceKeyword:(NSString *)word withString:(NSString *)newWord;
60 - (void) safeReplaceCharactersInRange:(NSRange)range withString:(NSString *)newWord;
63 @implementation NSMutableString (AIKeywordReplacementAdditions)
64 - (void) replaceKeyword:(NSString *)keyWord withString:(NSString *)newWord
67 if(!newWord) newWord = @"";
68 [self replaceOccurrencesOfString:keyWord
70 options:NSLiteralSearch
71 range:NSMakeRange(0.0, [self length])];
74 - (void) safeReplaceCharactersInRange:(NSRange)range withString:(NSString *)newWord
76 if (range.location == NSNotFound || range.length == 0) return;
77 if (!newWord) [self deleteCharactersInRange:range];
78 else [self replaceCharactersInRange:range withString:newWord];
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;
90 @implementation NSBundle (StupidCompatibilityHack)
91 - (NSString *)semiCaseInsensitivePathForResource:(NSString *)res ofType:(NSString *)type
93 NSString *path = [self pathForResource:res ofType:type];
95 path = [self pathForResource:[res lowercaseString] ofType:type];
99 - (NSString *)semiCaseInsensitivePathForResource:(NSString *)res ofType:(NSString *)type inDirectory:(NSString *)dirpath
101 NSString *path = [self pathForResource:res ofType:type inDirectory:dirpath];
103 path = [self pathForResource:[res lowercaseString] ofType:type inDirectory:dirpath];
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;
119 @implementation AIWebkitMessageViewStyle
121 + (id)messageViewStyleFromBundle:(NSBundle *)inBundle
123 return [[[self alloc] initWithBundle:inBundle] autorelease];
126 + (id)messageViewStyleFromPath:(NSString *)path
128 NSBundle *styleBundle = [NSBundle bundleWithPath:path];
130 return [[[self alloc] initWithBundle:styleBundle] autorelease];
137 - (id)initWithBundle:(NSBundle *)inBundle
139 if ((self = [super init])) {
140 styleBundle = [inBundle retain];
141 stylePath = [[styleBundle resourcePath] retain];
150 [self releaseResources];
153 allowTextBackgrounds = YES;
155 /* Our styles are versioned so we can change how they work without breaking compatibility.
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.
171 styleVersion = [[styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_VERSION] integerValue];
173 //Pre-fetch our templates
174 [self _loadTemplates];
177 allowsCustomBackground = ![[styleBundle objectForInfoDictionaryKey:@"DisableCustomBackground"] boolValue];
178 transparentDefaultBackground = [[styleBundle objectForInfoDictionaryKey:@"DefaultBackgroundIsTransparent"] boolValue];
180 combineConsecutive = ![[styleBundle objectForInfoDictionaryKey:@"DisableCombineConsecutive"] boolValue];
182 NSNumber *tmpNum = [styleBundle objectForInfoDictionaryKey:@"ShowsUserIcons"];
183 allowsUserIcons = (tmpNum ? [tmpNum boolValue] : YES);
186 NSString *tmpName = [styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_USER_ICON_MASK];
187 if (tmpName) userIconMask = [[NSImage alloc] initWithContentsOfFile:[stylePath stringByAppendingPathComponent:tmpName]];
189 NSNumber *allowsColorsNumber = [styleBundle objectForInfoDictionaryKey:@"AllowTextColors"];
190 allowsColors = (allowsColorsNumber ? [allowsColorsNumber boolValue] : YES);
194 * @brief release everything we loaded from the style bundle
196 - (void)releaseResources
199 [headerHTML release];
200 [footerHTML 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];
215 [customBackgroundPath release];
216 [customBackgroundColor release];
218 [userIconMask release];
226 [styleBundle release];
229 [self releaseResources];
230 [timeStampFormatter release];
232 [statusIconPathCache release];
237 @synthesize bundle = styleBundle;
241 return styleVersion < LEGACY_VERSION_THRESHOLD;
244 #pragma mark Settings
246 @synthesize allowsCustomBackground, allowsUserIcons, allowsColors, userIconMask;
248 - (NSArray *)validSenderColors
250 if(!checkedSenderColors) {
251 NSURL *url = [NSURL fileURLWithPath:[stylePath stringByAppendingPathComponent:@"Incoming/SenderColors.txt"]];
252 NSString *senderColorsFile = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
255 validSenderColors = [[senderColorsFile componentsSeparatedByString:@":"] retain];
257 checkedSenderColors = YES;
260 return validSenderColors;
263 - (BOOL)isBackgroundTransparent
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));
270 - (NSString *)defaultFontFamily
272 NSString *defaultFontFamily = [styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_DEFAULT_FONT_FAMILY];
273 if (!defaultFontFamily) defaultFontFamily = [[NSFont systemFontOfSize:0] familyName];
275 return defaultFontFamily;
278 - (NSNumber *)defaultFontSize
280 NSNumber *defaultFontSize = [styleBundle objectForInfoDictionaryKey:KEY_WEBKIT_DEFAULT_FONT_SIZE];
282 if (!defaultFontSize) defaultFontSize = [NSNumber numberWithInteger:[[NSFont systemFontOfSize:0] pointSize]];
284 return defaultFontSize;
289 return headerHTML && [headerHTML length];
294 return topicHTML && [topicHTML length];
297 #pragma mark Behavior
299 - (void)setDateFormat:(NSString *)format
301 if (!format || [format length] == 0) {
302 format = [NSDateFormatter localizedDateFormatStringShowingSeconds:NO showingAMorPM:NO];
305 [timeStampFormatter release];
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];
311 timeStampFormatter = [[NSDateFormatter alloc] init];
312 [timeStampFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
313 [timeStampFormatter setDateFormat:format];
317 @synthesize allowTextBackgrounds, customBackgroundType, customBackgroundColor, showIncomingMessageColors=showIncomingColors, showIncomingMessageFonts=showIncomingFonts, customBackgroundPath, nameFormat, useCustomNameFormat, showHeader, showUserIcons;
319 //Templates ------------------------------------------------------------------------------------------------------------
320 #pragma mark Templates
321 - (NSString *)baseTemplateWithVariant:(NSString *)variant chat:(AIChat *)chat
323 NSMutableString *templateHTML;
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 = @"";
329 if (chat.isGroupChat) {
330 headerContent = (chat.supportsTopic ? TOPIC_MAIN_DIV : @"");
331 } else if (headerHTML) {
332 headerContent = headerHTML;
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
343 (footerHTML ? footerHTML : @"")];
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
350 (footerHTML ? footerHTML : @"")];
353 return [self fillKeywordsForBaseTemplate:templateHTML chat:chat];
356 - (NSString *)templateForContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar
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);
365 template = (contentIsSimilar ? nextContentInHTML : contentInHTML);
368 } else if ([[content type] isEqualToString:CONTENT_CONTEXT_TYPE]) {
369 if ([content isOutgoing]) {
370 template = (contentIsSimilar ? nextContextOutHTML : contextOutHTML);
372 template = (contentIsSimilar ? nextContextInHTML : contextInHTML);
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;
381 template = statusHTML;
387 - (NSString *)completedTemplateForContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar
389 NSMutableString *mutableTemplate = [[self templateForContent:content similar:contentIsSimilar] mutableCopy];
391 if (mutableTemplate) {
392 mutableTemplate = [self fillKeywords:mutableTemplate forContent:content similar:contentIsSimilar];
395 return [mutableTemplate autorelease];
399 * @brief Pre-fetch all the style templates
401 * This needs to be called before either baseTemplate or templateForContent is called
403 - (void)_loadTemplates
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"]];
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;
419 usingCustomTemplateHTML = YES;
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.
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"
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"
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"
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"
472 " alignChat(shouldScroll);\n"
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"
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"
493 options:NSLiteralSearch];
494 baseHTML = imageSwapFixedBaseHTML;
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];
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];
513 //Fall back to Resources/Content.html if Incoming isn't present
514 if (!contentInHTML) contentInHTML = [contentHTML retain];
516 //Fall back to Content if NextContent doesn't need to use different HTML
517 if (!nextContentInHTML) nextContentInHTML = [contentInHTML retain];
519 //Fall back to Content if Context isn't present
520 if (!nextContextInHTML) nextContextInHTML = [nextContentInHTML retain];
521 if (!contextInHTML) contextInHTML = [contentInHTML retain];
523 //Fall back to Content if Context isn't present
524 if (!nextContextOutHTML && nextContentOutHTML) nextContextOutHTML = [nextContentOutHTML retain];
525 if (!contextOutHTML && contentOutHTML) contextOutHTML = [contentOutHTML retain];
527 //Fall back to Content if Context isn't present
528 if (!nextContextOutHTML) nextContextOutHTML = [nextContextInHTML retain];
529 if (!contextOutHTML) contextOutHTML = [contextInHTML retain];
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];
536 statusHTML = [[NSString stringWithContentsOfUTF8File:[styleBundle semiCaseInsensitivePathForResource:@"Status" ofType:@"html"]] retain];
538 //Fall back to Resources/Incoming/Content.html if Status isn't present
539 if (!statusHTML) statusHTML = [contentInHTML retain];
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>"];
549 [fileTransferHTMLTemplate replaceKeyword:@"Download %fileName%"
550 withString:[NSString stringWithFormat:AILocalizedString(@"Download %@", "%@ will be a file name"), @"%fileName%"]];
551 fileTransferHTML = fileTransferHTMLTemplate;
555 - (NSString *)scriptForAppendingContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar willAddMoreContentObjects:(BOOL)willAddMoreContentObjects replaceLastContent:(BOOL)replaceLastContent
557 NSMutableString *newHTML;
560 //If combining of consecutive messages has been disabled, we treat all content as non-similar
561 if (!combineConsecutive) contentIsSimilar = NO;
563 //Fetch the correct template and substitute keywords for the passed content
564 newHTML = [[[self completedTemplateForContent:content similar:contentIsSimilar] mutableCopy] autorelease];
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);
574 script = (contentIsSimilar ? APPEND_NEXT_MESSAGE : APPEND_MESSAGE);
577 } else if (styleVersion >= 3) {
578 if (willAddMoreContentObjects) {
579 script = (contentIsSimilar ? APPEND_NEXT_MESSAGE_NO_SCROLL : APPEND_MESSAGE_NO_SCROLL);
581 script = (contentIsSimilar ? APPEND_NEXT_MESSAGE : APPEND_MESSAGE);
583 } else if (styleVersion >= 1) {
584 script = (contentIsSimilar ? APPEND_NEXT_MESSAGE : APPEND_MESSAGE);
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.
591 script = APPEND_MESSAGE_WITH_SCROLL;
593 script = (contentIsSimilar ? APPEND_NEXT_MESSAGE_WITH_SCROLL : APPEND_MESSAGE_WITH_SCROLL);
597 return [NSString stringWithFormat:script, [self _escapeStringForPassingToScript:newHTML]];
600 - (NSString *)scriptForChangingVariant:(NSString *)variant
602 AILogWithSignature(@"%@",[NSString stringWithFormat:@"setStylesheet(\"mainStyle\",\"%@\");",[self pathForVariant:variant]]);
604 return [NSString stringWithFormat:@"setStylesheet(\"mainStyle\",\"%@\");",[self pathForVariant:variant]];
607 - (NSString *)scriptForScrollingAfterAddingMultipleContentObjects
609 if ((styleVersion >= 3) || !usingCustomTemplateHTML) {
610 return @"alignChat(true);";
617 * @brief Escape a string for passing to our BOM scripts
619 - (NSMutableString *)_escapeStringForPassingToScript:(NSMutableString *)inString
621 //We need to escape a few things to get our string to the javascript without trouble
622 [inString replaceOccurrencesOfString:@"\\"
624 options:NSLiteralSearch];
626 [inString replaceOccurrencesOfString:@"\""
628 options:NSLiteralSearch];
630 [inString replaceOccurrencesOfString:@"\n"
632 options:NSLiteralSearch];
634 [inString replaceOccurrencesOfString:@"\r"
636 options:NSLiteralSearch];
641 #pragma mark Variants
643 - (NSArray *)availableVariants
645 NSMutableArray *availableVariants = [NSMutableArray array];
647 //Build an array of all variant names
648 for (NSString *path in [styleBundle pathsForResourcesOfType:@"css" inDirectory:@"Variants"]) {
649 [availableVariants addObject:[[path lastPathComponent] stringByDeletingPathExtension]];
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]];
658 //Alphabetize the variants
659 [availableVariants sortUsingSelector:@selector(compare:)];
661 return availableVariants;
664 - (NSString *)pathForVariant:(NSString *)variant
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]]) {
670 return [NSString stringWithFormat:@"Variants/%@.css",variant];
675 * @brief Base variant name for styles before version 2
677 - (NSString *)noVariantName
679 NSString *noVariantName = [styleBundle objectForInfoDictionaryKey:@"DisplayNameForNoVariant"];
680 return noVariantName ? noVariantName : AILocalizedString(@"Normal","Normal style variant menu item");
683 + (NSString *)noVariantNameForBundle:(NSBundle *)inBundle
685 NSString *noVariantName = [inBundle objectForInfoDictionaryKey:@"DisplayNameForNoVariant"];
686 return noVariantName ? noVariantName : AILocalizedString(@"Normal","Normal style variant menu item");
689 - (NSString *)defaultVariant
691 return styleVersion < 3 ? [self noVariantName] : [styleBundle objectForInfoDictionaryKey:@"DefaultVariant"];
694 + (NSString *)defaultVariantForBundle:(NSBundle *)inBundle
696 return [[inBundle objectForInfoDictionaryKey:KEY_WEBKIT_VERSION] integerValue] < 3 ?
697 [self noVariantNameForBundle:inBundle] :
698 [inBundle objectForInfoDictionaryKey:@"DefaultVariant"];
701 #pragma mark Keyword replacement
703 - (NSMutableString *)fillKeywords:(NSMutableString *)inString forContent:(AIContentObject *)content similar:(BOOL)contentIsSimilar
707 AIListObject *contentSource = [content source];
708 AIListObject *theSource = ([contentSource isKindOfClass:[AIListContact class]] ?
709 [(AIListContact *)contentSource parentContact] :
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
717 NSString *htmlEncodedMessage = [AIHTMLDecoder encodeHTML:[content message]
719 fontTags:showIncomingFonts
720 includingColorTags:(allowsColors && showIncomingColors)
723 closeStyleTagsOnFontChange:YES
726 imagesPath:NSTemporaryDirectory()
728 onlyIncludeOutgoingImages:NO
731 allowJavascriptURLs:NO];
733 if (styleVersion >= 4)
734 htmlEncodedMessage = [adium.contentController filterHTMLString:htmlEncodedMessage
735 direction:[content isOutgoing] ? AIFilterOutgoing : AIFilterIncoming
739 if ([content respondsToSelector:@selector(date)])
740 date = [(AIContentMessage *)content date];
742 //Replacements applicable to any AIContentObject
743 [inString replaceKeyword:@"%time%"
744 withString:(date ? [timeStampFormatter stringFromDate:date] : @"")];
746 NSString *shortTimeString = (date ? [[NSDateFormatter localizedDateFormatterShowingSeconds:NO showingAMorPM:NO] stringFromDate:date] : @"");
747 [inString replaceKeyword:@"%shortTime%"
748 withString:shortTimeString];
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]];
756 //Replaces %localized{x}% with a a localized version of x, searching the style's localizations, and then Adium's localizations
758 range = [inString rangeOfString:@"%localized{"];
759 if (range.location != NSNotFound) {
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)))];
765 NSString *translated = [styleBundle localizedStringForKey:untranslated
768 if (!translated || [translated length] == 0) {
769 translated = [[NSBundle bundleForClass:[self class]] localizedStringForKey:untranslated
772 if (!translated || [translated length] == 0) {
773 translated = [[NSBundle mainBundle] localizedStringForKey:untranslated
780 [inString safeReplaceCharactersInRange:NSUnionRange(range, endRange)
781 withString:translated];
784 } while (range.location != NSNotFound);
786 [inString replaceKeyword:@"%userIcons%"
787 withString:(showUserIcons ? @"showIcons" : @"hideIcons")];
789 [inString replaceKeyword:@"%messageClasses%"
790 withString:[(contentIsSimilar ? @"consecutive " : @"") stringByAppendingString:[[content displayClasses] componentsJoinedByString:@" "]]];
792 [inString replaceKeyword:@"%senderColor%"
793 withString:[NSColor representedColorForObject:contentSource.UID withValidColors:self.validSenderColors]];
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")];
799 //Replaces %time{x}% with a timestamp formatted like x (using NSDateFormatter)
801 range = [inString rangeOfString:@"%time{"];
802 if (range.location != NSNotFound) {
804 endRange = [inString rangeOfString:@"}%" options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), [inString length] - NSMaxRange(range))];
805 if (endRange.location != NSNotFound && endRange.location > NSMaxRange(range)) {
807 NSString *timeFormat = [inString substringWithRange:NSMakeRange(NSMaxRange(range), (endRange.location - NSMaxRange(range)))];
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];
814 dateFormatter = [[NSDateFormatter alloc] init];
815 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
816 [dateFormatter setDateFormat:timeFormat];
819 [inString safeReplaceCharactersInRange:NSUnionRange(range, endRange)
820 withString:[dateFormatter stringFromDate:date]];
822 [dateFormatter release];
825 [inString deleteCharactersInRange:NSUnionRange(range, endRange)];
829 } while (range.location != NSNotFound);
832 range = [inString rangeOfString:@"%userIconPath%"];
833 if (range.location != NSNotFound) {
834 NSString *userIconPath;
835 NSString *replacementString;
837 userIconPath = [theSource valueForProperty:KEY_WEBKIT_USER_ICON];
839 userIconPath = [theSource valueForProperty:@"UserIconPath"];
842 if (showUserIcons && userIconPath) {
843 replacementString = [NSString stringWithFormat:@"file://%@", userIconPath];
846 replacementString = ([content isOutgoing]
847 ? @"Outgoing/buddy_icon.png"
848 : @"Incoming/buddy_icon.png");
851 [inString safeReplaceCharactersInRange:range withString:replacementString];
853 } while (range.location != NSNotFound);
855 [inString replaceKeyword:@"%service%"
856 withString:[content.chat.account.service shortDescription]];
858 [inString replaceKeyword:@"%serviceIconPath%"
859 withString:[AIServiceIcons pathForServiceIconForServiceID:content.chat.account.service.serviceID
860 type:AIServiceIconLarge]];
863 if ([content isKindOfClass:[AIContentMessage class]]) {
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];
870 formattedUID = contentSource.formattedUID;
873 NSString *displayName = [content.chat displayNameForContact:contentSource];
875 [inString replaceKeyword:@"%status%"
878 [inString replaceKeyword:@"%senderScreenName%"
879 withString:[(formattedUID ?
881 displayName) stringByEscapingForXMLWithEntities:nil]];
884 [inString replaceKeyword:@"%senderPrefix%"
885 withString:((AIContentMessage *)content).senderPrefix];
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) {
898 senderDisplay = displayName;
901 case AIDisplayName_ScreenName:
902 senderDisplay = [NSString stringWithFormat:@"%@ (%@)",displayName,formattedUID];
905 case AIScreenName_DisplayName:
906 senderDisplay = [NSString stringWithFormat:@"%@ (%@)",formattedUID,displayName];
910 senderDisplay = formattedUID;
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);
927 senderDisplay = displayName;
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")];
934 [inString safeReplaceCharactersInRange:range withString:[senderDisplay stringByEscapingForXMLWithEntities:nil]];
936 } while (range.location != NSNotFound);
939 range = [inString rangeOfString:@"%senderDisplayName%"];
940 if (range.location != NSNotFound) {
941 NSString *serversideDisplayName = ([theSource isKindOfClass:[AIListContact class]] ?
942 [(AIListContact *)theSource serversideDisplayName] :
944 if (!serversideDisplayName) {
945 serversideDisplayName = theSource.displayName;
948 [inString safeReplaceCharactersInRange:range
949 withString:[serversideDisplayName stringByEscapingForXMLWithEntities:nil]];
951 } while (range.location != NSNotFound);
953 //Blatantly stealing the date code for the background color script.
955 range = [inString rangeOfString:@"%textbackgroundcolor{"];
956 if (range.location != NSNotFound) {
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)))];
963 if (allowTextBackgrounds && showIncomingColors) {
964 NSString *thisIsATemporaryString;
965 unsigned rgb = 0, red, green, blue;
967 thisIsATemporaryString = [AIHTMLDecoder encodeHTML:[content message] headers:NO
969 includingColorTags:NO
972 closeStyleTagsOnFontChange:NO
975 imagesPath:NSTemporaryDirectory()
977 onlyIncludeOutgoingImages:NO
980 allowJavascriptURLs:NO];
981 hexcode = [NSScanner scannerWithString:thisIsATemporaryString];
982 [hexcode scanHexInt:&rgb];
983 if (![thisIsATemporaryString length] && rgb == 0) {
984 [inString deleteCharactersInRange:NSUnionRange(range, endRange)];
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]];
993 [inString deleteCharactersInRange:NSUnionRange(range, endRange)];
995 } else if (endRange.location == NSMaxRange(range)) {
996 if (allowTextBackgrounds && showIncomingColors) {
997 NSString *thisIsATemporaryString;
999 thisIsATemporaryString = [AIHTMLDecoder encodeHTML:[content message] headers:NO
1001 includingColorTags:NO
1004 closeStyleTagsOnFontChange:NO
1007 imagesPath:NSTemporaryDirectory()
1008 attachmentsAsText:NO
1009 onlyIncludeOutgoingImages:NO
1012 allowJavascriptURLs:NO];
1013 [inString safeReplaceCharactersInRange:NSUnionRange(range, endRange)
1014 withString:[NSString stringWithFormat:@"#%@", thisIsATemporaryString]];
1016 [inString deleteCharactersInRange:NSUnionRange(range, endRange)];
1020 } while (range.location != NSNotFound);
1022 if ([content isKindOfClass:[ESFileTransfer class]]) { //file transfers are an AIContentMessage subclass
1024 ESFileTransfer *transfer = (ESFileTransfer *)content;
1025 NSString *fileName = [[transfer remoteFilename] stringByEscapingForXMLWithEntities:nil];
1026 NSString *fileTransferID = [[transfer uniqueID] stringByEscapingForXMLWithEntities:nil];
1028 range = [inString rangeOfString:@"%fileIconPath%"];
1029 if (range.location != NSNotFound) {
1030 NSString *iconPath = [self iconPathForFileTransfer:transfer];
1031 NSImage *icon = [transfer iconImage];
1033 [[icon TIFFRepresentation] writeToFile:iconPath atomically:YES];
1034 [inString safeReplaceCharactersInRange:range withString:iconPath];
1035 range = [inString rangeOfString:@"%fileIconPath%"];
1036 } while (range.location != NSNotFound);
1039 [inString replaceKeyword:@"%fileName%"
1040 withString:fileName];
1042 [inString replaceKeyword:@"%saveFileHandler%"
1043 withString:[NSString stringWithFormat:@"client.handleFileTransfer('Save', '%@')", fileTransferID]];
1045 [inString replaceKeyword:@"%saveFileAsHandler%"
1046 withString:[NSString stringWithFormat:@"client.handleFileTransfer('SaveAs', '%@')", fileTransferID]];
1048 [inString replaceKeyword:@"%cancelRequestHandler%"
1049 withString:[NSString stringWithFormat:@"client.handleFileTransfer('Cancel', '%@')", fileTransferID]];
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)];
1062 // Topic replacement (if applicable)
1063 if ([content isKindOfClass:[AIContentTopic class]]) {
1064 range = [inString rangeOfString:@"%topic%"];
1066 if (range.location != NSNotFound) {
1067 [inString safeReplaceCharactersInRange:range withString:[NSString stringWithFormat:TOPIC_INDIVIDUAL_WRAPPER, htmlEncodedMessage]];
1070 } else if ([content isKindOfClass:[AIContentStatus class]]) {
1071 NSString *statusPhrase;
1072 BOOL replacedStatusPhrase = NO;
1074 [inString replaceKeyword:@"%status%"
1075 withString:[[(AIContentStatus *)content status] stringByEscapingForXMLWithEntities:nil]];
1077 [inString replaceKeyword:@"%statusSender%"
1078 withString:[theSource.displayName stringByEscapingForXMLWithEntities:nil]];
1080 [inString replaceKeyword:@"%senderScreenName%"
1083 [inString replaceKeyword:@"%senderPrefix%"
1086 [inString replaceKeyword:@"%sender%"
1089 if ((statusPhrase = [[content userInfo] objectForKey:@"Status Phrase"])) {
1091 range = [inString rangeOfString:@"%statusPhrase%"];
1092 if (range.location != NSNotFound) {
1093 [inString safeReplaceCharactersInRange:range
1094 withString:[statusPhrase stringByEscapingForXMLWithEntities:nil]];
1095 replacedStatusPhrase = YES;
1097 } while (range.location != NSNotFound);
1100 //Message (must do last)
1101 range = [inString rangeOfString:@"%message%"];
1102 if (range.location != NSNotFound) {
1103 NSString *messageString;
1105 if (replacedStatusPhrase) {
1106 //If the status phrase was used, clear the message tag
1107 messageString = @"";
1109 messageString = [AIHTMLDecoder encodeHTML:[content message]
1112 includingColorTags:NO
1115 closeStyleTagsOnFontChange:YES
1118 imagesPath:NSTemporaryDirectory()
1119 attachmentsAsText:NO
1120 onlyIncludeOutgoingImages:NO
1123 allowJavascriptURLs:NO];
1126 [inString safeReplaceCharactersInRange:range withString:messageString];
1133 - (NSMutableString *)fillKeywordsForBaseTemplate:(NSMutableString *)inString chat:(AIChat *)chat
1137 [inString replaceKeyword:@"%chatName%"
1138 withString:[chat.displayName stringByEscapingForXMLWithEntities:nil]];
1140 NSString * sourceName = [chat.account.displayName stringByEscapingForXMLWithEntities:nil];
1141 if(!sourceName) sourceName = @" ";
1142 [inString replaceKeyword:@"%sourceName%"
1143 withString:sourceName];
1145 NSString *destinationName = chat.listObject.displayName;
1146 if (!destinationName) destinationName = chat.displayName;
1147 [inString replaceKeyword:@"%destinationName%"
1148 withString:destinationName];
1150 NSString *serversideDisplayName = chat.listObject.serversideDisplayName;
1151 if (!serversideDisplayName) serversideDisplayName = chat.displayName;
1152 [inString replaceKeyword:@"%destinationDisplayName%"
1153 withString:[serversideDisplayName stringByEscapingForXMLWithEntities:nil]];
1155 AIListContact *listObject = chat.listObject;
1156 NSString *iconPath = nil;
1158 [inString replaceKeyword:@"%incomingColor%"
1159 withString:[NSColor representedColorForObject:listObject.UID withValidColors:self.validSenderColors]];
1161 [inString replaceKeyword:@"%outgoingColor%"
1162 withString:[NSColor representedColorForObject:chat.account.UID withValidColors:self.validSenderColors]];
1165 iconPath = [listObject valueForProperty:KEY_WEBKIT_USER_ICON];
1167 iconPath = [listObject valueForProperty:@"UserIconPath"];
1170 [inString replaceKeyword:@"%incomingIconPath%"
1171 withString:(iconPath ? iconPath : @"incoming_icon.png")];
1173 AIListObject *account = chat.account;
1177 iconPath = [account valueForProperty:KEY_WEBKIT_USER_ICON];
1179 iconPath = [account valueForProperty:@"UserIconPath"];
1182 [inString replaceKeyword:@"%outgoingIconPath%"
1183 withString:(iconPath ? iconPath : @"outgoing_icon.png")];
1185 NSString *serviceIconPath = [AIServiceIcons pathForServiceIconForServiceID:account.service.serviceID
1186 type:AIServiceIconLarge];
1188 NSString *serviceIconTag = [NSString stringWithFormat:@"<img class=\"serviceIcon\" src=\"%@\" alt=\"%@\" title=\"%@\">", serviceIconPath ? serviceIconPath : @"outgoing_icon.png", [account.service shortDescription], [account.service shortDescription]];
1190 [inString replaceKeyword:@"%serviceIconImg%"
1191 withString:serviceIconTag];
1193 [inString replaceKeyword:@"%serviceIconPath%"
1194 withString:serviceIconPath];
1196 [inString replaceKeyword:@"%timeOpened%"
1197 withString:[timeStampFormatter stringFromDate:[chat dateOpened]]];
1199 //Replaces %time{x}% with a timestamp formatted like x (using NSDateFormatter)
1201 range = [inString rangeOfString:@"%timeOpened{"];
1202 if (range.location != NSNotFound) {
1204 endRange = [inString rangeOfString:@"}%" options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), [inString length] - NSMaxRange(range))];
1206 if (endRange.location != NSNotFound && endRange.location > NSMaxRange(range)) {
1207 NSString *timeFormat = [inString substringWithRange:NSMakeRange(NSMaxRange(range), (endRange.location - NSMaxRange(range)))];
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];
1214 dateFormatter = [[NSDateFormatter alloc] init];
1215 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
1216 [dateFormatter setDateFormat:timeFormat];
1219 [inString safeReplaceCharactersInRange:NSUnionRange(range, endRange)
1220 withString:[dateFormatter stringFromDate:[chat dateOpened]]];
1221 [dateFormatter release];
1225 } while (range.location != NSNotFound);
1227 [inString replaceKeyword:@"%dateOpened%"
1228 withString:[[NSDateFormatter localizedDateFormatter] stringFromDate:[chat dateOpened]]];
1232 range = [inString rangeOfString:@"==bodyBackground=="];
1234 if (range.location != NSNotFound) { //a backgroundImage tag is not required
1235 NSMutableString *bodyTag = nil;
1237 if (allowsCustomBackground && (customBackgroundPath || customBackgroundColor)) {
1238 bodyTag = [[[NSMutableString alloc] init] autorelease];
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]];
1246 case BackgroundCenter:
1247 [bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-position: center; background-repeat: no-repeat; background-attachment:fixed;", customBackgroundPath]];
1249 case BackgroundTile:
1250 [bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-repeat: repeat;", customBackgroundPath]];
1252 case BackgroundTileCenter:
1253 [bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); background-repeat: repeat; background-position: center;", customBackgroundPath]];
1255 case BackgroundScale:
1256 [bodyTag appendString:[NSString stringWithFormat:@"background-image: url('%@'); -webkit-background-size: 100%% 100%%; background-size: 100%% 100%%; background-attachment: fixed;", customBackgroundPath]];
1260 [bodyTag appendString:@"background-image: none; "];
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]];
1270 //Replace the body background tag
1271 [inString safeReplaceCharactersInRange:range withString:(bodyTag ? (NSString *)bodyTag : @"")];
1280 - (NSString *)iconPathForFileTransfer:(ESFileTransfer *)inObject
1282 NSString *filename = [NSString stringWithFormat:@"TEMP-%@%@.tiff", [inObject remoteFilename], [NSString randomStringOfLength:5]];
1283 return [[adium cachesPath] stringByAppendingPathComponent:filename];
1286 - (NSString *)statusIconPathForListObject:(AIListObject *)inObject
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];
1294 statusName = @"UnknownStatus";
1295 NSString *path = [statusIconPathCache objectForKey:statusName];
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];