William Bowling is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

wbowling / adium (fork of adium / adium)

Fork of Adium for patches/improvements

Clone this repository (size: 338.7 MB): HTTPS / SSH
hg clone https://bitbucket.org/wbowling/adium
hg clone ssh://hg@bitbucket.org/wbowling/adium

adium / Source / ESStatusPreferences.m

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//
//  ESStatusPreferences.m
//  Adium
//
//  Created by Evan Schoenberg on 2/26/05.
//  Copyright 2006 The Adium Team. All rights reserved.
//

#import "ESStatusPreferences.h"
#import "AIStatusController.h"
#import "ESEditStatusGroupWindowController.h"
#import <Adium/AIAccountControllerProtocol.h>
#import <Adium/AIAccount.h>
#import <Adium/AIEditStateWindowController.h>
#import <Adium/AIStatusMenu.h>
#import <Adium/AIStatusGroup.h>
#import <AIUtilities/AIImageAdditions.h>
#import <AIUtilities/AIImageTextCell.h>
#import <AIUtilities/AIAutoScrollView.h>
#import <AIUtilities/AIVerticallyCenteredTextCell.h>
#import <AIUtilities/AIOutlineViewAdditions.h>
#import <AIUtilities/AIAlternatingRowOutlineView.h>
#import <AIUtilities/AIImageDrawingAdditions.h>

#define STATE_DRAG_TYPE @"AIState"

@interface ESStatusPreferences ()
- (void)configureOtherControls;
- (void)configureAutoAwayStatusStatePopUp;
- (void)saveTimeValues;
- (void)_selectStatusWithUniqueID:(NSNumber *)uniqueID inPopUpButton:(NSPopUpButton *)inPopUpButton;

- (BOOL)addItemIfNeeded:(NSMenuItem *)menuItem toPopUpButton:(NSPopUpButton *)popUpButton alreadyShowingAnItem:(BOOL)alreadyShowing;
@end

@implementation ESStatusPreferences

- (NSString *)paneIdentifier
{
        return @"Status";
}
- (NSString *)paneName
{
    return AILocalizedString(@"Status",nil);
}
- (NSImage *)paneIcon
{
        return [NSImage imageNamed:@"pref-status" forClass:[self class]];
}

/*!
 * @brief Nib name
 */
- (NSString *)nibName{
    return @"StatusPreferences";
}

/*!
 * @brief Configure the preference view
 */
- (void)viewDidLoad
{
        //Configure the controls
        [self configureStateList];

        [outlineView_stateList setDrawsBackground:NO];
        [outlineView_stateList setUsesAlternatingRowBackgroundColors:YES];
        
        //Manually size and position our buttons
        {
                NSRect  newFrame, oldFrame;
                
                //Edit, right justified and far enough away from Remove that it can't conceivably overlap
                oldFrame = [button_editState frame];
                [button_editState setTitle:AILocalizedStringFromTable(@"Edit", @"Buttons", "Verb 'edit' on a button")];
                [button_editState sizeToFit];
                newFrame = [button_editState frame];
                if (newFrame.size.width < oldFrame.size.width) newFrame.size.width = oldFrame.size.width;
                if (newFrame.size.height < oldFrame.size.height) newFrame.size.height = oldFrame.size.height;
                newFrame.origin.x = oldFrame.origin.x + oldFrame.size.width - newFrame.size.width;
                [button_editState setFrame:newFrame];

                //Add Group
                oldFrame = [button_addGroup frame];
                [button_addGroup setTitle:AILocalizedString(@"Add Group",nil)];
                [button_addGroup sizeToFit];
                newFrame = [button_addGroup frame];
                if (newFrame.size.height < oldFrame.size.height) newFrame.size.height = oldFrame.size.height;
                if (newFrame.size.width < oldFrame.size.width) newFrame.size.width = oldFrame.size.width;
                if (newFrame.size.width > oldFrame.size.width) newFrame.size.width += 8;
                [button_addGroup setFrame:newFrame];
        }
                
        [outlineView_stateList accessibilitySetOverrideValue:AILocalizedString(@"Statuses", nil)
                                                                                        forAttribute:NSAccessibilityRoleDescriptionAttribute];

        /* Register as an observer of state array changes so we can refresh our list
         * in response to changes. */
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                   selector:@selector(stateArrayChanged:)
                                                                           name:AIStatusStateArrayChangedNotification
                                                                         object:nil];
        [self stateArrayChanged:nil];

        [self configureOtherControls];
}

