-
Notifications
You must be signed in to change notification settings - Fork 0
/
AICustomEmoticonController.m
538 lines (453 loc) · 22.6 KB
/
AICustomEmoticonController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//
// AICustomEmoticonController.m
// MSNColorNicknames
//
// Created by Tiziano Carotti on 05/09/09.
// Copyright 2009 Tiziano Carotti. All rights reserved.
//
// This code has been taken from Adium - AIEmoticonController class and has been slightly modified
#import "AICustomEmoticonController.h"
#import "AISmileyController.h"
#import <Adium/AIListContact.h>
#import <Adium/AIListObject.h>
#import <Adium/AIEmoticon.h>
#import <Adium/AIContentMessage.h>
#import <Adium/ESDebugAILog.h>
#import <AdiumLibpurple/CBPurpleAccount.h>
#import <AdiumLibpurple/ESMSNService.h>
#import <AIUtilities/AIStringAdditions.h>
#import <AIUtilities/AIDictionaryAdditions.h>
#import <AIUtilities/AIMutableOwnerArray.h>
#import <AIUtilities/AICharacterSetAdditions.h>
@interface AICustomEmoticonController (PRIVATE)
- (BOOL)_isCustomEmoticonApplicable:(id)context;
- (void)_buildCharacterSetsAndIndexCustomEmoticons;
- (NSMutableAttributedString *)_convertEmoticonsInMessage:(NSAttributedString *)inMessage context:(id)context;
- (AIEmoticon *) _bestReplacementFromEmoticons:(NSArray *)candidateEmoticons
withEquivalents:(NSArray *)candidateEmoticonTextEquivalents
context:(NSString *)serviceClassContext
equivalent:(NSString **)replacementString
equivalentLength:(int *)textLength;
- (unsigned int)replaceAnEmoticonStartingAtLocation:(unsigned *)currentLocation
fromString:(NSString *)messageString
messageStringLength:(unsigned int)messageStringLength
originalAttributedString:(NSAttributedString *)originalAttributedString
intoString:(NSMutableAttributedString **)newMessage
replacementCount:(unsigned *)replacementCount
callingRecursively:(BOOL)callingRecursively
serviceClassContext:(id)serviceClassContext
emoticonStartCharacterSet:(NSCharacterSet *)emoticonStartCharacterSet
emoticonIndex:(NSDictionary *)emoticonIndex
isMessage:(BOOL)isMessage;
@end
@implementation AICustomEmoticonController
- (id)init {
self = [super init];
if(self == nil)
return nil;
_customEmoticonHintCharacterSet = nil;
_customEmoticonStartCharacterSet = nil;
_customEmoticonIndexDict = nil;
[NOTIFICATION_CENTER addObserver:self selector:@selector(resetCustomEmoticon) name:AICustomSmileyChangeNotification object:nil];
return self;
}
- (void) dealloc {
[NOTIFICATION_CENTER removeObserver:self];
[_customEmoticonHintCharacterSet release];
[_customEmoticonStartCharacterSet release];
[_customEmoticonIndexDict release];
[super dealloc];
}
- (void)_buildCharacterSetsAndIndexCustomEmoticons {
NSEnumerator *emoticonEnumerator;
AIEmoticon *emoticon;
PurpleCustomSmiley *pemoticon;
//Start with a fresh character set, and a fresh index
NSMutableCharacterSet *tmpEmoticonHintCharacterSet = [[NSMutableCharacterSet alloc] init];
NSMutableCharacterSet *tmpEmoticonStartCharacterSet = [[NSMutableCharacterSet alloc] init];
[_customEmoticonIndexDict release]; _customEmoticonIndexDict = [[NSMutableDictionary alloc] init];
NSArray* smileys=[AISmileyController getAllSmileys];
emoticonEnumerator = [smileys objectEnumerator];
while ((pemoticon = [emoticonEnumerator nextObject])) {
emoticon = [AIEmoticon emoticonWithIconPath:[pemoticon path] equivalents:[NSArray arrayWithObject:[pemoticon shortcut]] name:[[pemoticon shortcut] stringByAppendingString:@"#custom"] pack:nil];
NSEnumerator *textEnumerator;
NSString *text;
textEnumerator = [[emoticon textEquivalents] objectEnumerator];
while ((text = [textEnumerator nextObject])) {
NSMutableArray *subIndex;
unichar firstCharacter;
NSString *firstCharacterString;
if ([text length] != 0) { //Invalid emoticon files may let empty text equivalents sneak in
firstCharacter = [text characterAtIndex:0];
firstCharacterString = [NSString stringWithFormat:@"%C",firstCharacter];
// -- Emoticon Hint Character Set --
//If any letter in this text equivalent already exists in the quick scan character set, we can skip it
if ([text rangeOfCharacterFromSet:tmpEmoticonHintCharacterSet].location == NSNotFound) {
//Potential for optimization!: Favor punctuation characters ( :();- ) over letters (especially vowels).
[tmpEmoticonHintCharacterSet addCharactersInString:firstCharacterString];
}
// -- Emoticon Start Character Set --
//First letter of this emoticon goes in the start set
if (![tmpEmoticonStartCharacterSet characterIsMember:firstCharacter]) {
[tmpEmoticonStartCharacterSet addCharactersInString:firstCharacterString];
}
// -- Index --
//Get the index according to this emoticon's first character
if (!(subIndex = [_customEmoticonIndexDict objectForKey:firstCharacterString])) {
subIndex = [[NSMutableArray alloc] init];
[_customEmoticonIndexDict setObject:subIndex forKey:firstCharacterString];
[subIndex release];
}
//Place the emoticon into that index (If it isn't already in there)
if (![subIndex containsObject:emoticon]) {
//Keep emoticons in order from largest to smallest. This prevents icons that contain other
//icons from being masked by the smaller icons they contain.
//This cannot work unless the emoticon equivelents are broken down.
/*
for (int i = 0;i < [subIndex count]; i++) {
if ([subIndex objectAtIndex:i] equivelentLength] < ourLength]) break;
}*/
//Instead of adding the emoticon, add all of its equivalents... ?
[subIndex addObject:emoticon];
}
}
}
}
[_customEmoticonHintCharacterSet release]; _customEmoticonHintCharacterSet = [tmpEmoticonHintCharacterSet immutableCopy];
[tmpEmoticonHintCharacterSet release];
[_customEmoticonStartCharacterSet release]; _customEmoticonStartCharacterSet = [tmpEmoticonStartCharacterSet immutableCopy];
[tmpEmoticonStartCharacterSet release];
//After building all the subIndexes, sort them by length here
}
//Returns a characterset containing characters that hint at the presence of an emoticon
- (NSCharacterSet *)customEmoticonHintCharacterSet {
if (!_customEmoticonHintCharacterSet) [self _buildCharacterSetsAndIndexCustomEmoticons];
return _customEmoticonHintCharacterSet;
}
//Returns a characterset containing all the characters that may start an emoticon
- (NSCharacterSet *)customEmoticonStartCharacterSet {
if (!_customEmoticonStartCharacterSet) [self _buildCharacterSetsAndIndexCustomEmoticons];
return _customEmoticonStartCharacterSet;
}
- (NSDictionary *)customEmoticonIndex {
if (!_customEmoticonIndexDict) [self _buildCharacterSetsAndIndexCustomEmoticons];
return _customEmoticonIndexDict;
}
- (BOOL)_isCustomEmoticonApplicable:(id)context {
BOOL result=FALSE;
if ([context isKindOfClass:[AIContentMessage class]]) {
AIContentMessage* contMessage=context;
if([contMessage isOutgoing] && ![contMessage isAutoreply] && [[contMessage type] isEqualToString:CONTENT_MESSAGE_TYPE] && [[[[[contMessage chat] account] service] serviceID] isEqualToString:@"MSN"])
{
#ifdef ADIUM_14
if([[[[contMessage chat] account] preferenceForKey:KEY_DISPLAY_CUSTOM_EMOTICONS group:GROUP_ACCOUNT_STATUS] boolValue])
#else
if(![[[adium preferenceController] preferenceForKey:KEY_MSN_DISPLAY_CUSTOM_EMOTICONS
group:PREF_GROUP_MSN_SERVICE] boolValue])
#endif
result=TRUE;
}
}
return result;
}
//Reset the active emoticons cache
- (void)resetCustomEmoticon {
[_customEmoticonHintCharacterSet release]; _customEmoticonHintCharacterSet = nil;
[_customEmoticonStartCharacterSet release]; _customEmoticonStartCharacterSet = nil;
[_customEmoticonIndexDict release]; _customEmoticonIndexDict = nil;
}
- (NSAttributedString *)filterAttributedString:(NSAttributedString *)inAttributedString context:(id)context {
if(!inAttributedString || ![inAttributedString length])
return inAttributedString;
NSMutableAttributedString *replacementMessage = nil;
if(![self _isCustomEmoticonApplicable:context])
return inAttributedString;
NSCharacterSet* customSet=[self customEmoticonHintCharacterSet];
if ([[inAttributedString string] rangeOfCharacterFromSet:customSet].location != NSNotFound )
replacementMessage = [self _convertEmoticonsInMessage:inAttributedString context:context];
return (replacementMessage ? replacementMessage : inAttributedString);
}
//Insert graphical emoticons into a string
- (NSMutableAttributedString *)_convertEmoticonsInMessage:(NSAttributedString *)inMessage context:(id)context {
NSString *messageString = [inMessage string];
NSMutableAttributedString *newMessage = nil; //We avoid creating a new string unless necessary
NSString *serviceClassContext = nil;
unsigned currentLocation = 0, messageStringLength;
NSCharacterSet *emoticonStartCharacterSet = nil;
NSDictionary *emoticonIndex = nil;
//we can avoid loading images if the emoticon is headed for the wkmv, since it will just load from the original path anyway
//Determine our service class context
if ([context isKindOfClass:[AIContentObject class]]) {
serviceClassContext = [[[(AIContentObject *)context destination] service] serviceClass];
//If there's no destination, try to use the source for context
if (!serviceClassContext) {
serviceClassContext = [[[(AIContentObject *)context source] service] serviceClass];
}
if ([self _isCustomEmoticonApplicable:context])
{
emoticonStartCharacterSet=[self customEmoticonStartCharacterSet];
emoticonIndex=[self customEmoticonIndex];
if(emoticonStartCharacterSet && emoticonIndex) {
//Number of characters we've replaced so far (used to calcluate placement in the destination string)
unsigned int replacementCount = 0;
messageStringLength = [messageString length];
while (currentLocation != NSNotFound && currentLocation < messageStringLength) {
[self replaceAnEmoticonStartingAtLocation:¤tLocation
fromString:messageString
messageStringLength:messageStringLength
originalAttributedString:inMessage
intoString:&newMessage
replacementCount:&replacementCount
callingRecursively:NO
serviceClassContext:serviceClassContext
emoticonStartCharacterSet:emoticonStartCharacterSet
emoticonIndex:emoticonIndex
isMessage:YES];
}
}
}
}
return (newMessage ? [newMessage autorelease] : inMessage);
}
/*!
* @brief Perform a single emoticon replacement
*
* This method may call itself recursively to perform additional adjacent emoticon replacements
*
* @result The location in messageString of the beginning of the emoticon replaced, or NSNotFound if no replacement was made
*/
- (unsigned int)replaceAnEmoticonStartingAtLocation:(unsigned *)currentLocation
fromString:(NSString *)messageString
messageStringLength:(unsigned int)messageStringLength
originalAttributedString:(NSAttributedString *)originalAttributedString
intoString:(NSMutableAttributedString **)newMessage
replacementCount:(unsigned *)replacementCount
callingRecursively:(BOOL)callingRecursively
serviceClassContext:(id)serviceClassContext
emoticonStartCharacterSet:(NSCharacterSet *)emoticonStartCharacterSet
emoticonIndex:(NSDictionary *)emoticonIndex
isMessage:(BOOL)isMessage
{
unsigned int originalEmoticonLocation = NSNotFound;
//Find the next occurence of a suspected emoticon
*currentLocation = [messageString rangeOfCharacterFromSet:emoticonStartCharacterSet
options:NSLiteralSearch
range:NSMakeRange(*currentLocation,
messageStringLength - *currentLocation)].location;
if (*currentLocation != NSNotFound) {
//Use paired arrays so multiple emoticons can qualify for the same text equivalent
NSMutableArray *candidateEmoticons = nil;
NSMutableArray *candidateEmoticonTextEquivalents = nil;
unichar currentCharacter = [messageString characterAtIndex:*currentLocation];
NSString *currentCharacterString = [NSString stringWithFormat:@"%C", currentCharacter];
NSEnumerator *emoticonEnumerator;
AIEmoticon *emoticon;
//Check for the presence of all emoticons starting with this character
emoticonEnumerator = [[emoticonIndex objectForKey:currentCharacterString] objectEnumerator];
while ((emoticon = [emoticonEnumerator nextObject])) {
NSEnumerator *textEnumerator;
NSString *text;
textEnumerator = [[emoticon textEquivalents] objectEnumerator];
while ((text = [textEnumerator nextObject])) {
int textLength = [text length];
if (textLength != 0) { //Invalid emoticon files may let empty text equivalents sneak in
//If there is not enough room in the string for this text, we can skip it
if (*currentLocation + textLength <= messageStringLength) {
if ([messageString compare:text
options:NSLiteralSearch
range:NSMakeRange(*currentLocation, textLength)] == NSOrderedSame) {
//Ignore emoticons within links
if ([originalAttributedString attribute:NSLinkAttributeName
atIndex:*currentLocation
effectiveRange:nil] == nil) {
if (!candidateEmoticons) {
candidateEmoticons = [[NSMutableArray alloc] init];
candidateEmoticonTextEquivalents = [[NSMutableArray alloc] init];
}
[candidateEmoticons addObject:emoticon];
[candidateEmoticonTextEquivalents addObject:text];
}
}
}
}
}
}
if ([candidateEmoticons count]) {
NSString *replacementString;
NSMutableAttributedString *replacement;
int textLength;
NSRange emoticonRangeInNewMessage;
int amountToIncreaseCurrentLocation = 0;
originalEmoticonLocation = *currentLocation;
//Use the most appropriate, longest string of those which could be used for the emoticon text we found here
emoticon = [self _bestReplacementFromEmoticons:candidateEmoticons
withEquivalents:candidateEmoticonTextEquivalents
context:serviceClassContext
equivalent:&replacementString
equivalentLength:&textLength];
emoticonRangeInNewMessage = NSMakeRange(*currentLocation - *replacementCount, textLength);
/* We want to show this emoticon if there is:
* It begins or ends the string
* It is bordered by spaces or line breaks or quotes on both sides
* It is bordered by a period on the left and a space or line break or quote the right
* It is bordered by emoticons on both sides or by an emoticon on the left and a period, space, or line break on the right
*/
BOOL acceptable = NO;
if ((messageStringLength == ((originalEmoticonLocation + textLength))) || //Ends the string
(originalEmoticonLocation == 0)) { //Begins the string
acceptable = YES;
}
if (!acceptable) {
/* Bordered by spaces or line breaks or quotes, or by a period on the left and a space or a line break or quote on the right
* If we're being called recursively, we have a potential emoticon to our left; we only need to check the right.
* This is also true if we're not being called recursively but there's an NSAttachmentAttribute to our left.
* That will happen if, for example, the string is ":):) ". The first emoticon is at the start of the line and
* so is immediately acceptable. The second should be acceptable because it is to the right of an emoticon and
* the left of a space.
*/
char previousCharacter = [messageString characterAtIndex:(originalEmoticonLocation - 1)] ;
char nextCharacter = [messageString characterAtIndex:(originalEmoticonLocation + textLength)] ;
if ((callingRecursively || (previousCharacter == ' ') || (previousCharacter == '\t') ||
(previousCharacter == '\n') || (previousCharacter == '\r') || (previousCharacter == '.') || (previousCharacter == '?') || (previousCharacter == '!') ||
(previousCharacter == '\"') || (previousCharacter == '\'') ||
(previousCharacter == '(') || (previousCharacter == '*') ||
(*newMessage && [*newMessage attribute:NSAttachmentAttributeName
atIndex:(emoticonRangeInNewMessage.location - 1)
effectiveRange:NULL])) &&
((nextCharacter == ' ') || (nextCharacter == '\t') || (nextCharacter == '\n') || (nextCharacter == '\r') ||
(nextCharacter == '.') || (nextCharacter == ',') || (nextCharacter == '?') || (nextCharacter == '!') ||
(nextCharacter == ')') || (nextCharacter == '*') ||
(nextCharacter == '\"') || (nextCharacter == '\''))) {
acceptable = YES;
}
}
if (!acceptable) {
/* If the emoticon would end the string except for whitespace, newlines, or punctionation at the end, or it begins the string after removing
* whitespace, newlines, or punctuation at the beginning, it is acceptable even if the previous conditions weren't met.
*/
static NSCharacterSet *endingTrimSet = nil;
if (!endingTrimSet) {
NSMutableCharacterSet *tempSet = [[NSCharacterSet punctuationCharacterSet] mutableCopy];
[tempSet formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
endingTrimSet = [tempSet immutableCopy];
[tempSet release];
}
NSString *trimmedString = [messageString stringByTrimmingCharactersInSet:endingTrimSet];
unsigned int trimmedLength = [trimmedString length];
if (trimmedLength == (originalEmoticonLocation + textLength)) {
acceptable = YES;
} else if ((originalEmoticonLocation - (messageStringLength - trimmedLength)) == 0) {
acceptable = YES;
}
}
if (!acceptable) {
/* If we still haven't determined it to be acceptable, look ahead.
* If we do a replacement adjacent to this emoticon, we can do this one, too.
*/
unsigned int newCurrentLocation = *currentLocation;
unsigned int nextEmoticonLocation;
/* Call ourself recursively, starting just after the end of the current emoticon candidate
* If the return value is not NSNotFound, an emoticon was found and replaced ahead of us. Discontinuous searching for the win.
*/
newCurrentLocation += textLength;
nextEmoticonLocation = [self replaceAnEmoticonStartingAtLocation:&newCurrentLocation
fromString:messageString
messageStringLength:messageStringLength
originalAttributedString:originalAttributedString
intoString:newMessage
replacementCount:replacementCount
callingRecursively:YES
serviceClassContext:serviceClassContext
emoticonStartCharacterSet:emoticonStartCharacterSet
emoticonIndex:emoticonIndex
isMessage:isMessage];
if (nextEmoticonLocation != NSNotFound) {
if (nextEmoticonLocation == (*currentLocation + textLength)) {
/* The next emoticon is immediately after the candidate we're looking at right now. That means
* our current candidate is in fact an emoticon (since it borders another emoticon).
*/
acceptable = YES;
}
}
/* Whether the current candidate is acceptable or not, we can now skip ahead to just after the next emoticon if
* there is one. If there isn't, we can skip ahead to the end of the string.
*
* We do -1 because we will do a +1 at the end of the loop no matter what.
*/
if (newCurrentLocation != NSNotFound) {
amountToIncreaseCurrentLocation = (newCurrentLocation - *currentLocation) - 1;
} else {
amountToIncreaseCurrentLocation = (messageStringLength - *currentLocation) - 1;
}
}
if (acceptable) {
replacement = [emoticon attributedStringWithTextEquivalent:replacementString attachImages:!isMessage];
//grab the original attributes, to ensure that the background is not lost in a message consisting only of an emoticon
[replacement addAttributes:[originalAttributedString attributesAtIndex:originalEmoticonLocation
effectiveRange:nil]
range:NSMakeRange(0,1)];
//insert the emoticon
if (!(*newMessage)) *newMessage = [originalAttributedString mutableCopy];
[*newMessage replaceCharactersInRange:emoticonRangeInNewMessage
withAttributedString:replacement];
//Update where we are in the original and replacement messages
*replacementCount += textLength-1;
*currentLocation += textLength-1;
} else {
//Didn't find an acceptable emoticon, so we should return NSNotFound
originalEmoticonLocation = NSNotFound;
}
//If appropriate, skip ahead by amountToIncreaseCurrentLocation
*currentLocation += amountToIncreaseCurrentLocation;
}
//Always increment the loop
*currentLocation += 1;
[candidateEmoticons release];
[candidateEmoticonTextEquivalents release];
}
return originalEmoticonLocation;
}
- (AIEmoticon *) _bestReplacementFromEmoticons:(NSArray *)candidateEmoticons
withEquivalents:(NSArray *)candidateEmoticonTextEquivalents
context:(NSString *)serviceClassContext
equivalent:(NSString **)replacementString
equivalentLength:(int *)textLength
{
unsigned i = 0;
unsigned bestIndex = 0, bestLength = 0;
unsigned bestServiceAppropriateIndex = 0, bestServiceAppropriateLength = 0;
NSString *serviceAppropriateReplacementString = nil;
unsigned count;
count = [candidateEmoticonTextEquivalents count];
while (i < count) {
NSString *thisString = [candidateEmoticonTextEquivalents objectAtIndex:i];
unsigned thisLength = [thisString length];
if (thisLength > bestLength) {
bestLength = thisLength;
bestIndex = i;
*replacementString = thisString;
}
//If we are using service appropriate emoticons, check if this is on the right service and, if so, compare.
if (thisLength > bestServiceAppropriateLength) {
AIEmoticon *thisEmoticon = [candidateEmoticons objectAtIndex:i];
if ([thisEmoticon isAppropriateForServiceClass:serviceClassContext]) {
bestServiceAppropriateLength = thisLength;
bestServiceAppropriateIndex = i;
serviceAppropriateReplacementString = thisString;
}
}
i++;
}
/* Did we get a service appropriate replacement? If so, use that rather than the current replacementString if it
* differs. */
if (serviceAppropriateReplacementString && (serviceAppropriateReplacementString != *replacementString)) {
bestLength = bestServiceAppropriateLength;
bestIndex = bestServiceAppropriateIndex;
*replacementString = serviceAppropriateReplacementString;
}
//Return the length by reference
*textLength = bestLength;
//Return the AIEmoticon we found to be best
return [candidateEmoticons objectAtIndex:bestIndex];
}
@end