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 <Adium/AIChatControllerProtocol.h>
18 #import <Adium/AIContactControllerProtocol.h>
19 #import <Adium/AIContentControllerProtocol.h>
20 #import <Adium/AIInterfaceControllerProtocol.h>
21 #import <Adium/AIPreferenceControllerProtocol.h>
22 #import <Adium/AIToolbarControllerProtocol.h>
23 #import "ESUserIconHandlingPlugin.h"
24 #import <AIUtilities/AIFileManagerAdditions.h>
25 #import <AIUtilities/AIMutableOwnerArray.h>
26 #import <AIUtilities/AIToolbarUtilities.h>
27 #import <AIUtilities/AIMenuAdditions.h>
28 #import <AIUtilities/AIImageAdditions.h>
29 #import <AIUtilities/AIImageButton.h>
30 #import <Adium/AIAccount.h>
31 #import <Adium/AIChat.h>
32 #import <Adium/AIListContact.h>
33 #import <Adium/AIListObject.h>
34 #import <Adium/AIServiceIcons.h>
36 #define TOOLBAR_ITEM_TAG -999
38 @interface ESUserIconHandlingPlugin (PRIVATE)
39 - (BOOL)cacheAndSetUserIconFromPreferenceForListObject:(AIListObject *)inObject;
40 - (BOOL)_cacheUserIconData:(NSData *)inData forObject:(AIListObject *)inObject;
41 - (NSString *)_cachedImagePathForObject:(AIListObject *)inObject;
42 - (BOOL)destroyCacheForListObject:(AIListObject *)inObject;
43 - (void)registerToolbarItem;
45 - (void)_updateToolbarIconOfChat:(AIChat *)inChat inWindow:(NSWindow *)window;
46 - (void)_updateToolbarItem:(NSToolbarItem *)item forChat:(AIChat *)chat;
48 - (void)updateToolbarItemForObject:(AIListObject *)inObject;
52 * @class ESUserIconHandlingPlugin
53 * @brief User icon handling component
55 * This component manages the Adium user icon cache. It also provides a toolbar icon which shows the user icon
56 * or service icon of the current chat in its window.
58 @implementation ESUserIconHandlingPlugin
65 //Register our observers
66 [[adium contactController] registerListObjectObserver:self];
67 [[adium preferenceController] registerPreferenceObserver:self forGroup:PREF_GROUP_USERICONS];
68 [[adium notificationCenter] addObserver:self
69 selector:@selector(listObjectAttributesChanged:)
70 name:ListObject_AttributesChanged
73 [self registerToolbarItem];
79 - (void)uninstallPlugin
81 [[adium contactController] unregisterListObjectObserver:self];
82 [[adium preferenceController] unregisterPreferenceObserver:self];
86 * @brief Update list object
88 * Handle object creation and changes to the userIcon status object, which should be set by account code
89 * when a user icon is retrieved for the object.
91 - (NSSet *)updateListObject:(AIListObject *)inObject keys:(NSSet *)inModifiedKeys silent:(BOOL)silent
93 if (inModifiedKeys == nil) {
94 //At object creation, load the user icon.
96 //Only load the cached image file if we do not load from a preference
97 if (![self cacheAndSetUserIconFromPreferenceForListObject:inObject]) {
98 //Load the cached image file by reference into the display array;
99 //It will only be loaded into memory if needed
100 NSString *cachedImagePath = [self _cachedImagePathForObject:inObject];
102 if ([[NSFileManager defaultManager] fileExistsAtPath:cachedImagePath]) {
103 NSImage *cachedImage;
105 cachedImage = [[NSImage alloc] initByReferencingFile:cachedImagePath];
108 //A cache image is used at lowest priority, since it is outdated data
109 [inObject setDisplayUserIcon:cachedImage
111 priorityLevel:Lowest_Priority];
112 [inObject setStatusObject:cachedImagePath
113 forKey:@"UserIconPath"
117 [cachedImage release];
120 } else if ([inModifiedKeys containsObject:KEY_USER_ICON]) {
121 //The status UserIcon object is set by account code; apply this to the display array and cache it if necesssary
123 NSImage *statusUserIcon = [inObject statusObjectForKey:KEY_USER_ICON];
124 AIMutableOwnerArray *userIconDisplayArray = [inObject displayArrayForKey:KEY_USER_ICON];
126 //Apply the image at medium priority if we don't already have a higher priority (lower float value) icon set
127 if (![userIconDisplayArray objectWithOwner:self] ||
128 [userIconDisplayArray priorityOfObjectWithOwner:self] >= Medium_Priority) {
129 [inObject setDisplayUserIcon:statusUserIcon
131 priorityLevel:Medium_Priority];
133 //If the new objectValue is what we just set, notify and cache
134 userIcon = [inObject displayUserIcon];
136 if (userIcon == statusUserIcon) {
137 //Cache using the raw data if possible, otherwise create a TIFF representation to cache
138 //Note: TIFF supports transparency but not animation
139 NSData *userIconData = [inObject statusObjectForKey:@"UserIconData"];
141 [self _cacheUserIconData:(userIconData ? userIconData : [userIcon TIFFRepresentation]) forObject:inObject];
143 [[adium contactController] listObjectAttributesChanged:inObject
144 modifiedKeys:[NSSet setWithObject:KEY_USER_ICON]];
146 [self updateToolbarItemForObject:inObject];
155 * @brief List object attributes changes
157 * A plugin, or this plugin, modified the display array for the object; ensure our cache is up to date.
159 - (void)listObjectAttributesChanged:(NSNotification *)notification
161 AIListObject *inObject = [notification object];
162 NSSet *keys = [[notification userInfo] objectForKey:@"Keys"];
164 if (inObject && [keys containsObject:KEY_USER_ICON]) {
165 AIMutableOwnerArray *userIconDisplayArray = [inObject displayArrayForKey:KEY_USER_ICON];
166 NSImage *userIcon = [userIconDisplayArray objectValue];
167 NSImage *ownedUserIcon = [userIconDisplayArray objectWithOwner:self];
169 /* If the new user icon is not the same as the one we own, we should update our cache
170 * and our toolbar item. If we get here from -[self updateListObject:keys:silent:] doing a
171 * listObjectAttributesChanged call, then the userIcon will be the same as ownedUserIcon, and we won't do anything
172 * since it was already done previously.
174 if (userIcon != ownedUserIcon) {
175 [self _cacheUserIconData:[userIcon TIFFRepresentation] forObject:inObject];
177 [self updateToolbarItemForObject:inObject];
183 * @brief The user icon preference was changed
185 - (void)preferencesChangedForGroup:(NSString *)group key:(NSString *)key
186 object:(AIListObject *)object preferenceDict:(NSDictionary *)prefDict firstTime:(BOOL)firstTime
189 if (![self cacheAndSetUserIconFromPreferenceForListObject:object]) {
190 [self destroyCacheForListObject:object];
196 * @brief Cache and set the user icon from a listObject's preference
198 * This loads the user-set preference for a listObject, sets it at highest priority, and then caches the
201 * @param inObject The listObject to modify if necessary.
202 * @result YES if the method resulted in setting an image
204 - (BOOL)cacheAndSetUserIconFromPreferenceForListObject:(AIListObject *)inObject
206 NSData *imageData = [inObject preferenceForKey:KEY_USER_ICON
207 group:PREF_GROUP_USERICONS
208 ignoreInheritedValues:YES];
210 //A preference is used at highest priority
214 image = [[NSImage alloc] initWithData:imageData];
216 [inObject setDisplayUserIcon:image
218 priorityLevel:Highest_Priority];
219 [self updateToolbarItemForObject:inObject];
225 //If we had a preference set before (that is, there's an object set at Highest_Priority), clear it
226 if ([[inObject displayArrayForKey:KEY_USER_ICON create:NO] objectWithOwner:self] &&
227 ([[inObject displayArrayForKey:KEY_USER_ICON create:NO] priorityOfObjectWithOwner:self] == Highest_Priority)) {
228 [inObject setDisplayUserIcon:nil
230 priorityLevel:Highest_Priority];
232 //Update the list object to grab the serverside icon as the one we're using, if necessary
233 [self updateListObject:inObject
234 keys:[NSSet setWithObject:KEY_USER_ICON]
237 [self updateToolbarItemForObject:inObject];
245 * @brief Cache user icon data for an object
247 * @param inData Image data to cache
248 * @param inObject AIListObject to cache the data for
250 * @result YES if successful
252 - (BOOL)_cacheUserIconData:(NSData *)inData forObject:(AIListObject *)inObject
255 NSString *cachedImagePath = [self _cachedImagePathForObject:inObject];
257 if (inData && [inData length]) {
258 success = ([inData writeToFile:cachedImagePath
261 success = [[NSFileManager defaultManager] removeFileAtPath:cachedImagePath
263 cachedImagePath = nil;
267 [inObject setStatusObject:cachedImagePath
268 forKey:@"UserIconPath"
275 * @brief Trash a list object's cached icon
277 * @result YES if successful
279 - (BOOL)destroyCacheForListObject:(AIListObject *)inObject
281 NSString *cachedImagePath = [self _cachedImagePathForObject:inObject];
284 if ((success = [[NSFileManager defaultManager] trashFileAtPath:cachedImagePath])) {
285 [inObject setStatusObject:nil
286 forKey:@"UserIconPath"
294 * @brief Retrieve the path at which to cache an <tt>AIListObject</tt>'s image
296 - (NSString *)_cachedImagePathForObject:(AIListObject *)inObject
298 return [[adium cachesPath] stringByAppendingPathComponent:[inObject internalObjectID]];
301 #pragma mark Toolbar Item
304 * @brief Register our toolbar item
306 * Our toolbar item shows an image for the current chat, displaying it full size/animating if clicked.
308 - (void)registerToolbarItem
310 AIImageButton *button;
311 NSToolbarItem *toolbarItem;
313 toolbarItems = [[NSMutableSet alloc] init];
314 validatedItems = [[NSMutableSet alloc] init];
316 //Toolbar item registration
317 [[NSNotificationCenter defaultCenter] addObserver:self
318 selector:@selector(toolbarWillAddItem:)
319 name:NSToolbarWillAddItemNotification
321 [[NSNotificationCenter defaultCenter] addObserver:self
322 selector:@selector(toolbarDidRemoveItem:)
323 name:NSToolbarDidRemoveItemNotification
326 button = [[AIImageButton alloc] initWithFrame:NSMakeRect(0,0,32,32)];
327 toolbarItem = [AIToolbarUtilities toolbarItemWithIdentifier:@"UserIcon"
328 label:AILocalizedString(@"Icon",nil)
329 paletteLabel:AILocalizedString(@"Contact Icon",nil)
330 toolTip:AILocalizedString(@"Show this contact's icon",nil)
332 settingSelector:@selector(setView:)
334 action:@selector(dummyAction:)
337 [toolbarItem setMinSize:NSMakeSize(32,32)];
338 [toolbarItem setMaxSize:NSMakeSize(32,32)];
339 [button setToolbarItem:toolbarItem];
340 [button setImage:[NSImage imageNamed:@"userIconToolbar" forClass:[self class]]];
343 //Register our toolbar item
344 [[adium toolbarController] registerToolbarItem:toolbarItem forToolbarType:@"MessageWindow"];
348 * @brief After the toolbar has added the item we can set up the submenus
350 - (void)toolbarWillAddItem:(NSNotification *)notification
352 NSToolbarItem *item = [[notification userInfo] objectForKey:@"item"];
354 if ([[item itemIdentifier] isEqualToString:@"UserIcon"]) {
356 [item setEnabled:YES];
358 //Add menu to toolbar item (for text mode)
359 NSMenuItem *menuFormRepresentation, *blankMenuItem;
362 menuFormRepresentation = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] init] autorelease];
364 menu = [[[NSMenu allocWithZone:[NSMenu menuZone]] init] autorelease];
365 [menu setDelegate:self];
366 [menu setAutoenablesItems:NO];
368 blankMenuItem = [[NSMenuItem alloc] initWithTitle:@""
370 action:@selector(dummyAction:)
372 [blankMenuItem setRepresentedObject:item];
373 [blankMenuItem setEnabled:YES];
374 [menu addItem:blankMenuItem];
376 [menuFormRepresentation setSubmenu:menu];
377 [menuFormRepresentation setTitle:[item label]];
378 [item setMenuFormRepresentation:menuFormRepresentation];
380 //If this is the first item added, start observing for chats becoming visible so we can update the icon
381 if ([toolbarItems count] == 0) {
382 [[adium notificationCenter] addObserver:self
383 selector:@selector(chatDidBecomeVisible:)
384 name:@"AIChatDidBecomeVisible"
388 [toolbarItems addObject:item];
390 [self performSelector:@selector(toolbarDidAddItem:)
396 - (void)toolbarDidAddItem:(NSToolbarItem *)item
398 /* Only need to take action if we haven't already validated the initial state of this item.
399 * This will only be true when the toolbar is revealed for the first time having been hidden when window opened.
401 if (![validatedItems containsObject:item]) {
402 NSEnumerator *enumerator = [[NSApp windows] objectEnumerator];
404 NSToolbar *thisItemsToolbar = [item toolbar];
406 //Look at each window to find the toolbar we are in
407 while ((window = [enumerator nextObject])) {
408 if ([window toolbar] == thisItemsToolbar) break;
412 [self _updateToolbarItem:item
413 forChat:[[adium interfaceController] activeChatInWindow:window]];
419 * @brief Toolbar removed an item.
421 * If the item is one of ours, stop tracking it.
423 * @param notification Notification with an @"item" userInfo key for an NSToolbarItem.
425 - (void)toolbarDidRemoveItem: (NSNotification *)notification
427 NSToolbarItem *item = [[notification userInfo] objectForKey:@"item"];
428 if ([toolbarItems containsObject:item]) {
430 [toolbarItems removeObject:item];
431 [validatedItems removeObject:item];
433 if ([toolbarItems count] == 0) {
434 [[adium notificationCenter] removeObserver:self
435 name:@"AIChatDidBecomeVisible"
442 * @brief A chat became visible in a window.
444 * Update the item with the @"UserIcon" identifier if necessary
446 * @param notification Notification with an AIChat object and an @"NSWindow" userInfo key
448 - (void)chatDidBecomeVisible:(NSNotification *)notification
450 [self _updateToolbarIconOfChat:[notification object]
451 inWindow:[[notification userInfo] objectForKey:@"NSWindow"]];
454 - (void)updateToolbarItemForObject:(AIListObject *)inObject
459 //Update the icon in the toolbar for this contact if a chat is open and we have any toolbar items
460 if (([toolbarItems count] > 0) &&
461 [inObject isKindOfClass:[AIListContact class]] &&
462 (chat = [[adium chatController] existingChatWithContact:(AIListContact *)inObject]) &&
463 (window = [[adium interfaceController] windowForChat:chat])) {
464 [self _updateToolbarIconOfChat:chat
469 - (void)_updateToolbarItem:(NSToolbarItem *)item forChat:(AIChat *)chat
471 AIListContact *listContact;
474 if ((listContact = [[chat listObject] parentContact]) && ![chat isGroupChat]) {
475 image = [listContact userIcon];
477 //Use the serviceIcon if no image can be found
478 if (!image) image = [AIServiceIcons serviceIconForObject:listContact
479 type:AIServiceIconLarge
480 direction:AIIconNormal];
482 //If we have no listObject or we have a name, we are a group chat and
483 //should use the account's service icon
484 image = [AIServiceIcons serviceIconForObject:[chat account]
485 type:AIServiceIconLarge
486 direction:AIIconNormal];
489 [(AIImageButton *)[item view] setImage:image];
491 [validatedItems addObject:item];
495 * @brief Update the user image toolbar icon in a chat
497 * @param chat The chat for which to retrieve an image
498 * @param window The window in which the chat resides
500 - (void)_updateToolbarIconOfChat:(AIChat *)chat inWindow:(NSWindow *)window
502 NSToolbar *toolbar = [window toolbar];
503 NSEnumerator *enumerator = [[toolbar items] objectEnumerator];
506 while ((item = [enumerator nextObject])) {
507 if ([[item itemIdentifier] isEqualToString:@"UserIcon"]) {
508 [self _updateToolbarItem:item forChat:chat];
515 * @brief Empty action for menu item validation purposes
517 - (IBAction)dummyAction:(id)sender{};
520 * @brief Menu needs update
522 * Should only be called for a menu off one of our toolbar items in text-only mode, and only when that menu is about
523 * to be displayed. The menu should have two items. The first is added by the system; the second has no title and is
524 * our menu item for showing the image.
526 - (void)menuNeedsUpdate:(NSMenu *)menu
528 //The first item is a root item inserted by the system. The second item is the single item
529 NSMenuItem *menuItem = [menu itemAtIndex:1];
530 NSToolbarItem *toolbarItem = [menuItem representedObject];
532 [menuItem setImage:[[[(AIImageButton *)[toolbarItem view] image] copy] autorelease]];
535 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem