{{{
[adiumx.git] / Source / AIStatusController.m
blob7a8b76b60aeae85d5a28ccfed1fc079893d90b15
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 "AIStatusController.h"
19 #import <Adium/AIAccountControllerProtocol.h>
20 #import <Adium/AISoundControllerProtocol.h>
22 #import <Adium/AIContactControllerProtocol.h>
23 #import <Adium/AIPreferenceControllerProtocol.h>
24 #import "AdiumIdleManager.h"
26 #import <AIUtilities/AIMenuAdditions.h>
27 #import <AIUtilities/AIArrayAdditions.h>
28 #import <AIUtilities/AIAttributedStringAdditions.h>
29 #import <AIUtilities/AIEventAdditions.h>
30 #import <AIUtilities/AIStringAdditions.h>
31 #import <AIUtilities/AIObjectAdditions.h>
32 #import <Adium/AIAccount.h>
33 #import <Adium/AIService.h>
34 #import <Adium/AIStatusIcons.h>
35 #import "AIStatusGroup.h"
36 #import <Adium/AIStatus.h>
38 //State menu
39 #define STATUS_TITLE_OFFLINE            AILocalizedString(@"Offline",nil)
41 #define BUILT_IN_STATE_ARRAY            @"BuiltInStatusStates"
43 #define TOP_STATUS_STATE_ID                     @"TopStatusID"
45 @interface AIStatusController (PRIVATE)
46 - (NSArray *)builtInStateArray;
48 - (void)_upgradeSavedAwaysToSavedStates;
50 - (NSArray *)_menuItemsForStatusesOfType:(AIStatusType)type forServiceCodeUniqueID:(NSString *)inServiceCodeUniqueID withTarget:(id)target;
51 - (void)_addMenuItemsForStatusOfType:(AIStatusType)type
52                                                   withTarget:(id)target
53                                                          fromSet:(NSSet *)sourceArray
54                                                          toArray:(NSMutableArray *)menuItems
55                                   alreadyAddedTitles:(NSMutableSet *)alreadyAddedTitles;
56 - (void)buildBuiltInStatusTypes;
57 - (void)notifyOfChangedStatusArray;
58 @end
60 /*!
61  * @class AIStatusController
62  * @brief Core status & state methods
63  *
64  * This class provides a foundation for Adium's status and status state systems.
65  */
66 @implementation AIStatusController
68 static  NSMutableSet                    *temporaryStateArray = nil;
70 /*!
71  * Init the status controller
72  */
73 - (id)init
75         if ((self = [super init])) {
76                 stateMenuItemArraysDict = [[NSMutableDictionary alloc] init];
77                 stateMenuPluginsArray = [[NSMutableArray alloc] init];
78                 stateMenuItemsNeedingUpdating = [[NSMutableSet alloc] init];
79                 activeStatusUpdateDelays = 0;
80                 _sortedFullStateArray = nil;
81                 _activeStatusState = nil;
82                 _allActiveStatusStates = nil;
83                 temporaryStateArray = [[NSMutableSet alloc] init];
84                 
85                 accountsToConnect = [[NSMutableSet alloc] init];
86                 
87                 idleManager = [[AdiumIdleManager alloc] init];
88         }
89         
90         return self;
93 /*!
94  * @brief Finish initing the status controller
95  *
96  * Set our initial status state, and restore our array of accounts to connect when a global state is selected.
97  */
98 - (void)controllerDidLoad
100         NSEnumerator                    *enumerator;
101         AIAccount                               *account;
103         [[adium contactController] registerListObjectObserver:self];
105         [self buildBuiltInStatusTypes];
107         //Put each account into the status it was in last time we quit.
108         BOOL            needToRebuildMenus = NO;
109         BOOL            allStatusesInSameState = YES;
110         AIStatus *prevStatus = nil;
111         enumerator = [[[adium accountController] accounts] objectEnumerator];
112         while ((account = [enumerator nextObject])) {
113                 NSData          *lastStatusData = [account preferenceForKey:@"LastStatus"
114                                                                                                                   group:GROUP_ACCOUNT_STATUS];
115                 AIStatus        *lastStatus = nil;
116                 if (lastStatusData)
117                         lastStatus = [NSKeyedUnarchiver unarchiveObjectWithData:lastStatusData];
119                 if (lastStatus && [lastStatus isKindOfClass:[AIStatus class]]) {
120                         AIStatus        *existingStatus;
121                         
122                         /* We want to use a loaded status instance if one exists.  This will be the case if the account
123                          * was last in a built-in or user defined and saved state.  If the last state was unsaved, existingStatus
124                          * will be nil.
125                          */
126                         existingStatus = [self statusStateWithUniqueStatusID:[lastStatus uniqueStatusID]];
127                         
128                         if (existingStatus) {
129                                 lastStatus = existingStatus;
130                         } else {
131                                 //Add to our temporary status array
132                                 [temporaryStateArray addObject:lastStatus];
133                                 
134                                 /* We could clear out _flatStatusSet for the next iteration, but we _know_ what changed,
135                                  * so modify it directly for efficiency.
136                                  */
137                                 [_flatStatusSet addObject:lastStatus];
139                                 needToRebuildMenus = YES;
140                         }
141                         if (!prevStatus)
142                                 prevStatus = lastStatus;
143                         else if (prevStatus != lastStatus)
144                                 allStatusesInSameState = NO;
145                         [account setStatusStateAndRemainOffline:lastStatus];
146                 }
147         }
149         if (needToRebuildMenus) {
150                 [self notifyOfChangedStatusArray];
151         }
155  * @brief Begin closing the status controller
157  * Save the online accounts; they will be the accounts connected by a global status change
159  * Also save the current status state of each account so it can be restored on next launch.
160  */
161 - (void)controllerWillClose
163         NSEnumerator    *enumerator;
164         AIAccount               *account;
166         enumerator = [[[adium accountController] accounts] objectEnumerator];
167         while ((account = [enumerator nextObject])) {
168                 /* Store the current status state for use on next launch.
169                  *
170                  * We use the statusObjectForKey:@"StatusState" accessor rather than [account statusState]
171                  * because we don't want anything besides the account's actual status state.  That is, we don't
172                  * want the default available state if the account doesn't have a state yet, and we want the
173                  * real last-state-which-was-set (not the offline one) if the account is offline.
174                  */
175                 AIStatus        *currentStatus = [account statusObjectForKey:@"StatusState"];
176                 [account setPreference:((currentStatus && (currentStatus != offlineStatusState)) ?
177                                                                 [NSKeyedArchiver archivedDataWithRootObject:currentStatus] :
178                                                                 nil)
179                                                 forKey:@"LastStatus"
180                                                  group:GROUP_ACCOUNT_STATUS];
181         }
182         
183         //XXX change this back sometime before 1.0 release
184 //      [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[self rootStateGroup]]
185         [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[[self rootStateGroup] containedStatusItems]]
186                                                                                  forKey:KEY_SAVED_STATUS
187                                                                                   group:PREF_GROUP_SAVED_STATUS];
189         [[adium notificationCenter] removeObserver:self];
190         [[adium preferenceController] unregisterPreferenceObserver:self];
191         [[adium contactController] unregisterListObjectObserver:self];
195  * @brief Deallocate
196  */
197 - (void)dealloc
199         [_rootStateGroup release]; _rootStateGroup = nil;
200         [_sortedFullStateArray release]; _sortedFullStateArray = nil;
201         [super dealloc];
204 #pragma mark Status registration
206  * @brief Register a status for a service
208  * Implementation note: Each AIStatusType has its own NSMutableDictionary, statusDictsByServiceCodeUniqueID.
209  * statusDictsByServiceCodeUniqueID is keyed by serviceCodeUniqueID; each object is an NSMutableSet of NSDictionaries.
210  * Each of these dictionaries has KEY_STATUS_NAME, KEY_STATUS_DESCRIPTION, and KEY_STATUS_TYPE.
212  * @param statusName A name which will be passed back to accounts of this service.  Internal use only.  Use the AIStatusController.h #defines where appropriate.
213  * @param description A human-readable localized description which will be shown to the user.  Use the AIStatusController.h #defines where appropriate.
214  * @param type An AIStatusType, the general type of this status.
215  * @param service The AIService for which to register the status
216  */
217 - (void)registerStatus:(NSString *)statusName withDescription:(NSString *)description ofType:(AIStatusType)type forService:(AIService *)service
219         NSMutableSet    *statusDicts;
220         NSString                *serviceCodeUniqueID = [service serviceCodeUniqueID];
222         //Create the set if necessary
223         if (!statusDictsByServiceCodeUniqueID[type]) statusDictsByServiceCodeUniqueID[type] = [[NSMutableDictionary alloc] init];
224         if (!(statusDicts = [statusDictsByServiceCodeUniqueID[type] objectForKey:serviceCodeUniqueID])) {
225                 statusDicts = [NSMutableSet set];
226                 [statusDictsByServiceCodeUniqueID[type] setObject:statusDicts
227                                                                                                    forKey:serviceCodeUniqueID];
228         }
230         //Create a dictionary for this status entry
231         NSDictionary *statusDict = [NSDictionary dictionaryWithObjectsAndKeys:
232                 statusName, KEY_STATUS_NAME,
233                 description, KEY_STATUS_DESCRIPTION,
234                 [NSNumber numberWithInt:type], KEY_STATUS_TYPE,
235                 nil];
237         [statusDicts addObject:statusDict];
240 #pragma mark Status menus
242  * @brief Generate and return a menu of status types (Away, Be right back, etc.)
244  * @param service The service for which to return a specific list of types, or nil to return all available types
245  * @param target The target for the menu items, which will have an action of @selector(selectStatus:)
247  * @result The menu of statuses, separated by available and away status types
248  */
249 - (NSMenu *)menuOfStatusesForService:(AIService *)service withTarget:(id)target
251         NSMenu                  *menu = [[NSMenu allocWithZone:[NSMenu menuZone]] init];
252         NSEnumerator    *enumerator;
253         NSMenuItem              *menuItem;
254         NSString                *serviceCodeUniqueID = [service serviceCodeUniqueID];
255         AIStatusType    type;
257         for (type = AIAvailableStatusType ; type < STATUS_TYPES_COUNT ; type++) {
258                 NSArray         *menuItemArray;
260                 menuItemArray = [self _menuItemsForStatusesOfType:type
261                                                                    forServiceCodeUniqueID:serviceCodeUniqueID
262                                                                                            withTarget:target];
264                 //Add a separator between each type after available
265                 if ((type > AIAvailableStatusType) && [menuItemArray count]) {
266                         [menu addItem:[NSMenuItem separatorItem]];
267                 }
269                 //Add the items for this type
270                 enumerator = [menuItemArray objectEnumerator];
271                 while ((menuItem = [enumerator nextObject])) {
272                         [menu addItem:menuItem];
273                 }
274         }
276         return [menu autorelease];
280  * @brief Return an array of menu items for an AIStatusType and service
282  * @pram type The AIStatusType for which to return statuses
283  * @param inServiceCodeUniqueID The service for which to return active statuses.  If nil, return all statuses for online services.
284  * @param target The target for the menu items
286  * @result An <tt>NSArray</tt> of <tt>NSMenuItem</tt> objects.
287  */
288 - (NSArray *)_menuItemsForStatusesOfType:(AIStatusType)type forServiceCodeUniqueID:(NSString *)inServiceCodeUniqueID withTarget:(id)target
290         NSMutableArray  *menuItems = [[NSMutableArray alloc] init];
291         NSMutableSet    *alreadyAddedTitles = [NSMutableSet set];
293         //First, add our built-in items (so they will be at the top of the array and service-specific 'copies' won't replace them)
294         [self _addMenuItemsForStatusOfType:type
295                                                         withTarget:target
296                                                            fromSet:builtInStatusTypes[type]
297                                                            toArray:menuItems
298                                         alreadyAddedTitles:alreadyAddedTitles];
300         //Now, add items for this service, or from all available services, as appropriate
301         if (inServiceCodeUniqueID) {
302                 NSSet   *statusDicts;
304                 //Obtain the status dicts for this type and service code unique ID
305                 if ((statusDicts = [statusDictsByServiceCodeUniqueID[type] objectForKey:inServiceCodeUniqueID])) {
306                         //And add them
307                         [self _addMenuItemsForStatusOfType:type
308                                                                         withTarget:target
309                                                                            fromSet:statusDicts
310                                                                            toArray:menuItems
311                                                         alreadyAddedTitles:alreadyAddedTitles];
312                 }
314         } else {
315                 NSEnumerator    *enumerator;
316                 AIService               *service;
318                 enumerator = [[[adium accountController] activeServicesIncludingCompatibleServices:NO] objectEnumerator];
319                 while ((service = [enumerator nextObject])) {
320                         NSSet   *statusDicts;
321                         
322                         //Obtain the status dicts for this type and service code unique ID
323                         if ((statusDicts = [statusDictsByServiceCodeUniqueID[type] objectForKey:[service serviceCodeUniqueID]])) {
324                                 //And add them
325                                 [self _addMenuItemsForStatusOfType:type
326                                                                                 withTarget:target
327                                                                                    fromSet:statusDicts
328                                                                                    toArray:menuItems
329                                                                 alreadyAddedTitles:alreadyAddedTitles];
330                         }
331                         
332                 }
333         }
335         [menuItems sortUsingSelector:@selector(titleCompare:)];
337         return [menuItems autorelease];
341  * @brief Add menu items for a particular type of status
343  * @param type The AIStatusType, used for determining the icon of the menu items
344  * @param target The target of the created menu items
345  * @param statusDicts An NSSet of NSDictionary objects, which should each represent a status of the passed type
346  * @param menuItems The NSMutableArray to which to add the menuItems
347  * @param alreadyAddedTitles NSMutableSet of NSString titles which have already been added and should not be duplicated. Will be updated as items are added.
348  */
349 - (void)_addMenuItemsForStatusOfType:(AIStatusType)type
350                                                   withTarget:(id)target
351                                                          fromSet:(NSSet *)statusDicts
352                                                          toArray:(NSMutableArray *)menuItems
353                                   alreadyAddedTitles:(NSMutableSet *)alreadyAddedTitles
355         NSEnumerator    *statusDictEnumerator = [statusDicts objectEnumerator];
356         NSDictionary    *statusDict;
358         //Enumerate the status dicts
359         while ((statusDict = [statusDictEnumerator nextObject])) {
360                 NSString        *title = [statusDict objectForKey:KEY_STATUS_DESCRIPTION];
362                 /*
363                  * Only add if it has not already been added by another service.... Services need to use unique titles if they have
364                  * unique state names, but are welcome to share common name/description combinations, which is why the #defines
365                  * exist.
366                  */
367                 if (![alreadyAddedTitles containsObject:title]) {
368                         NSImage         *image;
369                         NSMenuItem      *menuItem;
371                         menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:title
372                                                                                                                                                         target:target
373                                                                                                                                                         action:@selector(selectStatus:)
374                                                                                                                                          keyEquivalent:@""];
376                         image = [AIStatusIcons statusIconForStatusName:[statusDict objectForKey:KEY_STATUS_NAME]
377                                                                                                   statusType:type
378                                                                                                         iconType:AIStatusIconMenu
379                                                                                                    direction:AIIconNormal];
381                         [menuItem setRepresentedObject:statusDict];
382                         [menuItem setImage:image];
383                         [menuItem setEnabled:YES];
384                         [menuItems addObject:menuItem];
385                         [menuItem release];
387                         [alreadyAddedTitles addObject:title];
388                 }
389         }
392 #pragma mark Status State Descriptions
393 - (NSString *)localizedDescriptionForCoreStatusName:(NSString *)statusName
395         static NSDictionary     *coreLocalizedStatusDescriptions = nil;
396         if(!coreLocalizedStatusDescriptions){
397                 coreLocalizedStatusDescriptions = [[NSDictionary dictionaryWithObjectsAndKeys:
398                         AILocalizedString(@"Available", nil), STATUS_NAME_AVAILABLE,
399                         AILocalizedString(@"Free for chat", nil), STATUS_NAME_FREE_FOR_CHAT,
400                         AILocalizedString(@"Available for friends only",nil), STATUS_NAME_AVAILABLE_FRIENDS_ONLY,
401                         AILocalizedString(@"Away", nil), STATUS_NAME_AWAY,
402                         AILocalizedString(@"Extended away",nil), STATUS_NAME_EXTENDED_AWAY,
403                         AILocalizedString(@"Away for friends only",nil), STATUS_NAME_AWAY_FRIENDS_ONLY,
404                         AILocalizedString(@"Do not disturb", nil), STATUS_NAME_DND,
405                         AILocalizedString(@"Not available", nil), STATUS_NAME_NOT_AVAILABLE,
406                         AILocalizedString(@"Occupied", nil), STATUS_NAME_OCCUPIED,
407                         AILocalizedString(@"Be right back",nil), STATUS_NAME_BRB,
408                         AILocalizedString(@"Busy",nil), STATUS_NAME_BUSY,
409                         AILocalizedString(@"On the phone",nil), STATUS_NAME_PHONE,
410                         AILocalizedString(@"Out to lunch",nil), STATUS_NAME_LUNCH,
411                         AILocalizedString(@"Not at home",nil), STATUS_NAME_NOT_AT_HOME,
412                         AILocalizedString(@"Not at my desk",nil), STATUS_NAME_NOT_AT_DESK,
413                         AILocalizedString(@"Not in the office",nil), STATUS_NAME_NOT_IN_OFFICE,
414                         AILocalizedString(@"On vacation",nil), STATUS_NAME_VACATION,
415                         AILocalizedString(@"Stepped out",nil), STATUS_NAME_STEPPED_OUT,
416                         AILocalizedString(@"Invisible",nil), STATUS_NAME_INVISIBLE,
417                         AILocalizedString(@"Offline",nil), STATUS_NAME_OFFLINE,
418                         nil] retain];
419         }
420         
421         return (statusName ? [coreLocalizedStatusDescriptions objectForKey:statusName] : nil);
424 - (NSString *)localizedDescriptionForStatusName:(NSString *)statusName statusType:(AIStatusType)statusType
426         NSString *description = nil;
428         if (statusName &&
429                 !(description = [self localizedDescriptionForCoreStatusName:statusName])) {
430                 NSEnumerator    *enumerator = [statusDictsByServiceCodeUniqueID[statusType] objectEnumerator];
431                 NSSet                   *set;
432                 
433                 while (!description && (set = [enumerator nextObject])) {
434                         NSEnumerator    *statusDictsEnumerator = [set objectEnumerator];
435                         NSDictionary    *statusDict;
436                         while (!description && (statusDict = [statusDictsEnumerator nextObject])) {
437                                 if ([[statusDict objectForKey:KEY_STATUS_NAME] isEqualToString:statusName]){
438                                         description = [statusDict objectForKey:KEY_STATUS_DESCRIPTION];
439                                 }
440                         }
441                 }               
442         }
443         
444         return description;
448  * @brief Return the localized description for the sate of the passed status
450  * This could be stored with the statusState, but that would break if the locale changed.  This way, the nonlocalized
451  * string is used to look up the appropriate localized one.
453  * @result A localized description such as @"Away" or @"Out to Lunch" of the state used by statusState
454  */
455 - (NSString *)descriptionForStateOfStatus:(AIStatus *)statusState
457         return [self localizedDescriptionForStatusName:[statusState statusName]
458                                                                                 statusType:[statusState statusType]];
462  * @brief The status name to use by default for a passed type
464  * This is the name which will be used for new AIStatus objects of this type.
465  */
466 - (NSString *)defaultStatusNameForType:(AIStatusType)statusType
468         //Set the default status name
469         switch (statusType) {
470                 case AIAvailableStatusType:
471                         return STATUS_NAME_AVAILABLE;
472                         break;
473                 case AIAwayStatusType:
474                         return STATUS_NAME_AWAY;
475                         break;
476                 case AIInvisibleStatusType:
477                         return STATUS_NAME_INVISIBLE;
478                         break;
479                 case AIOfflineStatusType:
480                         return STATUS_NAME_OFFLINE;
481                         break;
482         }
484         return nil;
487 #pragma mark Setting Status States
489  * @brief Set the active status state
491  * Sets the currently active status state.  This applies throughout Adium and to all accounts.  The state will become
492  * effective immediately.
493  */
494 - (void)setActiveStatusState:(AIStatus *)statusState
496         //Apply the state to our accounts and notify (delay to the next run loop to improve perceived speed)
497         [self performSelector:@selector(applyState:toAccounts:)
498                            withObject:statusState
499                            withObject:[[adium accountController] accounts]
500                            afterDelay:0];
504  * @brief Return the <tt>AIStatus</tt> to be used by accounts as they are created
505  */
506 - (AIStatus *)defaultInitialStatusState
508         return [[self builtInStateArray] objectAtIndex:0];
512  * @brief Reset the active status state
514  * All active status states cache will also reset.  Posts an active status changed notification.  The active state
515  * will be regenerated the next time it is requested.
516  */
517 - (void)_resetActiveStatusState
519         //Clear the active status state.  It will be rebuilt next time it is requested
520         [_activeStatusState release]; _activeStatusState = nil;
521         [_allActiveStatusStates release]; _allActiveStatusStates = nil;
523         //Let observers know the active state has changed
524         if (!activeStatusUpdateDelays) {
525                 [[adium notificationCenter] postNotificationName:AIStatusActiveStateChangedNotification object:nil];
526         }
530  * @brief Account status changed.
532  * Rebuild all our state menus
533  */
534 - (NSSet *)updateListObject:(AIListObject *)inObject keys:(NSSet *)inModifiedKeys silent:(BOOL)silent
536         if ([inObject isKindOfClass:[AIAccount class]]) {
537                 if ([inModifiedKeys containsObject:@"Online"] ||
538                         [inModifiedKeys containsObject:@"IdleSince"] ||
539                         [inModifiedKeys containsObject:@"StatusState"]) {
540                         
541                         [self _resetActiveStatusState];
542                 }
543         }
544         
545     return nil;
550  * @brief Delay activee status menu updates
552  * This should be called to prevent duplicative updates when multiple accounts are changing status simultaneously.
553  */
554 - (void)setDelayActiveStatusUpdates:(BOOL)shouldDelay
556         if (shouldDelay)
557                 activeStatusUpdateDelays++;
558         else
559                 activeStatusUpdateDelays--;
560         
561         if (!activeStatusUpdateDelays) {
562                 [[adium notificationCenter] postNotificationName:AIStatusActiveStateChangedNotification object:nil];
563         }
567  * @brief Delay activee status menu updates
569  * This should be called to prevent duplicative rebuilds when the status menu will change multple times.
570  */
571 - (void)setDelayStatusMenuRebuilding:(BOOL)shouldDelay
573         if (shouldDelay)
574                 statusMenuRebuildDelays++;
575         else
576                 statusMenuRebuildDelays--;
577         
578         if (!statusMenuRebuildDelays) {
579                 [[adium notificationCenter] postNotificationName:AIStatusStateArrayChangedNotification object:nil];     
580         }
584  * @brief Apply a state to multiple accounts
585  */
586 - (void)applyState:(AIStatus *)statusState toAccounts:(NSArray *)accountArray
588         NSEnumerator    *enumerator;
589         AIAccount               *account;
590         AIStatus                *aStatusState;
591         BOOL                    shouldRebuild = NO;
592         BOOL                    noConnectedAccounts = ![[adium accountController] oneOrMoreConnectedOrConnectingAccounts];
593         BOOL                    isOfflineStatus = ([statusState statusType] == AIOfflineStatusType);
594         [self setDelayActiveStatusUpdates:YES];
595         
596         /* If we're going offline, determine what accounts are currently online, first, so that we can restore that when an online state
597          * is chosen later.
598          */
599         if  (isOfflineStatus && !noConnectedAccounts) {
600                 [accountsToConnect removeAllObjects];
602                 enumerator = [accountArray objectEnumerator];
603                 while ((account = [enumerator nextObject])) {
604                         if ([account online]) [accountsToConnect addObject:account];
605                 }
606         }
608         if (noConnectedAccounts) {
609                 /* No connected accounts: Connect all enabled accounts which were set offline previously.
610                  * If we have no such list of accounts, connect 'em all.
611                  */
612                 BOOL noAccountsToConnectCount = ([accountsToConnect count] == 0);
613                 enumerator = [accountArray objectEnumerator];
614                 while ((account = [enumerator nextObject])) {
615                         if ([account enabled] &&
616                                 ([accountsToConnect containsObject:account] || noAccountsToConnectCount)) {
617                                 [account setStatusState:statusState];
619                         } else {
620                                 [account setStatusStateAndRemainOffline:statusState];   
621                         }
622                 }
624         } else {
625                 //At least one account is online.  Just change its status without taking any other accounts online.
626                 enumerator = [accountArray objectEnumerator];
627                 while ((account = [enumerator nextObject])) {
628                         if ([account online] || isOfflineStatus) {
629                                 [account setStatusState:statusState];
630                                 
631                         } else {
632                                 [account setStatusStateAndRemainOffline:statusState];                   
633                         }
634                 }
635         }
637         //If this is not an offline status, we've now made use of accountsToConnect and should clear it so it isn't used again.
638         if (!isOfflineStatus) {
639                 [accountsToConnect removeAllObjects];
640         }
642         //Any objects in the temporary state array which aren't the state we just set should now be removed.
643         enumerator = [[[temporaryStateArray copy] autorelease] objectEnumerator];
644         while ((aStatusState = [enumerator nextObject])) {
645                 if (aStatusState != statusState) {
646                         [temporaryStateArray removeObject:aStatusState];
647                         shouldRebuild = YES;
648                 }
649         }
651         if (shouldRebuild) {
652                 [self notifyOfChangedStatusArray];
653         }
655         [self setDelayActiveStatusUpdates:NO];
658 #pragma mark Retrieving Status States
660  * @brief Access to Adium's user-defined states
662  * Returns the root AIStatusGroup of user-defined states
663  */
664 - (AIStatusGroup *)rootStateGroup
666         if (!_rootStateGroup) {
667                 NSData  *savedStateData = [[adium preferenceController] preferenceForKey:KEY_SAVED_STATUS
668                                                                                                                                                    group:PREF_GROUP_SAVED_STATUS];
669                 if (savedStateData) {
670                         id archivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:savedStateData];
672                         if ([archivedObject isKindOfClass:[AIStatusGroup class]]) {
673                                 //Adium 1.0 archives an AIStatusGroup
674                                 _rootStateGroup = [archivedObject retain];
675                         
676                         } else if  ([archivedObject isKindOfClass:[NSArray class]]) {
677                                 //Adium 0.8x archived an NSArray
678                                 _rootStateGroup = [[AIStatusGroup statusGroupWithContainedStatusItems:archivedObject] retain];
679                         }
680                 }
682                 if (!_rootStateGroup) _rootStateGroup = [[AIStatusGroup statusGroup] retain];
684                 //Upgrade Adium 0.7x away messages
685                 [self _upgradeSavedAwaysToSavedStates];
686         }
688         return _rootStateGroup;
692  * @brief Return the array of built-in states
694  * These are basic Available and Away states which should always be visible and are (by convention) immutable.
695  * The first state in BUILT_IN_STATE_ARRAY will be used as the default for accounts as they are created.
696  */
697 - (NSArray *)builtInStateArray
699         if (!builtInStateArray) {
700                 NSArray                 *savedBuiltInStateArray = [NSArray arrayNamed:BUILT_IN_STATE_ARRAY forClass:[self class]];
701                 NSEnumerator    *enumerator;
702                 NSDictionary    *dict;
704                 builtInStateArray = [[NSMutableArray alloc] initWithCapacity:[savedBuiltInStateArray count]];
706                 enumerator = [savedBuiltInStateArray objectEnumerator];
707                 while ((dict = [enumerator nextObject])) {
708                         AIStatus        *status = [AIStatus statusWithDictionary:dict];
709                         [builtInStateArray addObject:status];
711                         //Store a reference to our offline state if we just loaded it
712                         if ([status statusType] == AIOfflineStatusType) {
713                                 [offlineStatusState release];
714                                 offlineStatusState = [status retain];
715                         }
716                 }
717         }
719         return builtInStateArray;
723 * @brief Create and add the built-in status types; even if no service explicitly registers these, they are available.
725  * The built-in status types are basic, generic "Available" and "Away" states.
726  */
727 - (void)buildBuiltInStatusTypes
729         NSDictionary    *statusDict;
730         
731         builtInStatusTypes[AIAvailableStatusType] = [[NSMutableSet alloc] init];
732         statusDict = [NSDictionary dictionaryWithObjectsAndKeys:
733                 STATUS_NAME_AVAILABLE, KEY_STATUS_NAME,
734                 [self localizedDescriptionForCoreStatusName:STATUS_NAME_AVAILABLE], KEY_STATUS_DESCRIPTION,
735                 [NSNumber numberWithInt:AIAvailableStatusType], KEY_STATUS_TYPE,
736                 nil];
737         [builtInStatusTypes[AIAvailableStatusType] addObject:statusDict];
738         
739         builtInStatusTypes[AIAwayStatusType] = [[NSMutableSet alloc] init];
740         statusDict = [NSDictionary dictionaryWithObjectsAndKeys:
741                 STATUS_NAME_AWAY, KEY_STATUS_NAME,
742                 [self localizedDescriptionForCoreStatusName:STATUS_NAME_AWAY], KEY_STATUS_DESCRIPTION,
743                 [NSNumber numberWithInt:AIAwayStatusType], KEY_STATUS_TYPE,
744                 nil];
745         [builtInStatusTypes[AIAwayStatusType] addObject:statusDict];
749 - (AIStatus *)offlineStatusState
751         //Ensure the built in states have been loaded
752         [self builtInStateArray];
754         NSAssert(offlineStatusState != nil, @"Nil offline status state");
755         return offlineStatusState;
759  * @brief Return a sorted state array for use in menu item creation
761  * The array is created by adding the built in states to the user states, then sorting using _statusArraySort
762  * The resulting array may contain AIStatus and AIStatusGroup objects.
764  * @result A cached NSArray which is sorted by status type (available, away), built-in vs. user-made, and then original ordering.
765  */
766 - (NSArray *)sortedFullStateArray
768         if (!_sortedFullStateArray) {
769                 NSArray                 *originalStateArray;
770                 NSMutableArray  *tempArray;
772                 //Start with everything contained 1) in our built-in array and then 2) in our root group
773                 originalStateArray = [[self builtInStateArray] arrayByAddingObjectsFromArray:[[self rootStateGroup] containedStatusItems]];
774                 
775                 tempArray = [originalStateArray mutableCopy];
777                 //Now add the temporary statues
778                 [tempArray addObjectsFromArray:[temporaryStateArray allObjects]];
780                 //Pass the original array so its indexes can be used for comparison of saved state ordering
781                 [AIStatusGroup sortArrayOfStatusItems:tempArray context:originalStateArray];
783                 _sortedFullStateArray = tempArray;
784         }
786         return _sortedFullStateArray;
790  * @brief Generate and return an array of AIStatus objects which are all known saved, temporary, and built-in statuses
791  */
792 - (NSArray *)flatStatusSet
794         if (!_flatStatusSet) {
795                 NSMutableArray  *tempArray = [[[self rootStateGroup] flatStatusSet] mutableCopy];
797                 //Add built in states
798                 [tempArray addObjectsFromArray:[self builtInStateArray]];
800                 //Add temporary ones
801                 [tempArray addObjectsFromArray:[temporaryStateArray allObjects]];
803                 _flatStatusSet = tempArray;
804         }
805         
806         return _flatStatusSet;
810  * @brief Retrieve active status state
812  * @result The currently active status state.
814  * This is defined as the status state which the most accounts are currently using.  The behavior in case of a tie
815  * is currently undefined but will yield one of the tying states.
816  */
817 - (AIStatus *)activeStatusState
819         if (!_activeStatusState) {
820                 NSEnumerator            *enumerator = [[[adium accountController] accounts] objectEnumerator];
821                 NSCountedSet            *statusCounts = [NSCountedSet set];
822                 AIAccount                       *account;
823                 AIStatus                        *statusState;
824                 unsigned                         highestCount = 0;
825                 BOOL                             accountsAreOnline = [[adium accountController] oneOrMoreConnectedOrConnectingAccounts];
827                 if (accountsAreOnline) {
828                         AIStatus        *bestStatusState = nil;
830                         while ((account = [enumerator nextObject])) {
831                                 if ([account online]) {
832                                         AIStatus *accountStatusState = [account statusState];
833                                         [statusCounts addObject:(accountStatusState ?
834                                                                                          accountStatusState :
835                                                                                          [self defaultInitialStatusState])];
836                                 }
837                         }
839                         enumerator = [statusCounts objectEnumerator];
840                         while ((statusState = [enumerator nextObject])) {
841                                 unsigned thisCount = [statusCounts countForObject:statusState];
842                                 if (thisCount > highestCount) {
843                                         bestStatusState = statusState;
844                                         highestCount = thisCount;
845                                 }
846                         }
848                         _activeStatusState = [bestStatusState retain];
849                 } else {
850                         _activeStatusState = [offlineStatusState retain];
851                 }
852         }
854         return _activeStatusState;
858  * @brief Find the 'active' AIStatusType
860  * The active type is the one used by the largest number of accounts.  In case of a tie, the order of the AIStatusType
861  * enum is respected
863  * @param invisibleIsAway If YES, AIInvisibleStatusType is trated as AIAwayStatusType
864  * @result The active AIStatusType for online accounts, or AIOfflineStatusType if all accounts are  offline
865  */
866 - (AIStatusType)activeStatusTypeTreatingInvisibleAsAway:(BOOL)invisibleIsAway
868         NSEnumerator            *enumerator = [[[adium accountController] accounts] objectEnumerator];
869         AIAccount                       *account;
870         int                                     statusTypeCount[STATUS_TYPES_COUNT];
871         AIStatusType            activeStatusType = AIOfflineStatusType;
872         unsigned                        highestCount = 0;
874         unsigned i;
875         for (i = 0 ; i < STATUS_TYPES_COUNT ; i++) {
876                 statusTypeCount[i] = 0;
877         }
879         while ((account = [enumerator nextObject])) {
880                 if ([account online] || [account integerStatusObjectForKey:@"Connecting"]) {
881                         AIStatusType statusType = [[account statusState] statusType];
883                         //If invisibleIsAway, pretend that invisible is away
884                         if (invisibleIsAway && (statusType == AIInvisibleStatusType)) statusType = AIAwayStatusType;
886                         statusTypeCount[statusType]++;
887                 }
888         }
890         for (i = 0 ; i < STATUS_TYPES_COUNT ; i++) {
891                 if (statusTypeCount[i] > highestCount) {
892                         activeStatusType = i;
893                         highestCount = statusTypeCount[i];
894                 }
895         }
897         return activeStatusType;
901  * @brief All active status states
903  * A status state is active if any enabled account is currently in that state.
905  * The return value of this method is cached.
907  * @result An <tt>NSSet</tt> of <tt>AIStatus</tt> objects
908  */
909 - (NSSet *)allActiveStatusStates
911         if (!_allActiveStatusStates) {
912                 _allActiveStatusStates = [[NSMutableSet alloc] init];
913                 NSEnumerator            *enumerator = [[[adium accountController] accounts] objectEnumerator];
914                 AIAccount                       *account;
916                 while ((account = [enumerator nextObject])) {
917                         if ([account enabled]) {
918                                 [_allActiveStatusStates addObject:[account statusState]];
919                         }
920                 }
921         }
923         return _allActiveStatusStates;
927  * @brief Return the set of all unavailable statuses in use by online or connection accounts
929  * @param activeUnvailableStatusType Pointer to an AIStatusType; returns by reference the most popular unavailable type
930  * @param activeUnvailableStatusName Pointer to an NSString*; returns by reference a status name if all states are in the same name, or nil if they differ
931  * @param allOnlineAccountsAreUnvailable Pointer to a BOOL; returns by reference YES is all online accounts are unavailable, NO if one or more is available
932  */
933 - (NSSet *)activeUnavailableStatusesAndType:(AIStatusType *)activeUnvailableStatusType withName:(NSString **)activeUnvailableStatusName allOnlineAccountsAreUnvailable:(BOOL *)allOnlineAccountsAreUnvailable
935         NSEnumerator            *enumerator = [[[adium accountController] accounts] objectEnumerator];
936         AIAccount                       *account;
937         NSMutableSet            *activeUnvailableStatuses = [NSMutableSet set];
938         BOOL                            foundStatusName = NO;
939         int                                     statusTypeCount[STATUS_TYPES_COUNT];
941         statusTypeCount[AIAwayStatusType] = 0;
942         statusTypeCount[AIInvisibleStatusType] = 0;
943         
944         //Assume all accounts are unavailable until proven otherwise
945         if (allOnlineAccountsAreUnvailable != NULL) {
946                 *allOnlineAccountsAreUnvailable = YES;
947         }
948         
949         while ((account = [enumerator nextObject])) {
950                 if ([account online] || [account integerStatusObjectForKey:@"Connecting"]) {
951                         AIStatus        *statusState = [account statusState];
952                         AIStatusType statusType = [statusState statusType];
953                         
954                         if ((statusType == AIAwayStatusType) || (statusType == AIInvisibleStatusType)) {
955                                 NSString        *statusName = [statusState statusName];
956                                 
957                                 [activeUnvailableStatuses addObject:statusState];
958                                 
959                                 statusTypeCount[statusType]++;
960                                 
961                                 if (foundStatusName) {
962                                         //Once we find a status name, we only want to return it if all our status names are the same.
963                                         if ((activeUnvailableStatusName != NULL) &&
964                                            (*activeUnvailableStatusName != nil) && 
965                                            ![*activeUnvailableStatusName isEqualToString:statusName]) {
966                                                 *activeUnvailableStatusName = nil;
967                                         }
968                                 } else {
969                                         //We haven't found a status name yet, so store this one as the active status name
970                                         if (activeUnvailableStatusName != NULL) {
971                                                 *activeUnvailableStatusName = [statusState statusName];
972                                         }
973                                         foundStatusName = YES;
974                                 }
975                         } else {
976                                 //An online account isn't unavailable
977                                 if (allOnlineAccountsAreUnvailable != NULL) {
978                                         *allOnlineAccountsAreUnvailable = NO;
979                                 }
980                         }
981                 }
982         }
983         
984         if (activeUnvailableStatusType != NULL) {
985                 if (statusTypeCount[AIAwayStatusType] > statusTypeCount[AIInvisibleStatusType]) {
986                         *activeUnvailableStatusType = AIAwayStatusType;
987                 } else {
988                         *activeUnvailableStatusType = AIInvisibleStatusType;            
989                 }
990         }
991         
992         return activeUnvailableStatuses;
997  * @brief Next available unique status ID
998  */
999 - (NSNumber *)nextUniqueStatusID
1001         NSNumber        *nextUniqueStatusID;
1003         //Retain and autorelease since we'll be replacing this value (and therefore releasing it) via the preferenceController.
1004         nextUniqueStatusID = [[[[adium preferenceController] preferenceForKey:TOP_STATUS_STATE_ID
1005                                                                                                                                   group:PREF_GROUP_SAVED_STATUS] retain] autorelease];
1006         if (!nextUniqueStatusID) nextUniqueStatusID = [NSNumber numberWithInt:1];
1008         [[adium preferenceController] setPreference:[NSNumber numberWithInt:([nextUniqueStatusID intValue] + 1)]
1009                                                                                  forKey:TOP_STATUS_STATE_ID
1010                                                                                   group:PREF_GROUP_SAVED_STATUS];
1012         return nextUniqueStatusID;
1016  * @brief Find the status state with the requested uniqueStatusID
1017  */
1018 - (AIStatus *)statusStateWithUniqueStatusID:(NSNumber *)uniqueStatusID
1020         AIStatus                *statusState = nil;
1022         if (uniqueStatusID) {
1023                 NSEnumerator    *enumerator = [[self flatStatusSet] objectEnumerator];
1025                 while ((statusState = [enumerator nextObject])) {
1026                         if ([[statusState uniqueStatusID] compare:uniqueStatusID] == NSOrderedSame)
1027                                 break;
1028                 }
1029         }
1031         return statusState;
1034 //State Editing --------------------------------------------------------------------------------------------------------
1035 #pragma mark State Editing
1037  * @brief Add a state
1039  * Add a new state to Adium's state array.
1040  * @param state AIState to add
1041  */
1042 - (void)addStatusState:(AIStatus *)statusState
1044         AIStatusMutabilityType mutabilityType = [statusState mutabilityType];
1045         
1046         if ((mutabilityType == AILockedStatusState) ||
1047                 (mutabilityType == AISecondaryLockedStatusState)) {
1048                 //If we are adding a locked status, add it to the built-in statuses
1049                 [(NSMutableArray *)[self builtInStateArray] addObject:statusState];
1051                 [self notifyOfChangedStatusArray];
1053         } else {
1054                 //Otherwise, add it to the user-created statuses
1055                 [[self rootStateGroup] addStatusItem:statusState atIndex:-1];
1056         }
1060  * @brief Remove a state
1062  * Remove a new state from Adium's state array.
1063  * @param state AIStatus to remove
1064  */
1065 - (void)removeStatusState:(AIStatus *)statusState
1067         NSLog(@"shouldn't be calling this.");
1068 //      [stateArray removeObject:statusState];
1069         [self savedStatusesChanged];
1072 - (void)notifyOfChangedStatusArray
1074         //Clear the sorted menu items array since our state array changed.
1075         [_sortedFullStateArray release]; _sortedFullStateArray = nil;
1076         [_flatStatusSet release]; _flatStatusSet = nil;
1078         if (!statusMenuRebuildDelays) {
1079                 [[adium notificationCenter] postNotificationName:AIStatusStateArrayChangedNotification object:nil];     
1080         }
1084  * @brief Save changes to the state array and notify observers
1086  * Saves any outstanding changes to the state array.  There should be no need to call this manually, since all the
1087  * state array modifying methods in this class call it automatically after making changes.
1089  * After the state array is saved, observers are notified that is has changed.  Call after making any changes to the
1090  * state array from within the controller.
1091  */
1092 - (void)savedStatusesChanged
1094         //XXX change this back sometime before 1.0 release
1095 //      [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[self rootStateGroup]]
1096         [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[[self rootStateGroup] containedStatusItems]]
1097                                                                                  forKey:KEY_SAVED_STATUS
1098                                                                                   group:PREF_GROUP_SAVED_STATUS];
1099         [self notifyOfChangedStatusArray];
1102 - (void)statusStateDidSetUniqueStatusID
1104         //XXX change this back sometime before 1.0 release
1105 //      [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[self rootStateGroup]]
1106         [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[[self rootStateGroup] containedStatusItems]]
1107                                                                                  forKey:KEY_SAVED_STATUS
1108                                                                                   group:PREF_GROUP_SAVED_STATUS];
1112 * @brief Called when a state could potentially need to removed from the temporary (non-saved) list
1114  * If originalState is in the temporary status array, and it is being used on one or zero accounts, it 
1115  * is removed from the temporary status array. This method should be used when one or more accounts have stopped
1116  * using a single status state to determine if that status state is both non-saved and unused.
1118  * Note that while it would seem logical to post AIStatusStateArrayChangedNotification when this method would
1119  * return YES, we don't want to force observers of the notification to update immediately since there may be further
1120  * processing. We therefore let the calling method take action if it chooses to.
1122  * @result YES if the state was removed
1123  */
1124 - (BOOL)removeIfNecessaryTemporaryStatusState:(AIStatus *)originalState
1126         BOOL didRemove = NO;
1128         /* If the original (old) status state is in our temporary array and is not being used in more than 1 account, 
1129         * then we should remove it.
1130         */
1131         if ([temporaryStateArray containsObject:originalState]) {
1132                 NSEnumerator    *enumerator;
1133                 AIAccount               *account;
1134                 int                             count = 0;
1135                 
1136                 enumerator = [[[adium accountController] accounts] objectEnumerator];
1137                 while ((account = [enumerator nextObject])) {
1138                         if ([account actualStatusState] == originalState) {
1139                                 if (++count > 1) break;
1140                         }
1141                 }
1143                 if (count <= 1) {
1144                         [temporaryStateArray removeObject:originalState];
1145                         didRemove = YES;
1146                 }
1147         }
1149         return didRemove;
1152 //Status state menu support ---------------------------------------------------------------------------------------------------
1153 #pragma mark Status state menu support
1155  * @brief Apply a custom state
1157  * Invoked when the custom state window is closed by the user clicking OK.  In response this method sets the custom
1158  * state as the active state.
1159  */
1160 - (void)customStatusState:(AIStatus *)originalState changedTo:(AIStatus *)newState forAccount:(AIAccount *)account
1162         BOOL shouldRebuild = NO;
1163         
1164         if (account) {
1165                 shouldRebuild = [self removeIfNecessaryTemporaryStatusState:originalState];
1167                 //Now set the newState for the account
1168                 [account setStatusState:newState];
1169                 
1170                 //Enable the account if it isn't currently enabled
1171                 if (![account enabled]) {
1172                         [account setEnabled:YES];
1173                 }               
1175         } else {
1176                 //Set the state for all accounts.  This will clear out the temporaryStatusArray as necessary.
1177                 [self setActiveStatusState:newState];
1178         }
1180         if ([newState mutabilityType] != AITemporaryEditableStatusState) {
1181                 [[adium statusController] addStatusState:newState];
1182         }
1184         NSMutableDictionary *lastStatusStates;
1186         lastStatusStates = [[[adium preferenceController] preferenceForKey:@"LastStatusStates"
1187                                                                                                                                  group:PREF_GROUP_STATUS_PREFERENCES] mutableCopy];
1188         if (!lastStatusStates) lastStatusStates = [NSMutableDictionary dictionary];
1190         [lastStatusStates setObject:[NSKeyedArchiver archivedDataWithRootObject:newState]
1191                                                  forKey:[NSNumber numberWithInt:[newState statusType]]];
1193         [[adium preferenceController] setPreference:lastStatusStates
1194                                                                                  forKey:@"LastStatusStates"
1195                                                                                   group:PREF_GROUP_STATUS_PREFERENCES];
1197         //Add to our temporary status array if it's not in our state array
1198         if (shouldRebuild || (![[self flatStatusSet] containsObject:newState])) {
1199                 [temporaryStateArray addObject:newState];
1201                 [self notifyOfChangedStatusArray];
1202         }
1206 #pragma mark Upgrade code
1208  * @brief Temporary upgrade code for 0.7x -> 0.8
1210  * Versions 0.7x and prior stored their away messages in a different format.  This code allows a seamless
1211  * transition from 0.7x to 0.8.  We can easily recognize the old format because the away messages are of
1212  * type "Away" instead of type "State", which is used for all 0.8 and later saved states.
1213  * Since we are changing the array as we scan it, an enumerator will not work here.
1214  */
1215 #define OLD_KEY_SAVED_AWAYS                     @"Saved Away Messages"
1216 #define OLD_GROUP_AWAY_MESSAGES         @"Away Messages"
1217 #define OLD_STATE_SAVED_AWAY            @"Away"
1218 #define OLD_STATE_AWAY                          @"Message"
1219 #define OLD_STATE_AUTO_REPLY            @"Autoresponse"
1220 #define OLD_STATE_TITLE                         @"Title"
1221 - (void)_upgradeSavedAwaysToSavedStates
1223         NSArray *savedAways = [[adium preferenceController] preferenceForKey:OLD_KEY_SAVED_AWAYS
1224                                                                                                                                    group:OLD_GROUP_AWAY_MESSAGES];
1226         if (savedAways) {
1227                 NSEnumerator    *enumerator = [savedAways objectEnumerator];
1228                 NSDictionary    *state;
1230                 AILog(@"*** Upgrading Adium 0.7x saved aways: %@", savedAways);
1232                 [self setDelayStatusMenuRebuilding:YES];
1234                 //Update all the away messages to states.
1235                 while ((state = [enumerator nextObject])) {
1236                         if ([[state objectForKey:@"Type"] isEqualToString:OLD_STATE_SAVED_AWAY]) {
1237                                 AIStatus        *statusState;
1239                                 //Extract the away message information from this old record
1240                                 NSData          *statusMessageData = [state objectForKey:OLD_STATE_AWAY];
1241                                 NSData          *autoReplyMessageData = [state objectForKey:OLD_STATE_AUTO_REPLY];
1242                                 NSString        *title = [state objectForKey:OLD_STATE_TITLE];
1244                                 //Create an AIStatus from this information
1245                                 statusState = [AIStatus status];
1247                                 //General category: It's an away type
1248                                 [statusState setStatusType:AIAwayStatusType];
1250                                 //Specific state: It's the generic away. Funny how that works out.
1251                                 [statusState setStatusName:STATUS_NAME_AWAY];
1253                                 //Set the status message (which is just the away message).
1254                                 [statusState setStatusMessage:[NSAttributedString stringWithData:statusMessageData]];
1256                                 //It has an auto reply.
1257                                 [statusState setHasAutoReply:YES];
1259                                 if (autoReplyMessageData) {
1260                                         //Use the custom auto reply if it was set.
1261                                         [statusState setAutoReply:[NSAttributedString stringWithData:autoReplyMessageData]];
1262                                 } else {
1263                                         //If no autoReplyMesssage, use the status message.
1264                                         [statusState setAutoReplyIsStatusMessage:YES];
1265                                 }
1267                                 if (title) [statusState setTitle:title];
1269                                 //Add the updated state to our state array.
1270                                 [self addStatusState:statusState];
1271                         }
1272                 }
1274                 AILog(@"*** Finished upgrading old saved statuses");
1276                 //Save these changes and delete the old aways so we don't need to do this again.
1277                 [self setDelayStatusMenuRebuilding:NO];
1279                 [[adium preferenceController] setPreference:nil
1280                                                                                          forKey:OLD_KEY_SAVED_AWAYS
1281                                                                                           group:OLD_GROUP_AWAY_MESSAGES];
1282         }
1285 @end