Request info to get user icons when a Jabber contact signs on. Fixes #4205
[adiumx.git] / Source / ESUserIconHandlingPlugin.m
blob28e07f659b6c9bb9dbc01ef1e56a0f4460419955
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  */
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;
49 @end
51 /*!
52  * @class ESUserIconHandlingPlugin
53  * @brief User icon handling component
54  *
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.
57  */
58 @implementation ESUserIconHandlingPlugin
60 /*!
61  * @brief Install
62  */
63 - (void)installPlugin
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
71                                                                          object:nil];
73         [self registerToolbarItem];
76 /*!
77  * @brief Uninstall
78  */
79 - (void)uninstallPlugin
81         [[adium contactController] unregisterListObjectObserver:self];
82         [[adium preferenceController] unregisterPreferenceObserver:self];
85 /*!
86  * @brief Update list object
87  *
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.
90  */
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];
107                                 if (cachedImage) {
108                                         //A cache image is used at lowest priority, since it is outdated data
109                                         [inObject setDisplayUserIcon:cachedImage
110                                                                            withOwner:self
111                                                                    priorityLevel:Lowest_Priority];
112                                         [inObject setStatusObject:cachedImagePath
113                                                                            forKey:@"UserIconPath"
114                                                                            notify:NotifyNever];
115                                 }
117                                 [cachedImage release];
118                         }
119                 }
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
122                 NSImage                         *userIcon;
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
130                                                            withOwner:self
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]];
145                                 
146                                 [self updateToolbarItemForObject:inObject];
147                         }
148                 }
149         }
151         return nil;
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.
158  */
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.
173                  */
174                 if (userIcon != ownedUserIcon) {
175                         [self _cacheUserIconData:[userIcon TIFFRepresentation] forObject:inObject];
176                         
177                         [self updateToolbarItemForObject:inObject];
178                 }
179         }
183  * @brief The user icon preference was changed
184  */
185 - (void)preferencesChangedForGroup:(NSString *)group key:(NSString *)key
186                                                         object:(AIListObject *)object preferenceDict:(NSDictionary *)prefDict firstTime:(BOOL)firstTime
188         if (object) {
189                 if (![self cacheAndSetUserIconFromPreferenceForListObject:object]) {
190                         [self destroyCacheForListObject:object];
191                 }
192         }
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
199  * newly set image.
201  * @param inObject The listObject to modify if necessary.
202  * @result YES if the method resulted in setting an image
203  */
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
211         if (imageData) {
212                 NSImage *image;
214                 image = [[NSImage alloc] initWithData:imageData];
216                 [inObject setDisplayUserIcon:image
217                                                    withOwner:self
218                                            priorityLevel:Highest_Priority];
219                 [self updateToolbarItemForObject:inObject];
221                 [image release];
223                 return YES;
224         } else {
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
229                                                            withOwner:self
230                                                    priorityLevel:Highest_Priority];
231                         
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]
235                                                         silent:NO];
236                         
237                         [self updateToolbarItemForObject:inObject];
238                 }
239         }
241         return NO;
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
251  */
252 - (BOOL)_cacheUserIconData:(NSData *)inData forObject:(AIListObject *)inObject
254         BOOL            success;
255         NSString        *cachedImagePath = [self _cachedImagePathForObject:inObject];
257         if (inData && [inData length]) {
258                 success = ([inData writeToFile:cachedImagePath
259                                                         atomically:YES]);
260         } else {
261                 success = [[NSFileManager defaultManager] removeFileAtPath:cachedImagePath
262                                                                                                                    handler:NULL];
263                 cachedImagePath = nil;
264         }
266         if (success) {
267                 [inObject setStatusObject:cachedImagePath
268                                                    forKey:@"UserIconPath"
269                                                    notify:YES];
270         }
272         return success;
275  * @brief Trash a list object's cached icon
277  * @result YES if successful
278  */
279 - (BOOL)destroyCacheForListObject:(AIListObject *)inObject
281         NSString        *cachedImagePath = [self _cachedImagePathForObject:inObject];
282         BOOL            success;
284         if ((success = [[NSFileManager defaultManager] trashFileAtPath:cachedImagePath])) {
285                 [inObject setStatusObject:nil
286                                                    forKey:@"UserIconPath"
287                                                    notify:YES];
288         }
290         return (success);
294  * @brief Retrieve the path at which to cache an <tt>AIListObject</tt>'s image
295  */
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.
307  */
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
320                                                                                            object:nil];
321         [[NSNotificationCenter defaultCenter] addObserver:self
322                                                                                          selector:@selector(toolbarDidRemoveItem:)
323                                                                                                  name:NSToolbarDidRemoveItemNotification
324                                                                                            object:nil];
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)
331                                                                                                                  target:self
332                                                                                                 settingSelector:@selector(setView:)
333                                                                                                         itemContent:button
334                                                                                                                  action:@selector(dummyAction:)
335                                                                                                                    menu:nil];
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]]];
341         [button release];
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
349  */
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;
360                 NSMenu          *menu;
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:@""
369                                                                                                    target:self
370                                                                                                    action:@selector(dummyAction:)
371                                                                                         keyEquivalent:@""];
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"
385                                                                                          object:nil];
386                 }
388                 [toolbarItems addObject:item];
389                 
390                 [self performSelector:@selector(toolbarDidAddItem:)
391                                    withObject:item
392                                    afterDelay:0];
393         }
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.
400         */
401         if (![validatedItems containsObject:item]) {
402                 NSEnumerator *enumerator = [[NSApp windows] objectEnumerator];
403                 NSWindow         *window;
404                 NSToolbar        *thisItemsToolbar = [item toolbar];
405                 
406                 //Look at each window to find the toolbar we are in
407                 while ((window = [enumerator nextObject])) {
408                         if ([window toolbar] == thisItemsToolbar) break;
409                 }
410                 
411                 if (window) {
412                         [self _updateToolbarItem:item
413                                                          forChat:[[adium interfaceController] activeChatInWindow:window]];
414                 }
415         }
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.
424  */
425 - (void)toolbarDidRemoveItem: (NSNotification *)notification
427         NSToolbarItem   *item = [[notification userInfo] objectForKey:@"item"];
428         if ([toolbarItems containsObject:item]) {
429                 [toolbarItems removeObject:item];
430                 [validatedItems removeObject:item];
432                 if ([toolbarItems count] == 0) {
433                         [[adium notificationCenter] removeObserver:self
434                                                                                                   name:@"AIChatDidBecomeVisible"
435                                                                                                 object:nil];
436                 }
437         }
441  * @brief A chat became visible in a window.
443  * Update the item with the @"UserIcon" identifier if necessary
445  * @param notification Notification with an AIChat object and an @"NSWindow" userInfo key
446  */
447 - (void)chatDidBecomeVisible:(NSNotification *)notification
449         [self _updateToolbarIconOfChat:[notification object]
450                                                   inWindow:[[notification userInfo] objectForKey:@"NSWindow"]];
453 - (void)updateToolbarItemForObject:(AIListObject *)inObject
455         AIChat          *chat;
456         NSWindow        *window;
458         //Update the icon in the toolbar for this contact if a chat is open and we have any toolbar items
459         if (([toolbarItems count] > 0) &&
460                 [inObject isKindOfClass:[AIListContact class]] &&
461                 (chat = [[adium chatController] existingChatWithContact:(AIListContact *)inObject]) &&
462                 (window = [[adium interfaceController] windowForChat:chat])) {
463                 [self _updateToolbarIconOfChat:chat
464                                                           inWindow:window];
465         }
468 - (void)_updateToolbarItem:(NSToolbarItem *)item forChat:(AIChat *)chat
470         AIListContact   *listContact;
471         NSImage                 *image;
472         
473         if ((listContact = [[chat listObject] parentContact]) && ![chat isGroupChat]) {
474                 image = [listContact userIcon];
475                 
476                 //Use the serviceIcon if no image can be found
477                 if (!image) image = [AIServiceIcons serviceIconForObject:listContact
478                                                                                                                         type:AIServiceIconLarge
479                                                                                                            direction:AIIconNormal];
480         } else {
481                 //If we have no listObject or we have a name, we are a group chat and
482                 //should use the account's service icon
483                 image = [AIServiceIcons serviceIconForObject:[chat account]
484                                                                                                 type:AIServiceIconLarge
485                                                                                    direction:AIIconNormal];
486         }
487         
488         [(AIImageButton *)[item view] setImage:image];
489         
490         [validatedItems addObject:item];
494  * @brief Update the user image toolbar icon in a chat
496  * @param chat The chat for which to retrieve an image
497  * @param window The window in which the chat resides
498  */
499 - (void)_updateToolbarIconOfChat:(AIChat *)chat inWindow:(NSWindow *)window
501         NSToolbar               *toolbar = [window toolbar];
502         NSEnumerator    *enumerator = [[toolbar items] objectEnumerator];
503         NSToolbarItem   *item;
505         while ((item = [enumerator nextObject])) {
506                 if ([[item itemIdentifier] isEqualToString:@"UserIcon"]) {
507                         [self _updateToolbarItem:item forChat:chat];
508                         break;
509                 }
510         }
514  * @brief Empty action for menu item validation purposes
515  */
516 - (IBAction)dummyAction:(id)sender{};
519  * @brief Menu needs update
521  * Should only be called for a menu off one of our toolbar items in text-only mode, and only when that menu is about
522  * to be displayed. The menu should have two items. The first is added by the system; the second has no title and is
523  * our menu item for showing the image.
524  */
525 - (void)menuNeedsUpdate:(NSMenu *)menu
527         //The first item is a root item inserted by the system. The second item is the single item
528         NSMenuItem              *menuItem = [menu itemAtIndex:1];
529         NSToolbarItem   *toolbarItem = [menuItem representedObject];
531         [menuItem setImage:[[[(AIImageButton *)[toolbarItem view] image] copy] autorelease]];
534 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
536         return YES;
539 @end