/*!
 * @brief Preference view is closing
 */
- (void)viewWillClose
{
        [self saveTimeValues];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*!
 * @brief Deallocate
 */
- (void)dealloc
{
        [super dealloc];
}

#pragma mark Status state list and controls
/*!
* @brief Configure the state list
 *
 * Configure the state list table view, setting up the custom table cells, padding, scroll view settings and other
 * state list interface related setup.
 */
- (void)configureStateList
{
    AIImageTextCell                     *cell;

        //Configure the table view
        [outlineView_stateList setTarget:self];
        [outlineView_stateList setDoubleAction:@selector(editState:)];
        [outlineView_stateList setIntercellSpacing:NSMakeSize(4,4)];
    [scrollView_stateList setAutohidesScrollers:YES];
        
        //Enable dragging of states
        [outlineView_stateList registerForDraggedTypes:[NSArray arrayWithObject:STATE_DRAG_TYPE]];
        
    //Custom vertically-centered text cell for status state names
    cell = [[AIVerticallyCenteredTextCell alloc] init];
    [cell setFont:[NSFont systemFontOfSize:13]];
    [[outlineView_stateList tableColumnWithIdentifier:@"name"] setDataCell:cell];
        [cell release];
}

/*!
 * @brief Update table control availability
 *
 * Updates table control availability based on the current state selection.  If no states are selected this method dims the
 * edit and delete buttons since they require a selection to function.  The edit and delete buttons are also
 * dimmed if the selected state is a built-in state.
 */
- (void)updateTableControlAvailability
{
//      NSArray *selectedItems = [outlineView_stateList arrayOfSelectedItems];
        NSIndexSet *selectedIndexes = [outlineView_stateList selectedRowIndexes];
        NSInteger                       count = [selectedIndexes count];

        [button_editState setEnabled:(count && 
                                                                  ([[outlineView_stateList itemAtRow:[selectedIndexes firstIndex]] mutabilityType] == AIEditableStatusState))];
        [button_deleteState setEnabled:count];
}

/*!
 * @brief Invoked when the state array changes
 *
 * This method is invoked when the state array changes.  In response, we hold onto the new array and refresh our state
 * list.
 */
- (void)stateArrayChanged:(NSNotification *)notification
{
        [outlineView_stateList reloadData];
        [self updateTableControlAvailability];
        
        //Update the auto away status pop up as necessary
        [self configureAutoAwayStatusStatePopUp];
}

//State Editing --------------------------------------------------------------------------------------------------------
#pragma mark State Editing
/*!
* @brief Edit the selected state
 *
 * Opens an edit state sheet for the selected state.  If the sheet is closed with success our
 * customStatusState:changedTo: method will be invoked and we can save the changes
 */
- (IBAction)editState:(id)sender
{
        NSInteger                               selectedRow = [outlineView_stateList selectedRow];
        AIStatusItem    *statusState = [outlineView_stateList itemAtRow:selectedRow];
        
        if (statusState) {
                if ([statusState isKindOfClass:[AIStatus class]]) {
                        [AIEditStateWindowController editCustomState:(AIStatus *)statusState
                                                                                                 forType:statusState.statusType
                                                                                          andAccount:nil
                                                                                  withSaveOption:NO
                                                                                                onWindow:[[self view] window]
                                                                                 notifyingTarget:self];
                        
                } else if ([statusState isKindOfClass:[AIStatusGroup class]]) {
                        [ESEditStatusGroupWindowController editStatusGroup:(AIStatusGroup *)statusState
                                                                                                          onWindow:[[self view] window]
                                                                                           notifyingTarget:self];                       
                }
        }
}

/*!
* @brief State edited callback
 *
 * Invoked when the user successfully edits a state.  This method adds the new or updated state to Adium's state array.
 */
- (void)customStatusState:(AIStatus *)originalState changedTo:(AIStatus *)newState forAccount:(AIAccount *)account
{
        if (originalState) {
                /* As far the user was concerned, this was an edit.  The unique status ID should remain the same so that anything
                 * depending upon this status will update to using it.  Furthermore, since this may be a copy of originalState
                 * rather than the exact same object, we should update all accounts which are using this state to use the new copy
                 */
                [newState setUniqueStatusID:[originalState uniqueStatusID]];
                
                for (AIAccount *account in adium.accountController.accounts) {
                        if (account.statusState == originalState) {
                                [account setStatusStateAndRemainOffline:newState];
                                
                                [account notifyOfChangedPropertiesSilently:YES];
                        }
                }

                [[originalState containingStatusGroup] replaceExistingStatusState:originalState withStatusState:newState];

                [originalState setUniqueStatusID:nil];

        } else {
                [adium.statusController addStatusState:newState];
        }
        
        [outlineView_stateList selectItemsInArray:[NSArray arrayWithObject:newState]];
        [outlineView_stateList scrollRowToVisible:[outlineView_stateList rowForItem:newState]];
}

- (void)finishedStatusGroupEdit:(AIStatusGroup *)inStatusGroup
{
        if (![inStatusGroup containingStatusGroup]) {
                //Add it if it's not already in a group
                [[adium.statusController rootStateGroup] addStatusItem:inStatusGroup atIndex:-1];

        } else {
                //Otherwise just save
                [adium.statusController savedStatusesChanged];
        }

        [outlineView_stateList selectItemsInArray:[NSArray arrayWithObject:inStatusGroup]];
        [outlineView_stateList scrollRowToVisible:[outlineView_stateList rowForItem:inStatusGroup]];
}

/*!
 * @brief Delete the selected state
 *
 * Deletes the selected state from Adium's state array.
 */
- (IBAction)deleteState:(id)sender
{
        NSArray          *selectedItems = [outlineView_stateList arrayOfSelectedItems];
        
        if ([selectedItems count]) {
                //Confirm deletion of a status group with contents
                NSUInteger                       numberOfItems = 0;

                for (AIStatusItem *statusItem in selectedItems) {
                        if ([statusItem isKindOfClass:[AIStatusGroup class]] &&
                                [[(AIStatusGroup *)statusItem flatStatusSet] count]) {
                                numberOfItems += [[(AIStatusGroup *)statusItem flatStatusSet] count];
                        } else {
                                numberOfItems++;
                        }
                }

                NSString *message = [NSString stringWithFormat:AILocalizedString(@"Are you sure you want to delete %lu saved status items?",nil),
                                                         numberOfItems];
                
                //Warn if deleting a group containing status items
                NSBeginAlertSheet(AILocalizedString(@"Status Deletion Confirmation",nil),
                                                  AILocalizedString(@"Delete", nil),
                                                  AILocalizedString(@"Cancel", nil), nil,
                                                  [[self view] window], self,
                                                  @selector(sheetDidEnd:returnCode:contextInfo:), NULL,
                                                  [selectedItems retain],
                                                  message);
        }
}

/*!
 * @brief Confirmed a status item deletion operation
 */
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
        NSArray *selectedItems = (NSArray *)contextInfo;
        if (returnCode == NSAlertDefaultReturn) {
                AIStatusItem *statusItem;

                for (statusItem in selectedItems) {
                        [[statusItem containingStatusGroup] removeStatusItem:statusItem];
                }
        }       
        
        [selectedItems release];
}

