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 "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>
39 #define STATUS_TITLE_OFFLINE AILocalizedStringFromTable(@"Offline", @"Statuses", "Name of a status")
41 #define BUILT_IN_STATE_ARRAY @"BuiltInStatusStates"
43 @interface AIStatusController (PRIVATE)
44 - (NSArray *)builtInStateArray;
46 - (void)_upgradeSavedAwaysToSavedStates;
48 - (NSArray *)_menuItemsForStatusesOfType:(AIStatusType)type forServiceCodeUniqueID:(NSString *)inServiceCodeUniqueID withTarget:(id)target;
49 - (void)_addMenuItemsForStatusOfType:(AIStatusType)type
51 fromSet:(NSSet *)sourceArray
52 toArray:(NSMutableArray *)menuItems
53 alreadyAddedTitles:(NSMutableSet *)alreadyAddedTitles;
54 - (void)buildBuiltInStatusTypes;
55 - (void)notifyOfChangedStatusArray;
59 * @class AIStatusController
60 * @brief Core status & state methods
62 * This class provides a foundation for Adium's status and status state systems.
64 @implementation AIStatusController
66 static NSMutableSet *temporaryStateArray = nil;
69 * Init the status controller
73 if ((self = [super init])) {
74 stateMenuItemArraysDict = [[NSMutableDictionary alloc] init];
75 stateMenuPluginsArray = [[NSMutableArray alloc] init];
76 stateMenuItemsNeedingUpdating = [[NSMutableSet alloc] init];
77 activeStatusUpdateDelays = 0;
78 _sortedFullStateArray = nil;
79 _activeStatusState = nil;
80 _allActiveStatusStates = nil;
81 temporaryStateArray = [[NSMutableSet alloc] init];
83 accountsToConnect = [[NSMutableSet alloc] init];
85 idleManager = [[AdiumIdleManager alloc] init];
92 * @brief Finish initing the status controller
94 * Set our initial status state, and restore our array of accounts to connect when a global state is selected.
96 - (void)controllerDidLoad
98 NSEnumerator *enumerator;
101 [[adium contactController] registerListObjectObserver:self];
103 [self buildBuiltInStatusTypes];
105 //Put each account into the status it was in last time we quit.
106 BOOL needToRebuildMenus = NO;
107 BOOL allStatusesInSameState = YES;
108 AIStatus *prevStatus = nil;
109 enumerator = [[[adium accountController] accounts] objectEnumerator];
110 while ((account = [enumerator nextObject])) {
111 NSData *lastStatusData = [account preferenceForKey:@"LastStatus"
112 group:GROUP_ACCOUNT_STATUS];
113 AIStatus *lastStatus = nil;
115 lastStatus = [NSKeyedUnarchiver unarchiveObjectWithData:lastStatusData];
117 if (lastStatus && [lastStatus isKindOfClass:[AIStatus class]]) {
118 AIStatus *existingStatus;
120 /* We want to use a loaded status instance if one exists. This will be the case if the account
121 * was last in a built-in or user defined and saved state. If the last state was unsaved, existingStatus
124 existingStatus = [self statusStateWithUniqueStatusID:[lastStatus uniqueStatusID]];
126 if (existingStatus) {
127 lastStatus = existingStatus;
129 //Add to our temporary status array
130 [temporaryStateArray addObject:lastStatus];
132 /* We could clear out _flatStatusSet for the next iteration, but we _know_ what changed,
133 * so modify it directly for efficiency.
135 [_flatStatusSet addObject:lastStatus];
137 needToRebuildMenus = YES;
140 prevStatus = lastStatus;
141 else if (prevStatus != lastStatus)
142 allStatusesInSameState = NO;
143 [account setStatusStateAndRemainOffline:lastStatus];
147 if (needToRebuildMenus) {
148 [self notifyOfChangedStatusArray];
153 * @brief Begin closing the status controller
155 * Save the online accounts; they will be the accounts connected by a global status change
157 * Also save the current status state of each account so it can be restored on next launch.
159 - (void)controllerWillClose
161 NSEnumerator *enumerator;
164 enumerator = [[[adium accountController] accounts] objectEnumerator];
165 while ((account = [enumerator nextObject])) {
166 /* Store the current status state for use on next launch.
168 * We use the statusObjectForKey:@"StatusState" accessor rather than [account statusState]
169 * because we don't want anything besides the account's actual status state. That is, we don't
170 * want the default available state if the account doesn't have a state yet, and we want the
171 * real last-state-which-was-set (not the offline one) if the account is offline.
173 AIStatus *currentStatus = [account statusObjectForKey:@"StatusState"];
174 [account setPreference:((currentStatus && (currentStatus != offlineStatusState)) ?
175 [NSKeyedArchiver archivedDataWithRootObject:currentStatus] :
178 group:GROUP_ACCOUNT_STATUS];
181 [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[[self rootStateGroup] containedStatusItems]]
182 forKey:KEY_SAVED_STATUS
183 group:PREF_GROUP_SAVED_STATUS];
185 [[adium notificationCenter] removeObserver:self];
186 [[adium preferenceController] unregisterPreferenceObserver:self];
187 [[adium contactController] unregisterListObjectObserver:self];
195 [_rootStateGroup release]; _rootStateGroup = nil;
196 [_sortedFullStateArray release]; _sortedFullStateArray = nil;
200 #pragma mark Status registration
202 * @brief Register a status for a service
204 * Implementation note: Each AIStatusType has its own NSMutableDictionary, statusDictsByServiceCodeUniqueID.
205 * statusDictsByServiceCodeUniqueID is keyed by serviceCodeUniqueID; each object is an NSMutableSet of NSDictionaries.
206 * Each of these dictionaries has KEY_STATUS_NAME, KEY_STATUS_DESCRIPTION, and KEY_STATUS_TYPE.
208 * @param statusName A name which will be passed back to accounts of this service. Internal use only. Use the AIStatusController.h #defines where appropriate.
209 * @param description A human-readable localized description which will be shown to the user. Use the AIStatusController.h #defines where appropriate.
210 * @param type An AIStatusType, the general type of this status.
211 * @param service The AIService for which to register the status
213 - (void)registerStatus:(NSString *)statusName withDescription:(NSString *)description ofType:(AIStatusType)type forService:(AIService *)service
215 NSMutableSet *statusDicts;
216 NSString *serviceCodeUniqueID = [service serviceCodeUniqueID];
218 //Create the set if necessary
219 if (!statusDictsByServiceCodeUniqueID[type]) statusDictsByServiceCodeUniqueID[type] = [[NSMutableDictionary alloc] init];
220 if (!(statusDicts = [statusDictsByServiceCodeUniqueID[type] objectForKey:serviceCodeUniqueID])) {
221 statusDicts = [NSMutableSet set];
222 [statusDictsByServiceCodeUniqueID[type] setObject:statusDicts
223 forKey:serviceCodeUniqueID];
226 //Create a dictionary for this status entry
227 NSDictionary *statusDict = [NSDictionary dictionaryWithObjectsAndKeys:
228 statusName, KEY_STATUS_NAME,
229 description, KEY_STATUS_DESCRIPTION,
230 [NSNumber numberWithInt:type], KEY_STATUS_TYPE,
233 [statusDicts addObject:statusDict];
236 #pragma mark Status menus
238 * @brief Generate and return a menu of status types (Away, Be right back, etc.)
240 * @param service The service for which to return a specific list of types, or nil to return all available types
241 * @param target The target for the menu items, which will have an action of @selector(selectStatus:)
243 * @result The menu of statuses, separated by available and away status types
245 - (NSMenu *)menuOfStatusesForService:(AIService *)service withTarget:(id)target
247 NSMenu *menu = [[NSMenu allocWithZone:[NSMenu menuZone]] init];
248 NSEnumerator *enumerator;
249 NSMenuItem *menuItem;
250 NSString *serviceCodeUniqueID = [service serviceCodeUniqueID];
253 for (type = AIAvailableStatusType ; type < STATUS_TYPES_COUNT ; type++) {
254 NSArray *menuItemArray;
256 menuItemArray = [self _menuItemsForStatusesOfType:type
257 forServiceCodeUniqueID:serviceCodeUniqueID
260 //Add a separator between each type after available
261 if ((type > AIAvailableStatusType) && [menuItemArray count]) {
262 [menu addItem:[NSMenuItem separatorItem]];
265 //Add the items for this type
266 enumerator = [menuItemArray objectEnumerator];
267 while ((menuItem = [enumerator nextObject])) {
268 [menu addItem:menuItem];
272 return [menu autorelease];
276 * @brief Return an array of menu items for an AIStatusType and service
278 * @pram type The AIStatusType for which to return statuses
279 * @param inServiceCodeUniqueID The service for which to return active statuses. If nil, return all statuses for online services.
280 * @param target The target for the menu items
282 * @result An <tt>NSArray</tt> of <tt>NSMenuItem</tt> objects.
284 - (NSArray *)_menuItemsForStatusesOfType:(AIStatusType)type forServiceCodeUniqueID:(NSString *)inServiceCodeUniqueID withTarget:(id)target
286 NSMutableArray *menuItems = [[NSMutableArray alloc] init];
287 NSMutableSet *alreadyAddedTitles = [NSMutableSet set];
289 //First, add our built-in items (so they will be at the top of the array and service-specific 'copies' won't replace them)
290 [self _addMenuItemsForStatusOfType:type
292 fromSet:builtInStatusTypes[type]
294 alreadyAddedTitles:alreadyAddedTitles];
296 //Now, add items for this service, or from all available services, as appropriate
297 if (inServiceCodeUniqueID) {
300 //Obtain the status dicts for this type and service code unique ID
301 if ((statusDicts = [statusDictsByServiceCodeUniqueID[type] objectForKey:inServiceCodeUniqueID])) {
303 [self _addMenuItemsForStatusOfType:type
307 alreadyAddedTitles:alreadyAddedTitles];
311 NSEnumerator *enumerator;
314 enumerator = [[[adium accountController] activeServicesIncludingCompatibleServices:NO] objectEnumerator];
315 while ((service = [enumerator nextObject])) {
318 //Obtain the status dicts for this type and service code unique ID
319 if ((statusDicts = [statusDictsByServiceCodeUniqueID[type] objectForKey:[service serviceCodeUniqueID]])) {
321 [self _addMenuItemsForStatusOfType:type
325 alreadyAddedTitles:alreadyAddedTitles];
331 [menuItems sortUsingSelector:@selector(titleCompare:)];
333 return [menuItems autorelease];
337 * @brief Add menu items for a particular type of status
339 * @param type The AIStatusType, used for determining the icon of the menu items
340 * @param target The target of the created menu items
341 * @param statusDicts An NSSet of NSDictionary objects, which should each represent a status of the passed type
342 * @param menuItems The NSMutableArray to which to add the menuItems
343 * @param alreadyAddedTitles NSMutableSet of NSString titles which have already been added and should not be duplicated. Will be updated as items are added.
345 - (void)_addMenuItemsForStatusOfType:(AIStatusType)type
346 withTarget:(id)target
347 fromSet:(NSSet *)statusDicts
348 toArray:(NSMutableArray *)menuItems
349 alreadyAddedTitles:(NSMutableSet *)alreadyAddedTitles
351 NSEnumerator *statusDictEnumerator = [statusDicts objectEnumerator];
352 NSDictionary *statusDict;
354 //Enumerate the status dicts
355 while ((statusDict = [statusDictEnumerator nextObject])) {
356 NSString *title = [statusDict objectForKey:KEY_STATUS_DESCRIPTION];
359 * Only add if it has not already been added by another service.... Services need to use unique titles if they have
360 * unique state names, but are welcome to share common name/description combinations, which is why the #defines
363 if (![alreadyAddedTitles containsObject:title]) {
365 NSMenuItem *menuItem;
367 menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:title
369 action:@selector(selectStatus:)
372 image = [AIStatusIcons statusIconForStatusName:[statusDict objectForKey:KEY_STATUS_NAME]
374 iconType:AIStatusIconMenu
375 direction:AIIconNormal];
377 [menuItem setRepresentedObject:statusDict];
378 [menuItem setImage:image];
379 [menuItem setEnabled:YES];
380 [menuItems addObject:menuItem];
383 [alreadyAddedTitles addObject:title];
388 #pragma mark Status State Descriptions
389 - (NSString *)localizedDescriptionForCoreStatusName:(NSString *)statusName
391 static NSDictionary *coreLocalizedStatusDescriptions = nil;
392 if(!coreLocalizedStatusDescriptions){
393 coreLocalizedStatusDescriptions = [[NSDictionary dictionaryWithObjectsAndKeys:
394 AILocalizedStringFromTable(@"Available", @"Statuses", "Name of a status"), STATUS_NAME_AVAILABLE,
395 AILocalizedStringFromTable(@"Free for chat", @"Statuses", "Name of a status"), STATUS_NAME_FREE_FOR_CHAT,
396 AILocalizedStringFromTable(@"Available for friends only", @"Statuses", "Name of a status"), STATUS_NAME_AVAILABLE_FRIENDS_ONLY,
397 AILocalizedStringFromTable(@"Away", @"Statuses", "Name of a status"), STATUS_NAME_AWAY,
398 AILocalizedStringFromTable(@"Extended away", @"Statuses", "Name of a status"), STATUS_NAME_EXTENDED_AWAY,
399 AILocalizedStringFromTable(@"Away for friends only", @"Statuses", "Name of a status"), STATUS_NAME_AWAY_FRIENDS_ONLY,
400 AILocalizedStringFromTable(@"Do not disturb", @"Statuses", "Name of a status"), STATUS_NAME_DND,
401 AILocalizedStringFromTable(@"Not available", @"Statuses", "Name of a status"), STATUS_NAME_NOT_AVAILABLE,
402 AILocalizedStringFromTable(@"Occupied", @"Statuses", "Name of a status"), STATUS_NAME_OCCUPIED,
403 AILocalizedStringFromTable(@"Be right back", @"Statuses", "Name of a status"), STATUS_NAME_BRB,
404 AILocalizedStringFromTable(@"Busy", @"Statuses", "Name of a status"), STATUS_NAME_BUSY,
405 AILocalizedStringFromTable(@"On the phone", @"Statuses", "Name of a status"), STATUS_NAME_PHONE,
406 AILocalizedStringFromTable(@"Out to lunch", @"Statuses", "Name of a status"), STATUS_NAME_LUNCH,
407 AILocalizedStringFromTable(@"Not at home", @"Statuses", "Name of a status"), STATUS_NAME_NOT_AT_HOME,
408 AILocalizedStringFromTable(@"Not at my desk", @"Statuses", "Name of a status"), STATUS_NAME_NOT_AT_DESK,
409 AILocalizedStringFromTable(@"Not in the office", @"Statuses", "Name of a status"), STATUS_NAME_NOT_IN_OFFICE,
410 AILocalizedStringFromTable(@"On vacation", @"Statuses", "Name of a status"), STATUS_NAME_VACATION,
411 AILocalizedStringFromTable(@"Stepped out", @"Statuses", "Name of a status"), STATUS_NAME_STEPPED_OUT,
412 AILocalizedStringFromTable(@"Invisible", @"Statuses", "Name of a status"), STATUS_NAME_INVISIBLE,
413 AILocalizedStringFromTable(@"Offline", @"Statuses", "Name of a status"), STATUS_NAME_OFFLINE,
417 return (statusName ? [coreLocalizedStatusDescriptions objectForKey:statusName] : nil);
420 - (NSString *)localizedDescriptionForStatusName:(NSString *)statusName statusType:(AIStatusType)statusType
422 NSString *description = nil;
425 !(description = [self localizedDescriptionForCoreStatusName:statusName])) {
426 NSEnumerator *enumerator = [statusDictsByServiceCodeUniqueID[statusType] objectEnumerator];
429 while (!description && (set = [enumerator nextObject])) {
430 NSEnumerator *statusDictsEnumerator = [set objectEnumerator];
431 NSDictionary *statusDict;
432 while (!description && (statusDict = [statusDictsEnumerator nextObject])) {
433 if ([[statusDict objectForKey:KEY_STATUS_NAME] isEqualToString:statusName]){
434 description = [statusDict objectForKey:KEY_STATUS_DESCRIPTION];
444 * @brief Return the localized description for the sate of the passed status
446 * This could be stored with the statusState, but that would break if the locale changed. This way, the nonlocalized
447 * string is used to look up the appropriate localized one.
449 * @result A localized description such as @"Away" or @"Out to Lunch" of the state used by statusState
451 - (NSString *)descriptionForStateOfStatus:(AIStatus *)statusState
453 return [self localizedDescriptionForStatusName:[statusState statusName]
454 statusType:[statusState statusType]];
458 * @brief The status name to use by default for a passed type
460 * This is the name which will be used for new AIStatus objects of this type.
462 - (NSString *)defaultStatusNameForType:(AIStatusType)statusType
464 //Set the default status name
465 switch (statusType) {
466 case AIAvailableStatusType:
467 return STATUS_NAME_AVAILABLE;
469 case AIAwayStatusType:
470 return STATUS_NAME_AWAY;
472 case AIInvisibleStatusType:
473 return STATUS_NAME_INVISIBLE;
475 case AIOfflineStatusType:
476 return STATUS_NAME_OFFLINE;
483 #pragma mark Setting Status States
485 * @brief Set the active status state
487 * Sets the currently active status state. This applies throughout Adium and to all accounts. The state will become
488 * effective immediately.
490 - (void)setActiveStatusState:(AIStatus *)statusState
492 //Apply the state to our accounts and notify (delay to the next run loop to improve perceived speed)
493 [self performSelector:@selector(applyState:toAccounts:)
494 withObject:statusState
495 withObject:[[adium accountController] accounts]
499 * @brief Set the active status state for some account
501 * Sets the currently active status state for the specified account.
502 * This applies throughout Adium and to all accounts. The state will become
503 * effective immediately.
505 - (void)setActiveStatusState:(AIStatus *)state forAccount:(AIAccount *)account
507 [self removeIfNecessaryTemporaryStatusState:[account statusState]];
508 [self applyState:state toAccounts:[NSArray arrayWithObject:account]];
512 * @brief Return the <tt>AIStatus</tt> to be used by accounts as they are created
514 - (AIStatus *)defaultInitialStatusState
516 return [self availableStatus];
520 * @brief Reset the active status state
522 * All active status states cache will also reset. Posts an active status changed notification. The active state
523 * will be regenerated the next time it is requested.
525 - (void)_resetActiveStatusState
527 //Clear the active status state. It will be rebuilt next time it is requested
528 [_activeStatusState release]; _activeStatusState = nil;
529 [_allActiveStatusStates release]; _allActiveStatusStates = nil;
531 //Let observers know the active state has changed
532 if (!activeStatusUpdateDelays) {
533 [[adium notificationCenter] postNotificationName:AIStatusActiveStateChangedNotification object:nil];
538 * @brief Account status changed.
540 * Rebuild all our state menus
542 - (NSSet *)updateListObject:(AIListObject *)inObject keys:(NSSet *)inModifiedKeys silent:(BOOL)silent
544 if ([inObject isKindOfClass:[AIAccount class]]) {
545 if ([inModifiedKeys containsObject:@"Online"] ||
546 [inModifiedKeys containsObject:@"IdleSince"] ||
547 [inModifiedKeys containsObject:@"StatusState"] ||
548 [inModifiedKeys containsObject:KEY_ENABLED]) {
550 [self _resetActiveStatusState];
559 * @brief Delay activee status menu updates
561 * This should be called to prevent duplicative updates when multiple accounts are changing status simultaneously.
563 - (void)setDelayActiveStatusUpdates:(BOOL)shouldDelay
566 activeStatusUpdateDelays++;
568 activeStatusUpdateDelays--;
570 if (!activeStatusUpdateDelays) {
571 [[adium notificationCenter] postNotificationName:AIStatusActiveStateChangedNotification object:nil];
576 * @brief Delay activee status menu updates
578 * This should be called to prevent duplicative rebuilds when the status menu will change multple times.
580 - (void)setDelayStatusMenuRebuilding:(BOOL)shouldDelay
583 statusMenuRebuildDelays++;
585 statusMenuRebuildDelays--;
587 if (!statusMenuRebuildDelays) {
588 [[adium notificationCenter] postNotificationName:AIStatusStateArrayChangedNotification object:nil];
593 * @brief Apply a state to multiple accounts
595 - (void)applyState:(AIStatus *)statusState toAccounts:(NSArray *)accountArray
597 NSEnumerator *enumerator;
599 AIStatus *aStatusState;
600 BOOL shouldRebuild = NO;
601 BOOL isOfflineStatus = ([statusState statusType] == AIOfflineStatusType);
602 [self setDelayActiveStatusUpdates:YES];
604 /* If we're going offline, determine what accounts are currently online or connecting/reconnecting, first,
605 * so that we can restore that when an online state is chosen later.
607 if (isOfflineStatus && [[adium accountController] oneOrMoreConnectedOrConnectingAccounts]) {
608 [accountsToConnect removeAllObjects];
610 enumerator = [accountArray objectEnumerator];
611 while ((account = [enumerator nextObject])) {
612 // Save the account if we're online or trying to be online.
613 if ([account online] || [[account statusObjectForKey:@"Connecting"] boolValue] || [account statusObjectForKey:@"Waiting to Reconnect"])
614 [accountsToConnect addObject:account];
618 // Don't consider "connecting" accounts when connecting previously offline.
619 if (![[adium accountController] oneOrMoreConnectedAccounts]) {
620 /* No connected accounts: Connect all enabled accounts which were set offline previously.
621 * If we have no such list of accounts, connect 'em all.
623 BOOL noAccountsToConnectCount = ([accountsToConnect count] == 0);
624 enumerator = [accountArray objectEnumerator];
625 while ((account = [enumerator nextObject])) {
626 if ([account enabled] &&
627 ([accountsToConnect containsObject:account] || noAccountsToConnectCount)) {
628 [account setStatusState:statusState];
631 [account setStatusStateAndRemainOffline:statusState];
636 //At least one account is online. Just change its status without taking any other accounts online.
637 enumerator = [accountArray objectEnumerator];
638 while ((account = [enumerator nextObject])) {
639 if ([account online] || isOfflineStatus) {
640 [account setStatusState:statusState];
643 [account setStatusStateAndRemainOffline:statusState];
649 //If this is not an offline status, we've now made use of accountsToConnect and should clear it so it isn't used again.
650 if (!isOfflineStatus) {
651 [accountsToConnect removeAllObjects];
654 //Any objects in the temporary state array which aren't the state we just set should now be removed.
655 enumerator = [[[temporaryStateArray copy] autorelease] objectEnumerator];
656 while ((aStatusState = [enumerator nextObject])) {
657 if (aStatusState != statusState) {
658 [temporaryStateArray removeObject:aStatusState];
663 //Add to our temporary status array if it's not in our state array
664 if (![[self flatStatusSet] containsObject:statusState] &&
665 ![temporaryStateArray containsObject:statusState]) {
666 [temporaryStateArray addObject:statusState];
671 [self notifyOfChangedStatusArray];
674 [self setDelayActiveStatusUpdates:NO];
677 #pragma mark Retrieving Status States
679 * @brief Access to Adium's user-defined states
681 * Returns the root AIStatusGroup of user-defined states
683 - (AIStatusGroup *)rootStateGroup
685 if (!_rootStateGroup) {
686 NSData *savedStateData = [[adium preferenceController] preferenceForKey:KEY_SAVED_STATUS
687 group:PREF_GROUP_SAVED_STATUS];
688 if (savedStateData) {
689 id archivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:savedStateData];
691 if ([archivedObject isKindOfClass:[AIStatusGroup class]]) {
692 //Adium 1.0 archives an AIStatusGroup
693 _rootStateGroup = [archivedObject retain];
695 } else if ([archivedObject isKindOfClass:[NSArray class]]) {
696 //Adium 0.8x archived an NSArray
697 _rootStateGroup = [[AIStatusGroup statusGroupWithContainedStatusItems:archivedObject] retain];
701 if (!_rootStateGroup) _rootStateGroup = [[AIStatusGroup statusGroup] retain];
703 //Upgrade Adium 0.7x away messages
704 [self _upgradeSavedAwaysToSavedStates];
707 return _rootStateGroup;
711 * @brief Return the array of built-in states
713 * These are basic Available and Away states which should always be visible and are (by convention) immutable.
714 * The first state in BUILT_IN_STATE_ARRAY will be used as the default for accounts as they are created.
716 - (NSArray *)builtInStateArray
718 if (!builtInStateArray) {
719 NSArray *savedBuiltInStateArray = [NSArray arrayNamed:BUILT_IN_STATE_ARRAY forClass:[self class]];
720 NSEnumerator *enumerator;
723 builtInStateArray = [[NSMutableArray alloc] initWithCapacity:[savedBuiltInStateArray count]];
725 enumerator = [savedBuiltInStateArray objectEnumerator];
726 while ((dict = [enumerator nextObject])) {
727 AIStatus *status = [AIStatus statusWithDictionary:dict];
728 [builtInStateArray addObject:status];
730 //Store a reference to our offline state if we just loaded it
731 if ([status statusType] == AIOfflineStatusType) {
732 [offlineStatusState release];
733 offlineStatusState = [status retain];
738 return builtInStateArray;
742 * @brief Create and add the built-in status types; even if no service explicitly registers these, they are available.
744 * The built-in status types are basic, generic "Available" and "Away" states.
746 - (void)buildBuiltInStatusTypes
748 NSDictionary *statusDict;
750 builtInStatusTypes[AIAvailableStatusType] = [[NSMutableSet alloc] init];
751 statusDict = [NSDictionary dictionaryWithObjectsAndKeys:
752 STATUS_NAME_AVAILABLE, KEY_STATUS_NAME,
753 [self localizedDescriptionForCoreStatusName:STATUS_NAME_AVAILABLE], KEY_STATUS_DESCRIPTION,
754 [NSNumber numberWithInt:AIAvailableStatusType], KEY_STATUS_TYPE,
756 [builtInStatusTypes[AIAvailableStatusType] addObject:statusDict];
758 builtInStatusTypes[AIAwayStatusType] = [[NSMutableSet alloc] init];
759 statusDict = [NSDictionary dictionaryWithObjectsAndKeys:
760 STATUS_NAME_AWAY, KEY_STATUS_NAME,
761 [self localizedDescriptionForCoreStatusName:STATUS_NAME_AWAY], KEY_STATUS_DESCRIPTION,
762 [NSNumber numberWithInt:AIAwayStatusType], KEY_STATUS_TYPE,
764 [builtInStatusTypes[AIAwayStatusType] addObject:statusDict];
768 * @brief Returns the built in available status
770 - (AIStatus *)availableStatus
772 return [[[self builtInStateArray] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"statusType == %i",AIAvailableStatusType]] objectAtIndex:0];
775 * @brief Returns the built in away status
777 - (AIStatus *)awayStatus
779 return [[[self builtInStateArray] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"statusType == %i",AIAwayStatusType]] objectAtIndex:0];
782 * @brief Returns the built in invisible status
784 - (AIStatus *)invisibleStatus
786 return [[[self builtInStateArray] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"statusType == %i",AIInvisibleStatusType]] objectAtIndex:0];
789 * @brief Returns the built in offline status
791 * This method duplicates the functionality found in - [AIStatusController offlineStatusState].
792 * However, this has the same method signature format as the other statuses.
794 - (AIStatus *)offlineStatus
796 return [[[self builtInStateArray] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"statusType == %i",AIOfflineStatusType]] objectAtIndex:0];
799 - (AIStatus *)offlineStatusState
801 //Ensure the built in states have been loaded
802 [self builtInStateArray];
804 NSAssert(offlineStatusState != nil, @"Nil offline status state");
805 return offlineStatusState;
809 * @brief Return a sorted state array for use in menu item creation
811 * The array is created by adding the built in states to the user states, then sorting using _statusArraySort
812 * The resulting array may contain AIStatus and AIStatusGroup objects.
814 * @result A cached NSArray which is sorted by status type (available, away), built-in vs. user-made, and then original ordering.
816 - (NSArray *)sortedFullStateArray
818 if (!_sortedFullStateArray) {
819 NSArray *originalStateArray;
820 NSMutableArray *tempArray;
822 //Start with everything contained 1) in our built-in array and then 2) in our root group
823 originalStateArray = [[self builtInStateArray] arrayByAddingObjectsFromArray:[[self rootStateGroup] containedStatusItems]];
825 tempArray = [originalStateArray mutableCopy];
827 //Now add the temporary statues
828 [tempArray addObjectsFromArray:[temporaryStateArray allObjects]];
830 //Pass the original array so its indexes can be used for comparison of saved state ordering
831 [AIStatusGroup sortArrayOfStatusItems:tempArray context:originalStateArray];
833 _sortedFullStateArray = tempArray;
836 return _sortedFullStateArray;
840 * @brief Generate and return an array of AIStatus objects which are all known saved, temporary, and built-in statuses
842 - (NSSet *)flatStatusSet
844 if (!_flatStatusSet) {
845 NSMutableSet *tempArray = [[[self rootStateGroup] flatStatusSet] mutableCopy];
847 //Add built in states
848 [tempArray addObjectsFromArray:[self builtInStateArray]];
851 [tempArray addObjectsFromArray:[temporaryStateArray allObjects]];
853 _flatStatusSet = tempArray;
856 return _flatStatusSet;
860 * @brief Retrieve active status state
862 * @result The currently active status state.
864 * This is defined as the status state which the most accounts are currently using. The behavior in case of a tie
865 * is currently undefined but will yield one of the tying states.
867 - (AIStatus *)activeStatusState
869 if (!_activeStatusState) {
870 NSEnumerator *enumerator = [[[adium accountController] accounts] objectEnumerator];
871 NSCountedSet *statusCounts = [NSCountedSet set];
873 AIStatus *statusState;
874 unsigned highestCount = 0;
875 //This was "oneOrMoreConnectedOrConnectingAccounts" before... was there a good reason?
876 BOOL accountsAreOnline = [[adium accountController] oneOrMoreConnectedAccounts];
878 if (accountsAreOnline) {
879 AIStatus *bestStatusState = nil;
881 while ((account = [enumerator nextObject])) {
882 if ([account online]) {
883 AIStatus *accountStatusState = [account statusState];
884 [statusCounts addObject:(accountStatusState ?
886 [self defaultInitialStatusState])];
890 enumerator = [statusCounts objectEnumerator];
891 while ((statusState = [enumerator nextObject])) {
892 unsigned thisCount = [statusCounts countForObject:statusState];
893 if (thisCount > highestCount) {
894 bestStatusState = statusState;
895 highestCount = thisCount;
899 _activeStatusState = (bestStatusState ? [bestStatusState retain]: [offlineStatusState retain]);
902 _activeStatusState = [offlineStatusState retain];
906 return _activeStatusState;
910 * @brief Find the 'active' AIStatusType
912 * The active type is the one used by the largest number of accounts. In case of a tie, the order of the AIStatusType
915 * @param invisibleIsAway If YES, AIInvisibleStatusType is trated as AIAwayStatusType
916 * @result The active AIStatusType for online accounts, or AIOfflineStatusType if all accounts are offline
918 - (AIStatusType)activeStatusTypeTreatingInvisibleAsAway:(BOOL)invisibleIsAway
920 NSEnumerator *enumerator = [[[adium accountController] accounts] objectEnumerator];
922 int statusTypeCount[STATUS_TYPES_COUNT];
923 AIStatusType activeStatusType = AIOfflineStatusType;
924 unsigned highestCount = 0;
927 for (i = 0 ; i < STATUS_TYPES_COUNT ; i++) {
928 statusTypeCount[i] = 0;
931 while ((account = [enumerator nextObject])) {
932 if ([account online] || [account integerStatusObjectForKey:@"Connecting"]) {
933 AIStatusType statusType = [[account statusState] statusType];
935 //If invisibleIsAway, pretend that invisible is away
936 if (invisibleIsAway && (statusType == AIInvisibleStatusType)) statusType = AIAwayStatusType;
938 statusTypeCount[statusType]++;
942 for (i = 0 ; i < STATUS_TYPES_COUNT ; i++) {
943 if (statusTypeCount[i] > highestCount) {
944 activeStatusType = i;
945 highestCount = statusTypeCount[i];
949 return activeStatusType;
953 * @brief All active status states
955 * A status state is active if any enabled account is currently in that state.
957 * The return value of this method is cached.
959 * @result An <tt>NSSet</tt> of <tt>AIStatus</tt> objects
961 - (NSSet *)allActiveStatusStates
963 if (!_allActiveStatusStates) {
964 _allActiveStatusStates = [[NSMutableSet alloc] init];
965 NSEnumerator *enumerator = [[[adium accountController] accounts] objectEnumerator];
968 while ((account = [enumerator nextObject])) {
969 if ([account enabled]) {
970 [_allActiveStatusStates addObject:[account statusState]];
975 return _allActiveStatusStates;
979 * @brief Return the set of all unavailable statuses in use by online or connection accounts
981 * @param activeUnvailableStatusType Pointer to an AIStatusType; returns by reference the most popular unavailable type
982 * @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
983 * @param allOnlineAccountsAreUnvailable Pointer to a BOOL; returns by reference YES is all online accounts are unavailable, NO if one or more is available
985 - (NSSet *)activeUnavailableStatusesAndType:(AIStatusType *)activeUnvailableStatusType withName:(NSString **)activeUnvailableStatusName allOnlineAccountsAreUnvailable:(BOOL *)allOnlineAccountsAreUnvailable
987 NSEnumerator *enumerator = [[[adium accountController] accounts] objectEnumerator];
989 NSMutableSet *activeUnvailableStatuses = [NSMutableSet set];
990 BOOL foundStatusName = NO;
991 int statusTypeCount[STATUS_TYPES_COUNT];
993 statusTypeCount[AIAwayStatusType] = 0;
994 statusTypeCount[AIInvisibleStatusType] = 0;
996 //Assume all accounts are unavailable until proven otherwise
997 if (allOnlineAccountsAreUnvailable != NULL) {
998 *allOnlineAccountsAreUnvailable = YES;
1001 while ((account = [enumerator nextObject])) {
1002 if ([account online] || [account integerStatusObjectForKey:@"Connecting"]) {
1003 AIStatus *statusState = [account statusState];
1004 AIStatusType statusType = [statusState statusType];
1006 if ((statusType == AIAwayStatusType) || (statusType == AIInvisibleStatusType)) {
1007 NSString *statusName = [statusState statusName];
1009 [activeUnvailableStatuses addObject:statusState];
1011 statusTypeCount[statusType]++;
1013 if (foundStatusName) {
1014 //Once we find a status name, we only want to return it if all our status names are the same.
1015 if ((activeUnvailableStatusName != NULL) &&
1016 (*activeUnvailableStatusName != nil) &&
1017 ![*activeUnvailableStatusName isEqualToString:statusName]) {
1018 *activeUnvailableStatusName = nil;
1021 //We haven't found a status name yet, so store this one as the active status name
1022 if (activeUnvailableStatusName != NULL) {
1023 *activeUnvailableStatusName = [statusState statusName];
1025 foundStatusName = YES;
1028 //An online account isn't unavailable
1029 if (allOnlineAccountsAreUnvailable != NULL) {
1030 *allOnlineAccountsAreUnvailable = NO;
1036 if (activeUnvailableStatusType != NULL) {
1037 if (statusTypeCount[AIAwayStatusType] > statusTypeCount[AIInvisibleStatusType]) {
1038 *activeUnvailableStatusType = AIAwayStatusType;
1040 *activeUnvailableStatusType = AIInvisibleStatusType;
1044 return activeUnvailableStatuses;
1048 * @brief Find the status state with the requested uniqueStatusID
1050 - (AIStatus *)statusStateWithUniqueStatusID:(NSNumber *)uniqueStatusID
1052 AIStatus *statusState = nil;
1054 if (uniqueStatusID) {
1055 NSEnumerator *enumerator = [[self flatStatusSet] objectEnumerator];
1057 while ((statusState = [enumerator nextObject])) {
1058 if ([[statusState uniqueStatusID] compare:uniqueStatusID] == NSOrderedSame)
1066 //State Editing --------------------------------------------------------------------------------------------------------
1067 #pragma mark State Editing
1069 * @brief Add a state
1071 * Add a new state to Adium's state array.
1072 * @param state AIState to add
1074 - (void)addStatusState:(AIStatus *)statusState
1076 AIStatusMutabilityType mutabilityType = [statusState mutabilityType];
1078 if ((mutabilityType == AILockedStatusState) ||
1079 (mutabilityType == AISecondaryLockedStatusState)) {
1080 //If we are adding a locked status, add it to the built-in statuses
1081 [(NSMutableArray *)[self builtInStateArray] addObject:statusState];
1083 [self notifyOfChangedStatusArray];
1086 //Otherwise, add it to the user-created statuses
1087 [[self rootStateGroup] addStatusItem:statusState atIndex:-1];
1092 * @brief Remove a state
1094 * Remove a new state from Adium's state array.
1095 * @param state AIStatus to remove
1097 - (void)removeStatusState:(AIStatus *)statusState
1099 NSLog(@"shouldn't be calling this.");
1100 // [stateArray removeObject:statusState];
1101 [self savedStatusesChanged];
1104 - (void)notifyOfChangedStatusArray
1106 //Clear the sorted menu items array since our state array changed.
1107 [_sortedFullStateArray release]; _sortedFullStateArray = nil;
1108 [_flatStatusSet release]; _flatStatusSet = nil;
1110 if (!statusMenuRebuildDelays) {
1111 [[adium notificationCenter] postNotificationName:AIStatusStateArrayChangedNotification object:nil];
1116 * @brief Save changes to the state array and notify observers
1118 * Saves any outstanding changes to the state array. There should be no need to call this manually, since all the
1119 * state array modifying methods in this class call it automatically after making changes.
1121 * After the state array is saved, observers are notified that is has changed. Call after making any changes to the
1122 * state array from within the controller.
1124 - (void)savedStatusesChanged
1126 [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[[self rootStateGroup] containedStatusItems]]
1127 forKey:KEY_SAVED_STATUS
1128 group:PREF_GROUP_SAVED_STATUS];
1129 [self notifyOfChangedStatusArray];
1132 - (void)statusStateDidSetUniqueStatusID
1134 [[adium preferenceController] setPreference:[NSKeyedArchiver archivedDataWithRootObject:[[self rootStateGroup] containedStatusItems]]
1135 forKey:KEY_SAVED_STATUS
1136 group:PREF_GROUP_SAVED_STATUS];
1140 * @brief Called when a state could potentially need to removed from the temporary (non-saved) list
1142 * If originalState is in the temporary status array, and it is being used on one or zero accounts, it
1143 * is removed from the temporary status array. This method should be used when one or more accounts have stopped
1144 * using a single status state to determine if that status state is both non-saved and unused.
1146 * Note that while it would seem logical to post AIStatusStateArrayChangedNotification when this method would
1147 * return YES, we don't want to force observers of the notification to update immediately since there may be further
1148 * processing. We therefore let the calling method take action if it chooses to.
1150 * @result YES if the state was removed
1152 - (BOOL)removeIfNecessaryTemporaryStatusState:(AIStatus *)originalState
1154 BOOL didRemove = NO;
1156 /* If the original (old) status state is in our temporary array and is not being used in more than 1 account,
1157 * then we should remove it.
1159 if ([temporaryStateArray containsObject:originalState]) {
1160 NSEnumerator *enumerator;
1164 enumerator = [[[adium accountController] accounts] objectEnumerator];
1165 while ((account = [enumerator nextObject])) {
1166 if ([account actualStatusState] == originalState) {
1167 if (++count > 1) break;
1172 [temporaryStateArray removeObject:originalState];
1180 - (void)saveStatusAsLastUsed:(AIStatus *)statusState
1182 NSMutableDictionary *lastStatusStates;
1184 lastStatusStates = [[[[adium preferenceController] preferenceForKey:@"LastStatusStates"
1185 group:PREF_GROUP_STATUS_PREFERENCES] mutableCopy] autorelease];
1186 if (!lastStatusStates) lastStatusStates = [NSMutableDictionary dictionary];
1188 [lastStatusStates setObject:[NSKeyedArchiver archivedDataWithRootObject:[NSArray arrayWithObject:statusState]]
1189 forKey:[[NSNumber numberWithInt:[statusState statusType]] stringValue]];
1191 [[adium preferenceController] setPreference:lastStatusStates
1192 forKey:@"LastStatusStates"
1193 group:PREF_GROUP_STATUS_PREFERENCES];
1195 //Status state menu support ---------------------------------------------------------------------------------------------------
1196 #pragma mark Status state menu support
1198 * @brief Apply a custom state
1200 * Invoked when the custom state window is closed by the user clicking OK. In response this method sets the custom
1201 * state as the active state.
1203 - (void)customStatusState:(AIStatus *)originalState changedTo:(AIStatus *)newState forAccount:(AIAccount *)account
1205 BOOL shouldRebuild = NO;
1207 if ([newState mutabilityType] != AITemporaryEditableStatusState) {
1208 [[adium statusController] addStatusState:newState];
1212 shouldRebuild = [self removeIfNecessaryTemporaryStatusState:originalState];
1214 //Now set the newState for the account
1215 [account setStatusState:newState];
1217 //Enable the account if it isn't currently enabled
1218 if (![account enabled]) {
1219 [account setEnabled:YES];
1222 //Add to our temporary status array if it's not in our state array
1223 if (shouldRebuild || (![[self flatStatusSet] containsObject:newState])) {
1224 [temporaryStateArray addObject:newState];
1226 [self notifyOfChangedStatusArray];
1230 //Set the state for all accounts. This will clear out the temporaryStatusArray as necessary and update its contents.
1231 [self setActiveStatusState:newState];
1234 [self saveStatusAsLastUsed:newState];
1238 #pragma mark Upgrade code
1240 * @brief Temporary upgrade code for 0.7x -> 0.8
1242 * Versions 0.7x and prior stored their away messages in a different format. This code allows a seamless
1243 * transition from 0.7x to 0.8. We can easily recognize the old format because the away messages are of
1244 * type "Away" instead of type "State", which is used for all 0.8 and later saved states.
1245 * Since we are changing the array as we scan it, an enumerator will not work here.
1247 #define OLD_KEY_SAVED_AWAYS @"Saved Away Messages"
1248 #define OLD_GROUP_AWAY_MESSAGES @"Away Messages"
1249 #define OLD_STATE_SAVED_AWAY @"Away"
1250 #define OLD_STATE_AWAY @"Message"
1251 #define OLD_STATE_AUTO_REPLY @"Autoresponse"
1252 #define OLD_STATE_TITLE @"Title"
1253 - (void)_upgradeSavedAwaysToSavedStates
1255 NSArray *savedAways = [[adium preferenceController] preferenceForKey:OLD_KEY_SAVED_AWAYS
1256 group:OLD_GROUP_AWAY_MESSAGES];
1259 NSEnumerator *enumerator = [savedAways objectEnumerator];
1260 NSDictionary *state;
1262 AILog(@"*** Upgrading Adium 0.7x saved aways: %@", savedAways);
1264 [self setDelayStatusMenuRebuilding:YES];
1266 //Update all the away messages to states.
1267 while ((state = [enumerator nextObject])) {
1268 if ([[state objectForKey:@"Type"] isEqualToString:OLD_STATE_SAVED_AWAY]) {
1269 AIStatus *statusState;
1271 //Extract the away message information from this old record
1272 NSData *statusMessageData = [state objectForKey:OLD_STATE_AWAY];
1273 NSData *autoReplyMessageData = [state objectForKey:OLD_STATE_AUTO_REPLY];
1274 NSString *title = [state objectForKey:OLD_STATE_TITLE];
1276 //Create an AIStatus from this information
1277 statusState = [AIStatus status];
1279 //General category: It's an away type
1280 [statusState setStatusType:AIAwayStatusType];
1282 //Specific state: It's the generic away. Funny how that works out.
1283 [statusState setStatusName:STATUS_NAME_AWAY];
1285 //Set the status message (which is just the away message).
1286 [statusState setStatusMessage:[NSAttributedString stringWithData:statusMessageData]];
1288 //It has an auto reply.
1289 [statusState setHasAutoReply:YES];
1291 if (autoReplyMessageData) {
1292 //Use the custom auto reply if it was set.
1293 [statusState setAutoReply:[NSAttributedString stringWithData:autoReplyMessageData]];
1295 //If no autoReplyMesssage, use the status message.
1296 [statusState setAutoReplyIsStatusMessage:YES];
1299 if (title) [statusState setTitle:title];
1301 //Add the updated state to our state array.
1302 [self addStatusState:statusState];
1306 AILog(@"*** Finished upgrading old saved statuses");
1308 //Save these changes and delete the old aways so we don't need to do this again.
1309 [self setDelayStatusMenuRebuilding:NO];
1311 [[adium preferenceController] setPreference:nil
1312 forKey:OLD_KEY_SAVED_AWAYS
1313 group:OLD_GROUP_AWAY_MESSAGES];