/*!
* @brief Add a new state
 *
 * Creates a new state.  This is done by invoking an edit window without passing it a base state.  When the edit window
 * returns successfully, it will invoke our customStatusState:changedTo: which adds the new state to Adium's state
 * array.
 */
- (IBAction)newState:(id)sender
{
        [AIEditStateWindowController editCustomState:nil
                                                                                 forType:AIAwayStatusType
                                                                          andAccount:nil
                                                                  withSaveOption:NO
                                                                                onWindow:[[self view] window]
                                                                 notifyingTarget:self];
}

- (IBAction)addGroup:(id)sender
{
        [ESEditStatusGroupWindowController editStatusGroup:nil
                                                                                          onWindow:[[self view] window]
                                                                           notifyingTarget:self];
}

//State List OutlinView Delegate --------------------------------------------------------------------------------------------
#pragma mark State List (OutlineView Delegate)
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item
{
        AIStatusGroup *statusGroup = (item ? item : [adium.statusController rootStateGroup]);
        
        return [[statusGroup containedStatusItems] objectAtIndex:index];
}

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
        AIStatusGroup *statusGroup = (item ? item : [adium.statusController rootStateGroup]);
        
        return [[statusGroup containedStatusItems] count];      
}

- (NSString *)outlineView:(NSOutlineView *)outlineView typeSelectStringForTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
        if([[tableColumn identifier] isEqualToString:@"name"])
                return [item title] ? [item title] : @"";
        return @"";
}
- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
{

}

- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
        NSString                *identifier = [tableColumn identifier];
        
        if ([identifier isEqualToString:@"icon"]) {
                return ([item respondsToSelector:@selector(icon)] ? [item icon] : nil);
                
        } else if ([identifier isEqualToString:@"name"]) {
                NSImage *icon = ([item respondsToSelector:@selector(icon)] ? [item icon] : nil);
                
                if (icon) {
                        NSMutableAttributedString *name;

                        NSTextAttachment                *attachment;
                        NSTextAttachmentCell    *cell;
                        
                        NSSize                                  iconSize = [icon size];
                        
                        if ((iconSize.width > 13) || (iconSize.height > 13)) {
                                icon = [icon imageByScalingToSize:NSMakeSize(13, 13)];
                        }

                        cell = [[[NSTextAttachmentCell alloc] init] autorelease];
                        [cell setImage:icon];
                        
                        attachment = [[[NSTextAttachment alloc] init] autorelease];
                        [attachment setAttachmentCell:cell];
                        
                        name = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
                        [name appendAttributedString:[[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@",([item title] ? [item title] : @"")]
                                                                                                                                                  attributes:nil] autorelease]];
                        return [name autorelease];
                } else {
                        return [item title]; 
                }
        }
        
        return nil;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
        return [item isKindOfClass:[AIStatusGroup class]];
}

/*!
* @brief Delete the selected row
 */
- (void)outlineViewDeleteSelectedRows:(NSTableView *)tableView
{
    [self deleteState:nil];
}

/*!
* @brief Selection change
 */
- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{
        [self updateTableControlAvailability];
}

/*!
* @brief Drag start
 */
- (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray*)items toPasteboard:(NSPasteboard*)pboard
{
    draggingItems = [items retain];
        
    [pboard declareTypes:[NSArray arrayWithObject:STATE_DRAG_TYPE] owner:self];
    [pboard setString:@"State" forType:STATE_DRAG_TYPE]; //Arbitrary state

    return YES;
}

- (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
{
    if (index == NSOutlineViewDropOnItemIndex && ![item isKindOfClass:[AIStatusGroup class]]) {
                AIStatusGroup *dropItem = [item containingStatusGroup];
                if (dropItem == [adium.statusController rootStateGroup])
                        dropItem = nil;

                [outlineView setDropItem:dropItem
                                  dropChildIndex:[[[item containingStatusGroup] containedStatusItems] indexOfObjectIdenticalTo:item]];
        }
     
        return NSDragOperationPrivate;
}

/*!
* @brief Drag complete
 */
- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
{
    NSString    *avaliableType = [[info draggingPasteboard] availableTypeFromArray:[NSArray arrayWithObject:STATE_DRAG_TYPE]];
    if ([avaliableType isEqualToString:STATE_DRAG_TYPE]) {              
                [adium.statusController setDelayStatusMenuRebuilding:YES];

                if (!item) item = [adium.statusController rootStateGroup];

                AIStatusItem *statusItem;
                

                for (statusItem in draggingItems) {
                        if ([statusItem containingStatusGroup] == item) {
                                BOOL shouldIncrement = NO;
                                if ([[[statusItem containingStatusGroup] containedStatusItems] indexOfObject:statusItem] > index) {
                                        shouldIncrement = YES;
                                }
                                
                                //Move the state and select it in the new location
                                [item moveStatusItem:statusItem toIndex:index];
                                
                                if (shouldIncrement) index++;
                        } else {
                                //Don't let an object be moved into itself...
                                if (item != statusItem) {
                                        [statusItem retain];
                                        [[statusItem containingStatusGroup] removeStatusItem:statusItem];
                                        [item addStatusItem:statusItem atIndex:index];
                                        [statusItem release];
                                        
                                        index++;
                                }
                        }
                }

                //Notify and reselect outside of the NSOutlineView callback
                [self performSelector:@selector(reselectDraggedItems:)
                                   withObject:draggingItems
                                   afterDelay:0];

                [draggingItems release]; draggingItems = nil;

        return YES;
    } else {
        return NO;
    }
}

- (void)reselectDraggedItems:(NSArray *)theDraggedItems
{
        [adium.statusController setDelayStatusMenuRebuilding:NO];

        [outlineView_stateList selectItemsInArray:theDraggedItems];
        [outlineView_stateList scrollRowToVisible:[outlineView_stateList rowForItem:[theDraggedItems objectAtIndex:0]]];
}

#pragma mark Other status-related controls

/*!
 * @brief Configure initial values for idle, auto-away, etc., preferences.
 */

- (void)configureOtherControls
{
        NSDictionary    *prefDict = [adium.preferenceController preferencesForGroup:PREF_GROUP_STATUS_PREFERENCES];
        
        [checkBox_idle setState:[[prefDict objectForKey:KEY_STATUS_REPORT_IDLE] boolValue]];
        [textField_idleMinutes setDoubleValue:([[prefDict objectForKey:KEY_STATUS_REPORT_IDLE_INTERVAL] doubleValue] / 60.0)];
        [stepper_idleMinutes setDoubleValue:([[prefDict objectForKey:KEY_STATUS_REPORT_IDLE_INTERVAL] doubleValue] / 60.0)];

        [checkBox_autoAway setState:[[prefDict objectForKey:KEY_STATUS_AUTO_AWAY] boolValue]];
        [textField_autoAwayMinutes setDoubleValue:([[prefDict objectForKey:KEY_STATUS_AUTO_AWAY_INTERVAL] doubleValue] / 60.0)];
        [stepper_autoAwayMinutes setDoubleValue:([[prefDict objectForKey:KEY_STATUS_AUTO_AWAY_INTERVAL] doubleValue] / 60.0)];

        [checkBox_fastUserSwitching setState:[[prefDict objectForKey:KEY_STATUS_FUS] boolValue]];
        [checkBox_screenSaver setState:[[prefDict objectForKey:KEY_STATUS_SS] boolValue]];

        [checkBox_showStatusWindow setState:[[prefDict objectForKey:KEY_STATUS_SHOW_STATUS_WINDOW] boolValue]];
        
        [self configureControlDimming];
}

/*!
 * @brief Configure the pop up of states for autoAway.
 *
 * Should be called by stateArrayChanged: both for initial set up and for updating when the states change.
 */
- (void)configureAutoAwayStatusStatePopUp
{
        NSMenu          *statusStatesMenu;
        NSNumber        *targetUniqueStatusIDNumber;

        statusStatesMenu = [AIStatusMenu staticStatusStatesMenuNotifyingTarget:self selector:@selector(changedAutoAwayStatus:)];
        [popUp_autoAwayStatusState setMenu:statusStatesMenu];
        
        statusStatesMenu = [AIStatusMenu staticStatusStatesMenuNotifyingTarget:self selector:@selector(changedFastUserSwitchingStatus:)];       
        [popUp_fastUserSwitchingStatusState setMenu:[[statusStatesMenu copy] autorelease]];
        
        statusStatesMenu = [AIStatusMenu staticStatusStatesMenuNotifyingTarget:self selector:@selector(changedScreenSaverStatus:)];     
        [popUp_screenSaverStatusState setMenu:[[statusStatesMenu copy] autorelease]];

        //Now select the proper state, or deselect all items if there is no chosen state or the chosen state doesn't exist
        targetUniqueStatusIDNumber = [adium.preferenceController preferenceForKey:KEY_STATUS_AUTO_AWAY_STATUS_STATE_ID
                                                                                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];
        [self _selectStatusWithUniqueID:targetUniqueStatusIDNumber inPopUpButton:popUp_autoAwayStatusState];
        
        targetUniqueStatusIDNumber = [adium.preferenceController preferenceForKey:KEY_STATUS_FUS_STATUS_STATE_ID
                                                                                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];
        [self _selectStatusWithUniqueID:targetUniqueStatusIDNumber inPopUpButton:popUp_fastUserSwitchingStatusState];   
        
        targetUniqueStatusIDNumber = [adium.preferenceController preferenceForKey:KEY_STATUS_SS_STATUS_STATE_ID
                                                                                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];
        [self _selectStatusWithUniqueID:targetUniqueStatusIDNumber inPopUpButton:popUp_screenSaverStatusState]; 
}

/*!
 * @brief Add all items in inMenu to an array, returning the resulting array
 *
 * This method adds items deeply; that is, submenus and their contents are recursively included
 *
 * @param inMenu The menu to start from
 * @param recursiveArray The array thus far; if nil an array will be created
 *
 * @result All the menu items in inMenu
 */
- (NSMutableArray *)addItemsFromMenu:(NSMenu *)inMenu toArray:(NSMutableArray *)recursiveArray
{
        NSArray                 *itemArray = [inMenu itemArray];
        NSMenuItem              *menuItem;

        if (!recursiveArray) recursiveArray = [NSMutableArray array];

        for (menuItem in itemArray) {
                [recursiveArray addObject:menuItem];

                if ([menuItem submenu]) {
                        [self addItemsFromMenu:[menuItem submenu] toArray:recursiveArray];
                }
        }

        return recursiveArray;
}

/*!
 * @brief Select a status with uniqueID in inPopUpButton
 */
- (void)_selectStatusWithUniqueID:(NSNumber *)uniqueID inPopUpButton:(NSPopUpButton *)inPopUpButton
{
        NSMenuItem      *menuItem = nil;
        
        if (uniqueID) {
                NSInteger                        targetUniqueStatusID= [uniqueID integerValue];

                for (menuItem in [self addItemsFromMenu:[inPopUpButton menu] toArray:nil]) {
                        AIStatusItem    *statusState;
                        
                        statusState = [[menuItem representedObject] objectForKey:@"AIStatus"];

                        //Found the right status by matching its status ID to our preferred one
                        if ([statusState preexistingUniqueStatusID] == targetUniqueStatusID) {
                                break;
                        }
                }
        }

        if (menuItem) {
                [inPopUpButton selectItem:menuItem];

                //Add it if we weren't able to select it initially
                if (![inPopUpButton selectedItem]) {
                        [self addItemIfNeeded:menuItem toPopUpButton:inPopUpButton alreadyShowingAnItem:NO];
                        
                        if (inPopUpButton == popUp_autoAwayStatusState) {
                                showingSubmenuItemInAutoAway = YES;
                                
                        } else if (inPopUpButton == popUp_fastUserSwitchingStatusState) {
                                showingSubmenuItemInFastUserSwitching = YES;
                                
                        } else if (inPopUpButton == popUp_screenSaverStatusState) {
                                showingSubmenuItemInScreenSaver = YES;
                                
                        }
                }
        }
}

/*!
 * @brief Configure control dimming for idle, auto-away, etc., preferences.
 */
- (void)configureControlDimming
{
        BOOL    idleControlsEnabled, autoAwayControlsEnabled;

        idleControlsEnabled = ([checkBox_idle state] == NSOnState);
        [textField_idleMinutes setEnabled:idleControlsEnabled];
        [stepper_idleMinutes setEnabled:idleControlsEnabled];
        
        autoAwayControlsEnabled = ([checkBox_autoAway state] == NSOnState);
        [popUp_autoAwayStatusState setEnabled:autoAwayControlsEnabled];
        [textField_autoAwayMinutes setEnabled:autoAwayControlsEnabled];
        [stepper_autoAwayMinutes setEnabled:autoAwayControlsEnabled];
        
        [popUp_fastUserSwitchingStatusState setEnabled:([checkBox_fastUserSwitching state] == NSOnState)];
        [popUp_screenSaverStatusState setEnabled:([checkBox_screenSaver state] == NSOnState)];
}

/*!
 * @brief Change preference
 *
 * Sent when controls are clicked
 */
- (void)changePreference:(id)sender
{
        if (sender == checkBox_idle) {
                [adium.preferenceController setPreference:[NSNumber numberWithBool:[sender state]]
                                                                                         forKey:KEY_STATUS_REPORT_IDLE
                                                                                          group:PREF_GROUP_STATUS_PREFERENCES];
                [self configureControlDimming];
                
        } else if (sender == checkBox_autoAway) {
                [adium.preferenceController setPreference:[NSNumber numberWithBool:[sender state]]
                                                                                         forKey:KEY_STATUS_AUTO_AWAY
                                                                                          group:PREF_GROUP_STATUS_PREFERENCES];
                [self configureControlDimming];
                
        } else if (sender == checkBox_showStatusWindow) {
                [adium.preferenceController setPreference:[NSNumber numberWithBool:[sender state]]
                                                                                         forKey:KEY_STATUS_SHOW_STATUS_WINDOW
                                                                                          group:PREF_GROUP_STATUS_PREFERENCES];         
                
        } else if (sender == checkBox_fastUserSwitching) {
                [adium.preferenceController setPreference:[NSNumber numberWithBool:[sender state]]
                                                                                         forKey:KEY_STATUS_FUS
                                                                                          group:PREF_GROUP_STATUS_PREFERENCES];
                [self configureControlDimming];
                
        } else if (sender == checkBox_screenSaver) {
                [adium.preferenceController setPreference:[NSNumber numberWithBool:[sender state]]
                                                                                         forKey:KEY_STATUS_SS
                                                                                          group:PREF_GROUP_STATUS_PREFERENCES];
                [self configureControlDimming];
                
        }
}

/*!
 * @brief If menuItem is not selectable in popUpButton, add it and select it
 *
 * Menu items located within submenus can't be directly selected. This method will add a spearator item and then the item itself
 * to the bottom of popUpButton if needed.  alreadyShowing should be YES if a similarly set separate + item exists; it will be removed
 * first.
 *
 * @result YES if the item was added to popUpButton.
 */
- (BOOL)addItemIfNeeded:(NSMenuItem *)menuItem toPopUpButton:(NSPopUpButton *)popUpButton alreadyShowingAnItem:(BOOL)alreadyShowing
{
        BOOL    nowShowing = NO;
        NSMenu  *menu = [popUpButton menu];

        [menuItem retain];
        if (alreadyShowing) {
                NSInteger count = [menu numberOfItems];
                [menu removeItemAtIndex:--count];
                [menu removeItemAtIndex:--count];                       
        }
        
        if ([popUpButton selectedItem] != menuItem) {
                NSMenuItem  *imitationMenuItem = [menuItem copy];
                
                [menu addItem:[NSMenuItem separatorItem]];
                [menu addItem:imitationMenuItem];
                
                [popUpButton selectItem:imitationMenuItem];
                [imitationMenuItem release];
                
                nowShowing = YES;
        }       
        [menuItem release];
        
        return nowShowing;
}
- (void)changedAutoAwayStatus:(id)sender
{
        AIStatus        *statusState = [[sender representedObject] objectForKey:@"AIStatus"];

        [adium.preferenceController setPreference:[statusState uniqueStatusID]
                                                                                 forKey:KEY_STATUS_AUTO_AWAY_STATUS_STATE_ID
                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];

        showingSubmenuItemInAutoAway = [self addItemIfNeeded:sender
                                                                                   toPopUpButton:popUp_autoAwayStatusState
                                                                        alreadyShowingAnItem:showingSubmenuItemInAutoAway];
}

- (void)changedFastUserSwitchingStatus:(id)sender
{
        AIStatus        *statusState = [[sender representedObject] objectForKey:@"AIStatus"];

        [adium.preferenceController setPreference:[statusState uniqueStatusID]
                                                                                 forKey:KEY_STATUS_FUS_STATUS_STATE_ID
                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];
        
        showingSubmenuItemInFastUserSwitching = [self addItemIfNeeded:sender
                                                                                                        toPopUpButton:popUp_fastUserSwitchingStatusState
                                                                                         alreadyShowingAnItem:showingSubmenuItemInFastUserSwitching];
}

- (void)changedScreenSaverStatus:(id)sender
{
        AIStatus        *statusState = [[sender representedObject] objectForKey:@"AIStatus"];
        
        [adium.preferenceController setPreference:[statusState uniqueStatusID]
                                                                                 forKey:KEY_STATUS_SS_STATUS_STATE_ID
                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];
        
        showingSubmenuItemInScreenSaver = [self addItemIfNeeded:sender
                                                                                                        toPopUpButton:popUp_screenSaverStatusState
                                                                                         alreadyShowingAnItem:showingSubmenuItemInScreenSaver];
}

/*!
 * @brief Control text did end editing
 *
 * In an attempt to get closer to a live-apply of preferences, save the preference when the
 * text field loses focus.  See saveTimeValues for more information.
 */
- (void)controlTextDidEndEditing:(NSNotification *)notification
{
        [self saveTimeValues];
}

/*!
 * @brief Save time text field values
 *
 * We can't get notified when the associated NSStepper is clicked, so we just save as requested.
 * This method should be called before the view closes.
 */
- (void)saveTimeValues
{
        [adium.preferenceController setPreference:[NSNumber numberWithDouble:([textField_idleMinutes doubleValue]*60.0)]
                                                                                 forKey:KEY_STATUS_REPORT_IDLE_INTERVAL
                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];

        [adium.preferenceController setPreference:[NSNumber numberWithDouble:([textField_autoAwayMinutes doubleValue]*60.0)]
                                                                                 forKey:KEY_STATUS_AUTO_AWAY_INTERVAL
                                                                                  group:PREF_GROUP_STATUS_PREFERENCES];
}

@end